diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 2b7e9f20..22946d6d 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -1,15 +1,16 @@ module.exports = { - "env": { - "browser": true, - "es2018": true, - "node": true + env: { + browser: true, + es2018: true, + node: true, }, - "extends": "eslint:recommended", - "parserOptions": { - "ecmaVersion": 2018, - "sourceType": "module" + extends: 'eslint:recommended', + parserOptions: { + ecmaVersion: 2018, + sourceType: 'module', }, - "rules": { - "no-cond-assign": 0 - } -} + rules: { + 'no-cond-assign': 0, + 'no-unused-vars': ['error', { args: 'none', varsIgnorePattern: '^_' }], + }, +}; diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..d18abd49 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,20 @@ +# Dependencies +node_modules/ + +# Build output +dist/ +coverage/ + +# Lock files +package-lock.json +**/package-lock.json + +# Generated / vendored +*.min.js +test/typescript/axios.js* + +# Misc +*.iml +.idea +.DS_Store +sauce_connect.log diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..bc5ca639 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "semi": true, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "es5", + "printWidth": 100 +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index aa3b2601..e286c126 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,38 +31,38 @@ ### Contributors to this release -- avatar [Ashvin Tiwari](https://github.com/ashvin2005 "+1752/-4 (#7218 #7218 )") -- avatar [Nikunj Mochi](https://github.com/mochinikunj "+940/-12 (#7294 #7294 )") -- avatar [Anchal Singh](https://github.com/imanchalsingh "+544/-102 (#7169 #7185 )") -- avatar [jasonsaayman](https://github.com/jasonsaayman "+317/-73 (#7334 #7298 )") -- avatar [Julian Dax](https://github.com/brodo "+99/-120 (#5558 )") -- avatar [Akash Dhar Dubey](https://github.com/AKASHDHARDUBEY "+167/-0 (#7287 #7288 )") -- avatar [Madhumita](https://github.com/madhumitaaa "+20/-68 (#7198 )") -- avatar [Tackoil](https://github.com/Tackoil "+80/-2 (#6269 )") -- avatar [Justin Dhillon](https://github.com/justindhillon "+41/-41 (#6324 #6315 )") -- avatar [Rudransh](https://github.com/Rudrxxx "+71/-2 (#7257 )") -- avatar [WuMingDao](https://github.com/WuMingDao "+36/-36 (#7215 )") -- avatar [codenomnom](https://github.com/codenomnom "+70/-0 (#7201 #7201 )") -- avatar [Nandan Acharya](https://github.com/Nandann018-ux "+60/-10 (#7272 )") -- avatar [Eric Dubé](https://github.com/KernelDeimos "+22/-40 (#7042 )") -- avatar [Tibor Pilz](https://github.com/tiborpilz "+40/-4 (#5551 )") -- avatar [Gabriel Quaresma](https://github.com/joaoGabriel55 "+31/-4 (#6314 )") -- avatar [Turadg Aleahmad](https://github.com/turadg "+23/-6 (#6265 )") -- avatar [JohnTitor](https://github.com/kiritosan "+14/-14 (#6155 )") -- avatar [rohit miryala](https://github.com/rohitmiryala "+22/-0 (#7250 )") -- avatar [Wilson Mun](https://github.com/wmundev "+20/-0 (#6053 )") -- avatar [techcodie](https://github.com/techcodie "+7/-7 (#7236 )") -- avatar [Ved Vadnere](https://github.com/Archis009 "+5/-6 (#7283 )") -- avatar [svihpinc](https://github.com/svihpinc "+5/-3 (#6134 )") -- avatar [SANDESH LENDVE](https://github.com/mrsandy1965 "+3/-3 (#7246 )") -- avatar [Lubos](https://github.com/mrlubos "+5/-1 (#7312 )") -- avatar [Jarred Sumner](https://github.com/Jarred-Sumner "+5/-1 (#5754 )") -- avatar [Adam Hines](https://github.com/thebanjomatic "+2/-1 (#5756 )") -- avatar [Subhan Kumar Rai](https://github.com/Subhan030 "+2/-1 (#7256 )") -- avatar [Joseph Frazier](https://github.com/josephfrazier "+1/-1 (#7311 )") -- avatar [KT0803](https://github.com/KT0803 "+0/-2 (#7229 )") -- avatar [Albie](https://github.com/AlbertoSadoc "+1/-1 (#5560 )") -- avatar [Jake Hayes](https://github.com/thejayhaykid "+1/-0 (#5999 )") +- avatar [Ashvin Tiwari](https://github.com/ashvin2005 '+1752/-4 (#7218 #7218 )') +- avatar [Nikunj Mochi](https://github.com/mochinikunj '+940/-12 (#7294 #7294 )') +- avatar [Anchal Singh](https://github.com/imanchalsingh '+544/-102 (#7169 #7185 )') +- avatar [jasonsaayman](https://github.com/jasonsaayman '+317/-73 (#7334 #7298 )') +- avatar [Julian Dax](https://github.com/brodo '+99/-120 (#5558 )') +- avatar [Akash Dhar Dubey](https://github.com/AKASHDHARDUBEY '+167/-0 (#7287 #7288 )') +- avatar [Madhumita](https://github.com/madhumitaaa '+20/-68 (#7198 )') +- avatar [Tackoil](https://github.com/Tackoil '+80/-2 (#6269 )') +- avatar [Justin Dhillon](https://github.com/justindhillon '+41/-41 (#6324 #6315 )') +- avatar [Rudransh](https://github.com/Rudrxxx '+71/-2 (#7257 )') +- avatar [WuMingDao](https://github.com/WuMingDao '+36/-36 (#7215 )') +- avatar [codenomnom](https://github.com/codenomnom '+70/-0 (#7201 #7201 )') +- avatar [Nandan Acharya](https://github.com/Nandann018-ux '+60/-10 (#7272 )') +- avatar [Eric Dubé](https://github.com/KernelDeimos '+22/-40 (#7042 )') +- avatar [Tibor Pilz](https://github.com/tiborpilz '+40/-4 (#5551 )') +- avatar [Gabriel Quaresma](https://github.com/joaoGabriel55 '+31/-4 (#6314 )') +- avatar [Turadg Aleahmad](https://github.com/turadg '+23/-6 (#6265 )') +- avatar [JohnTitor](https://github.com/kiritosan '+14/-14 (#6155 )') +- avatar [rohit miryala](https://github.com/rohitmiryala '+22/-0 (#7250 )') +- avatar [Wilson Mun](https://github.com/wmundev '+20/-0 (#6053 )') +- avatar [techcodie](https://github.com/techcodie '+7/-7 (#7236 )') +- avatar [Ved Vadnere](https://github.com/Archis009 '+5/-6 (#7283 )') +- avatar [svihpinc](https://github.com/svihpinc '+5/-3 (#6134 )') +- avatar [SANDESH LENDVE](https://github.com/mrsandy1965 '+3/-3 (#7246 )') +- avatar [Lubos](https://github.com/mrlubos '+5/-1 (#7312 )') +- avatar [Jarred Sumner](https://github.com/Jarred-Sumner '+5/-1 (#5754 )') +- avatar [Adam Hines](https://github.com/thebanjomatic '+2/-1 (#5756 )') +- avatar [Subhan Kumar Rai](https://github.com/Subhan030 '+2/-1 (#7256 )') +- avatar [Joseph Frazier](https://github.com/josephfrazier '+1/-1 (#7311 )') +- avatar [KT0803](https://github.com/KT0803 '+0/-2 (#7229 )') +- avatar [Albie](https://github.com/AlbertoSadoc '+1/-1 (#5560 )') +- avatar [Jake Hayes](https://github.com/thejayhaykid '+1/-0 (#5999 )') ## [1.13.2](https://github.com/axios/axios/compare/v1.13.1...v1.13.2) (2025-11-04) @@ -77,8 +77,8 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+28/-9 (#7206 #7202 )") -- avatar [Kasper Isager Dalsgarð](https://github.com/kasperisager "+9/-9 (#7196 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+28/-9 (#7206 #7202 )') +- avatar [Kasper Isager Dalsgarð](https://github.com/kasperisager '+9/-9 (#7196 )') ## [1.13.1](https://github.com/axios/axios/compare/v1.13.0...v1.13.1) (2025-10-28) @@ -88,8 +88,8 @@ ### Contributors to this release -- avatar [Anchal Singh](https://github.com/imanchalsingh "+220/-111 (#7173 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+18/-1 (#7193 )") +- avatar [Anchal Singh](https://github.com/imanchalsingh '+220/-111 (#7173 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+18/-1 (#7193 )') # [1.13.0](https://github.com/axios/axios/compare/v1.12.2...v1.13.0) (2025-10-27) @@ -104,23 +104,23 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+794/-180 (#7186 #7150 #7039 )") -- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 "+24/-509 (#7032 )") -- avatar [Aviraj2929](https://github.com/Aviraj2929 "+211/-93 (#7136 #7135 #7134 #7112 )") -- avatar [prasoon patel](https://github.com/Prasoon52 "+167/-6 (#7099 )") -- avatar [Samyak Dandge](https://github.com/Samy-in "+134/-0 (#7171 )") -- avatar [Anchal Singh](https://github.com/imanchalsingh "+53/-56 (#7170 )") -- avatar [Rahul Kumar](https://github.com/jaiyankargupta "+28/-28 (#7073 )") -- avatar [Amit Verma](https://github.com/Amitverma0509 "+24/-13 (#7129 )") -- avatar [Abhishek3880](https://github.com/abhishekmaniy "+23/-4 (#7119 #7117 #7116 #7115 )") -- avatar [Dhvani Maktuporia](https://github.com/Dhvani365 "+14/-5 (#7175 )") -- avatar [Usama Ayoub](https://github.com/sam3690 "+4/-4 (#7133 )") -- avatar [ikuy1203](https://github.com/ikuy1203 "+3/-3 (#7166 )") -- avatar [Nikhil Simon Toppo](https://github.com/Kirito-Excalibur "+1/-1 (#7172 )") -- avatar [Jane Wangari](https://github.com/Wangarijane "+1/-1 (#7155 )") -- avatar [Supakorn Ieamgomol](https://github.com/Supakornn "+1/-1 (#7065 )") -- avatar [Kian-Meng Ang](https://github.com/kianmeng "+1/-1 (#7046 )") -- avatar [UTSUMI Keiji](https://github.com/k-utsumi "+1/-1 (#7037 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+794/-180 (#7186 #7150 #7039 )') +- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 '+24/-509 (#7032 )') +- avatar [Aviraj2929](https://github.com/Aviraj2929 '+211/-93 (#7136 #7135 #7134 #7112 )') +- avatar [prasoon patel](https://github.com/Prasoon52 '+167/-6 (#7099 )') +- avatar [Samyak Dandge](https://github.com/Samy-in '+134/-0 (#7171 )') +- avatar [Anchal Singh](https://github.com/imanchalsingh '+53/-56 (#7170 )') +- avatar [Rahul Kumar](https://github.com/jaiyankargupta '+28/-28 (#7073 )') +- avatar [Amit Verma](https://github.com/Amitverma0509 '+24/-13 (#7129 )') +- avatar [Abhishek3880](https://github.com/abhishekmaniy '+23/-4 (#7119 #7117 #7116 #7115 )') +- avatar [Dhvani Maktuporia](https://github.com/Dhvani365 '+14/-5 (#7175 )') +- avatar [Usama Ayoub](https://github.com/sam3690 '+4/-4 (#7133 )') +- avatar [ikuy1203](https://github.com/ikuy1203 '+3/-3 (#7166 )') +- avatar [Nikhil Simon Toppo](https://github.com/Kirito-Excalibur '+1/-1 (#7172 )') +- avatar [Jane Wangari](https://github.com/Wangarijane '+1/-1 (#7155 )') +- avatar [Supakorn Ieamgomol](https://github.com/Supakornn '+1/-1 (#7065 )') +- avatar [Kian-Meng Ang](https://github.com/kianmeng '+1/-1 (#7046 )') +- avatar [UTSUMI Keiji](https://github.com/k-utsumi '+1/-1 (#7037 )') ## [1.12.2](https://github.com/axios/axios/compare/v1.12.1...v1.12.2) (2025-09-14) @@ -130,8 +130,8 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+247/-16 (#7030 #7022 #7024 )") -- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 "+2/-6 (#7028 #7029 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+247/-16 (#7030 #7022 #7024 )') +- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 '+2/-6 (#7028 #7029 )') ## [1.12.1](https://github.com/axios/axios/compare/v1.12.0...v1.12.1) (2025-09-12) @@ -141,7 +141,7 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+10/-4 (#7020 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+10/-4 (#7020 )') # [1.12.0](https://github.com/axios/axios/compare/v1.11.0...v1.12.0) (2025-09-11) @@ -165,16 +165,16 @@ ### Contributors to this release -- avatar [Willian Agostini](https://github.com/WillianAgostini "+132/-16760 (#7002 #5926 #6782 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+4263/-293 (#7006 #7003 )") -- avatar [khani](https://github.com/mkhani01 "+111/-15 (#6982 )") -- avatar [Ameer Assadi](https://github.com/AmeerAssadi "+123/-0 (#7011 )") -- avatar [Emiedonmokumo Dick-Boro](https://github.com/emiedonmokumo "+55/-35 (#6998 )") -- avatar [Zeroday BYTE](https://github.com/opsysdebug "+8/-8 (#6980 )") -- avatar [Jason Saayman](https://github.com/jasonsaayman "+7/-7 (#6985 #6985 )") -- avatar [최예찬](https://github.com/HealGaren "+5/-7 (#5715 )") -- avatar [Gligor Kotushevski](https://github.com/gligorkot "+3/-1 (#5627 )") -- avatar [Aleksandar Dimitrov](https://github.com/adimit "+2/-1 (#5595 )") +- avatar [Willian Agostini](https://github.com/WillianAgostini '+132/-16760 (#7002 #5926 #6782 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+4263/-293 (#7006 #7003 )') +- avatar [khani](https://github.com/mkhani01 '+111/-15 (#6982 )') +- avatar [Ameer Assadi](https://github.com/AmeerAssadi '+123/-0 (#7011 )') +- avatar [Emiedonmokumo Dick-Boro](https://github.com/emiedonmokumo '+55/-35 (#6998 )') +- avatar [Zeroday BYTE](https://github.com/opsysdebug '+8/-8 (#6980 )') +- avatar [Jason Saayman](https://github.com/jasonsaayman '+7/-7 (#6985 #6985 )') +- avatar [최예찬](https://github.com/HealGaren '+5/-7 (#5715 )') +- avatar [Gligor Kotushevski](https://github.com/gligorkot '+3/-1 (#5627 )') +- avatar [Aleksandar Dimitrov](https://github.com/adimit '+2/-1 (#5595 )') # [1.11.0](https://github.com/axios/axios/compare/v1.10.0...v1.11.0) (2025-07-22) @@ -186,11 +186,11 @@ ### Contributors to this release -- avatar [izzy goldman](https://github.com/izzygld "+186/-93 (#6970 )") -- avatar [Manish Sahani](https://github.com/manishsahanidev "+70/-0 (#6961 )") -- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 "+12/-10 (#6938 #6939 )") -- avatar [James Nail](https://github.com/jrnail23 "+13/-2 (#6956 )") -- avatar [Tejaswi1305](https://github.com/Tejaswi1305 "+1/-1 (#6894 )") +- avatar [izzy goldman](https://github.com/izzygld '+186/-93 (#6970 )') +- avatar [Manish Sahani](https://github.com/manishsahanidev '+70/-0 (#6961 )') +- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 '+12/-10 (#6938 #6939 )') +- avatar [James Nail](https://github.com/jrnail23 '+13/-2 (#6956 )') +- avatar [Tejaswi1305](https://github.com/Tejaswi1305 '+1/-1 (#6894 )') # [1.10.0](https://github.com/axios/axios/compare/v1.9.0...v1.10.0) (2025-06-14) @@ -206,13 +206,13 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+30/-19 (#6933 #6920 #6893 #6892 )") -- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 "+2/-6 (#6922 #6923 )") -- avatar [Dimitrios Lazanas](https://github.com/dimitry-lzs "+4/-0 (#6917 )") -- avatar [Adrian Knapp](https://github.com/AdrianKnapp "+2/-2 (#6867 )") -- avatar [Howie Zhao](https://github.com/howiezhao "+3/-1 (#6872 )") -- avatar [Uhyeon Park](https://github.com/warpdev "+1/-1 (#6883 )") -- avatar [Sampo Silvennoinen](https://github.com/stscoundrel "+1/-1 (#6913 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-19 (#6933 #6920 #6893 #6892 )') +- avatar [Noritaka Kobayashi](https://github.com/noritaka1166 '+2/-6 (#6922 #6923 )') +- avatar [Dimitrios Lazanas](https://github.com/dimitry-lzs '+4/-0 (#6917 )') +- avatar [Adrian Knapp](https://github.com/AdrianKnapp '+2/-2 (#6867 )') +- avatar [Howie Zhao](https://github.com/howiezhao '+3/-1 (#6872 )') +- avatar [Uhyeon Park](https://github.com/warpdev '+1/-1 (#6883 )') +- avatar [Sampo Silvennoinen](https://github.com/stscoundrel '+1/-1 (#6913 )') # [1.9.0](https://github.com/axios/axios/compare/v1.8.4...v1.9.0) (2025-04-24) @@ -232,12 +232,12 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+200/-34 (#6890 #6889 #6888 #6885 #6881 #6767 #6874 #6873 )") -- avatar [Jay](https://github.com/jasonsaayman "+26/-1 ()") -- avatar [Willian Agostini](https://github.com/WillianAgostini "+21/-0 (#5707 )") -- avatar [George Cheng](https://github.com/Gerhut "+3/-3 (#5096 )") -- avatar [FatahChan](https://github.com/FatahChan "+2/-2 (#6855 )") -- avatar [Ionuț G. Stan](https://github.com/igstan "+1/-1 (#6661 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+200/-34 (#6890 #6889 #6888 #6885 #6881 #6767 #6874 #6873 )') +- avatar [Jay](https://github.com/jasonsaayman '+26/-1 ()') +- avatar [Willian Agostini](https://github.com/WillianAgostini '+21/-0 (#5707 )') +- avatar [George Cheng](https://github.com/Gerhut '+3/-3 (#5096 )') +- avatar [FatahChan](https://github.com/FatahChan '+2/-2 (#6855 )') +- avatar [Ionuț G. Stan](https://github.com/igstan '+1/-1 (#6661 )') ## [1.8.4](https://github.com/axios/axios/compare/v1.8.3...v1.8.4) (2025-03-19) @@ -247,7 +247,7 @@ ### Contributors to this release -- avatar [Marc Hassan](https://github.com/mhassan1 "+5/-1 (#6833 )") +- avatar [Marc Hassan](https://github.com/mhassan1 '+5/-1 (#6833 )') ## [1.8.3](https://github.com/axios/axios/compare/v1.8.2...v1.8.3) (2025-03-10) @@ -258,9 +258,9 @@ ### Contributors to this release -- avatar [Ashcon Partovi](https://github.com/Electroid "+6/-0 (#6811 )") -- avatar [StefanBRas](https://github.com/StefanBRas "+4/-0 (#6818 )") -- avatar [Marc Hassan](https://github.com/mhassan1 "+2/-2 (#6814 )") +- avatar [Ashcon Partovi](https://github.com/Electroid '+6/-0 (#6811 )') +- avatar [StefanBRas](https://github.com/StefanBRas '+4/-0 (#6818 )') +- avatar [Marc Hassan](https://github.com/mhassan1 '+2/-2 (#6814 )') ## [1.8.2](https://github.com/axios/axios/compare/v1.8.1...v1.8.2) (2025-03-07) @@ -270,7 +270,7 @@ ### Contributors to this release -- avatar [Fasoro-Joseph Alexander](https://github.com/lexcorp16 "+1/-1 (#6810 )") +- avatar [Fasoro-Joseph Alexander](https://github.com/lexcorp16 '+1/-1 (#6810 )') ## [1.8.1](https://github.com/axios/axios/compare/v1.8.0...v1.8.1) (2025-02-26) @@ -280,7 +280,7 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+51/-47 (#6789 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+51/-47 (#6789 )') # [1.8.0](https://github.com/axios/axios/compare/v1.7.9...v1.8.0) (2025-02-25) @@ -310,23 +310,23 @@ ### Contributors to this release -- avatar [Michael Toscano](https://github.com/GethosTheWalrus "+42/-8 (#6192 )") -- avatar [Willian Agostini](https://github.com/WillianAgostini "+26/-3 (#6788 #6777 )") -- avatar [Naron](https://github.com/naronchen "+27/-0 (#5901 )") -- avatar [shravan || श्रvan](https://github.com/shravan20 "+7/-3 (#6116 )") -- avatar [Justin Dhillon](https://github.com/justindhillon "+0/-7 (#6312 )") -- avatar [yionr](https://github.com/yionr "+5/-1 (#6129 )") -- avatar [Shin'ya Ueoka](https://github.com/ueokande "+3/-3 (#5935 )") -- avatar [Dan Dascalescu](https://github.com/dandv "+3/-3 (#5908 #6757 )") -- avatar [Nitin Ramnani](https://github.com/NitinRamnani "+2/-2 (#5938 )") -- avatar [Shay Molcho](https://github.com/shaymolcho "+2/-2 (#6770 )") -- avatar [Jay](https://github.com/jasonsaayman "+0/-3 (#6732 )") +- avatar [Michael Toscano](https://github.com/GethosTheWalrus '+42/-8 (#6192 )') +- avatar [Willian Agostini](https://github.com/WillianAgostini '+26/-3 (#6788 #6777 )') +- avatar [Naron](https://github.com/naronchen '+27/-0 (#5901 )') +- avatar [shravan || श्रvan](https://github.com/shravan20 '+7/-3 (#6116 )') +- avatar [Justin Dhillon](https://github.com/justindhillon '+0/-7 (#6312 )') +- avatar [yionr](https://github.com/yionr '+5/-1 (#6129 )') +- avatar [Shin'ya Ueoka](https://github.com/ueokande '+3/-3 (#5935 )') +- avatar [Dan Dascalescu](https://github.com/dandv '+3/-3 (#5908 #6757 )') +- avatar [Nitin Ramnani](https://github.com/NitinRamnani '+2/-2 (#5938 )') +- avatar [Shay Molcho](https://github.com/shaymolcho '+2/-2 (#6770 )') +- avatar [Jay](https://github.com/jasonsaayman '+0/-3 (#6732 )') - fancy45daddy -- avatar [Habip Akyol](https://github.com/habipakyol "+1/-1 (#6030 )") -- avatar [Bailey Lissington](https://github.com/llamington "+1/-1 (#6771 )") -- avatar [Bernardo da Eira Duarte](https://github.com/bernardoduarte "+1/-1 (#6480 )") -- avatar [Shivam Batham](https://github.com/Shivam-Batham "+1/-1 (#5949 )") -- avatar [Lipin Kariappa](https://github.com/lipinnnnn "+1/-1 (#5936 )") +- avatar [Habip Akyol](https://github.com/habipakyol '+1/-1 (#6030 )') +- avatar [Bailey Lissington](https://github.com/llamington '+1/-1 (#6771 )') +- avatar [Bernardo da Eira Duarte](https://github.com/bernardoduarte '+1/-1 (#6480 )') +- avatar [Shivam Batham](https://github.com/Shivam-Batham '+1/-1 (#5949 )') +- avatar [Lipin Kariappa](https://github.com/lipinnnnn '+1/-1 (#5936 )') ## [1.7.9](https://github.com/axios/axios/compare/v1.7.8...v1.7.9) (2024-12-04) @@ -336,7 +336,7 @@ ### Contributors to this release -- avatar [Jay](https://github.com/jasonsaayman "+596/-108 (#6729 )") +- avatar [Jay](https://github.com/jasonsaayman '+596/-108 (#6729 )') ## [1.7.8](https://github.com/axios/axios/compare/v1.7.7...v1.7.8) (2024-11-25) @@ -356,24 +356,24 @@ ### Contributors to this release -- avatar [Remco Haszing](https://github.com/remcohaszing "+108/-596 (#6218 )") -- avatar [Jay](https://github.com/jasonsaayman "+281/-19 (#6640 #6619 )") -- avatar [Aayush Yadav](https://github.com/aayushyadav020 "+124/-111 (#6617 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+12/-65 (#6714 )") -- avatar [Ell Bradshaw](https://github.com/cincodenada "+29/-0 (#6489 )") -- avatar [Amit Saini](https://github.com/amitsainii "+13/-3 (#5237 )") -- avatar [Tommaso Paulon](https://github.com/guuido "+14/-1 (#6680 )") -- avatar [Akki](https://github.com/Aakash-Rana "+5/-5 (#6668 )") -- avatar [Sampo Silvennoinen](https://github.com/stscoundrel "+3/-3 (#6633 )") -- avatar [Kasper Isager Dalsgarð](https://github.com/kasperisager "+2/-2 (#6634 )") -- avatar [Christian Clauss](https://github.com/cclauss "+4/-0 (#6683 )") -- avatar [Pavan Welihinda](https://github.com/pavan168 "+2/-2 (#5222 )") -- avatar [Taylor Flatt](https://github.com/taylorflatt "+2/-2 (#6615 )") -- avatar [Kenzo Wada](https://github.com/Kenzo-Wada "+2/-2 (#6608 )") -- avatar [Ngole Lawson](https://github.com/echelonnought "+3/-0 (#6644 )") -- avatar [Haven](https://github.com/Baoyx007 "+3/-0 (#6590 )") -- avatar [Shrivali Dutt](https://github.com/shrivalidutt "+1/-1 (#6637 )") -- avatar [Henco Appel](https://github.com/hencoappel "+1/-1 (#6605 )") +- avatar [Remco Haszing](https://github.com/remcohaszing '+108/-596 (#6218 )') +- avatar [Jay](https://github.com/jasonsaayman '+281/-19 (#6640 #6619 )') +- avatar [Aayush Yadav](https://github.com/aayushyadav020 '+124/-111 (#6617 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+12/-65 (#6714 )') +- avatar [Ell Bradshaw](https://github.com/cincodenada '+29/-0 (#6489 )') +- avatar [Amit Saini](https://github.com/amitsainii '+13/-3 (#5237 )') +- avatar [Tommaso Paulon](https://github.com/guuido '+14/-1 (#6680 )') +- avatar [Akki](https://github.com/Aakash-Rana '+5/-5 (#6668 )') +- avatar [Sampo Silvennoinen](https://github.com/stscoundrel '+3/-3 (#6633 )') +- avatar [Kasper Isager Dalsgarð](https://github.com/kasperisager '+2/-2 (#6634 )') +- avatar [Christian Clauss](https://github.com/cclauss '+4/-0 (#6683 )') +- avatar [Pavan Welihinda](https://github.com/pavan168 '+2/-2 (#5222 )') +- avatar [Taylor Flatt](https://github.com/taylorflatt '+2/-2 (#6615 )') +- avatar [Kenzo Wada](https://github.com/Kenzo-Wada '+2/-2 (#6608 )') +- avatar [Ngole Lawson](https://github.com/echelonnought '+3/-0 (#6644 )') +- avatar [Haven](https://github.com/Baoyx007 '+3/-0 (#6590 )') +- avatar [Shrivali Dutt](https://github.com/shrivalidutt '+1/-1 (#6637 )') +- avatar [Henco Appel](https://github.com/hencoappel '+1/-1 (#6605 )') ## [1.7.7](https://github.com/axios/axios/compare/v1.7.6...v1.7.7) (2024-08-31) @@ -384,8 +384,8 @@ ### Contributors to this release -- avatar [Rishi556](https://github.com/Rishi556 "+39/-1 (#5731 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+27/-7 (#6584 )") +- avatar [Rishi556](https://github.com/Rishi556 '+39/-1 (#5731 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+27/-7 (#6584 )') ## [1.7.6](https://github.com/axios/axios/compare/v1.7.5...v1.7.6) (2024-08-30) @@ -396,9 +396,9 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+98/-46 (#6582 )") -- avatar [Jacques Germishuys](https://github.com/jacquesg "+5/-1 (#6524 )") -- avatar [kuroino721](https://github.com/kuroino721 "+3/-1 (#6575 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+98/-46 (#6582 )') +- avatar [Jacques Germishuys](https://github.com/jacquesg '+5/-1 (#6524 )') +- avatar [kuroino721](https://github.com/kuroino721 '+3/-1 (#6575 )') ## [1.7.5](https://github.com/axios/axios/compare/v1.7.4...v1.7.5) (2024-08-23) @@ -411,9 +411,9 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+187/-83 (#6573 #6567 #6566 #6564 #6563 #6557 #6556 #6555 #6554 #6552 )") -- avatar [Antonin Bas](https://github.com/antoninbas "+6/-6 (#6572 )") -- avatar [Hans Otto Wirtz](https://github.com/hansottowirtz "+4/-1 (#6533 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+187/-83 (#6573 #6567 #6566 #6564 #6563 #6557 #6556 #6555 #6554 #6552 )') +- avatar [Antonin Bas](https://github.com/antoninbas '+6/-6 (#6572 )') +- avatar [Hans Otto Wirtz](https://github.com/hansottowirtz '+4/-1 (#6533 )') ## [1.7.4](https://github.com/axios/axios/compare/v1.7.3...v1.7.4) (2024-08-13) @@ -424,8 +424,8 @@ ### Contributors to this release -- avatar [Lev Pachmanov](https://github.com/levpachmanov "+47/-11 (#6543 )") -- avatar [Đỗ Trọng Hải](https://github.com/hainenber "+49/-4 (#6539 )") +- avatar [Lev Pachmanov](https://github.com/levpachmanov '+47/-11 (#6543 )') +- avatar [Đỗ Trọng Hải](https://github.com/hainenber '+49/-4 (#6539 )') ## [1.7.3](https://github.com/axios/axios/compare/v1.7.2...v1.7.3) (2024-08-01) @@ -437,9 +437,9 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+211/-159 (#6518 #6519 )") -- avatar [Valerii Sidorenko](https://github.com/ValeraS "+3/-3 (#6515 )") -- avatar [prianYu](https://github.com/prianyu "+2/-2 (#6505 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+211/-159 (#6518 #6519 )') +- avatar [Valerii Sidorenko](https://github.com/ValeraS '+3/-3 (#6515 )') +- avatar [prianYu](https://github.com/prianyu '+2/-2 (#6505 )') ## [1.7.2](https://github.com/axios/axios/compare/v1.7.1...v1.7.2) (2024-05-21) @@ -449,7 +449,7 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+3/-3 (#6413 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+3/-3 (#6413 )') ## [1.7.1](https://github.com/axios/axios/compare/v1.7.0...v1.7.1) (2024-05-20) @@ -459,7 +459,7 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+14/-9 (#6410 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+14/-9 (#6410 )') # [1.7.0](https://github.com/axios/axios/compare/v1.7.0-beta.2...v1.7.0) (2024-05-19) @@ -473,9 +473,9 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+1015/-127 (#6371 )") -- avatar [Jay](https://github.com/jasonsaayman "+30/-14 ()") -- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux "+56/-6 (#6362 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+1015/-127 (#6371 )') +- avatar [Jay](https://github.com/jasonsaayman '+30/-14 ()') +- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux '+56/-6 (#6362 )') # [1.7.0-beta.2](https://github.com/axios/axios/compare/v1.7.0-beta.1...v1.7.0-beta.2) (2024-05-19) @@ -487,7 +487,7 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+99/-46 (#6405 #6404 #6401 #6400 #6395 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+99/-46 (#6405 #6404 #6401 #6400 #6395 )') # [1.7.0-beta.1](https://github.com/axios/axios/compare/v1.7.0-beta.0...v1.7.0-beta.1) (2024-05-07) @@ -499,8 +499,8 @@ ### Contributors to this release -- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux "+56/-6 (#6362 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+42/-17 (#6380 #6377 )") +- avatar [Alexandre ABRIOUX](https://github.com/alexandre-abrioux '+56/-6 (#6362 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+42/-17 (#6380 #6377 )') # [1.7.0-beta.0](https://github.com/axios/axios/compare/v1.6.8...v1.7.0-beta.0) (2024-04-28) @@ -510,8 +510,8 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+1015/-127 (#6371 )") -- avatar [Jay](https://github.com/jasonsaayman "+30/-14 ()") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+1015/-127 (#6371 )') +- avatar [Jay](https://github.com/jasonsaayman '+30/-14 ()') ## [1.6.8](https://github.com/axios/axios/compare/v1.6.7...v1.6.8) (2024-03-15) @@ -523,13 +523,13 @@ ### Contributors to this release -- avatar [Jay](https://github.com/jasonsaayman "+4572/-3446 (#6238 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+30/-0 (#6231 )") -- avatar [Mitchell](https://github.com/Creaous "+9/-9 (#6300 )") -- avatar [Emmanuel](https://github.com/mannoeu "+2/-2 (#6196 )") -- avatar [Lucas Keller](https://github.com/ljkeller "+3/-0 (#6194 )") -- avatar [Aditya Mogili](https://github.com/ADITYA-176 "+1/-1 ()") -- avatar [Miroslav Petrov](https://github.com/petrovmiroslav "+1/-1 (#6243 )") +- avatar [Jay](https://github.com/jasonsaayman '+4572/-3446 (#6238 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-0 (#6231 )') +- avatar [Mitchell](https://github.com/Creaous '+9/-9 (#6300 )') +- avatar [Emmanuel](https://github.com/mannoeu '+2/-2 (#6196 )') +- avatar [Lucas Keller](https://github.com/ljkeller '+3/-0 (#6194 )') +- avatar [Aditya Mogili](https://github.com/ADITYA-176 '+1/-1 ()') +- avatar [Miroslav Petrov](https://github.com/petrovmiroslav '+1/-1 (#6243 )') ## [1.6.7](https://github.com/axios/axios/compare/v1.6.6...v1.6.7) (2024-01-25) @@ -539,8 +539,8 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+30/-26 (#6203 )") -- avatar [zhoulixiang](https://github.com/zh-lx "+0/-3 (#6186 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-26 (#6203 )') +- avatar [zhoulixiang](https://github.com/zh-lx '+0/-3 (#6186 )') ## [1.6.6](https://github.com/axios/axios/compare/v1.6.5...v1.6.6) (2024-01-24) @@ -551,8 +551,8 @@ ### Contributors to this release -- avatar [Ilya Priven](https://github.com/ikonst "+91/-8 (#5987 )") -- avatar [Zao Soula](https://github.com/zaosoula "+6/-6 (#5778 )") +- avatar [Ilya Priven](https://github.com/ikonst '+91/-8 (#5987 )') +- avatar [Zao Soula](https://github.com/zaosoula '+6/-6 (#5778 )') ## [1.6.5](https://github.com/axios/axios/compare/v1.6.4...v1.6.5) (2024-01-05) @@ -563,8 +563,8 @@ ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+41/-6 (#6176 #6175 )") -- avatar [Jay](https://github.com/jasonsaayman "+6/-1 ()") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+41/-6 (#6176 #6175 )') +- avatar [Jay](https://github.com/jasonsaayman '+6/-1 ()') ## [1.6.4](https://github.com/axios/axios/compare/v1.6.3...v1.6.4) (2024-01-03) @@ -575,9 +575,9 @@ ### Contributors to this release -- avatar [Jay](https://github.com/jasonsaayman "+34/-6 ()") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+34/-3 (#6172 #6167 )") -- avatar [Guy Nesher](https://github.com/gnesher "+10/-10 (#6163 )") +- avatar [Jay](https://github.com/jasonsaayman '+34/-6 ()') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+34/-3 (#6172 #6167 )') +- avatar [Guy Nesher](https://github.com/gnesher '+10/-10 (#6163 )') ## [1.6.3](https://github.com/axios/axios/compare/v1.6.2...v1.6.3) (2023-12-26) @@ -587,9 +587,9 @@ ### Contributors to this release -- avatar [Jay](https://github.com/jasonsaayman "+15/-6 (#6145 )") -- avatar [Willian Agostini](https://github.com/WillianAgostini "+17/-2 (#6132 )") -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+3/-0 (#6084 )") +- avatar [Jay](https://github.com/jasonsaayman '+15/-6 (#6145 )') +- avatar [Willian Agostini](https://github.com/WillianAgostini '+17/-2 (#6132 )') +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+3/-0 (#6084 )') ## [1.6.2](https://github.com/axios/axios/compare/v1.6.1...v1.6.2) (2023-11-14) @@ -610,9 +610,9 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+271/-146 (#6081 #6080 #6079 #6078 #6046 #6064 #6063 )") -- avatar [Ng Choon Khon (CK)](https://github.com/ckng0221 "+4/-4 (#6073 )") -- avatar [Muhammad Noman](https://github.com/mnomanmemon "+2/-2 (#6048 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+271/-146 (#6081 #6080 #6079 #6078 #6046 #6064 #6063 )') +- avatar [Ng Choon Khon (CK)](https://github.com/ckng0221 '+4/-4 (#6073 )') +- avatar [Muhammad Noman](https://github.com/mnomanmemon '+2/-2 (#6048 )') ## [1.6.1](https://github.com/axios/axios/compare/v1.6.0...v1.6.1) (2023-11-08) @@ -623,8 +623,8 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+432/-65 (#6059 #6056 #6055 )") -- avatar [Fabian Meyer](https://github.com/meyfa "+5/-2 (#5835 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+432/-65 (#6059 #6056 #6055 )') +- avatar [Fabian Meyer](https://github.com/meyfa '+5/-2 (#5835 )') ### PRs @@ -656,9 +656,9 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+449/-114 (#6032 #6021 #6011 #5932 #5931 )") -- avatar [Valentin Panov](https://github.com/valentin-panov "+4/-4 (#6028 )") -- avatar [Rinku Chaudhari](https://github.com/therealrinku "+1/-1 (#5889 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+449/-114 (#6032 #6021 #6011 #5932 #5931 )') +- avatar [Valentin Panov](https://github.com/valentin-panov '+4/-4 (#6028 )') +- avatar [Rinku Chaudhari](https://github.com/therealrinku '+1/-1 (#5889 )') ## [1.5.1](https://github.com/axios/axios/compare/v1.5.0...v1.5.1) (2023-09-26) @@ -671,12 +671,12 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+89/-18 (#5919 #5917 )") -- avatar [David Dallas](https://github.com/DavidJDallas "+11/-5 ()") -- avatar [Sean Sattler](https://github.com/fb-sean "+2/-8 ()") -- avatar [Mustafa Ateş Uzun](https://github.com/0o001 "+4/-4 ()") -- avatar [Przemyslaw Motacki](https://github.com/sfc-gh-pmotacki "+2/-1 (#5892 )") -- avatar [Michael Di Prisco](https://github.com/Cadienvan "+1/-1 ()") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+89/-18 (#5919 #5917 )') +- avatar [David Dallas](https://github.com/DavidJDallas '+11/-5 ()') +- avatar [Sean Sattler](https://github.com/fb-sean '+2/-8 ()') +- avatar [Mustafa Ateş Uzun](https://github.com/0o001 '+4/-4 ()') +- avatar [Przemyslaw Motacki](https://github.com/sfc-gh-pmotacki '+2/-1 (#5892 )') +- avatar [Michael Di Prisco](https://github.com/Cadienvan '+1/-1 ()') ### PRs @@ -703,10 +703,10 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+66/-29 (#5839 #5837 #5836 #5832 #5831 )") -- avatar [夜葬](https://github.com/geekact "+42/-0 (#5324 )") -- avatar [Jonathan Budiman](https://github.com/JBudiman00 "+30/-0 (#5788 )") -- avatar [Michael Di Prisco](https://github.com/Cadienvan "+3/-5 (#5791 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+66/-29 (#5839 #5837 #5836 #5832 #5831 )') +- avatar [夜葬](https://github.com/geekact '+42/-0 (#5324 )') +- avatar [Jonathan Budiman](https://github.com/JBudiman00 '+30/-0 (#5788 )') +- avatar [Michael Di Prisco](https://github.com/Cadienvan '+3/-5 (#5791 )') ### PRs @@ -735,9 +735,9 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+151/-16 (#5684 #5339 #5679 #5678 #5677 )") -- avatar [Arthur Fiorette](https://github.com/arthurfiorette "+19/-19 (#5525 )") -- avatar [PIYUSH NEGI](https://github.com/npiyush97 "+2/-18 (#5670 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+151/-16 (#5684 #5339 #5679 #5678 #5677 )') +- avatar [Arthur Fiorette](https://github.com/arthurfiorette '+19/-19 (#5525 )') +- avatar [PIYUSH NEGI](https://github.com/npiyush97 '+2/-18 (#5670 )') ### PRs @@ -757,8 +757,8 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+48/-10 (#5665 #5661 #5663 )") -- avatar [Michael Di Prisco](https://github.com/Cadienvan "+2/-0 (#5445 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+48/-10 (#5665 #5661 #5663 )') +- avatar [Michael Di Prisco](https://github.com/Cadienvan '+2/-0 (#5445 )') ### PRs @@ -778,7 +778,7 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+28/-10 (#5633 #5584 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+28/-10 (#5633 #5584 )') ### PRs @@ -798,9 +798,9 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+38/-26 (#5564 )") -- avatar [lcysgsg](https://github.com/lcysgsg "+4/-0 (#5548 )") -- avatar [Michael Di Prisco](https://github.com/Cadienvan "+3/-0 (#5444 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+38/-26 (#5564 )') +- avatar [lcysgsg](https://github.com/lcysgsg '+4/-0 (#5548 )') +- avatar [Michael Di Prisco](https://github.com/Cadienvan '+3/-0 (#5444 )') ### PRs @@ -821,8 +821,8 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+11/-7 (#5545 #5535 #5542 )") -- avatar [陈若枫](https://github.com/ruofee "+2/-2 (#5467 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+11/-7 (#5545 #5535 #5542 )') +- avatar [陈若枫](https://github.com/ruofee '+2/-2 (#5467 )') ### PRs @@ -842,7 +842,7 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+2/-1 (#5530 #5528 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+2/-1 (#5530 #5528 )') ### PRs @@ -862,7 +862,7 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+27/-8 (#5521 #5518 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+27/-8 (#5521 #5518 )') ### PRs @@ -886,8 +886,8 @@ This functionality is considered as a fix. ### Contributors to this release -- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+352/-67 (#5514 #5512 #5510 #5509 #5508 #5316 #5507 )") -- avatar [ItsNotGoodName](https://github.com/ItsNotGoodName "+43/-2 (#5497 )") +- avatar [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+352/-67 (#5514 #5512 #5510 #5509 #5508 #5316 #5507 )') +- avatar [ItsNotGoodName](https://github.com/ItsNotGoodName '+43/-2 (#5497 )') ### PRs @@ -907,7 +907,7 @@ This functionality is considered as a fix. ### Contributors to this release -- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+24/-9 (#5503 #5502 )") +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+24/-9 (#5503 #5502 )') ### PRs @@ -926,8 +926,8 @@ This functionality is considered as a fix. ### Contributors to this release -- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+82/-54 (#5499 )") -- ![avatar](https://avatars.githubusercontent.com/u/20516159?v=4&s=16) [Elliot Ford](https://github.com/EFord36 "+1/-1 (#5462 )") +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+82/-54 (#5499 )') +- ![avatar](https://avatars.githubusercontent.com/u/20516159?v=4&s=16) [Elliot Ford](https://github.com/EFord36 '+1/-1 (#5462 )') ### PRs @@ -947,8 +947,8 @@ This functionality is considered as a fix. ### Contributors to this release -- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+242/-108 (#5486 #5482 )") -- ![avatar](https://avatars.githubusercontent.com/u/9430821?v=4&s=16) [Daniel Hillmann](https://github.com/hilleer "+1/-1 (#5478 )") +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+242/-108 (#5486 #5482 )') +- ![avatar](https://avatars.githubusercontent.com/u/9430821?v=4&s=16) [Daniel Hillmann](https://github.com/hilleer '+1/-1 (#5478 )') ### PRs @@ -967,7 +967,7 @@ This functionality is considered as a fix. ### Contributors to this release -- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS "+938/-442 (#5456 #5455 #5453 #5451 #5449 #5447 #5446 #5443 #5442 #5439 #5420 )") +- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+938/-442 (#5456 #5455 #5453 #5451 #5449 #5447 #5446 #5443 #5442 #5439 #5420 )') ### PRs diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index c59f6384..b4d9e03f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,7 +5,7 @@ Thank you to all the wonderful people who have contributed to axios! ## Core Team - [Jay](https://github.com/jasonsaayman) - Lead Maintainer -- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) - Core Contributor +- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS) - Core Contributor - [Matt Zabriskie](https://github.com/mzabriskie) - Creator ## Notable Contributors @@ -18,4 +18,4 @@ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) f --- -*This list is manually maintained. If you've contributed and would like to be added, please submit a pull request!* \ No newline at end of file +_This list is manually maintained. If you've contributed and would like to be added, please submit a pull request!_ diff --git a/bin/GithubAPI.js b/bin/GithubAPI.js index 296f7f6d..deb02533 100644 --- a/bin/GithubAPI.js +++ b/bin/GithubAPI.js @@ -1,7 +1,7 @@ -import util from "util"; -import cp from "child_process"; -import {parseVersion} from "./helpers/parser.js"; -import githubAxios from "./githubAxios.js"; +import util from 'util'; +import cp from 'child_process'; +import { parseVersion } from './helpers/parser.js'; +import githubAxios from './githubAxios.js'; import memoize from 'memoizee'; const exec = util.promisify(cp.exec); @@ -20,15 +20,19 @@ export default class GithubAPI { this.owner = owner; this.axios = githubAxios.create({ baseURL: `https://api.github.com/repos/${this.owner}/${this.repo}/`, - }) + }); } async createComment(issue, body) { - return (await this.axios.post(`/issues/${issue}/comments`, {body})).data; + return (await this.axios.post(`/issues/${issue}/comments`, { body })).data; } - async getComments(issue, {desc = false, per_page= 100, page = 1} = {}) { - return (await this.axios.get(`/issues/${issue}/comments`, {params: {direction: desc ? 'desc' : 'asc', per_page, page}})).data; + async getComments(issue, { desc = false, per_page = 100, page = 1 } = {}) { + return ( + await this.axios.get(`/issues/${issue}/comments`, { + params: { direction: desc ? 'desc' : 'asc', per_page, page }, + }) + ).data; } async getComment(id) { @@ -36,11 +40,11 @@ export default class GithubAPI { } async updateComment(id, body) { - return (await this.axios.patch(`/issues/comments/${id}`, {body})).data; + return (await this.axios.patch(`/issues/comments/${id}`, { body })).data; } async appendLabels(issue, labels) { - return (await this.axios.post(`/issues/${issue}/labels`, {labels})).data; + return (await this.axios.post(`/issues/${issue}/labels`, { labels })).data; } async getUser(user) { @@ -51,7 +55,7 @@ export default class GithubAPI { try { return (await this.axios.get(`/collaborators/${user}`)).status === 204; } catch (e) { - + // Do nothing } } @@ -67,8 +71,19 @@ export default class GithubAPI { return (await this.axios.get(`/pulls/${issue}`)).data; } - async getIssues({state= 'open', labels, sort = 'created', desc = false, per_page = 100, page = 1}) { - return (await this.axios.get(`/issues`, {params: {state, labels, sort, direction: desc ? 'desc' : 'asc', per_page, page}})).data; + async getIssues({ + state = 'open', + labels, + sort = 'created', + desc = false, + per_page = 100, + page = 1, + }) { + return ( + await this.axios.get(`/issues`, { + params: { state, labels, sort, direction: desc ? 'desc' : 'asc', per_page, page }, + }) + ).data; } async updateIssue(issue, data) { @@ -77,55 +92,66 @@ export default class GithubAPI { async closeIssue(issue) { return this.updateIssue(issue, { - state: "closed" - }) + state: 'closed', + }); } - async getReleases({per_page = 30, page= 1} = {}) { - return (await this.axios.get(`/releases`, {params: {per_page, page}})).data; + async getReleases({ per_page = 30, page = 1 } = {}) { + return (await this.axios.get(`/releases`, { params: { per_page, page } })).data; } async getRelease(release = 'latest') { - return (await this.axios.get(parseVersion(release) ? `/releases/tags/${release}` : `/releases/${release}`)).data; + return ( + await this.axios.get( + parseVersion(release) ? `/releases/tags/${release}` : `/releases/${release}` + ) + ).data; } - async getTags({per_page = 30, page= 1} = {}) { - return (await this.axios.get(`/tags`, {params: {per_page, page}})).data; + async getTags({ per_page = 30, page = 1 } = {}) { + return (await this.axios.get(`/tags`, { params: { per_page, page } })).data; } async reopenIssue(issue) { return this.updateIssue(issue, { - state: "open" - }) + state: 'open', + }); } static async getTagRef(tag) { try { return (await exec(`git show-ref --tags "refs/tags/${tag}"`)).stdout.split(' ')[0]; } catch (e) { + // Do nothing } } static async getLatestTag() { - try{ - const {stdout} = await exec(`git for-each-ref refs/tags --sort=-taggerdate --format='%(refname)' --count=1`); + try { + const { stdout } = await exec( + `git for-each-ref refs/tags --sort=-taggerdate --format='%(refname)' --count=1` + ); return stdout.split('/').pop(); - } catch (e) {} + } catch (e) { + // Do nothing + } } - static normalizeTag(tag){ + static normalizeTag(tag) { return tag ? 'v' + tag.replace(/^v/, '') : ''; } } -const {prototype} = GithubAPI; +const { prototype } = GithubAPI; -['getUser', 'isCollaborator'].forEach(methodName => { - prototype[methodName] = memoize(prototype[methodName], { promise: true }) -}); - -['get', 'post', 'put', 'delete', 'isAxiosError'].forEach((method) => prototype[method] = function(...args){ - return this.axios[method](...args); +['getUser', 'isCollaborator'].forEach((methodName) => { + prototype[methodName] = memoize(prototype[methodName], { promise: true }); }); +['get', 'post', 'put', 'delete', 'isAxiosError'].forEach( + (method) => + (prototype[method] = function (...args) { + return this.axios[method](...args); + }) +); diff --git a/bin/RepoBot.js b/bin/RepoBot.js index e56dcdfa..7edb946b 100644 --- a/bin/RepoBot.js +++ b/bin/RepoBot.js @@ -1,17 +1,17 @@ -import GithubAPI from "./GithubAPI.js"; +import GithubAPI from './GithubAPI.js'; import api from './api.js'; -import Handlebars from "handlebars"; -import fs from "fs/promises"; -import {colorize} from "./helpers/colorize.js"; -import {getReleaseInfo} from "./contributors.js"; -import path from "path"; -import {fileURLToPath} from "url"; +import Handlebars from 'handlebars'; +import fs from 'fs/promises'; +import { colorize } from './helpers/colorize.js'; +import { getReleaseInfo } from './contributors.js'; +import path from 'path'; +import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const NOTIFY_PR_TEMPLATE = path.resolve(__dirname, '../templates/pr_published.hbs'); -const normalizeTag = (tag) => tag ? 'v' + tag.replace(/^v/, '') : ''; +const normalizeTag = (tag) => (tag ? 'v' + tag.replace(/^v/, '') : ''); const GITHUB_BOT_LOGIN = 'github-actions[bot]'; @@ -19,14 +19,11 @@ const skipCollaboratorPRs = true; class RepoBot { constructor(options) { - const { - owner, repo, - templates - } = options || {}; + const { owner, repo, templates } = options || {}; this.templates = { published: NOTIFY_PR_TEMPLATE, - ...templates + ...templates, }; this.github = api || new GithubAPI(owner, repo); @@ -45,7 +42,7 @@ class RepoBot { try { pr = await this.github.getPR(id); } catch (err) { - if(err.response?.status === 404) { + if (err.response?.status === 404) { throw new Error(`PR #${id} not found (404)`); } @@ -54,25 +51,33 @@ class RepoBot { tag = normalizeTag(tag); - const {merged, labels, user: {login, type}} = pr; + const { + merged, + labels, + user: { login, type }, + } = pr; const isBot = type === 'Bot'; if (!merged) { - return false + return false; } await this.github.appendLabels(id, [tag]); - if (isBot || labels.find(({name}) => name === 'automated pr') || (skipCollaboratorPRs && await this.github.isCollaborator(login))) { + if ( + isBot || + labels.find(({ name }) => name === 'automated pr') || + (skipCollaboratorPRs && (await this.github.isCollaborator(login))) + ) { return false; } - const comments = await this.github.getComments(id, {desc: true}); + const comments = await this.github.getComments(id, { desc: true }); const comment = comments.find( - ({body, user}) => user.login === GITHUB_BOT_LOGIN && body.indexOf('published in') >= 0 - ) + ({ body, user }) => user.login === GITHUB_BOT_LOGIN && body.indexOf('published in') >= 0 + ); if (comment) { console.log(colorize()`Release comment [${comment.html_url}] already exists in #${pr.id}`); @@ -88,8 +93,8 @@ class RepoBot { author, release: { tag, - url: `https://github.com/${this.owner}/${this.repo}/releases/tag/${tag}` - } + url: `https://github.com/${this.owner}/${this.repo}/releases/tag/${tag}`, + }, }); return await this.addComment(id, message); @@ -104,7 +109,7 @@ class RepoBot { throw Error(colorize()`Can't get release info for ${tag}`); } - const {merges} = release; + const { merges } = release; console.log(colorize()`Found ${merges.length} PRs in ${tag}:`); @@ -112,7 +117,7 @@ class RepoBot { for (const pr of merges) { try { - console.log(colorize()`${i++}) Notify PR #${pr.id}`) + console.log(colorize()`${i++}) Notify PR #${pr.id}`); const result = await this.notifyPRPublished(pr.id, tag); console.log('✔️', result ? 'Label, comment' : 'Label'); } catch (err) { diff --git a/bin/actions/notify_published.js b/bin/actions/notify_published.js index 22a50d94..8e8ec8aa 100644 --- a/bin/actions/notify_published.js +++ b/bin/actions/notify_published.js @@ -1,4 +1,4 @@ -import minimist from "minimist"; +import minimist from 'minimist'; import RepoBot from '../RepoBot.js'; import fs from 'fs/promises'; @@ -13,7 +13,6 @@ let { tag } = argv; tag = 'v' + version; } else if (typeof tag !== 'string') { - throw new Error('tag must be a string'); } @@ -25,4 +24,3 @@ let { tag } = argv; console.warn('Error:', err.message); } })(); - diff --git a/bin/api.js b/bin/api.js index 5d9ab5b5..708e5bfb 100644 --- a/bin/api.js +++ b/bin/api.js @@ -1,3 +1,3 @@ -import GithubAPI from "./GithubAPI.js"; +import GithubAPI from './GithubAPI.js'; export default new GithubAPI('axios', 'axios'); diff --git a/bin/check-build-version.js b/bin/check-build-version.js index e1d5b607..ce0111f0 100644 --- a/bin/check-build-version.js +++ b/bin/check-build-version.js @@ -3,9 +3,9 @@ import assert from 'assert'; import axios from '../index.js'; import axiosBuild from '../dist/node/axios.cjs'; -const {version} = JSON.parse(fs.readFileSync('./package.json')); +const { version } = JSON.parse(fs.readFileSync('./package.json')); -console.log('Checking versions...\n----------------------------') +console.log('Checking versions...\n----------------------------'); console.log(`Package version: v${version}`); console.log(`Axios version: v${axios.VERSION}`); @@ -25,5 +25,3 @@ assert.strictEqual( ); console.log('✔️ PASSED\n'); - - diff --git a/bin/contributors.js b/bin/contributors.js index 12dc2499..1e6685b9 100644 --- a/bin/contributors.js +++ b/bin/contributors.js @@ -1,9 +1,9 @@ -import axios from "./githubAxios.js"; -import util from "util"; -import cp from "child_process"; -import Handlebars from "handlebars"; -import fs from "fs/promises"; -import {colorize} from "./helpers/colorize.js"; +import axios from './githubAxios.js'; +import util from 'util'; +import cp from 'child_process'; +import Handlebars from 'handlebars'; +import fs from 'fs/promises'; +import { colorize } from './helpers/colorize.js'; const exec = util.promisify(cp.exec); @@ -11,48 +11,49 @@ const ONE_MB = 1024 * 1024; const removeExtraLineBreaks = (str) => str.replace(/(?:\r\n|\r|\n){3,}/gm, '\r\n\r\n'); -const cleanTemplate = template => template - .replace(/\n +/g, '\n') - .replace(/^ +/, '') - .replace(/\n\n\n+/g, '\n\n') - .replace(/\n\n$/, '\n'); +const cleanTemplate = (template) => + template + .replace(/\n +/g, '\n') + .replace(/^ +/, '') + .replace(/\n\n\n+/g, '\n\n') + .replace(/\n\n$/, '\n'); const getUserFromCommit = ((commitCache) => async (sha) => { try { - if(commitCache[sha] !== undefined) { + if (commitCache[sha] !== undefined) { return commitCache[sha]; } console.log(colorize()`fetch github commit info (${sha})`); - const {data} = await axios.get(`https://api.github.com/repos/axios/axios/commits/${sha}`); + const { data } = await axios.get(`https://api.github.com/repos/axios/axios/commits/${sha}`); - return commitCache[sha] = { + return (commitCache[sha] = { ...data.commit.author, ...data.author, avatar_url_sm: data.author.avatar_url ? data.author.avatar_url + '&s=18' : '', - }; + }); } catch (err) { - return commitCache[sha] = null; + return (commitCache[sha] = null); } })({}); const getIssueById = ((cache) => async (id) => { - if(cache[id] !== undefined) { + if (cache[id] !== undefined) { return cache[id]; } try { - const {data} = await axios.get(`https://api.github.com/repos/axios/axios/issues/${id}`); + const { data } = await axios.get(`https://api.github.com/repos/axios/axios/issues/${id}`); - return cache[id] = data; + return (cache[id] = data); } catch (err) { return null; } })({}); const getUserInfo = ((userCache) => async (userEntry) => { - const {email, commits} = userEntry; + const { email, commits } = userEntry; if (userCache[email] !== undefined) { return userCache[email]; @@ -60,32 +61,32 @@ const getUserInfo = ((userCache) => async (userEntry) => { console.log(colorize()`fetch github user info [${userEntry.name}]`); - return userCache[email] = { + return (userCache[email] = { ...userEntry, - ...await getUserFromCommit(commits[0].hash) - } + ...(await getUserFromCommit(commits[0].hash)), + }); })({}); const deduplicate = (authors) => { const loginsMap = {}; - const combined= {}; + const combined = {}; const assign = (a, b) => { - const {insertions, deletions, points, ...rest} = b; + const { insertions, _deletions, _points, ...rest } = b; Object.assign(a, rest); a.insertions += insertions; a.deletions += insertions; a.insertions += insertions; - } + }; - for(const [email, user] of Object.entries(authors)) { - const {login} = user; + for (const [email, user] of Object.entries(authors)) { + const { login } = user; let entry; - if(login && (entry = loginsMap[login])) { - assign(entry, user); + if (login && (entry = loginsMap[login])) { + assign(entry, user); } else { login && (loginsMap[login] = user); combined[email] = user; @@ -93,10 +94,10 @@ const deduplicate = (authors) => { } return combined; -} +}; const getReleaseInfo = ((releaseCache) => async (tag) => { - if(releaseCache[tag] !== undefined) { + if (releaseCache[tag] !== undefined) { return releaseCache[tag]; } @@ -104,47 +105,48 @@ const getReleaseInfo = ((releaseCache) => async (tag) => { const version = 'v' + tag.replace(/^v/, ''); - const command = isUnreleasedTag ? - `npx auto-changelog --unreleased-only --stdout --commit-limit false --template json` : - `npx auto-changelog ${ - version ? '--starting-version ' + version + ' --ending-version ' + version : '' - } --stdout --commit-limit false --template json`; + const command = isUnreleasedTag + ? `npx auto-changelog --unreleased-only --stdout --commit-limit false --template json` + : `npx auto-changelog ${ + version ? '--starting-version ' + version + ' --ending-version ' + version : '' + } --stdout --commit-limit false --template json`; console.log(command); - const {stdout} = await exec(command, {maxBuffer: 10 * ONE_MB}); + const { stdout } = await exec(command, { maxBuffer: 10 * ONE_MB }); const release = JSON.parse(stdout)[0]; - if(release) { + if (release) { const authors = {}; const commits = [ ...release.commits, - ...release.fixes.map(fix => fix.commit), - ...release.merges.map(fix => fix.commit) + ...release.fixes.map((fix) => fix.commit), + ...release.merges.map((fix) => fix.commit), ].filter(Boolean); const commitMergeMap = {}; - for(const merge of release.merges) { + for (const merge of release.merges) { commitMergeMap[merge.commit.hash] = merge.id; } - for (const {hash, author, email, insertions, deletions} of commits) { - const entry = authors[email] = (authors[email] || { + for (const { hash, author, email, insertions, deletions } of commits) { + const entry = (authors[email] = authors[email] || { name: author, prs: [], email, commits: [], - insertions: 0, deletions: 0 + insertions: 0, + deletions: 0, }); - entry.commits.push({hash}); + entry.commits.push({ hash }); let pr; - if((pr = commitMergeMap[hash])) { + if ((pr = commitMergeMap[hash])) { entry.prs.push(pr); } @@ -160,13 +162,12 @@ const getReleaseInfo = ((releaseCache) => async (tag) => { } for (const [email, author] of Object.entries(authors)) { - const entry = authors[email] = await getUserInfo(author); + const entry = (authors[email] = await getUserInfo(author)); - entry.isBot = entry.type === "Bot"; + entry.isBot = entry.type === 'Bot'; } - release.authors = Object.values(deduplicate(authors)) - .sort((a, b) => b.points - a.points); + release.authors = Object.values(deduplicate(authors)).sort((a, b) => b.points - a.points); release.allCommits = commits; } @@ -179,27 +180,36 @@ const getReleaseInfo = ((releaseCache) => async (tag) => { const renderContributorsList = async (tag, template) => { const release = await getReleaseInfo(tag); - const compile = Handlebars.compile(String(await fs.readFile(template))) + const compile = Handlebars.compile(String(await fs.readFile(template))); const content = compile(release); return removeExtraLineBreaks(cleanTemplate(content)); -} +}; -const renderPRsList = async (tag, template, {comments_threshold= 5, awesome_threshold= 5, label = 'add_to_changelog'} = {}) => { +const renderPRsList = async ( + tag, + template, + { comments_threshold = 5, awesome_threshold = 5, label = 'add_to_changelog' } = {} +) => { const release = await getReleaseInfo(tag); const prs = {}; - for(const merge of release.merges) { + for (const merge of release.merges) { const pr = await getIssueById(merge.id); - if (pr && pr.labels.find(({name}) => name === label)) { - const {reactions, body} = pr; + if (pr && pr.labels.find(({ name }) => name === label)) { + const { reactions, body } = pr; prs[pr.number] = pr; pr.isHot = pr.comments > comments_threshold; - const points = reactions['+1'] + - reactions['hooray'] + reactions['rocket'] + reactions['heart'] + reactions['laugh'] - reactions['-1']; + const points = + reactions['+1'] + + reactions['hooray'] + + reactions['rocket'] + + reactions['heart'] + + reactions['laugh'] - + reactions['-1']; pr.isAwesome = points > awesome_threshold; @@ -210,7 +220,7 @@ const renderPRsList = async (tag, template, {comments_threshold= 5, awesome_thre if (body) { const reg = /```+changelog\n*(.+?)?\n*```/gms; - while((match = reg.exec(body))) { + while ((match = reg.exec(body))) { match[1] && pr.messages.push(match[1]); } } @@ -219,23 +229,19 @@ const renderPRsList = async (tag, template, {comments_threshold= 5, awesome_thre release.prs = Object.values(prs); - const compile = Handlebars.compile(String(await fs.readFile(template))) + const compile = Handlebars.compile(String(await fs.readFile(template))); const content = compile(release); return removeExtraLineBreaks(cleanTemplate(content)); -} +}; const getTagRef = async (tag) => { try { return (await exec(`git show-ref --tags "refs/tags/${tag}"`)).stdout.split(' ')[0]; - } catch(e) { + } catch (e) { + // Do nothing } -} +}; -export { - renderContributorsList, - getReleaseInfo, - renderPRsList, - getTagRef -} +export { renderContributorsList, getReleaseInfo, renderPRsList, getTagRef }; diff --git a/bin/githubAxios.js b/bin/githubAxios.js index ed9c4a0d..23a4b9e6 100644 --- a/bin/githubAxios.js +++ b/bin/githubAxios.js @@ -1,19 +1,24 @@ import axios from '../index.js'; -import {colorize} from "./helpers/colorize.js"; +import { colorize } from './helpers/colorize.js'; -const {GITHUB_TOKEN} = process.env; +const { GITHUB_TOKEN } = process.env; GITHUB_TOKEN ? console.log(`[GITHUB_TOKEN OK]`) : console.warn(`[GITHUB_TOKEN is not defined]`); const defaultTransform = axios.defaults.transformRequest; export default axios.create({ - transformRequest: [defaultTransform[0], function (data) { - console.log(colorize()`[${this.method.toUpperCase()}] Request [${new URL(axios.getUri(this)).pathname}]`); - return data; - }], + transformRequest: [ + defaultTransform[0], + function (data) { + console.log( + colorize()`[${this.method.toUpperCase()}] Request [${new URL(axios.getUri(this)).pathname}]` + ); + return data; + }, + ], baseURL: 'https://api.github.com/', headers: { - Authorization: GITHUB_TOKEN ? `token ${GITHUB_TOKEN}` : null - } + Authorization: GITHUB_TOKEN ? `token ${GITHUB_TOKEN}` : null, + }, }); diff --git a/bin/helpers/colorize.js b/bin/helpers/colorize.js index 3e02bdb5..a250b8e7 100644 --- a/bin/helpers/colorize.js +++ b/bin/helpers/colorize.js @@ -1,14 +1,16 @@ import chalk from 'chalk'; export const colorize = (...colors) => { - if(!colors.length) { + if (!colors.length) { colors = ['green', 'cyan', 'magenta', 'blue', 'yellow', 'red']; } const colorsCount = colors.length; return (strings, ...values) => { - const {length} = values; - return strings.map((str, i) => i < length ? str + chalk[colors[i%colorsCount]].bold(values[i]) : str).join(''); - } -} + const { length } = values; + return strings + .map((str, i) => (i < length ? str + chalk[colors[i % colorsCount]].bold(values[i]) : str)) + .join(''); + }; +}; diff --git a/bin/helpers/parser.js b/bin/helpers/parser.js index 84311da3..338e9dda 100644 --- a/bin/helpers/parser.js +++ b/bin/helpers/parser.js @@ -1,12 +1,13 @@ export const matchAll = (text, regexp, cb) => { let match; - while((match = regexp.exec(text))) { + + while ((match = regexp.exec(text))) { cb(match); } -} +}; export const parseSection = (body, name, cb) => { matchAll(body, new RegExp(`^(#+)\\s+${name}?(.*?)^\\1\\s+\\w+`, 'gims'), cb); -} +}; export const parseVersion = (rawVersion) => /^v?(\d+).(\d+).(\d+)/.exec(rawVersion); diff --git a/bin/injectContributorsList.js b/bin/injectContributorsList.js index 2b25c590..d74e7bcf 100644 --- a/bin/injectContributorsList.js +++ b/bin/injectContributorsList.js @@ -1,9 +1,9 @@ import fs from 'fs/promises'; import path from 'path'; -import {renderContributorsList, getTagRef, renderPRsList} from './contributors.js'; +import { renderContributorsList, getTagRef, renderPRsList } from './contributors.js'; import asyncReplace from 'string-replace-async'; -import {fileURLToPath} from "url"; -import {colorize} from "./helpers/colorize.js"; +import { fileURLToPath } from 'url'; +import { colorize } from './helpers/colorize.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -16,7 +16,7 @@ const injectSection = async (name, contributorsRE, injector, infile = '../CHANGE infile = path.resolve(__dirname, infile); const content = String(await fs.readFile(infile)); - const headerRE = /^#+\s+\[([-_\d.\w]+)].+?$/mig; + const headerRE = /^#+\s+\[([-_\d.\w]+)].+?$/gim; let tag; let index = 0; @@ -32,11 +32,11 @@ const injectSection = async (name, contributorsRE, injector, infile = '../CHANGE tag = nextTag; index = offset + match.length; - if(currentTag) { + if (currentTag) { if (hasSection) { console.log(colorize()`[${currentTag}]: ✓ OK`); } else { - const target = isFirstTag && (!await getTagRef(currentTag)) ? '' : currentTag; + const target = isFirstTag && !(await getTagRef(currentTag)) ? '' : currentTag; console.log(colorize()`[${currentTag}]: ❌ MISSED` + (!target ? ' (UNRELEASED)' : '')); @@ -63,16 +63,12 @@ const injectSection = async (name, contributorsRE, injector, infile = '../CHANGE }); await fs.writeFile(infile, newContent); -} +}; -await injectSection( - 'PRs', - /^\s*### PRs/mi, - (tag) => tag ? '' : renderPRsList(tag, PRS_TEMPLATE, {awesome_threshold: 5, comments_threshold: 7}), +await injectSection('PRs', /^\s*### PRs/im, (tag) => + tag ? '' : renderPRsList(tag, PRS_TEMPLATE, { awesome_threshold: 5, comments_threshold: 7 }) ); -await injectSection( - 'contributors', - /^\s*### Contributors/mi, - (tag) => renderContributorsList(tag, CONTRIBUTORS_TEMPLATE) +await injectSection('contributors', /^\s*### Contributors/im, (tag) => + renderContributorsList(tag, CONTRIBUTORS_TEMPLATE) ); diff --git a/bin/pr.js b/bin/pr.js index 6fc9bae6..71d66b8b 100644 --- a/bin/pr.js +++ b/bin/pr.js @@ -1,22 +1,22 @@ -import Handlebars from "handlebars"; -import fs from "fs/promises"; +import Handlebars from 'handlebars'; +import fs from 'fs/promises'; import prettyBytes from 'pretty-bytes'; -import {getBlobHistory} from './repo.js'; -import pacote from "pacote"; -import zlib from "zlib"; -import tar from "tar-stream"; -import { Readable } from "stream"; +import { getBlobHistory } from './repo.js'; +import pacote from 'pacote'; +import zlib from 'zlib'; +import tar from 'tar-stream'; +import { Readable } from 'stream'; const FILE_SIZE_DIFF_THRESHOLD = 512; // 0.5KB const readJSONFile = async (file) => JSON.parse(String(await fs.readFile(file))); -const {version} = await readJSONFile('./package.json'); +const { version } = await readJSONFile('./package.json'); const parseVersion = (tag) => { const [, major, minor, patch] = /^v?(\d+)\.(\d+)\.(\d+)/.exec(tag) || []; return [major, minor, patch]; -} +}; const [MAJOR_NUMBER] = parseVersion(version); @@ -27,14 +27,14 @@ async function getFilesFromNPM(pkg) { return new Promise((resolve, reject) => { const extract = tar.extract(); - extract.on("entry", (header, stream, next) => { + extract.on('entry', (header, stream, next) => { const buffers = []; stream.on('data', (buffer) => { buffers.push(buffer); }); - stream.on("end", () => { + stream.on('end', () => { const content = Buffer.concat(buffers); const gzipped = zlib.gzipSync(content); @@ -42,7 +42,7 @@ async function getFilesFromNPM(pkg) { files[header.name.replace(/^package\//, '')] = { gzip: gzipped.length, compressed: header.size ? gzipped.length / header.size : 1, - ...header + ...header, }; next(); @@ -52,51 +52,50 @@ async function getFilesFromNPM(pkg) { Readable.from(tgzData) .pipe(zlib.createGunzip()) .pipe(extract) - .on("error", reject) + .on('error', reject) .on('finish', () => resolve(files)); }); } - - - const generateFileReport = async (files, historyCount = 3) => { const allFilesStat = {}; - const commits = (await getBlobHistory('package.json', historyCount)).filter(({tag}) => { + const commits = (await getBlobHistory('package.json', historyCount)).filter(({ tag }) => { return MAJOR_NUMBER === parseVersion(tag)[0]; }); const warns = []; const npmHistory = {}; - await Promise.all(commits.map(async ({tag}) => { - npmHistory[tag] = await getFilesFromNPM(`axios@${tag.replace(/^v/, '')}`); - })); + await Promise.all( + commits.map(async ({ tag }) => { + npmHistory[tag] = await getFilesFromNPM(`axios@${tag.replace(/^v/, '')}`); + }) + ); - for(const [name, filename] of Object.entries(files)) { + for (const [name, filename] of Object.entries(files)) { const file = await fs.stat(filename).catch(console.warn); const gzip = file ? zlib.gzipSync(await fs.readFile(filename)).length : 0; - const stat = allFilesStat[filename] = file ? { - name, - size: file.size, - path: filename, - gzip, - compressed: file.size ? gzip / file.size : 1, - history: commits.map(({tag}) => { - const files = npmHistory[tag]; - const file = files && files[filename] || null; + const stat = (allFilesStat[filename] = file + ? { + name, + size: file.size, + path: filename, + gzip, + compressed: file.size ? gzip / file.size : 1, + history: commits.map(({ tag }) => { + const files = npmHistory[tag]; + const file = (files && files[filename]) || null; - return { - tag, - ...file - }; - }) - } : null; + return { + tag, + ...file, + }; + }), + } + : null); - - - if(stat.history[0]) { + if (stat.history[0]) { const diff = stat.gzip - stat.history[0].gzip; if (diff > FILE_SIZE_DIFF_THRESHOLD) { @@ -113,22 +112,28 @@ const generateFileReport = async (files, historyCount = 3) => { return { version, files: allFilesStat, - warns + warns, }; -} +}; -const generateBody = async ({files, template = './templates/pr.hbs'} = {}) => { +const generateBody = async ({ files, template = './templates/pr.hbs' } = {}) => { const data = await generateFileReport(files); - Handlebars.registerHelper('filesize', (bytes) => bytes != null ? prettyBytes(bytes) : ''); - Handlebars.registerHelper('percent', (value) => Number.isFinite(value) ? `${(value * 100).toFixed(1)}%` : `---` ); + Handlebars.registerHelper('filesize', (bytes) => + bytes != null ? prettyBytes(bytes) : '' + ); + Handlebars.registerHelper('percent', (value) => + Number.isFinite(value) ? `${(value * 100).toFixed(1)}%` : `---` + ); return Handlebars.compile(String(await fs.readFile(template)))(data); -} +}; -console.log(await generateBody({ - files: { - 'Browser build (UMD)' : 'dist/axios.min.js', - 'Browser build (ESM)' : 'dist/esm/axios.min.js', - } -})); +console.log( + await generateBody({ + files: { + 'Browser build (UMD)': 'dist/axios.min.js', + 'Browser build (ESM)': 'dist/esm/axios.min.js', + }, + }) +); diff --git a/bin/repo.js b/bin/repo.js index 884d9e40..ce191054 100644 --- a/bin/repo.js +++ b/bin/repo.js @@ -1,20 +1,20 @@ -import util from "util"; -import cp from "child_process"; +import util from 'util'; +import cp from 'child_process'; export const exec = util.promisify(cp.exec); -export const getBlobSize = async (filepath, sha ='HEAD') => { - const size = (await exec( - `git cat-file -s ${sha}:${filepath}` - )).stdout; +export const getBlobSize = async (filepath, sha = 'HEAD') => { + const size = (await exec(`git cat-file -s ${sha}:${filepath}`)).stdout; return size ? +size : 0; -} +}; -export const getBlobHistory = async (filepath, maxCount= 5) => { - const log = (await exec( - `git log --max-count=${maxCount} --no-walk --tags=v* --oneline --format=%H%d -- ${filepath}` - )).stdout; +export const getBlobHistory = async (filepath, maxCount = 5) => { + const log = ( + await exec( + `git log --max-count=${maxCount} --no-walk --tags=v* --oneline --format=%H%d -- ${filepath}` + ) + ).stdout; const commits = []; @@ -22,21 +22,19 @@ export const getBlobHistory = async (filepath, maxCount= 5) => { const regexp = /^(\w+) \(tag: (v?[.\d]+)\)$/gm; - while((match = regexp.exec(log))) { + while ((match = regexp.exec(log))) { commits.push({ sha: match[1], tag: match[2], - size: await getBlobSize(filepath, match[1]) - }) + size: await getBlobSize(filepath, match[1]), + }); } return commits; -} +}; export const getTags = async (pattern = 'v*', sort = '-v:refname') => { - const log = (await exec( - `git tag -l ${pattern} --sort=${sort}` - )).stdout; + const log = (await exec(`git tag -l ${pattern} --sort=${sort}`)).stdout; return log.split(/\r?\n/); -} +}; diff --git a/bin/resolveNPMTag.js b/bin/resolveNPMTag.js index 608d3a45..fc78758c 100644 --- a/bin/resolveNPMTag.js +++ b/bin/resolveNPMTag.js @@ -1,8 +1,8 @@ -import {exec, getTags} from "./repo.js"; -import fs from "fs"; -import {colorize} from "./helpers/colorize.js"; +import { exec, getTags } from './repo.js'; +import fs from 'fs'; +import { colorize } from './helpers/colorize.js'; -const {version} = JSON.parse(fs.readFileSync('./package.json')); +const { version } = JSON.parse(fs.readFileSync('./package.json')); const [major] = version.split('.'); const tags = await getTags(); @@ -13,6 +13,8 @@ const isLatest = latestTag === version; let tag = isBeta ? 'next' : isLatest ? 'latest' : `v${major}`; -console.log(colorize()`Version [${version}] [${isBeta ? 'prerelease' : 'release'}] latest [${latestTag}]=> NPM Tag [${tag}]`); +console.log( + colorize()`Version [${version}] [${isBeta ? 'prerelease' : 'release'}] latest [${latestTag}]=> NPM Tag [${tag}]` +); await exec(`echo "tag=${tag}" >> $GITHUB_OUTPUT`); diff --git a/bin/run-karma-tests.js b/bin/run-karma-tests.js index afa7e148..178af1ad 100644 --- a/bin/run-karma-tests.js +++ b/bin/run-karma-tests.js @@ -1,11 +1,10 @@ import { startTestServer, stopHTTPServer } from '../test/helpers/server.js'; import { spawn } from 'child_process'; -import chalk from "chalk"; +import chalk from 'chalk'; let server; async function run() { - console.log(chalk.red.bold(`[ Starting HTTP server... ]`)); server = await startTestServer(3000); @@ -13,25 +12,19 @@ async function run() { await new Promise((resolve, reject) => { console.log('Starting karma runner...'); - const karma = spawn( - 'npx', - ['karma', 'start', 'karma.conf.cjs', '--single-run'], - { - stdio: 'inherit', - shell: true, - env: { ...process.env, LISTEN_ADDR: '0.0.0.0' }, - }); + const karma = spawn('npx', ['karma', 'start', 'karma.conf.cjs', '--single-run'], { + stdio: 'inherit', + shell: true, + env: { ...process.env, LISTEN_ADDR: '0.0.0.0' }, + }); karma.on('exit', (code) => { code ? reject(new Error(`Karma tests failed with exit code ${code}`)) : resolve(); }); }); - } - - -(async() => { +(async () => { try { await run(); } finally { @@ -42,5 +35,3 @@ async function run() { } } })(); - - diff --git a/bin/sponsors.js b/bin/sponsors.js index 73af873e..803d9323 100644 --- a/bin/sponsors.js +++ b/bin/sponsors.js @@ -1,12 +1,12 @@ -import fs from "fs/promises"; -import _axios from "../index.js"; -import { exec } from "./repo.js"; -import { colorize } from "./helpers/colorize.js"; +import fs from 'fs/promises'; +import _axios from '../index.js'; +import { exec } from './repo.js'; +import { colorize } from './helpers/colorize.js'; const axios = _axios.create({ headers: { - "User-Agent": - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36", + 'User-Agent': + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36', }, }); @@ -19,9 +19,7 @@ const getWithRetry = (url, retries = 3) => { if (counter++ >= retries) { throw err; } - await new Promise((resolve) => - setTimeout(resolve, counter ** counter * 1000), - ); + await new Promise((resolve) => setTimeout(resolve, counter ** counter * 1000)); return doRequest(); } }; @@ -29,11 +27,7 @@ const getWithRetry = (url, retries = 3) => { return doRequest(); }; -const updateReadmeSponsors = async ( - url, - path, - marker = "", -) => { +const updateReadmeSponsors = async (url, path, marker = '') => { let fileContent = (await fs.readFile(path)).toString(); const index = fileContent.indexOf(marker); @@ -42,7 +36,7 @@ const updateReadmeSponsors = async ( const readmeContent = fileContent.slice(index); let { data: sponsorContent } = await getWithRetry(url); - sponsorContent += "\n"; + sponsorContent += '\n'; const currentSponsorContent = fileContent.slice(0, index); @@ -54,22 +48,18 @@ const updateReadmeSponsors = async ( console.log(colorize()`Sponsor block in [${path}] is up to date`); } } else { - console.warn( - colorize()`Can not find marker (${marker}) in ${path} to inject sponsor block`, - ); + console.warn(colorize()`Can not find marker (${marker}) in ${path} to inject sponsor block`); } return false; }; (async (url) => { - const newContent = await updateReadmeSponsors(url, "./README.md"); + const newContent = await updateReadmeSponsors(url, './README.md'); - await exec( - `echo "changed=${newContent ? "true" : "false"}" >> $GITHUB_OUTPUT`, - ); + await exec(`echo "changed=${newContent ? 'true' : 'false'}" >> $GITHUB_OUTPUT`); if (newContent !== false) { - await fs.mkdir("./temp").catch(() => {}); - await fs.writeFile("./temp/sponsors.md", newContent); + await fs.mkdir('./temp').catch(() => {}); + await fs.writeFile('./temp/sponsors.md', newContent); } -})("https://axios-http.com/data/sponsors.md"); +})('https://axios-http.com/data/sponsors.md'); diff --git a/bin/ssl_hotfix.js b/bin/ssl_hotfix.js index 6147bf04..4a671aec 100644 --- a/bin/ssl_hotfix.js +++ b/bin/ssl_hotfix.js @@ -1,4 +1,4 @@ -import {spawn} from 'child_process'; +import { spawn } from 'child_process'; const args = process.argv.slice(2); @@ -10,13 +10,15 @@ const isHotfixNeeded = match && match[1] > 16; isHotfixNeeded && console.warn('Setting --openssl-legacy-provider as ssl hotfix'); -const test = spawn('cross-env', - isHotfixNeeded ? ['NODE_OPTIONS=--openssl-legacy-provider', ...args] : args, { +const test = spawn( + 'cross-env', + isHotfixNeeded ? ['NODE_OPTIONS=--openssl-legacy-provider', ...args] : args, + { shell: true, - stdio: 'inherit' + stdio: 'inherit', } ); test.on('exit', function (code) { - process.exit(code) -}) + process.exit(code); +}); diff --git a/examples/README.md b/examples/README.md index 114634e5..c1e5bfac 100644 --- a/examples/README.md +++ b/examples/README.md @@ -7,4 +7,4 @@ To run the examples: 3. `npm install` 4. `npm run build` 5. `npm run examples` -6. [http://localhost:3000](http://localhost:3000) \ No newline at end of file +6. [http://localhost:3000](http://localhost:3000) diff --git a/examples/abort-controller/index.html b/examples/abort-controller/index.html index bd3747ae..66dd3d79 100644 --- a/examples/abort-controller/index.html +++ b/examples/abort-controller/index.html @@ -1,69 +1,73 @@ - - axios - abort controller example - - - - -

axios.AbortController

- -
-
-

1. Single Request Cancellation

-

Click "Start Request" to begin a 3-second request. Click "Cancel Request" to abort it.

- - -
-
+ + + axios - abort controller example + + + + + +

axios.AbortController

+ +
+
+

1. Single Request Cancellation

+

Click "Start Request" to begin a 3-second request. Click "Cancel Request" to abort it.

+ + +
+
-
+
-
-
-

2. Search-as-you-type (Race Condition Handling)

-

Type quickly. Previous pending requests will be cancelled automatically.

-
- -
-
-
    +
    +
    +

    2. Search-as-you-type (Race Condition Handling)

    +

    Type quickly. Previous pending requests will be cancelled automatically.

    +
    +
    +
    +
      +
      - - + - - + function log(msg) { + const li = document.createElement('li'); + li.className = 'list-group-item py-1'; + li.textContent = new Date().toLocaleTimeString() + ' - ' + msg; + searchLog.prepend(li); + } + + + + \ No newline at end of file diff --git a/examples/abort-controller/server.js b/examples/abort-controller/server.js index 8e273265..3ec4ddde 100644 --- a/examples/abort-controller/server.js +++ b/examples/abort-controller/server.js @@ -6,11 +6,13 @@ export default function (req, res) { setTimeout(() => { res.writeHead(200, { - 'Content-Type': 'text/json' + 'Content-Type': 'text/json', }); - res.write(JSON.stringify({ - message: 'Response completed successfully after ' + delay + 'ms' - })); + res.write( + JSON.stringify({ + message: 'Response completed successfully after ' + delay + 'ms', + }) + ); res.end(); }, delay); -}; +} diff --git a/examples/all/index.html b/examples/all/index.html index caaafdcf..93640488 100644 --- a/examples/all/index.html +++ b/examples/all/index.html @@ -1,44 +1,47 @@ - - axios - all example - - - -

      axios.all

      -
      -

      User

      -
      - -
      - -
      + + axios - all example + + + + +

      axios.all

      + +
      +

      User

      +
      + +
      +
      -
      -

      Orgs

      -
        +
        +

        Orgs

        +
          +
          - - - - + + + + + \ No newline at end of file diff --git a/examples/amd/index.html b/examples/amd/index.html index ce3800d8..60e850fd 100644 --- a/examples/amd/index.html +++ b/examples/amd/index.html @@ -1,37 +1,40 @@ - - AMD - - - -

          AMD

          -
          -

          User

          -
          - -
          - -
          + + AMD + + + + +

          AMD

          + +
          +

          User

          +
          + +
          +
          +
          - - + - - + requirejs(['axios'], function (axios) { + axios.get('https://api.github.com/users/mzabriskie') + .then(function (user) { + document.getElementById('useravatar').src = user.data.avatar_url; + document.getElementById('username').innerHTML = user.data.name; + }); + }); + + + + \ No newline at end of file diff --git a/examples/get/index.html b/examples/get/index.html index f09c9ae3..826e3f68 100644 --- a/examples/get/index.html +++ b/examples/get/index.html @@ -1,33 +1,36 @@ - - axios - get example - - - -

          axios.get

          -
            - - - - + + axios - get example + + + + +

            axios.get

            +
              + + + + + + \ No newline at end of file diff --git a/examples/get/server.js b/examples/get/server.js index 7312f42b..3ecad7f2 100644 --- a/examples/get/server.js +++ b/examples/get/server.js @@ -1,34 +1,34 @@ const people = [ { - "name": "Matt Zabriskie", - "github": "mzabriskie", - "twitter": "mzabriskie", - "avatar": "199035" + name: 'Matt Zabriskie', + github: 'mzabriskie', + twitter: 'mzabriskie', + avatar: '199035', }, { - "name": "Ryan Florence", - "github": "rpflorence", - "twitter": "ryanflorence", - "avatar": "100200" + name: 'Ryan Florence', + github: 'rpflorence', + twitter: 'ryanflorence', + avatar: '100200', }, { - "name": "Kent C. Dodds", - "github": "kentcdodds", - "twitter": "kentcdodds", - "avatar": "1500684" + name: 'Kent C. Dodds', + github: 'kentcdodds', + twitter: 'kentcdodds', + avatar: '1500684', }, { - "name": "Chris Esplin", - "github": "deltaepsilon", - "twitter": "chrisesplin", - "avatar": "878947" - } + name: 'Chris Esplin', + github: 'deltaepsilon', + twitter: 'chrisesplin', + avatar: '878947', + }, ]; export default function (req, res) { res.writeHead(200, { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }); res.write(JSON.stringify(people)); res.end(); -}; +} diff --git a/examples/improved-network-errors.md b/examples/improved-network-errors.md index 508c46cc..9bfc656a 100644 --- a/examples/improved-network-errors.md +++ b/examples/improved-network-errors.md @@ -2,7 +2,7 @@ This document explains a simple approach to make Axios network errors more helpful and human-readable. By default, Axios shows a generic `"Network Error"` message for many failures. -This can be confusing because it doesn't explain "what actually went wrong" (e.g., no internet, a timeout, a CORS issue, etc.). +This can be confusing because it doesn't explain "what actually went wrong" (e.g., no internet, a timeout, a CORS issue, etc.). Our approach adds clear, categorised error messages for different network issues. @@ -10,19 +10,20 @@ Our approach adds clear, categorised error messages for different network issues ==> Problem Axios currently throws the same `Network Error` message for many different cases: -- The Internet is disconnected -- DNS lookup fails -- Server is down or refusing connections -- CORS blocked requests -- Request timed out + +- The Internet is disconnected +- DNS lookup fails +- Server is down or refusing connections +- CORS blocked requests +- Request timed out These cases all look the same to developers and users, making debugging harder. - --> Our Approach — Wrapper / Middleware We created a small wrapper function called `enhanceNetworkError()` that: -- Detects Common network problems using `error.code`, `error.message`, and response status. + +- Detects Common network problems using `error.code`, `error.message`, and response status. - Adds a new field `error.detailedMessage` with a short, clear explanation. - Assigns a new `error.code` (like `ERR_TIMEOUT`, `ERR_DNS_FAILURE`, etc.). - Works for both browser and Node.js environments. @@ -31,7 +32,7 @@ The wrapper is used inside an Axios instance via a Response interceptor. -> How It Works -1. When Axios throws an error, the interceptor catches it. +1. When Axios throws an error, the interceptor catches it. 2. The `enhanceNetworkError()` function checks what type of error it is: - Offline → `ERR_NO_INTERNET` - DNS failure → `ERR_DNS_FAILURE` @@ -42,16 +43,16 @@ The wrapper is used inside an Axios instance via a Response interceptor. - Other → `ERR_NETWORK_GENERIC` 3. It returns a more descriptive error with both `code` and `detailedMessage`. - -> Example Usage ```javascript const api = createEnhancedClient({ baseURL: 'https://example.com' }); -api.get('/data') - .then(res => console.log(res.data)) - .catch(err => { - console.error(err.code); // e.g., ERR_TIMEOUT +api + .get('/data') + .then((res) => console.log(res.data)) + .catch((err) => { + console.error(err.code); // e.g., ERR_TIMEOUT console.error(err.detailedMessage); // e.g., "The request took too long to respond." }); ``` diff --git a/examples/network_enhanced.js b/examples/network_enhanced.js index 72f722d3..6d9b3a2d 100644 --- a/examples/network_enhanced.js +++ b/examples/network_enhanced.js @@ -25,29 +25,25 @@ function enhanceNetworkError(error) { // when Request timeout happens else if (error.code === 'ETIMEDOUT' || /timeout/i.test(error.message)) { error.code = 'ERR_TIMEOUT'; - error.detailedMessage = - 'The request took too long to respond. Please try again later.'; + error.detailedMessage = 'The request took too long to respond. Please try again later.'; } // when CORS restriction happens (for browser only) else if (/CORS/i.test(error.message)) { error.code = 'ERR_CORS_BLOCKED'; - error.detailedMessage = - 'The request was blocked due to cross-origin restrictions.'; + error.detailedMessage = 'The request was blocked due to cross-origin restrictions.'; } - // when Server-side error occurs + // when Server-side error occurs else if (error.response && error.response.status >= 500) { error.code = 'ERR_SERVER'; - error.detailedMessage = - 'A server-side issue occurred. Please try again later.'; + error.detailedMessage = 'A server-side issue occurred. Please try again later.'; } // when Client-side error occurs else if (error.response && error.response.status >= 400) { error.code = 'ERR_CLIENT'; - error.detailedMessage = - 'A client-side error occurred. Please check your request.'; + error.detailedMessage = 'A client-side error occurred. Please check your request.'; } // when unknown network issue occurs @@ -60,13 +56,12 @@ function enhanceNetworkError(error) { return error; } - export function createEnhancedClient(config = {}) { const client = axios.create(config); client.interceptors.response.use( - response => response, - error => { + (response) => response, + (error) => { throw enhanceNetworkError(error); } ); diff --git a/examples/post/index.html b/examples/post/index.html index 43914a11..11182248 100644 --- a/examples/post/index.html +++ b/examples/post/index.html @@ -1,40 +1,43 @@ - - axios - post example - - - -

              axios.post

              -
              -
              - - -
              - -
              + + axios - post example + + -
              + +

              axios.post

              - - - - +
              + + + + + + \ No newline at end of file diff --git a/examples/post/server.js b/examples/post/server.js index 68756d1b..2208ffaf 100644 --- a/examples/post/server.js +++ b/examples/post/server.js @@ -8,9 +8,9 @@ export default function (req, res) { req.on('end', function () { console.log('POST data received'); res.writeHead(200, { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }); res.write(JSON.stringify(data)); res.end(); }); -}; +} diff --git a/examples/postMultipartFormData/index.html b/examples/postMultipartFormData/index.html index 553e8d73..e3a3eb6d 100644 --- a/examples/postMultipartFormData/index.html +++ b/examples/postMultipartFormData/index.html @@ -1,526 +1,531 @@ - - Axios - Multipart Form Example - - - + - .theme-toggle { - background: rgba(255, 255, 255, 0.2); - border: none; - border-radius: 50px; - width: 60px; - height: 30px; - display: flex; - align-items: center; - padding: 0 5px; - cursor: pointer; - position: relative; - transition: var(--transition); - } + +
              +
              +

              Multipart Form Data

              + +
              - .theme-toggle:hover { - background: rgba(255, 255, 255, 0.3); - } +
              +
              +
              +
              + + +
              +
              + + +
              +
              + + +
              +
              + + +
              - .toggle-circle { - width: 22px; - height: 22px; - background: white; - border-radius: 50%; - position: absolute; - left: 4px; - transition: var(--transition); - } - - [data-theme="dark"] .toggle-circle { - left: 34px; - } - - .theme-toggle i { - color: white; - font-size: 14px; - position: absolute; - } - - .fa-sun { - left: 8px; - } - - .fa-moon { - right: 8px; - } - - .content-wrapper { - display: flex; - flex-direction: row; - min-height: 600px; - } - - @media (max-width: 992px) { - .content-wrapper { - flex-direction: column; - } - } - - .form-section { - flex: 1; - padding: 30px; - border-right: 1px solid var(--border-color); - } - - .result-section { - flex: 1; - padding: 30px; - background-color: rgba(108, 99, 255, 0.03); - display: flex; - flex-direction: column; - } - - [data-theme="dark"] .result-section { - background-color: rgba(26, 26, 46, 0.5); - } - - .form-group { - margin-bottom: 24px; - } - - label { - display: block; - margin-bottom: 8px; - font-weight: 500; - color: var(--text-color); - } - - input[type="text"], - input[type="number"], - input[type="file"] { - width: 100%; - padding: 14px 16px; - border: 1px solid var(--border-color); - border-radius: var(--border-radius); - font-size: 16px; - transition: var(--transition); - background-color: var(--input-bg); - color: var(--text-color); - } - - input[type="text"]:focus, - input[type="number"]:focus, - input[type="file"]:focus { - outline: none; - border-color: var(--primary); - box-shadow: 0 0 0 3px rgba(108, 99, 255, 0.2); - } - - .radio-group { - display: flex; - flex-direction: column; - gap: 15px; - margin: 25px 0; - } - - .radio-option { - display: flex; - align-items: center; - padding: 15px; - border: 1px solid var(--border-color); - border-radius: var(--border-radius); - cursor: pointer; - transition: var(--transition); - background-color: var(--input-bg); - } - - .radio-option:hover { - background-color: rgba(108, 99, 255, 0.05); - border-color: var(--primary); - } - - .radio-option input { - margin-right: 12px; - transform: scale(1.2); - } - - .radio-option label { - margin-bottom: 0; - cursor: pointer; - } - - .btn-primary { - background: linear-gradient(135deg, var(--primary), var(--primary-dark)); - border: none; - padding: 16px 28px; - font-size: 16px; - font-weight: 600; - border-radius: var(--border-radius); - cursor: pointer; - transition: var(--transition); - width: 100%; - display: flex; - align-items: center; - justify-content: center; - gap: 10px; - color: white; - box-shadow: 0 4px 12px rgba(108, 99, 255, 0.3); - } - - .btn-primary:hover { - transform: translateY(-2px); - box-shadow: 0 6px 15px rgba(108, 99, 255, 0.4); - } - - .postSubmission { - margin-top: 20px; - padding: 25px; - background-color: var(--light); - border-radius: var(--border-radius); - flex-grow: 1; - display: flex; - flex-direction: column; - } - - [data-theme="dark"] .postSubmission { - background-color: var(--gray-light); - } - - .checkNetwork { - margin-bottom: 20px; - padding: 15px; - background-color: rgba(108, 99, 255, 0.1); - border-left: 4px solid var(--primary); - border-radius: 4px; - } - - .text-strong { - font-weight: 700; - color: var(--primary); - } - - .hidden { - display: none; - } - - .text-danger { - padding: 15px; - background-color: rgba(220, 53, 69, 0.1); - border-left: 4px solid var(--danger); - border-radius: 4px; - color: var(--danger); - margin-top: 20px; - } - - .text-success { - padding: 15px; - background-color: rgba(75, 181, 67, 0.1); - border-left: 4px solid var(--success); - border-radius: 4px; - color: var(--success); - margin-top: 20px; - } - - .info-box { - display: flex; - align-items: center; - gap: 12px; - margin-top: 20px; - padding: 15px; - background-color: rgba(108, 99, 255, 0.05); - border-radius: var(--border-radius); - } - - .info-box i { - color: var(--primary); - font-size: 20px; - } - - .result-title { - font-size: 20px; - font-weight: 600; - margin-bottom: 20px; - color: var(--primary); - display: flex; - align-items: center; - gap: 10px; - } - - .result-content { - background-color: var(--input-bg); - border-radius: var(--border-radius); - padding: 20px; - flex-grow: 1; - overflow-y: auto; - border: 1px solid var(--border-color); - font-family: 'Courier New', monospace; - white-space: pre-wrap; - } - - .result-placeholder { - color: var(--gray); - font-style: italic; - text-align: center; - margin-top: 50%; - transform: translateY(-50%); - } - - @media (max-width: 600px) { - .container { - margin: 10px; - } - - .form-section, .result-section { - padding: 20px; - } - - .header { - padding: 20px; - flex-direction: column; - gap: 15px; - } - - h1 { - font-size: 24px; - } - } - - - -
              -
              -

              Multipart Form Data

              - -
              - -
              -
              - -
              - - +
              +
              + +
              -
              - - -
              -
              - - -
              -
              - - -
              - -
              -
              - - -
              -
              - - -
              -
              - - - - -
              - - - -
              -
              -
              - Response Data + + + +
              + -
              -
              Submit the form to see the response data here
              + +
              -
              - -
              This form demonstrates how to submit multipart/form-data with both text fields and files.
              +
              +
              + Response Data +
              +
              +
              Submit the form to see the response data here
              +
              - - + - - + .catch(err => { + console.error("Error posting data:", err); + errorOutput.textContent = `${err.message}`; + errorOutput.classList.add("text-danger"); + errorOutput.classList.remove("text-success"); + errorOutput.classList.remove("hidden"); + + // Display error in the result section + resultContent.textContent = `Error: ${err.message}\n\n${JSON.stringify(err.response?.data || {}, null, 2)}`; + }); + }; + })(); + + + + \ No newline at end of file diff --git a/examples/postMultipartFormData/server.js b/examples/postMultipartFormData/server.js index eb95af6a..f46a57bf 100644 --- a/examples/postMultipartFormData/server.js +++ b/examples/postMultipartFormData/server.js @@ -1,13 +1,11 @@ export default function (req, res) { - - req.on('data', function (chunk) { - }); + req.on('data', function (chunk) {}); req.on('end', function () { console.log('POST received'); res.writeHead(200, { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }); res.end(); }); -}; +} diff --git a/examples/server.js b/examples/server.js index 2c9cfda5..ff377866 100644 --- a/examples/server.js +++ b/examples/server.js @@ -2,7 +2,7 @@ import fs from 'fs'; import path from 'path'; import http from 'http'; import minimist from 'minimist'; -import url from "url"; +import url from 'url'; const argv = minimist(process.argv.slice(2)); let server; @@ -31,7 +31,9 @@ function listDirs(root) { function getIndexTemplate() { const links = dirs.map(function (dir) { const url = '/' + dir; - return '
            • ' + url + '
            • '; + return ( + '
            • ' + url + '
            • ' + ); }); return ( @@ -72,14 +74,14 @@ function pipeFileToResponse(res, file, type) { // Validate file path - prevent directory traversal const safeBasePath = path.join(__dirname, 'examples'); const resolvedPath = path.resolve(path.join(safeBasePath, file)); - + // Ensure the resolved path is within intended directory if (!resolvedPath.startsWith(safeBasePath)) { res.writeHead(400); res.end('Invalid file path'); return; } - + // Check if file exists if (!fs.existsSync(resolvedPath)) { res.writeHead(404); @@ -89,7 +91,7 @@ function pipeFileToResponse(res, file, type) { if (type) { res.writeHead(200, { - "Content-Type": type + 'Content-Type': type, }); } else { res.writeHead(200); @@ -97,21 +99,21 @@ function pipeFileToResponse(res, file, type) { const stream = fs.createReadStream(resolvedPath); - stream.on("error", (err) => { - console.error("Error while reading file:", err.message); + stream.on('error', (err) => { + console.error('Error while reading file:', err.message); if (!res.headersSent) { - res.writeHead(500, { "Content-Type": "text/plain" }); + res.writeHead(500, { 'Content-Type': 'text/plain' }); } - res.end("File read error"); + res.end('File read error'); }); stream.pipe(res); } catch (err) { - console.error("Unexpected error:", err.message); + console.error('Unexpected error:', err.message); if (!res.headersSent) { - res.writeHead(500, { "Content-Type": "text/plain" }); + res.writeHead(500, { 'Content-Type': 'text/plain' }); } - res.end("Internal server error"); + res.end('Internal server error'); } } @@ -168,18 +170,19 @@ server = http.createServer(function (req, res) { // Process server request else if (new RegExp('(' + dirs.join('|') + ')\/server').test(url)) { if (fs.existsSync(path.join(__dirname, url + '.js'))) { - import('file://' + path.join(__dirname, url + '.js')).then((server) => { - server.default(req, res); - }).catch(err => { - console.error('Error importing server:', err); - send404(res); - }); + import('file://' + path.join(__dirname, url + '.js')) + .then((server) => { + server.default(req, res); + }) + .catch((err) => { + console.error('Error importing server:', err); + send404(res); + }); } else { send404(res); } return; - } - else { + } else { send404(res); } }); diff --git a/examples/transform-response/index.html b/examples/transform-response/index.html index 36dd26a1..3e710bad 100644 --- a/examples/transform-response/index.html +++ b/examples/transform-response/index.html @@ -1,44 +1,47 @@ - - axios - transform response example - - - -

              transformResponse

              -
              - -
              -
              - Created:
              - Updated: -
              + + axios - transform response example + + + + +

              transformResponse

              + +
              + +
              +
              + Created:
              + Updated:
              - - - + - - + return data; + }) + }) + .then(function (res) { + document.getElementById('useravatar').src = res.data.avatar_url; + document.getElementById('username').innerHTML = res.data.name; + document.getElementById('created').innerHTML = formatDate(res.data.created_at); + document.getElementById('updated').innerHTML = formatDate(res.data.updated_at); + }); + + + + \ No newline at end of file diff --git a/examples/upload/index.html b/examples/upload/index.html index c26b41fb..0b8ef84d 100644 --- a/examples/upload/index.html +++ b/examples/upload/index.html @@ -1,48 +1,53 @@ - - axios - file upload example - - - -

              file upload

              -
              -
              - - -
              - -
              + + axios - file upload example + + -
              + +

              file upload

              - - + - - + + axios.put('/upload/server', data, config) + .then(function (res) { + output.className = 'container'; + output.textContent = res.data; + }) + .catch(function (err) { + output.className = 'container text-danger'; + output.textContent = err.message; + }); + }; + })(); + + + + \ No newline at end of file diff --git a/examples/upload/server.js b/examples/upload/server.js index 3d365be9..91116a1c 100644 --- a/examples/upload/server.js +++ b/examples/upload/server.js @@ -1,8 +1,8 @@ export default function (req, res) { - let data = ''; + let _data = ''; req.on('data', function (chunk) { - data += chunk; + _data += chunk; }); req.on('end', function () { @@ -10,4 +10,4 @@ export default function (req, res) { res.writeHead(200); res.end(); }); -}; +} diff --git a/gulpfile.js b/gulpfile.js index 8c215a45..439b63e1 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,30 +1,23 @@ import gulp from 'gulp'; import fs from 'fs-extra'; import axios from './bin/githubAxios.js'; -import minimist from 'minimist' +import minimist from 'minimist'; const argv = minimist(process.argv.slice(2)); - gulp.task('default', async function(){ +gulp.task('default', async function () { console.log('hello!'); }); -const clear = gulp.task('clear', async function() { - await fs.emptyDir('./dist/') +const clear = gulp.task('clear', async function () { + await fs.emptyDir('./dist/'); }); const bower = gulp.task('bower', async function () { const npm = JSON.parse(await fs.readFile('package.json')); const bower = JSON.parse(await fs.readFile('bower.json')); - const fields = [ - 'name', - 'description', - 'version', - 'homepage', - 'license', - 'keywords' - ]; + const fields = ['name', 'description', 'version', 'homepage', 'license', 'keywords']; for (let i = 0, l = fields.length; i < l; i++) { const field = fields[i]; @@ -35,16 +28,23 @@ const bower = gulp.task('bower', async function () { }); async function getContributors(user, repo, maxCount = 1) { - const contributors = (await axios.get( - `https://api.github.com/repos/${encodeURIComponent(user)}/${encodeURIComponent(repo)}/contributors`, - { params: { per_page: maxCount } } - )).data; + const contributors = ( + await axios.get( + `https://api.github.com/repos/${encodeURIComponent(user)}/${encodeURIComponent(repo)}/contributors`, + { params: { per_page: maxCount } } + ) + ).data; - return Promise.all(contributors.map(async (contributor) => { - return {...contributor, ...(await axios.get( - `https://api.github.com/users/${encodeURIComponent(contributor.login)}` - )).data}; - })) + return Promise.all( + contributors.map(async (contributor) => { + return { + ...contributor, + ...( + await axios.get(`https://api.github.com/users/${encodeURIComponent(contributor.login)}`) + ).data, + }; + }) + ); } const packageJSON = gulp.task('package', async function () { @@ -57,9 +57,10 @@ const packageJSON = gulp.task('package', async function () { npm.contributors = contributors .filter( - ({type, contributions}) => type.toLowerCase() === 'user' && contributions >= CONTRIBUTION_THRESHOLD + ({ type, contributions }) => + type.toLowerCase() === 'user' && contributions >= CONTRIBUTION_THRESHOLD ) - .map(({login, name, url}) => `${name || login} (https://github.com/${login})`); + .map(({ login, name, _ }) => `${name || login} (https://github.com/${login})`); await fs.writeFile('package.json', JSON.stringify(npm, null, 2)); } catch (err) { @@ -75,19 +76,18 @@ const env = gulp.task('env', async function () { const envFilePath = './lib/env/data.js'; - await fs.writeFile(envFilePath, Object.entries({ - VERSION: (argv.bump || npm.version).replace(/^v/, '') - }).map(([key, value]) => { - return `export const ${key} = ${JSON.stringify(value)};` - }).join('\n')); + await fs.writeFile( + envFilePath, + Object.entries({ + VERSION: (argv.bump || npm.version).replace(/^v/, ''), + }) + .map(([key, value]) => { + return `export const ${key} = ${JSON.stringify(value)};`; + }) + .join('\n') + ); }); const version = gulp.series('bower', 'env', 'package'); -export { - bower, - env, - clear, - version, - packageJSON -} +export { bower, env, clear, version, packageJSON }; diff --git a/index.d.cts b/index.d.cts index 7a4eff94..4c953a02 100644 --- a/index.d.cts +++ b/index.d.cts @@ -2,30 +2,54 @@ interface RawAxiosHeaders { [key: string]: axios.AxiosHeaderValue; } -type MethodsHeaders = Partial<{ - [Key in axios.Method as Lowercase]: AxiosHeaders; -} & {common: AxiosHeaders}>; +type MethodsHeaders = Partial< + { + [Key in axios.Method as Lowercase]: AxiosHeaders; + } & { common: AxiosHeaders } +>; -type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean); +type AxiosHeaderMatcher = + | string + | RegExp + | ((this: AxiosHeaders, value: string, name: string) => boolean); type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any; -type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent'| 'Content-Encoding' | 'Authorization'; +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 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'; +type CommonResponseHeadersList = + | 'Server' + | 'Content-Type' + | 'Content-Length' + | 'Cache-Control' + | 'Content-Encoding'; type BrowserProgressEvent = any; declare class AxiosHeaders { - constructor( - headers?: RawAxiosHeaders | AxiosHeaders | string - ); + constructor(headers?: RawAxiosHeaders | AxiosHeaders | string); [key: string]: any; - set(headerName?: string, value?: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + 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; @@ -39,7 +63,9 @@ declare class AxiosHeaders { normalize(format: boolean): AxiosHeaders; - concat(...targets: Array): AxiosHeaders; + concat( + ...targets: Array + ): AxiosHeaders; toJSON(asStrings?: boolean): RawAxiosHeaders; @@ -47,14 +73,19 @@ declare class AxiosHeaders { static accessor(header: string | string[]): AxiosHeaders; - static concat(...targets: Array): AxiosHeaders; + static concat( + ...targets: Array + ): 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; + setContentLength( + value: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; getContentLength(parser?: RegExp): RegExpExecArray | null; getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; hasContentLength(matcher?: AxiosHeaderMatcher): boolean; @@ -69,12 +100,18 @@ declare class AxiosHeaders { getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; - setContentEncoding(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; + 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; + setAuthorization( + value: axios.AxiosHeaderValue, + rewrite?: boolean | AxiosHeaderMatcher + ): AxiosHeaders; getAuthorization(parser?: RegExp): RegExpExecArray | null; getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue; hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; @@ -86,11 +123,11 @@ declare class AxiosHeaders { declare class AxiosError extends Error { constructor( - message?: string, - code?: string, - config?: axios.InternalAxiosRequestConfig, - request?: any, - response?: axios.AxiosResponse + message?: string, + code?: string, + config?: axios.InternalAxiosRequestConfig, + request?: any, + response?: axios.AxiosResponse ); config?: axios.InternalAxiosRequestConfig; @@ -108,24 +145,23 @@ declare class AxiosError extends Error { config?: axios.InternalAxiosRequestConfig, request?: any, response?: axios.AxiosResponse, - customProps?: object, -): AxiosError; - 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"; + customProps?: object + ): AxiosError; + 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 extends AxiosError { -} +declare class CanceledError extends AxiosError {} declare class Axios { constructor(config?: axios.AxiosRequestConfig); @@ -135,17 +171,55 @@ declare class Axios { response: axios.AxiosInterceptorManager; }; getUri(config?: axios.AxiosRequestConfig): string; - request, D = any>(config: axios.AxiosRequestConfig): Promise; - get, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; - delete, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; - head, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; - options, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; - post, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; - put, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; - patch, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; - postForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; - putForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; - patchForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + request, D = any>( + config: axios.AxiosRequestConfig + ): Promise; + get, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + delete, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + head, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + options, D = any>( + url: string, + config?: axios.AxiosRequestConfig + ): Promise; + post, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + put, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + patch, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + postForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + putForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; + patchForm, D = any>( + url: string, + data?: D, + config?: axios.AxiosRequestConfig + ): Promise; } declare enum HttpStatusCode { @@ -219,11 +293,13 @@ type InternalAxiosError = AxiosError; declare namespace axios { type AxiosError = InternalAxiosError; - type RawAxiosRequestHeaders = Partial; + type RawAxiosRequestHeaders = Partial< + RawAxiosHeaders & { + [Key in CommonRequestHeadersList]: AxiosHeaderValue; + } & { + 'Content-Type': ContentType; + } + >; type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders; @@ -232,7 +308,7 @@ declare namespace axios { type RawCommonResponseHeaders = { [Key in CommonResponseHeadersList]: AxiosHeaderValue; } & { - "set-cookie": string[]; + 'set-cookie': string[]; }; type RawAxiosResponseHeaders = Partial; @@ -244,7 +320,12 @@ declare namespace axios { } interface AxiosResponseTransformer { - (this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any; + ( + this: InternalAxiosRequestConfig, + data: any, + headers: AxiosResponseHeaders, + status?: number + ): any; } interface AxiosAdapter { @@ -264,39 +345,54 @@ declare namespace axios { } type Method = - | 'get' | 'GET' - | 'delete' | 'DELETE' - | 'head' | 'HEAD' - | 'options' | 'OPTIONS' - | 'post' | 'POST' - | 'put' | 'PUT' - | 'patch' | 'PATCH' - | 'purge' | 'PURGE' - | 'link' | 'LINK' - | 'unlink' | 'UNLINK'; + | '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' - | 'formdata'; + type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata'; 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'; + | '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; @@ -320,11 +416,11 @@ declare namespace axios { interface SerializerVisitor { ( - this: GenericFormData, - value: any, - key: string | number, - path: null | Array, - helpers: FormDataVisitorHelpers + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers ): boolean; } @@ -336,8 +432,7 @@ declare namespace axios { } // tslint:disable-next-line - interface FormSerializerOptions extends SerializerOptions { - } + interface FormSerializerOptions extends SerializerOptions {} interface ParamEncoder { (value: any, defaultEncoder: (value: any) => any): any; @@ -411,7 +506,10 @@ declare namespace axios { maxBodyLength?: number; maxRedirects?: number; maxRate?: number | [MaxUploadRate, MaxDownloadRate]; - beforeRedirect?: (options: Record, responseDetails: {headers: Record, statusCode: HttpStatusCode}) => void; + beforeRedirect?: ( + options: Record, + responseDetails: { headers: Record; statusCode: HttpStatusCode } + ) => void; socketPath?: string | null; transport?: any; httpAgent?: any; @@ -427,16 +525,33 @@ declare namespace axios { fetch?: (input: URL | Request | string, init?: RequestInit) => Promise; Request?: new (input: URL | Request | string, init?: RequestInit) => Request; Response?: new ( - body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null, - init?: ResponseInit + body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null, + init?: ResponseInit ) => Response; }; 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>); + 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); - fetchOptions?: Omit | Record; + fetchOptions?: + | Omit + | Record; httpVersion?: 1 | 2; http2Options?: Record & { sessionTimeout?: number; @@ -472,11 +587,11 @@ declare namespace axios { headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial; } - interface AxiosResponse { + interface AxiosResponse { data: T; status: number; statusText: string; - headers: H & RawAxiosResponseHeaders | AxiosResponseHeaders; + headers: (H & RawAxiosResponseHeaders) | AxiosResponseHeaders; config: InternalAxiosRequestConfig; request?: any; } @@ -546,13 +661,16 @@ declare namespace axios { interface AxiosInstance extends Axios { , D = any>(config: AxiosRequestConfig): Promise; - , D = any>(url: string, config?: AxiosRequestConfig): Promise; + , D = any>( + url: string, + config?: AxiosRequestConfig + ): Promise; create(config?: CreateAxiosDefaults): AxiosInstance; defaults: Omit & { headers: HeadersDefaults & { - [key: string]: AxiosHeaderValue - } + [key: string]: AxiosHeaderValue; + }; }; } @@ -578,11 +696,18 @@ declare namespace axios { all(values: Array>): Promise; spread(callback: (...args: T[]) => R): (array: T[]) => R; isAxiosError(payload: any): payload is AxiosError; - toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; - formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + toFormData( + sourceObj: object, + targetFormData?: GenericFormData, + options?: FormSerializerOptions + ): GenericFormData; + formToJSON(form: GenericFormData | GenericHTMLFormElement): object; getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter; AxiosHeaders: typeof AxiosHeaders; - mergeConfig(config1: AxiosRequestConfig, config2: AxiosRequestConfig): AxiosRequestConfig; + mergeConfig( + config1: AxiosRequestConfig, + config2: AxiosRequestConfig + ): AxiosRequestConfig; } } diff --git a/index.js b/index.js index fba3990d..7dbe23b9 100644 --- a/index.js +++ b/index.js @@ -19,7 +19,7 @@ const { HttpStatusCode, formToJSON, getAdapter, - mergeConfig + mergeConfig, } = axios; export { @@ -39,5 +39,5 @@ export { HttpStatusCode, formToJSON, getAdapter, - mergeConfig -} + mergeConfig, +}; diff --git a/karma.conf.cjs b/karma.conf.cjs index 9e69f5e1..9f102319 100644 --- a/karma.conf.cjs +++ b/karma.conf.cjs @@ -14,11 +14,11 @@ function createCustomLauncher(browser, version, platform) { base: 'SauceLabs', browserName: browser, version: version, - platform: platform + platform: platform, }; } -module.exports = function(config) { +module.exports = function (config) { var customLaunchers = {}; var browsers = process.env.Browsers && process.env.Browsers.split(','); var sauceLabs; @@ -35,10 +35,10 @@ module.exports = function(config) { 'SAUCE_IE', 'SAUCE_EDGE', 'SAUCE_IOS', - 'SAUCE_ANDROID' + 'SAUCE_ANDROID', ]; - options.forEach(function(opt) { + options.forEach(function (opt) { if (process.env[opt]) { runAll = false; } @@ -62,21 +62,9 @@ module.exports = function(config) { if (runAll || process.env.SAUCE_SAFARI) { // customLaunchers.SL_Safari7 = createCustomLauncher('safari', 7); // customLaunchers.SL_Safari8 = createCustomLauncher('safari', 8); - customLaunchers.SL_Safari9 = createCustomLauncher( - 'safari', - 9.0, - 'OS X 10.11' - ); - customLaunchers.SL_Safari10 = createCustomLauncher( - 'safari', - '10.1', - 'macOS 10.12' - ); - customLaunchers.SL_Safari11 = createCustomLauncher( - 'safari', - '11.1', - 'macOS 10.13' - ); + customLaunchers.SL_Safari9 = createCustomLauncher('safari', 9.0, 'OS X 10.11'); + customLaunchers.SL_Safari10 = createCustomLauncher('safari', '10.1', 'macOS 10.12'); + customLaunchers.SL_Safari11 = createCustomLauncher('safari', '11.1', 'macOS 10.13'); } // Opera @@ -118,14 +106,14 @@ module.exports = function(config) { recordScreenshots: false, connectOptions: { // port: 5757, - logfile: 'sauce_connect.log' + logfile: 'sauce_connect.log', }, - public: 'public' + public: 'public', }; } else if (process.env.TRAVIS_PULL_REQUEST && process.env.TRAVIS_PULL_REQUEST !== 'false') { console.log( 'Cannot run on Sauce Labs as encrypted environment variables are not available to PRs. ' + - 'Running on Travis.' + 'Running on Travis.' ); browsers = ['Firefox']; } else if (process.env.GITHUB_ACTIONS === 'true') { @@ -133,50 +121,44 @@ module.exports = function(config) { browsers = ['FirefoxHeadless', 'ChromeHeadless']; } else { browsers = browsers || ['Chrome']; - console.log(`Running ${browsers} locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.`); + console.log( + `Running ${browsers} locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.` + ); } config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', - // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine-ajax', 'jasmine', 'sinon'], - // list of files / patterns to load in the browser files: [ - {pattern: 'test/specs/__helpers.js', watched: false}, - {pattern: 'test/specs/**/*.spec.js', watched: false} + { pattern: 'test/specs/__helpers.js', watched: false }, + { pattern: 'test/specs/**/*.spec.js', watched: false }, ], - // list of files to exclude exclude: [], - // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/specs/__helpers.js': ['rollup'], - 'test/specs/**/*.spec.js': ['rollup'] + 'test/specs/**/*.spec.js': ['rollup'], }, rollupPreprocessor: { - plugins: [ - resolve({browser: true}), - commonjs() - ], + plugins: [resolve({ browser: true }), commonjs()], output: { format: 'iife', name: '_axios', - sourcemap: 'inline' - } + sourcemap: 'inline', + }, }, - // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter @@ -184,36 +166,29 @@ module.exports = function(config) { // reporters: ['dots', 'coverage', 'saucelabs'], reporters: ['progress'], - // web server port port: 9876, - // Increase timeouts to prevent the issue with disconnected tests (https://goo.gl/nstA69) captureTimeout: 4 * 60 * 1000, browserDisconnectTimeout: 10000, browserDisconnectTolerance: 1, browserNoActivityTimeout: 4 * 60 * 1000, - // enable / disable colors in the output (reporters and logs) colors: true, - // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, - // enable / disable watching file and executing tests whenever any file changes autoWatch: false, - // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: browsers, - // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, @@ -225,26 +200,25 @@ module.exports = function(config) { devtool: 'inline-source-map', externals: [ { - './adapters/http': 'var undefined' - } - ] + './adapters/http': 'var undefined', + }, + ], }, webpackServer: { stats: { - colors: true - } + colors: true, + }, }, - // Coverage reporting coverageReporter: { type: 'lcov', dir: 'coverage/', - subdir: '.' + subdir: '.', }, sauceLabs: sauceLabs, - customLaunchers: customLaunchers + customLaunchers: customLaunchers, }); }; diff --git a/lib/adapters/README.md b/lib/adapters/README.md index 13afdc79..8d9dd97d 100644 --- a/lib/adapters/README.md +++ b/lib/adapters/README.md @@ -12,19 +12,18 @@ module.exports = function myAdapter(config) { // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run - + // Make the request using config provided // Upon response settle the Promise - return new Promise(function(resolve, reject) { - + return new Promise(function (resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, - request: request + request: request, }; settle(resolve, reject, response); @@ -33,5 +32,5 @@ module.exports = function myAdapter(config) { // - response transformers will run // - response interceptors will run }); -} +}; ``` diff --git a/lib/adapters/adapters.js b/lib/adapters/adapters.js index 2e117db3..5d18745a 100644 --- a/lib/adapters/adapters.js +++ b/lib/adapters/adapters.js @@ -2,7 +2,7 @@ import utils from '../utils.js'; import httpAdapter from './http.js'; import xhrAdapter from './xhr.js'; import * as fetchAdapter from './fetch.js'; -import AxiosError from "../core/AxiosError.js"; +import AxiosError from '../core/AxiosError.js'; /** * Known adapters mapping. @@ -10,7 +10,7 @@ import AxiosError from "../core/AxiosError.js"; * - `http` for Node.js * - `xhr` for browsers * - `fetch` for fetch API-based requests - * + * * @type {Object} */ const knownAdapters = { @@ -18,7 +18,7 @@ const knownAdapters = { xhr: xhrAdapter, fetch: { get: fetchAdapter.getFetch, - } + }, }; // Assign adapter names for easier debugging and identification @@ -35,7 +35,7 @@ utils.forEach(knownAdapters, (fn, value) => { /** * Render a rejection reason string for unknown or unsupported adapters - * + * * @param {string} reason * @returns {string} */ @@ -43,17 +43,18 @@ const renderReason = (reason) => `- ${reason}`; /** * Check if the adapter is resolved (function, null, or false) - * + * * @param {Function|null|false} adapter * @returns {boolean} */ -const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; +const isResolvedHandle = (adapter) => + utils.isFunction(adapter) || adapter === null || adapter === false; /** * Get the first suitable adapter from the provided list. * Tries each adapter in order until a supported one is found. * Throws an AxiosError if no adapter is suitable. - * + * * @param {Array|string|Function} adapters - Adapter(s) by name or function. * @param {Object} config - Axios request configuration * @throws {AxiosError} If no suitable adapter is available @@ -90,14 +91,17 @@ function getAdapter(adapters, config) { } if (!adapter) { - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + + 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'; + 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, @@ -122,5 +126,5 @@ export default { * Exposes all known adapters * @type {Object} */ - adapters: knownAdapters + adapters: knownAdapters, }; diff --git a/lib/adapters/fetch.js b/lib/adapters/fetch.js index db1795db..99dedbcc 100644 --- a/lib/adapters/fetch.js +++ b/lib/adapters/fetch.js @@ -1,40 +1,46 @@ -import platform from "../platform/index.js"; -import utils from "../utils.js"; -import AxiosError from "../core/AxiosError.js"; -import composeSignals from "../helpers/composeSignals.js"; -import {trackStream} from "../helpers/trackStream.js"; -import AxiosHeaders from "../core/AxiosHeaders.js"; -import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js"; -import resolveConfig from "../helpers/resolveConfig.js"; -import settle from "../core/settle.js"; +import platform from '../platform/index.js'; +import utils from '../utils.js'; +import AxiosError from '../core/AxiosError.js'; +import composeSignals from '../helpers/composeSignals.js'; +import { trackStream } from '../helpers/trackStream.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import { + progressEventReducer, + progressEventDecorator, + asyncDecorator, +} from '../helpers/progressEventReducer.js'; +import resolveConfig from '../helpers/resolveConfig.js'; +import settle from '../core/settle.js'; const DEFAULT_CHUNK_SIZE = 64 * 1024; -const {isFunction} = utils; +const { isFunction } = utils; -const globalFetchAPI = (({Request, Response}) => ({ - Request, Response +const globalFetchAPI = (({ Request, Response }) => ({ + Request, + Response, }))(utils.global); -const { - ReadableStream, TextEncoder -} = utils.global; - +const { ReadableStream, TextEncoder } = utils.global; const test = (fn, ...args) => { try { return !!fn(...args); } catch (e) { - return false + return false; } -} +}; const factory = (env) => { - env = utils.merge.call({ - skipUndefined: true - }, globalFetchAPI, env); + env = utils.merge.call( + { + skipUndefined: true, + }, + globalFetchAPI, + env + ); - const {fetch: envFetch, Request, Response} = env; + const { fetch: envFetch, Request, Response } = env; const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; const isRequestSupported = isFunction(Request); const isResponseSupported = isFunction(Response); @@ -45,46 +51,61 @@ const factory = (env) => { const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream); - const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? - ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : - async (str) => new Uint8Array(await new Request(str).arrayBuffer()) - ); + const encodeText = + isFetchSupported && + (typeof TextEncoder === 'function' + ? ( + (encoder) => (str) => + encoder.encode(str) + )(new TextEncoder()) + : async (str) => new Uint8Array(await new Request(str).arrayBuffer())); - const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { - let duplexAccessed = false; + const supportsRequestStream = + isRequestSupported && + isReadableStreamSupported && + test(() => { + let duplexAccessed = false; - const hasContentType = new Request(platform.origin, { - body: new ReadableStream(), - method: 'POST', - get duplex() { - duplexAccessed = true; - return 'half'; - }, - }).headers.has('Content-Type'); + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: 'POST', + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); - return duplexAccessed && !hasContentType; - }); + return duplexAccessed && !hasContentType; + }); - const supportsResponseStream = isResponseSupported && isReadableStreamSupported && + const supportsResponseStream = + isResponseSupported && + isReadableStreamSupported && test(() => utils.isReadableStream(new Response('').body)); const resolvers = { - stream: supportsResponseStream && ((res) => res.body) + stream: supportsResponseStream && ((res) => res.body), }; - isFetchSupported && ((() => { - ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { - !resolvers[type] && (resolvers[type] = (res, config) => { - let method = res && res[type]; + isFetchSupported && + (() => { + ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => { + !resolvers[type] && + (resolvers[type] = (res, config) => { + let method = res && res[type]; - if (method) { - return method.call(res); - } + if (method) { + return method.call(res); + } - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }) - }); - })()); + throw new AxiosError( + `Response type '${type}' is not supported`, + AxiosError.ERR_NOT_SUPPORT, + config + ); + }); + }); + })(); const getBodyLength = async (body) => { if (body == null) { @@ -114,13 +135,13 @@ const factory = (env) => { if (utils.isString(body)) { return (await encodeText(body)).byteLength; } - } + }; const resolveBodyLength = async (headers, body) => { const length = utils.toFiniteNumber(headers.getContentLength()); return length == null ? getBodyLength(body) : length; - } + }; return async (config) => { let { @@ -135,38 +156,47 @@ const factory = (env) => { responseType, headers, withCredentials = 'same-origin', - fetchOptions + fetchOptions, } = resolveConfig(config); let _fetch = envFetch || fetch; responseType = responseType ? (responseType + '').toLowerCase() : 'text'; - let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let composedSignal = composeSignals( + [signal, cancelToken && cancelToken.toAbortSignal()], + timeout + ); let request = null; - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); + const unsubscribe = + composedSignal && + composedSignal.unsubscribe && + (() => { + composedSignal.unsubscribe(); + }); let requestContentLength; try { if ( - onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && + onUploadProgress && + supportsRequestStream && + method !== 'get' && + method !== 'head' && (requestContentLength = await resolveBodyLength(headers, data)) !== 0 ) { let _request = new Request(url, { method: 'POST', body: data, - duplex: "half" + duplex: 'half', }); let contentTypeHeader; if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { - headers.setContentType(contentTypeHeader) + headers.setContentType(contentTypeHeader); } if (_request.body) { @@ -185,7 +215,7 @@ const factory = (env) => { // Cloudflare Workers throws when credentials are defined // see https://github.com/cloudflare/workerd/issues/902 - const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; + const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype; const resolvedOptions = { ...fetchOptions, @@ -193,29 +223,35 @@ const factory = (env) => { method: method.toUpperCase(), headers: headers.normalize().toJSON(), body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : undefined + duplex: 'half', + credentials: isCredentialsSupported ? withCredentials : undefined, }; request = isRequestSupported && new Request(url, resolvedOptions); - let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); + let response = await (isRequestSupported + ? _fetch(request, fetchOptions) + : _fetch(url, resolvedOptions)); - const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); + const isStreamResponse = + supportsResponseStream && (responseType === 'stream' || responseType === 'response'); if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { const options = {}; - ['status', 'statusText', 'headers'].forEach(prop => { + ['status', 'statusText', 'headers'].forEach((prop) => { options[prop] = response[prop]; }); const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length')); - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; + const [onProgress, flush] = + (onDownloadProgress && + progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + )) || + []; response = new Response( trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { @@ -228,7 +264,10 @@ const factory = (env) => { responseType = responseType || 'text'; - let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config); + let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text']( + response, + config + ); !isStreamResponse && unsubscribe && unsubscribe(); @@ -239,43 +278,50 @@ const factory = (env) => { status: response.status, statusText: response.statusText, config, - request - }) - }) + request, + }); + }); } catch (err) { unsubscribe && unsubscribe(); if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response), + new AxiosError( + 'Network Error', + AxiosError.ERR_NETWORK, + config, + request, + err && err.response + ), { - cause: err.cause || err + cause: err.cause || err, } - ) + ); } throw AxiosError.from(err, err && err.code, config, request, err && err.response); } - } -} + }; +}; const seedCache = new Map(); export const getFetch = (config) => { let env = (config && config.env) || {}; - const {fetch, Request, Response} = env; - const seeds = [ - Request, Response, fetch - ]; + const { fetch, Request, Response } = env; + const seeds = [Request, Response, fetch]; - let len = seeds.length, i = len, - seed, target, map = seedCache; + let len = seeds.length, + i = len, + seed, + target, + map = seedCache; while (i--) { seed = seeds[i]; target = map.get(seed); - target === undefined && map.set(seed, target = (i ? new Map() : factory(env))) + target === undefined && map.set(seed, (target = i ? new Map() : factory(env))); map = target; } diff --git a/lib/adapters/http.js b/lib/adapters/http.js index 6a8a05dd..20ba3cf8 100755 --- a/lib/adapters/http.js +++ b/lib/adapters/http.js @@ -9,7 +9,7 @@ import http2 from 'http2'; import util from 'util'; import followRedirects from 'follow-redirects'; import zlib from 'zlib'; -import {VERSION} from '../env/data.js'; +import { VERSION } from '../env/data.js'; import transitionalDefaults from '../defaults/transitional.js'; import AxiosError from '../core/AxiosError.js'; import CanceledError from '../cancel/CanceledError.js'; @@ -18,42 +18,43 @@ 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 { 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"; -import {progressEventReducer, progressEventDecorator, asyncDecorator} from "../helpers/progressEventReducer.js"; +import callbackify from '../helpers/callbackify.js'; +import { + progressEventReducer, + progressEventDecorator, + asyncDecorator, +} from '../helpers/progressEventReducer.js'; import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js'; const zlibOptions = { flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: 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 -} + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH, +}; const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress); -const {http: httpFollow, https: httpsFollow} = followRedirects; +const { http: httpFollow, https: httpsFollow } = followRedirects; const isHttps = /https:?/; -const supportedProtocols = platform.protocols.map(protocol => { +const supportedProtocols = platform.protocols.map((protocol) => { return protocol + ':'; }); - const flushOnFinish = (stream, [throttled, flush]) => { - stream - .on('end', flush) - .on('error', flush); + stream.on('end', flush).on('error', flush); return throttled; -} +}; class Http2Sessions { constructor() { @@ -61,9 +62,12 @@ class Http2Sessions { } getSession(authority, options) { - options = Object.assign({ - sessionTimeout: 1000 - }, options); + options = Object.assign( + { + sessionTimeout: 1000, + }, + options + ); let authoritySessions = this.sessions[authority]; @@ -72,7 +76,11 @@ class Http2Sessions { for (let i = 0; i < len; i++) { const [sessionHandle, sessionOptions] = authoritySessions[i]; - if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) { + if ( + !sessionHandle.destroyed && + !sessionHandle.closed && + util.isDeepStrictEqual(sessionOptions, options) + ) { return sessionHandle; } } @@ -89,7 +97,9 @@ class Http2Sessions { removed = true; - let entries = authoritySessions, len = entries.length, i = len; + let entries = authoritySessions, + len = entries.length, + i = len; while (i--) { if (entries[i][0] === session) { @@ -105,10 +115,9 @@ class Http2Sessions { const originalRequestFn = session.request; - const {sessionTimeout} = options; - - if(sessionTimeout != null) { + const { sessionTimeout } = options; + if (sessionTimeout != null) { let timer; let streamsCount = 0; @@ -132,17 +141,16 @@ class Http2Sessions { }); return stream; - } + }; } session.once('close', removeSession); - let entry = [ - session, - options - ]; + let entry = [session, options]; - authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry]; + authoritySessions + ? authoritySessions.push(entry) + : (authoritySessions = this.sessions[authority] = [entry]); return session; } @@ -150,7 +158,6 @@ class Http2Sessions { const http2Sessions = new Http2Sessions(); - /** * If the proxy or config beforeRedirects functions are defined, call them with the options * object. @@ -225,7 +232,8 @@ function setProxy(options, configProxy, location) { }; } -const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; +const isHttpAdapterSupported = + typeof process !== 'undefined' && utils.kindOf(process) === 'process'; // temporary hotfix @@ -238,7 +246,7 @@ const wrapAsync = (asyncExecutor) => { if (isDone) return; isDone = true; onDone && onDone(value, isRejected); - } + }; const _resolve = (value) => { done(value); @@ -248,651 +256,694 @@ const wrapAsync = (asyncExecutor) => { const _reject = (reason) => { done(reason, true); reject(reason); - } + }; asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); - }) + }); }; -const resolveFamily = ({address, family}) => { +const resolveFamily = ({ address, family }) => { if (!utils.isString(address)) { throw TypeError('address must be a string'); } - return ({ + return { address, - family: family || (address.indexOf('.') < 0 ? 6 : 4) - }); -} + family: family || (address.indexOf('.') < 0 ? 6 : 4), + }; +}; -const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family}); +const buildAddressEntry = (address, family) => + resolveFamily(utils.isObject(address) ? address : { address, family }); const http2Transport = { request(options, cb) { - const authority = options.protocol + '//' + options.hostname + ':' + (options.port ||(options.protocol === 'https:' ? 443 : 80)); + const authority = + options.protocol + + '//' + + options.hostname + + ':' + + (options.port || (options.protocol === 'https:' ? 443 : 80)); + const { http2Options, headers } = options; - const {http2Options, headers} = options; + const session = http2Sessions.getSession(authority, http2Options); - const session = http2Sessions.getSession(authority, http2Options); + const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = + http2.constants; - const { - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_STATUS - } = http2.constants; - - const http2Headers = { - [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), - [HTTP2_HEADER_METHOD]: options.method, - [HTTP2_HEADER_PATH]: options.path, - } - - utils.forEach(headers, (header, name) => { - name.charAt(0) !== ':' && (http2Headers[name] = header); - }); - - const req = session.request(http2Headers); - - req.once('response', (responseHeaders) => { - const response = req; //duplex - - responseHeaders = Object.assign({}, responseHeaders); - - const status = responseHeaders[HTTP2_HEADER_STATUS]; - - delete responseHeaders[HTTP2_HEADER_STATUS]; - - response.headers = responseHeaders; - - response.statusCode = +status; - - cb(response); - }) - - return req; - } -} - -/*eslint consistent-return:0*/ -export default isHttpAdapterSupported && function httpAdapter(config) { - return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let {data, lookup, family, httpVersion = 1, http2Options} = config; - const {responseType, responseEncoding} = config; - const method = config.method.toUpperCase(); - let isDone; - let rejected = false; - let req; - - httpVersion = +httpVersion; - - if (Number.isNaN(httpVersion)) { - throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); - } - - if (httpVersion !== 1 && httpVersion !== 2) { - throw TypeError(`Unsupported protocol version '${httpVersion}'`); - } - - const isHttp2 = httpVersion === 2; - - 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); - }); - } - } - - const abortEmitter = new EventEmitter(); - - function abort(reason) { - try { - abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); - } catch(err) { - console.warn('emit error', err); - } - } - - abortEmitter.once('abort', reject); - - const onFinished = () => { - if (config.cancelToken) { - config.cancelToken.unsubscribe(abort); - } - - if (config.signal) { - config.signal.removeEventListener('abort', abort); - } - - abortEmitter.removeAllListeners(); - } - - if (config.cancelToken || config.signal) { - config.cancelToken && config.cancelToken.subscribe(abort); - if (config.signal) { - config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); - } - } - - onDone((response, isRejected) => { - isDone = true; - - if (isRejected) { - rejected = true; - onFinished(); - return; - } - - const {data} = response; - - if (data instanceof stream.Readable || data instanceof stream.Duplex) { - const offListeners = stream.finished(data, () => { - offListeners(); - onFinished(); - }); - } else { - onFinished(); - } - }); - - - - - - // Parse url - const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); - const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); - const protocol = parsed.protocol || supportedProtocols[0]; - - if (protocol === 'data:') { - // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. - if (config.maxContentLength > -1) { - // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed. - const dataUrl = String(config.url || fullPath || ''); - const estimated = estimateDataURLDecodedBytes(dataUrl); - - if (estimated > config.maxContentLength) { - return reject(new AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, - config - )); - } - } - - 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(); - - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - // User-Agent is specified; handle case where no UA header is desired - // Only set header if it hasn't been set in config - headers.set('User-Agent', 'axios/' + VERSION, false); - - const {onUploadProgress, onDownloadProgress} = config; - 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) { - } - } - } else if (utils.isBlob(data) || utils.isFile(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 (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new AxiosError( - '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({ - maxRate: utils.toFiniteNumber(maxUploadRate) - })], utils.noop); - - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); - } - - // HTTP basic authentication - let auth = undefined; - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password || ''; - auth = username + ':' + password; - } - - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - 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); - } - - headers.set( - 'Accept-Encoding', - 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false - ); - - const options = { - path, - method: method, - headers: headers.toJSON(), - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {}, - http2Options + const http2Headers = { + [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), + [HTTP2_HEADER_METHOD]: options.method, + [HTTP2_HEADER_PATH]: options.path, }; - // cacheable-lookup integration hotfix - !utils.isUndefined(lookup) && (options.lookup = lookup); + utils.forEach(headers, (header, name) => { + name.charAt(0) !== ':' && (http2Headers[name] = header); + }); - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; - options.port = parsed.port; - setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } + const req = session.request(http2Headers); - let transport; - const isHttpsRequest = isHttps.test(options.protocol); - options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + req.once('response', (responseHeaders) => { + const response = req; //duplex - if (isHttp2) { - transport = http2Transport; - } else { - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsRequest ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirects.config = config.beforeRedirect; - } - transport = isHttpsRequest ? httpsFollow : httpFollow; - } - } + responseHeaders = Object.assign({}, responseHeaders); - 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; - } + const status = responseHeaders[HTTP2_HEADER_STATUS]; - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; - } + delete responseHeaders[HTTP2_HEADER_STATUS]; - // Create the request - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; + response.headers = responseHeaders; - const streams = [res]; + response.statusCode = +status; - const responseLength = utils.toFiniteNumber(res.headers['content-length']); + cb(response); + }); - if (onDownloadProgress || maxDownloadRate) { - const transformStream = new AxiosTransformStream({ - maxRate: utils.toFiniteNumber(maxDownloadRate) - }); + return req; + }, +}; - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); +/*eslint consistent-return:0*/ +export default isHttpAdapterSupported && + function httpAdapter(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family, httpVersion = 1, http2Options } = config; + const { responseType, responseEncoding } = config; + const method = config.method.toUpperCase(); + let isDone; + let rejected = false; + let req; - streams.push(transformStream); + httpVersion = +httpVersion; + + if (Number.isNaN(httpVersion)) { + throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); } - // decompress the response body transparently if required - let responseStream = res; + if (httpVersion !== 1 && httpVersion !== 2) { + throw TypeError(`Unsupported protocol version '${httpVersion}'`); + } - // return the last request in case of redirects - const lastRequest = res.req || req; + const isHttp2 = httpVersion === 2; - // 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']; - } + 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); + } - switch ((res.headers['content-encoding'] || '').toLowerCase()) { - /*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)); + const addresses = utils.isArray(arg0) + ? arg0.map((addr) => buildAddressEntry(addr)) + : [buildAddressEntry(arg0, arg1)]; - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'deflate': - streams.push(new ZlibHeaderTransformStream()); + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } - // add the unzipper to the body stream processing pipeline - streams.push(zlib.createUnzip(zlibOptions)); + const abortEmitter = new EventEmitter(); - // 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']; - } + function abort(reason) { + try { + abortEmitter.emit( + 'abort', + !reason || reason.type ? new CanceledError(null, config, req) : reason + ); + } catch (err) { + console.warn('emit error', err); } } - responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0]; + abortEmitter.once('abort', reject); + const onFinished = () => { + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + if (config.signal) { + config.signal.removeEventListener('abort', abort); + } - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new AxiosHeaders(res.headers), - config, - request: lastRequest + abortEmitter.removeAllListeners(); }; - if (responseType === 'stream') { - response.data = responseStream; - settle(resolve, reject, response); - } else { - const responseBuffer = []; - let totalResponseBytes = 0; + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } + } - responseStream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; + onDone((response, isRejected) => { + isDone = true; - // 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(); - abort(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + if (isRejected) { + rejected = true; + onFinished(); + return; + } + + const { data } = response; + + if (data instanceof stream.Readable || data instanceof stream.Duplex) { + const offListeners = stream.finished(data, () => { + offListeners(); + onFinished(); + }); + } else { + onFinished(); + } + }); + + // Parse url + const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); + const protocol = parsed.protocol || supportedProtocols[0]; + + if (protocol === 'data:') { + // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. + if (config.maxContentLength > -1) { + // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed. + const dataUrl = String(config.url || fullPath || ''); + const estimated = estimateDataURLDecodedBytes(dataUrl); + + if (estimated > config.maxContentLength) { + return reject( + new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config + ) + ); } - }); + } - responseStream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } + let convertedData; - const err = new AxiosError( - 'stream has been aborted', - AxiosError.ERR_BAD_RESPONSE, + if (method !== 'GET') { + return settle(resolve, reject, { + status: 405, + statusText: 'method not allowed', + headers: {}, config, - lastRequest - ); - responseStream.destroy(err); - reject(err); - }); + }); + } - responseStream.on('error', function handleStreamError(err) { - if (req.destroyed) return; - reject(AxiosError.from(err, null, config, lastRequest)); - }); + try { + convertedData = fromDataURI(config.url, responseType === 'blob', { + Blob: config.env && config.env.Blob, + }); + } catch (err) { + throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + } - 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') { - responseData = utils.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - return reject(AxiosError.from(err, null, config, response.request, response)); + if (responseType === 'text') { + convertedData = convertedData.toString(responseEncoding); + + if (!responseEncoding || responseEncoding === 'utf8') { + convertedData = utils.stripBOM(convertedData); } - settle(resolve, reject, response); + } else if (responseType === 'stream') { + convertedData = stream.Readable.from(convertedData); + } + + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: 'OK', + headers: new AxiosHeaders(), + config, }); } - abortEmitter.once('abort', err => { - if (!responseStream.destroyed) { - responseStream.emit('error', err); - responseStream.destroy(); - } - }); - }); + if (supportedProtocols.indexOf(protocol) === -1) { + return reject( + new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config) + ); + } - abortEmitter.once('abort', err => { - if (req.close) { - req.close(); + const headers = AxiosHeaders.from(config.headers).normalize(); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + // User-Agent is specified; handle case where no UA header is desired + // Only set header if it hasn't been set in config + headers.set('User-Agent', 'axios/' + VERSION, false); + + const { onUploadProgress, onDownloadProgress } = config; + 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) {} + } + } else if (utils.isBlob(data) || utils.isFile(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 (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject( + new AxiosError( + '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 { - req.destroy(err); - } - }); - - // Handle errors - req.on('error', function handleRequestError(err) { - 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); - }); - - // 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); - - if (Number.isNaN(timeout)) { - abort(new AxiosError( - 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); - - return; + maxUploadRate = maxDownloadRate = maxRate; } - // 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. - // 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; + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils.isStream(data)) { + data = stream.Readable.from(data, { objectMode: false }); } - abort(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + + data = stream.pipeline( + [ + data, + new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxUploadRate), + }), + ], + utils.noop + ); + + onUploadProgress && + data.on( + 'progress', + flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + ) + ); + } + + // HTTP basic authentication + let auth = undefined; + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password || ''; + auth = username + ':' + password; + } + + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + 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); + } + + headers.set( + 'Accept-Encoding', + 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), + false + ); + + const options = { + path, + method: method, + headers: headers.toJSON(), + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {}, + http2Options, + }; + + // cacheable-lookup integration hotfix + !utils.isUndefined(lookup) && (options.lookup = lookup); + + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname.startsWith('[') + ? parsed.hostname.slice(1, -1) + : 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; + + if (isHttp2) { + transport = http2Transport; + } else { + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? 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; + + const streams = [res]; + + const responseLength = utils.toFiniteNumber(res.headers['content-length']); + + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream({ + maxRate: utils.toFiniteNumber(maxDownloadRate), + }); + + onDownloadProgress && + transformStream.on( + 'progress', + flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + ) + ); + + streams.push(transformStream); + } + + // decompress the response body transparently if required + let responseStream = res; + + // return the last request in case of redirects + const 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()) { + /*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)); + + // 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 response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders(res.headers), config, - req - )); - }); - } else { - // explicitly reset the socket timeout value for a possible `keep-alive` request - req.setTimeout(0); - } + request: lastRequest, + }; + if (responseType === 'stream') { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; - // Send the request - if (utils.isStream(data)) { - let ended = false; - let errored = false; + responseStream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; - data.on('end', () => { - ended = true; + // 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(); + abort( + new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ) + ); + } + }); + + responseStream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + + const err = new AxiosError( + 'stream has been aborted', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + + 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') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + + abortEmitter.once('abort', (err) => { + if (!responseStream.destroyed) { + responseStream.emit('error', err); + responseStream.destroy(); + } + }); }); - 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)); + abortEmitter.once('abort', (err) => { + if (req.close) { + req.close(); + } else { + req.destroy(err); } }); - data.pipe(req); - } else { - data && req.write(data); - req.end(); - } - }); -} + // Handle errors + req.on('error', function handleRequestError(err) { + 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); + }); + + // 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); + + if (Number.isNaN(timeout)) { + abort( + new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + ) + ); + + return; + } + + // 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. + // 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; + } + abort( + new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + ) + ); + }); + } else { + // explicitly reset the socket timeout value for a possible `keep-alive` request + req.setTimeout(0); + } + + // 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); + } else { + data && req.write(data); + req.end(); + } + }); + }; export const __setProxy = setProxy; diff --git a/lib/adapters/xhr.js b/lib/adapters/xhr.js index dc573602..1d2c8375 100644 --- a/lib/adapters/xhr.js +++ b/lib/adapters/xhr.js @@ -6,195 +6,217 @@ 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 {progressEventReducer} from '../helpers/progressEventReducer.js'; -import resolveConfig from "../helpers/resolveConfig.js"; +import { progressEventReducer } from '../helpers/progressEventReducer.js'; +import resolveConfig from '../helpers/resolveConfig.js'; const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; -export default isXHRAdapterSupported && function (config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config); - let requestData = _config.data; - const requestHeaders = AxiosHeaders.from(_config.headers).normalize(); - let {responseType, onUploadProgress, onDownloadProgress} = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; +export default isXHRAdapterSupported && + function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config); + let requestData = _config.data; + const requestHeaders = AxiosHeaders.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events + function done() { + flushUpload && flushUpload(); // flush events + flushDownload && flushDownload(); // flush events - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); - _config.signal && _config.signal.removeEventListener('abort', onCanceled); - } - - let request = new XMLHttpRequest(); - - request.open(_config.method.toUpperCase(), _config.url, true); - - // Set the request timeout in MS - request.timeout = _config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - const responseHeaders = AxiosHeaders.from( - 'getAllResponseHeaders' in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; - - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - - // Clean up request - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } - - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; + _config.signal && _config.signal.removeEventListener('abort', onCanceled); } - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + let request = new XMLHttpRequest(); - // Clean up request - request = null; - }; + request.open(_config.method.toUpperCase(), _config.url, true); - // Handle low level network errors - request.onerror = function handleError(event) { - // Browsers deliver a ProgressEvent in XHR onerror - // (message may be empty; when present, surface it) - // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event - const msg = event && event.message ? event.message : 'Network Error'; - const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request); - // attach the underlying event for consumers who want details - err.event = event || null; - reject(err); - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - 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, - config, - request)); + // Set the request timeout in MS + request.timeout = _config.timeout; - // Clean up request - request = null; - }; - - // 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) { - request.setRequestHeader(key, val); - }); - } - - // Add withCredentials to request if needed - if (!utils.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; - } - - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = _config.responseType; - } - - // Handle progress if needed - if (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); - } - - // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); - - request.upload.addEventListener('progress', uploadThrottled); - - request.upload.addEventListener('loadend', flushUpload); - } - - if (_config.cancelToken || _config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = cancel => { + function onloadend() { if (!request) { return; } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); + // Prepare the response + const responseHeaders = AxiosHeaders.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = + !responseType || responseType === 'text' || responseType === 'json' + ? request.responseText + : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request, + }; + + settle( + function _resolve(value) { + resolve(value); + done(); + }, + function _reject(err) { + reject(err); + done(); + }, + response + ); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if ( + request.status === 0 && + !(request.responseURL && request.responseURL.indexOf('file:') === 0) + ) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request request = null; }; - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) { - _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); + // Handle low level network errors + request.onerror = function handleError(event) { + // Browsers deliver a ProgressEvent in XHR onerror + // (message may be empty; when present, surface it) + // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event + const msg = event && event.message ? event.message : 'Network Error'; + const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request); + // attach the underlying event for consumers who want details + err.event = event || null; + reject(err); + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + 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, + config, + request + ) + ); + + // Clean up request + request = null; + }; + + // 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) { + request.setRequestHeader(key, val); + }); } - } - const protocol = parseProtocol(_config.url); + // Add withCredentials to request if needed + if (!utils.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; - } + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = _config.responseType; + } + // Handle progress if needed + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + request.addEventListener('progress', downloadThrottled); + } - // Send the request - request.send(requestData || null); - }); -} + // Not all browsers support upload events + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); + + request.upload.addEventListener('progress', uploadThrottled); + + request.upload.addEventListener('loadend', flushUpload); + } + + if (_config.cancelToken || _config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted + ? onCanceled() + : _config.signal.addEventListener('abort', onCanceled); + } + } + + const protocol = parseProtocol(_config.url); + + 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); + }); + }; diff --git a/lib/axios.js b/lib/axios.js index 873f246d..5a3a876c 100644 --- a/lib/axios.js +++ b/lib/axios.js @@ -9,12 +9,12 @@ 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 { 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 AxiosHeaders from './core/AxiosHeaders.js'; import adapters from './adapters/adapters.js'; import HttpStatusCode from './helpers/HttpStatusCode.js'; @@ -30,10 +30,10 @@ function createInstance(defaultConfig) { const 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, { allOwnKeys: true }); // Copy context to instance - utils.extend(instance, context, null, {allOwnKeys: true}); + utils.extend(instance, context, null, { allOwnKeys: true }); // Factory for creating new instances instance.create = function create(instanceConfig) { @@ -77,7 +77,7 @@ axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders; -axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.formToJSON = (thing) => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = adapters.getAdapter; @@ -86,4 +86,4 @@ axios.HttpStatusCode = HttpStatusCode; axios.default = axios; // this module should only have a default export -export default axios +export default axios; diff --git a/lib/cancel/CancelToken.js b/lib/cancel/CancelToken.js index 0fc20252..357381ed 100644 --- a/lib/cancel/CancelToken.js +++ b/lib/cancel/CancelToken.js @@ -24,7 +24,7 @@ class CancelToken { const token = this; // eslint-disable-next-line func-names - this.promise.then(cancel => { + this.promise.then((cancel) => { if (!token._listeners) return; let i = token._listeners.length; @@ -36,10 +36,10 @@ class CancelToken { }); // eslint-disable-next-line func-names - this.promise.then = onfulfilled => { + this.promise.then = (onfulfilled) => { let _resolve; // eslint-disable-next-line func-names - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); @@ -127,7 +127,7 @@ class CancelToken { }); return { token, - cancel + cancel, }; } } diff --git a/lib/core/Axios.js b/lib/core/Axios.js index d3bbde03..149ed3fc 100644 --- a/lib/core/Axios.js +++ b/lib/core/Axios.js @@ -24,7 +24,7 @@ class Axios { this.defaults = instanceConfig || {}; this.interceptors = { request: new InterceptorManager(), - response: new InterceptorManager() + response: new InterceptorManager(), }; } @@ -52,7 +52,7 @@ class Axios { 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 + err.stack += '\n' + stack; } } catch (e) { // ignore the case where "stack" is an un-writable property @@ -75,27 +75,35 @@ class Axios { config = mergeConfig(this.defaults, config); - const {transitional, paramsSerializer, headers} = config; + const { transitional, paramsSerializer, headers } = config; if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean), - legacyInterceptorReqResOrdering: validators.transitional(validators.boolean) - }, false); + validator.assertOptions( + transitional, + { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean), + legacyInterceptorReqResOrdering: validators.transitional(validators.boolean), + }, + false + ); } if (paramsSerializer != null) { if (utils.isFunction(paramsSerializer)) { config.paramsSerializer = { - serialize: paramsSerializer - } + serialize: paramsSerializer, + }; } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); + validator.assertOptions( + paramsSerializer, + { + encode: validators.function, + serialize: validators.function, + }, + true + ); } } @@ -108,26 +116,25 @@ class Axios { config.allowAbsoluteUrls = true; } - validator.assertOptions(config, { - baseUrl: validators.spelling('baseURL'), - withXsrfToken: validators.spelling('withXSRFToken') - }, true); + validator.assertOptions( + config, + { + baseUrl: validators.spelling('baseURL'), + withXsrfToken: validators.spelling('withXSRFToken'), + }, + 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] - ); + let contextHeaders = headers && utils.merge(headers.common, headers[config.method]); - headers && utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { + headers && + utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => { delete headers[method]; - } - ); + }); config.headers = AxiosHeaders.concat(contextHeaders, headers); @@ -142,7 +149,8 @@ class Axios { synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; const transitional = config.transitional || transitionalDefaults; - const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering; + const legacyInterceptorReqResOrdering = + transitional && transitional.legacyInterceptorReqResOrdering; if (legacyInterceptorReqResOrdering) { requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); @@ -216,12 +224,14 @@ class Axios { // 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, - data: (config || {}).data - })); + Axios.prototype[method] = function (url, config) { + return this.request( + mergeConfig(config || {}, { + method, + url, + data: (config || {}).data, + }) + ); }; }); @@ -230,14 +240,18 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url, - data - })); + return this.request( + mergeConfig(config || {}, { + method, + headers: isForm + ? { + 'Content-Type': 'multipart/form-data', + } + : {}, + url, + data, + }) + ); }; } diff --git a/lib/core/AxiosError.js b/lib/core/AxiosError.js index 89de3dee..60818f2b 100644 --- a/lib/core/AxiosError.js +++ b/lib/core/AxiosError.js @@ -3,57 +3,57 @@ import utils from '../utils.js'; class AxiosError extends Error { - static from(error, code, config, request, response, customProps) { - const axiosError = new AxiosError(error.message, code || error.code, config, request, response); - axiosError.cause = error; - axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); - return axiosError; - } + static from(error, code, config, request, response, customProps) { + const axiosError = new AxiosError(error.message, code || error.code, config, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + } - /** - * 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. - */ - constructor(message, code, config, request, response) { - super(message); - this.name = 'AxiosError'; - this.isAxiosError = true; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status; - } + /** + * 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. + */ + constructor(message, code, config, request, response) { + super(message); + this.name = 'AxiosError'; + this.isAxiosError = true; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status; } + } - 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.status, - }; - } + 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.status, + }; + } } // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated. diff --git a/lib/core/AxiosHeaders.js b/lib/core/AxiosHeaders.js index 67445815..36f85122 100644 --- a/lib/core/AxiosHeaders.js +++ b/lib/core/AxiosHeaders.js @@ -52,8 +52,10 @@ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { } function formatHeader(header) { - return header.trim() - .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return header + .trim() + .toLowerCase() + .replace(/([a-z\d])(\w*)/g, (w, char, str) => { return char.toUpperCase() + str; }); } @@ -61,12 +63,12 @@ function formatHeader(header) { function buildAccessors(obj, header) { const accessorName = utils.toCamelCase(' ' + header); - ['get', 'set', 'has'].forEach(methodName => { + ['get', 'set', 'has'].forEach((methodName) => { Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { + value: function (arg1, arg2, arg3) { return this[methodName].call(this, header, arg1, arg2, arg3); }, - configurable: true + configurable: true, }); }); } @@ -88,7 +90,12 @@ class AxiosHeaders { const key = utils.findKey(self, lHeader); - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + if ( + !key || + self[key] === undefined || + _rewrite === true || + (_rewrite === undefined && self[key] !== false) + ) { self[key || _header] = normalizeValue(_value); } } @@ -97,21 +104,26 @@ class AxiosHeaders { 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(header, valueOrRewrite); + } else if (utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { setHeaders(parseHeaders(header), valueOrRewrite); } else if (utils.isObject(header) && utils.isIterable(header)) { - let obj = {}, dest, key; + let obj = {}, + dest, + key; for (const entry of header) { if (!utils.isArray(entry)) { throw TypeError('Object iterator must return a key-value pair'); } - obj[key = entry[0]] = (dest = obj[key]) ? - (utils.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1]; + obj[(key = entry[0])] = (dest = obj[key]) + ? utils.isArray(dest) + ? [...dest, entry[1]] + : [dest, entry[1]] + : entry[1]; } - setHeaders(obj, valueOrRewrite) + setHeaders(obj, valueOrRewrite); } else { header != null && setHeader(valueOrRewrite, header, rewrite); } @@ -155,7 +167,11 @@ class AxiosHeaders { if (header) { const key = utils.findKey(this, header); - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + return !!( + key && + this[key] !== undefined && + (!matcher || matchHeaderValue(this, this[key], key, matcher)) + ); } return false; @@ -195,7 +211,7 @@ class AxiosHeaders { while (i--) { const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { delete this[key]; deleted = true; } @@ -239,7 +255,9 @@ class AxiosHeaders { const obj = Object.create(null); utils.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + value != null && + value !== false && + (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); }); return obj; @@ -250,11 +268,13 @@ class AxiosHeaders { } toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + return Object.entries(this.toJSON()) + .map(([header, value]) => header + ': ' + value) + .join('\n'); } getSetCookie() { - return this.get("set-cookie") || []; + return this.get('set-cookie') || []; } get [Symbol.toStringTag]() { @@ -274,9 +294,12 @@ class AxiosHeaders { } static accessor(header) { - const internals = this[$internals] = (this[$internals] = { - accessors: {} - }); + const internals = + (this[$internals] = + this[$internals] = + { + accessors: {}, + }); const accessors = internals.accessors; const prototype = this.prototype; @@ -296,17 +319,24 @@ class AxiosHeaders { } } -AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); +AxiosHeaders.accessor([ + 'Content-Type', + 'Content-Length', + 'Accept', + 'Accept-Encoding', + 'User-Agent', + 'Authorization', +]); // reserved names hotfix -utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { +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); diff --git a/lib/core/InterceptorManager.js b/lib/core/InterceptorManager.js index 90d3610e..fe10f3d7 100644 --- a/lib/core/InterceptorManager.js +++ b/lib/core/InterceptorManager.js @@ -21,7 +21,7 @@ class InterceptorManager { fulfilled, rejected, synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null + runWhen: options ? options.runWhen : null, }); return this.handlers.length - 1; } diff --git a/lib/core/dispatchRequest.js b/lib/core/dispatchRequest.js index bdd07f8e..2015b549 100644 --- a/lib/core/dispatchRequest.js +++ b/lib/core/dispatchRequest.js @@ -5,7 +5,7 @@ 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"; +import adapters from '../adapters/adapters.js'; /** * Throws a `CanceledError` if cancellation has been requested. @@ -37,10 +37,7 @@ export default function dispatchRequest(config) { config.headers = AxiosHeaders.from(config.headers); // Transform request data - config.data = transformData.call( - config, - config.transformRequest - ); + config.data = transformData.call(config, config.transformRequest); if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { config.headers.setContentType('application/x-www-form-urlencoded', false); @@ -48,34 +45,33 @@ export default function dispatchRequest(config) { const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config); - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - config.transformResponse, - response - ); - - response.headers = AxiosHeaders.from(response.headers); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { + return adapter(config).then( + function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders.from(reason.response.headers); - } - } + response.data = transformData.call(config, config.transformResponse, response); - return Promise.reject(reason); - }); + response.headers = AxiosHeaders.from(response.headers); + + return response; + }, + function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders.from(reason.response.headers); + } + } + + return Promise.reject(reason); + } + ); } diff --git a/lib/core/mergeConfig.js b/lib/core/mergeConfig.js index de8e3941..38ac341f 100644 --- a/lib/core/mergeConfig.js +++ b/lib/core/mergeConfig.js @@ -1,10 +1,9 @@ -"use strict"; +'use strict'; -import utils from "../utils.js"; -import AxiosHeaders from "./AxiosHeaders.js"; +import utils from '../utils.js'; +import AxiosHeaders from './AxiosHeaders.js'; -const headersToObject = (thing) => - thing instanceof AxiosHeaders ? { ...thing } : thing; +const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing); /** * Config-specific merge-function which creates a new config-object @@ -97,23 +96,12 @@ export default function mergeConfig(config1, config2) { mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true), }; - utils.forEach( - Object.keys({ ...config1, ...config2 }), - function computeConfigValue(prop) { - if ( - prop === "__proto__" || - prop === "constructor" || - prop === "prototype" - ) - return; - const merge = utils.hasOwnProp(mergeMap, prop) - ? mergeMap[prop] - : mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || - (config[prop] = configValue); - }, - ); + utils.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) { + if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return; + const merge = utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); return config; } diff --git a/lib/core/settle.js b/lib/core/settle.js index ac905c43..8629ad05 100644 --- a/lib/core/settle.js +++ b/lib/core/settle.js @@ -16,12 +16,16 @@ export default function settle(resolve, reject, response) { if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); + reject( + new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][ + Math.floor(response.status / 100) - 4 + ], + response.config, + response.request, + response + ) + ); } } diff --git a/lib/defaults/index.js b/lib/defaults/index.js index cc14a8b3..b83c2c0b 100644 --- a/lib/defaults/index.js +++ b/lib/defaults/index.js @@ -34,96 +34,107 @@ function stringifySafely(rawValue, parser, encoder) { } const defaults = { - transitional: transitionalDefaults, adapter: ['xhr', 'http', 'fetch'], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils.isObject(data); + 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) || - utils.isReadableStream(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 (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); } - if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; + const isFormData = utils.isFormData(data); - return toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); + if (isFormData) { + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; } - } - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); - } + if ( + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) || + utils.isReadableStream(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(); + } - return data; - }], + let isFileList; - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } - if (utils.isResponse(data) || utils.isReadableStream(data)) { - return data; - } + if ( + (isFileList = utils.isFileList(data)) || + contentType.indexOf('multipart/form-data') > -1 + ) { + const _FormData = this.env && this.env.FormData; - if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - - try { - return JSON.parse(data, this.parseReviver); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; + return toFormData( + isFileList ? { 'files[]': data } : data, + _FormData && new _FormData(), + this.formSerializer + ); } } - } - return data; - }], + 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 (utils.isResponse(data) || utils.isReadableStream(data)) { + return data; + } + + if ( + data && + utils.isString(data) && + ((forcedJSONParsing && !this.responseType) || JSONRequested) + ) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data, this.parseReviver); + } 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 @@ -139,7 +150,7 @@ const defaults = { env: { FormData: platform.classes.FormData, - Blob: platform.classes.Blob + Blob: platform.classes.Blob, }, validateStatus: function validateStatus(status) { @@ -148,10 +159,10 @@ const defaults = { headers: { common: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': undefined - } - } + Accept: 'application/json, text/plain, */*', + 'Content-Type': undefined, + }, + }, }; utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { diff --git a/lib/defaults/transitional.js b/lib/defaults/transitional.js index 63d1c947..714b6644 100644 --- a/lib/defaults/transitional.js +++ b/lib/defaults/transitional.js @@ -4,5 +4,5 @@ export default { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false, - legacyInterceptorReqResOrdering: true + legacyInterceptorReqResOrdering: true, }; diff --git a/lib/env/data.js b/lib/env/data.js index 57083dcb..847a60d9 100644 --- a/lib/env/data.js +++ b/lib/env/data.js @@ -1 +1 @@ -export const VERSION = "1.13.5"; \ No newline at end of file +export const VERSION = '1.13.5'; diff --git a/lib/helpers/AxiosTransformStream.js b/lib/helpers/AxiosTransformStream.js index 41400712..96e8acb0 100644 --- a/lib/helpers/AxiosTransformStream.js +++ b/lib/helpers/AxiosTransformStream.js @@ -5,24 +5,29 @@ import utils from '../utils.js'; const kInternals = Symbol('internals'); -class AxiosTransformStream extends stream.Transform{ +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]); - }); + 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 + readableHighWaterMark: options.chunkSize, }); - const internals = this[kInternals] = { + const internals = (this[kInternals] = { timeWindow: options.timeWindow, chunkSize: options.chunkSize, maxRate: options.maxRate, @@ -32,10 +37,10 @@ class AxiosTransformStream extends stream.Transform{ notifiedBytesLoaded: 0, ts: Date.now(), bytes: 0, - onReadCallback: null - }; + onReadCallback: null, + }); - this.on('newListener', event => { + this.on('newListener', (event) => { if (event === 'progress') { if (!internals.isCaptured) { internals.isCaptured = true; @@ -63,8 +68,11 @@ class AxiosTransformStream extends stream.Transform{ 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; + const bytesThreshold = maxRate / divider; + const minChunkSize = + internals.minChunkSize !== false + ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) + : 0; const pushChunk = (_chunk, _callback) => { const bytes = Buffer.byteLength(_chunk); @@ -81,7 +89,7 @@ class AxiosTransformStream extends stream.Transform{ process.nextTick(_callback); }; } - } + }; const transformChunk = (_chunk, _callback) => { const chunkSize = Buffer.byteLength(_chunk); @@ -93,7 +101,7 @@ class AxiosTransformStream extends stream.Transform{ if (maxRate) { const now = Date.now(); - if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { internals.ts = now; bytesLeft = bytesThreshold - internals.bytes; internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; @@ -116,14 +124,19 @@ class AxiosTransformStream extends stream.Transform{ } } - if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { + 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); + pushChunk( + _chunk, + chunkRemainder + ? () => { + process.nextTick(_callback, null, chunkRemainder); + } + : _callback + ); }; transformChunk(chunk, function transformNextChunk(err, _chunk) { diff --git a/lib/helpers/AxiosURLSearchParams.js b/lib/helpers/AxiosURLSearchParams.js index b9aa9f02..da63392e 100644 --- a/lib/helpers/AxiosURLSearchParams.js +++ b/lib/helpers/AxiosURLSearchParams.js @@ -18,7 +18,7 @@ function encode(str) { ')': '%29', '~': '%7E', '%20': '+', - '%00': '\x00' + '%00': '\x00', }; return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { return charMap[match]; @@ -46,13 +46,17 @@ prototype.append = function append(name, value) { }; prototype.toString = function toString(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode); - } : encode; + 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('&'); + return this._pairs + .map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '') + .join('&'); }; export default AxiosURLSearchParams; diff --git a/lib/helpers/ZlibHeaderTransformStream.js b/lib/helpers/ZlibHeaderTransformStream.js index d1791f0b..c588dede 100644 --- a/lib/helpers/ZlibHeaderTransformStream.js +++ b/lib/helpers/ZlibHeaderTransformStream.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; -import stream from "stream"; +import stream from 'stream'; class ZlibHeaderTransformStream extends stream.Transform { __transform(chunk, encoding, callback) { @@ -13,10 +13,11 @@ class ZlibHeaderTransformStream extends stream.Transform { this._transform = this.__transform; // Add Default Compression headers if no zlib headers are present - if (chunk[0] !== 120) { // Hex: 78 + if (chunk[0] !== 120) { + // Hex: 78 const header = Buffer.alloc(2); header[0] = 120; // Hex: 78 - header[1] = 156; // Hex: 9C + header[1] = 156; // Hex: 9C this.push(header, encoding); } } diff --git a/lib/helpers/buildURL.js b/lib/helpers/buildURL.js index e1596656..f10e26c6 100644 --- a/lib/helpers/buildURL.js +++ b/lib/helpers/buildURL.js @@ -12,11 +12,11 @@ import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js'; * @returns {string} The encoded value. */ function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'); + return encodeURIComponent(val) + .replace(/%3A/gi, ':') + .replace(/%24/g, '$') + .replace(/%2C/gi, ',') + .replace(/%20/g, '+'); } /** @@ -33,11 +33,13 @@ export default function buildURL(url, params, options) { return url; } - const _encode = options && options.encode || encode; + const _encode = (options && options.encode) || encode; - const _options = utils.isFunction(options) ? { - serialize: options - } : options; + const _options = utils.isFunction(options) + ? { + serialize: options, + } + : options; const serializeFn = _options && _options.serialize; @@ -46,13 +48,13 @@ export default function buildURL(url, params, options) { if (serializeFn) { serializedParams = serializeFn(params, _options); } else { - serializedParams = utils.isURLSearchParams(params) ? - params.toString() : - new AxiosURLSearchParams(params, _options).toString(_encode); + serializedParams = utils.isURLSearchParams(params) + ? params.toString() + : new AxiosURLSearchParams(params, _options).toString(_encode); } if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); + const hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); diff --git a/lib/helpers/callbackify.js b/lib/helpers/callbackify.js index 4603badc..e8cea687 100644 --- a/lib/helpers/callbackify.js +++ b/lib/helpers/callbackify.js @@ -1,16 +1,18 @@ -import utils from "../utils.js"; +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); + 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); } - }, cb); - } : fn; -} + : fn; +}; export default callbackify; diff --git a/lib/helpers/composeSignals.js b/lib/helpers/composeSignals.js index cf27ddf5..04e3012d 100644 --- a/lib/helpers/composeSignals.js +++ b/lib/helpers/composeSignals.js @@ -1,9 +1,9 @@ -import CanceledError from "../cancel/CanceledError.js"; -import AxiosError from "../core/AxiosError.js"; +import CanceledError from '../cancel/CanceledError.js'; +import AxiosError from '../core/AxiosError.js'; import utils from '../utils.js'; const composeSignals = (signals, timeout) => { - const {length} = (signals = signals ? signals.filter(Boolean) : []); + const { length } = (signals = signals ? signals.filter(Boolean) : []); if (timeout || length) { let controller = new AbortController(); @@ -15,34 +15,42 @@ const composeSignals = (signals, timeout) => { aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); + controller.abort( + err instanceof AxiosError + ? err + : new CanceledError(err instanceof Error ? err.message : err) + ); } - } + }; - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT)) - }, timeout) + let timer = + timeout && + setTimeout(() => { + timer = null; + onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT)); + }, timeout); const unsubscribe = () => { if (signals) { timer && clearTimeout(timer); timer = null; - signals.forEach(signal => { - signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); + signals.forEach((signal) => { + signal.unsubscribe + ? signal.unsubscribe(onabort) + : signal.removeEventListener('abort', onabort); }); signals = null; } - } + }; signals.forEach((signal) => signal.addEventListener('abort', onabort)); - const {signal} = controller; + const { signal } = controller; signal.unsubscribe = () => utils.asap(unsubscribe); return signal; } -} +}; export default composeSignals; diff --git a/lib/helpers/cookies.js b/lib/helpers/cookies.js index 5c440d0e..1553fb29 100644 --- a/lib/helpers/cookies.js +++ b/lib/helpers/cookies.js @@ -1,53 +1,48 @@ import utils from '../utils.js'; import platform from '../platform/index.js'; -export default platform.hasStandardBrowserEnv ? +export default platform.hasStandardBrowserEnv + ? // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure, sameSite) { + if (typeof document === 'undefined') return; - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure, sameSite) { - if (typeof document === 'undefined') return; + const cookie = [`${name}=${encodeURIComponent(value)}`]; - const cookie = [`${name}=${encodeURIComponent(value)}`]; + if (utils.isNumber(expires)) { + cookie.push(`expires=${new Date(expires).toUTCString()}`); + } + if (utils.isString(path)) { + cookie.push(`path=${path}`); + } + if (utils.isString(domain)) { + cookie.push(`domain=${domain}`); + } + if (secure === true) { + cookie.push('secure'); + } + if (utils.isString(sameSite)) { + cookie.push(`SameSite=${sameSite}`); + } - if (utils.isNumber(expires)) { - cookie.push(`expires=${new Date(expires).toUTCString()}`); - } - if (utils.isString(path)) { - cookie.push(`path=${path}`); - } - if (utils.isString(domain)) { - cookie.push(`domain=${domain}`); - } - if (secure === true) { - cookie.push('secure'); - } - if (utils.isString(sameSite)) { - cookie.push(`SameSite=${sameSite}`); - } + document.cookie = cookie.join('; '); + }, - document.cookie = cookie.join('; '); - }, + read(name) { + if (typeof document === 'undefined') return null; + const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); + return match ? decodeURIComponent(match[1]) : null; + }, - read(name) { - if (typeof document === 'undefined') return null; - const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); - return match ? decodeURIComponent(match[1]) : null; - }, - - remove(name) { - this.write(name, '', Date.now() - 86400000, '/'); + 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. + { + write() {}, + read() { + return null; + }, + remove() {}, + }; diff --git a/lib/helpers/deprecatedMethod.js b/lib/helpers/deprecatedMethod.js index 9e8fae6b..ec112de2 100644 --- a/lib/helpers/deprecatedMethod.js +++ b/lib/helpers/deprecatedMethod.js @@ -15,12 +15,17 @@ export default function deprecatedMethod(method, instead, docs) { try { console.warn( - 'DEPRECATED method `' + method + '`.' + - (instead ? ' Use `' + instead + '` instead.' : '') + - ' This method will be removed in a future release.'); + 'DEPRECATED method `' + + method + + '`.' + + (instead ? ' Use `' + instead + '` instead.' : '') + + ' This method will be removed in a future release.' + ); if (docs) { console.warn('For more information about usage see ' + docs); } - } catch (e) { /* Ignore */ } + } catch (e) { + /* Ignore */ + } } diff --git a/lib/helpers/formDataToJSON.js b/lib/helpers/formDataToJSON.js index 906ce602..e8db891f 100644 --- a/lib/helpers/formDataToJSON.js +++ b/lib/helpers/formDataToJSON.js @@ -14,7 +14,7 @@ function parsePropPath(name) { // foo.x.y.z // foo-x-y-z // foo x y z - return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return utils.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { return match[0] === '[]' ? '' : match[1] || match[0]; }); } diff --git a/lib/helpers/formDataToStream.js b/lib/helpers/formDataToStream.js index afc61742..f191e8cb 100644 --- a/lib/helpers/formDataToStream.js +++ b/lib/helpers/formDataToStream.js @@ -1,8 +1,8 @@ import util from 'util'; -import {Readable} from 'stream'; -import utils from "../utils.js"; -import readBlob from "./readBlob.js"; -import platform from "../platform/index.js"; +import { Readable } from 'stream'; +import utils from '../utils.js'; +import readBlob from './readBlob.js'; +import platform from '../platform/index.js'; const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_'; @@ -14,7 +14,7 @@ const CRLF_BYTES_COUNT = 2; class FormDataPart { constructor(name, value) { - const {escapeName} = this.constructor; + const { escapeName } = this.constructor; const isStringValue = utils.isString(value); let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ @@ -24,7 +24,7 @@ class FormDataPart { if (isStringValue) { value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}` + headers += `Content-Type: ${value.type || 'application/octet-stream'}${CRLF}`; } this.headers = textEncoder.encode(headers + CRLF); @@ -37,12 +37,12 @@ class FormDataPart { this.value = value; } - async *encode(){ + async *encode() { yield this.headers; - const {value} = this; + const { value } = this; - if(utils.isTypedArray(value)) { + if (utils.isTypedArray(value)) { yield value; } else { yield* readBlob(value); @@ -52,11 +52,15 @@ class FormDataPart { } static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - '\r' : '%0D', - '\n' : '%0A', - '"' : '%22', - }[match])); + return String(name).replace( + /[\r\n"]/g, + (match) => + ({ + '\r': '%0D', + '\n': '%0A', + '"': '%22', + })[match] + ); } } @@ -64,15 +68,15 @@ const formDataToStream = (form, headersHandler, options) => { const { tag = 'form-data-boundary', size = 25, - boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET) + boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET), } = options || {}; - if(!utils.isFormData(form)) { + 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') + throw Error('boundary must be 10-70 characters long'); } const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); @@ -90,8 +94,8 @@ const formDataToStream = (form, headersHandler, options) => { contentLength = utils.toFiniteNumber(contentLength); const computedHeaders = { - 'Content-Type': `multipart/form-data; boundary=${boundary}` - } + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + }; if (Number.isFinite(contentLength)) { computedHeaders['Content-Length'] = contentLength; @@ -99,14 +103,16 @@ const formDataToStream = (form, headersHandler, options) => { headersHandler && headersHandler(computedHeaders); - return Readable.from((async function *() { - for(const part of parts) { - yield boundaryBytes; - yield* part.encode(); - } + return Readable.from( + (async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } - yield footerBytes; - })()); + yield footerBytes; + })() + ); }; export default formDataToStream; diff --git a/lib/helpers/fromDataURI.js b/lib/helpers/fromDataURI.js index eb71d3f3..989a4178 100644 --- a/lib/helpers/fromDataURI.js +++ b/lib/helpers/fromDataURI.js @@ -17,7 +17,7 @@ const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; * @returns {Buffer|Blob} */ export default function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || platform.classes.Blob; + const _Blob = (options && options.Blob) || platform.classes.Blob; const protocol = parseProtocol(uri); if (asBlob === undefined && _Blob) { @@ -43,7 +43,7 @@ export default function fromDataURI(uri, asBlob, options) { throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); } - return new _Blob([buffer], {type: mime}); + return new _Blob([buffer], { type: mime }); } return buffer; diff --git a/lib/helpers/isAbsoluteURL.js b/lib/helpers/isAbsoluteURL.js index d8b4e59c..c4619002 100644 --- a/lib/helpers/isAbsoluteURL.js +++ b/lib/helpers/isAbsoluteURL.js @@ -17,4 +17,3 @@ export default function isAbsoluteURL(url) { return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } - diff --git a/lib/helpers/isAxiosError.js b/lib/helpers/isAxiosError.js index a174314a..ffba6101 100644 --- a/lib/helpers/isAxiosError.js +++ b/lib/helpers/isAxiosError.js @@ -10,5 +10,5 @@ import utils from '../utils.js'; * @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); + return utils.isObject(payload) && payload.isAxiosError === true; } diff --git a/lib/helpers/isURLSameOrigin.js b/lib/helpers/isURLSameOrigin.js index 6a92aa15..66af2743 100644 --- a/lib/helpers/isURLSameOrigin.js +++ b/lib/helpers/isURLSameOrigin.js @@ -1,14 +1,16 @@ import platform from '../platform/index.js'; -export default platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { - url = new URL(url, platform.origin); +export default platform.hasStandardBrowserEnv + ? ((origin, isMSIE) => (url) => { + url = new URL(url, platform.origin); - return ( - origin.protocol === url.protocol && - origin.host === url.host && - (isMSIE || origin.port === url.port) - ); -})( - new URL(platform.origin), - platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) -) : () => true; + return ( + origin.protocol === url.protocol && + origin.host === url.host && + (isMSIE || origin.port === url.port) + ); + })( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) + ) + : () => true; diff --git a/lib/helpers/parseHeaders.js b/lib/helpers/parseHeaders.js index b4c3cad4..fb0eba44 100644 --- a/lib/helpers/parseHeaders.js +++ b/lib/helpers/parseHeaders.js @@ -5,10 +5,23 @@ import utils from '../utils.js'; // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers const ignoreDuplicateOf = utils.toObjectSet([ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' + 'age', + 'authorization', + 'content-length', + 'content-type', + 'etag', + 'expires', + 'from', + 'host', + 'if-modified-since', + 'if-unmodified-since', + 'last-modified', + 'location', + 'max-forwards', + 'proxy-authorization', + 'referer', + 'retry-after', + 'user-agent', ]); /** @@ -25,31 +38,32 @@ const ignoreDuplicateOf = utils.toObjectSet([ * * @returns {Object} Headers parsed into an object */ -export default rawHeaders => { +export default (rawHeaders) => { const parsed = {}; let key; let val; let i; - rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { - i = line.indexOf(':'); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); + rawHeaders && + rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { - return; - } - - if (key === 'set-cookie') { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; } - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - }); + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); return parsed; }; diff --git a/lib/helpers/parseProtocol.js b/lib/helpers/parseProtocol.js index 586ec964..1ad6658c 100644 --- a/lib/helpers/parseProtocol.js +++ b/lib/helpers/parseProtocol.js @@ -2,5 +2,5 @@ export default function parseProtocol(url) { const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; + return (match && match[1]) || ''; } diff --git a/lib/helpers/progressEventReducer.js b/lib/helpers/progressEventReducer.js index ff601cc4..d09d753c 100644 --- a/lib/helpers/progressEventReducer.js +++ b/lib/helpers/progressEventReducer.js @@ -1,12 +1,12 @@ -import speedometer from "./speedometer.js"; -import throttle from "./throttle.js"; -import utils from "../utils.js"; +import speedometer from './speedometer.js'; +import throttle from './throttle.js'; +import utils from '../utils.js'; export const progressEventReducer = (listener, isDownloadStream, freq = 3) => { let bytesNotified = 0; const _speedometer = speedometer(50, 250); - return throttle(e => { + return throttle((e) => { const loaded = e.loaded; const total = e.lengthComputable ? e.total : undefined; const progressBytes = loaded - bytesNotified; @@ -18,27 +18,34 @@ export const progressEventReducer = (listener, isDownloadStream, freq = 3) => { const data = { loaded, total, - progress: total ? (loaded / total) : undefined, + progress: total ? loaded / total : undefined, bytes: progressBytes, rate: rate ? rate : undefined, estimated: rate && total && inRange ? (total - loaded) / rate : undefined, event: e, lengthComputable: total != null, - [isDownloadStream ? 'download' : 'upload']: true + [isDownloadStream ? 'download' : 'upload']: true, }; listener(data); }, freq); -} +}; export const progressEventDecorator = (total, throttled) => { const lengthComputable = total != null; - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; -} + return [ + (loaded) => + throttled[0]({ + lengthComputable, + total, + loaded, + }), + throttled[1], + ]; +}; -export const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args)); +export const asyncDecorator = + (fn) => + (...args) => + utils.asap(() => fn(...args)); diff --git a/lib/helpers/readBlob.js b/lib/helpers/readBlob.js index 6de748e8..87d0ea8d 100644 --- a/lib/helpers/readBlob.js +++ b/lib/helpers/readBlob.js @@ -1,15 +1,15 @@ -const {asyncIterator} = Symbol; +const { asyncIterator } = Symbol; const readBlob = async function* (blob) { if (blob.stream) { - yield* blob.stream() + yield* blob.stream(); } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer() + yield await blob.arrayBuffer(); } else if (blob[asyncIterator]) { yield* blob[asyncIterator](); } else { yield blob; } -} +}; export default readBlob; diff --git a/lib/helpers/resolveConfig.js b/lib/helpers/resolveConfig.js index 26bce9d7..bf22d591 100644 --- a/lib/helpers/resolveConfig.js +++ b/lib/helpers/resolveConfig.js @@ -1,11 +1,11 @@ -import platform from "../platform/index.js"; -import utils from "../utils.js"; -import isURLSameOrigin from "./isURLSameOrigin.js"; -import cookies from "./cookies.js"; -import buildFullPath from "../core/buildFullPath.js"; -import mergeConfig from "../core/mergeConfig.js"; -import AxiosHeaders from "../core/AxiosHeaders.js"; -import buildURL from "./buildURL.js"; +import platform from '../platform/index.js'; +import utils from '../utils.js'; +import isURLSameOrigin from './isURLSameOrigin.js'; +import cookies from './cookies.js'; +import buildFullPath from '../core/buildFullPath.js'; +import mergeConfig from '../core/mergeConfig.js'; +import AxiosHeaders from '../core/AxiosHeaders.js'; +import buildURL from './buildURL.js'; export default (config) => { const newConfig = mergeConfig({}, config); @@ -14,12 +14,22 @@ export default (config) => { newConfig.headers = headers = AxiosHeaders.from(headers); - newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer); + newConfig.url = buildURL( + buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), + config.params, + config.paramsSerializer + ); // HTTP basic authentication if (auth) { - headers.set('Authorization', 'Basic ' + - btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + headers.set( + 'Authorization', + 'Basic ' + + btoa( + (auth.username || '') + + ':' + + (auth.password ? unescape(encodeURIComponent(auth.password)) : '') + ) ); } @@ -37,7 +47,7 @@ export default (config) => { } }); } - } + } // Add xsrf header // This is only done if running in a standard browser environment. @@ -57,5 +67,4 @@ export default (config) => { } return newConfig; -} - +}; diff --git a/lib/helpers/speedometer.js b/lib/helpers/speedometer.js index 3b3c6662..566a1fff 100644 --- a/lib/helpers/speedometer.js +++ b/lib/helpers/speedometer.js @@ -48,7 +48,7 @@ function speedometer(samplesCount, min) { const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + return passed ? Math.round((bytesCount * 1000) / passed) : undefined; }; } diff --git a/lib/helpers/throttle.js b/lib/helpers/throttle.js index 73e263d1..fbef472c 100644 --- a/lib/helpers/throttle.js +++ b/lib/helpers/throttle.js @@ -18,23 +18,23 @@ function throttle(fn, freq) { timer = null; } fn(...args); - } + }; const throttled = (...args) => { const now = Date.now(); const passed = now - timestamp; - if ( passed >= threshold) { + if (passed >= threshold) { invoke(args, now); } else { lastArgs = args; if (!timer) { timer = setTimeout(() => { timer = null; - invoke(lastArgs) + invoke(lastArgs); }, threshold - passed); } } - } + }; const flush = () => lastArgs && invoke(lastArgs); diff --git a/lib/helpers/toFormData.js b/lib/helpers/toFormData.js index ec47d8ce..5a503cfe 100644 --- a/lib/helpers/toFormData.js +++ b/lib/helpers/toFormData.js @@ -38,11 +38,14 @@ function removeBrackets(key) { */ function renderKey(path, key, dots) { if (!path) return key; - return path.concat(key).map(function each(token, i) { - // eslint-disable-next-line no-param-reassign - token = removeBrackets(token); - return !dots && i ? '[' + token + ']' : token; - }).join(dots ? '.' : ''); + return path + .concat(key) + .map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }) + .join(dots ? '.' : ''); } /** @@ -92,21 +95,26 @@ function toFormData(obj, formData, options) { formData = formData || new (PlatformFormData || FormData)(); // eslint-disable-next-line no-param-reassign - options = utils.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils.isUndefined(source[option]); - }); + options = utils.toFlatObject( + options, + { + metaTokens: true, + dots: false, + indexes: false, + }, + false, + function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + } + ); const metaTokens = options.metaTokens; // eslint-disable-next-line no-use-before-define const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob); const useBlob = _Blob && utils.isSpecCompliantForm(formData); if (!utils.isFunction(visitor)) { @@ -156,17 +164,22 @@ function toFormData(obj, formData, options) { value = JSON.stringify(value); } else if ( (utils.isArray(value) && isFlatArray(value)) || - ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) - )) { + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))) + ) { // eslint-disable-next-line no-param-reassign key = removeBrackets(key); arr.forEach(function each(el, index) { - !(utils.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), - convertValue(el) - ); + !(utils.isUndefined(el) || el === null) && + formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true + ? renderKey([key], index, dots) + : indexes === null + ? key + : key + '[]', + convertValue(el) + ); }); return false; } @@ -186,7 +199,7 @@ function toFormData(obj, formData, options) { const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, - isVisitable + isVisitable, }); function build(value, path) { @@ -199,9 +212,9 @@ function toFormData(obj, formData, options) { stack.push(value); utils.forEach(value, function each(el, key) { - const result = !(utils.isUndefined(el) || el === null) && visitor.call( - formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers - ); + const result = + !(utils.isUndefined(el) || el === null) && + visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers); if (result === true) { build(el, path ? path.concat(key) : [key]); diff --git a/lib/helpers/toURLEncodedForm.js b/lib/helpers/toURLEncodedForm.js index ffa95ec9..749e13a6 100644 --- a/lib/helpers/toURLEncodedForm.js +++ b/lib/helpers/toURLEncodedForm.js @@ -6,7 +6,7 @@ import platform from '../platform/index.js'; export default function toURLEncodedForm(data, options) { return toFormData(data, new platform.classes.URLSearchParams(), { - visitor: function(value, key, path, helpers) { + visitor: function (value, key, path, helpers) { if (platform.isNode && utils.isBuffer(value)) { this.append(key, value.toString('base64')); return false; @@ -14,6 +14,6 @@ export default function toURLEncodedForm(data, options) { return helpers.defaultVisitor.apply(this, arguments); }, - ...options + ...options, }); } diff --git a/lib/helpers/trackStream.js b/lib/helpers/trackStream.js index 95d60081..c75eace5 100644 --- a/lib/helpers/trackStream.js +++ b/lib/helpers/trackStream.js @@ -1,4 +1,3 @@ - export const streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; @@ -15,13 +14,13 @@ export const streamChunk = function* (chunk, chunkSize) { yield chunk.slice(pos, end); pos = end; } -} +}; export const readBytes = async function* (iterable, chunkSize) { for await (const chunk of readStream(iterable)) { yield* streamChunk(chunk, chunkSize); } -} +}; const readStream = async function* (stream) { if (stream[Symbol.asyncIterator]) { @@ -32,7 +31,7 @@ const readStream = async function* (stream) { const reader = stream.getReader(); try { for (;;) { - const {done, value} = await reader.read(); + const { done, value } = await reader.read(); if (done) { break; } @@ -41,7 +40,7 @@ const readStream = async function* (stream) { } finally { await reader.cancel(); } -} +}; export const trackStream = (stream, chunkSize, onProgress, onFinish) => { const iterator = readBytes(stream, chunkSize); @@ -53,35 +52,38 @@ export const trackStream = (stream, chunkSize, onProgress, onFinish) => { done = true; onFinish && onFinish(e); } - } + }; - return new ReadableStream({ - async pull(controller) { - try { - const {done, value} = await iterator.next(); + return new ReadableStream( + { + async pull(controller) { + try { + const { done, value } = await iterator.next(); - if (done) { - _onFinish(); - controller.close(); - return; + if (done) { + _onFinish(); + controller.close(); + return; + } + + let len = value.byteLength; + if (onProgress) { + let loadedBytes = (bytes += len); + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; } - - let len = value.byteLength; - if (onProgress) { - let loadedBytes = bytes += len; - onProgress(loadedBytes); - } - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; - } + }, + cancel(reason) { + _onFinish(reason); + return iterator.return(); + }, }, - cancel(reason) { - _onFinish(reason); - return iterator.return(); + { + highWaterMark: 2, } - }, { - highWaterMark: 2 - }) -} + ); +}; diff --git a/lib/helpers/validator.js b/lib/helpers/validator.js index 12705687..22798aa9 100644 --- a/lib/helpers/validator.js +++ b/lib/helpers/validator.js @@ -1,6 +1,6 @@ 'use strict'; -import {VERSION} from '../env/data.js'; +import { VERSION } from '../env/data.js'; import AxiosError from '../core/AxiosError.js'; const validators = {}; @@ -25,7 +25,15 @@ const deprecatedWarnings = {}; */ validators.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + return ( + '[Axios v' + + VERSION + + "] Transitional option '" + + opt + + "'" + + desc + + (message ? '. ' + message : '') + ); } // eslint-disable-next-line func-names @@ -57,7 +65,7 @@ validators.spelling = function spelling(correctSpelling) { // eslint-disable-next-line no-console console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); return true; - } + }; }; /** @@ -83,7 +91,10 @@ function assertOptions(options, schema, allowUnknown) { const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + throw new AxiosError( + 'option ' + opt + ' must be ' + result, + AxiosError.ERR_BAD_OPTION_VALUE + ); } continue; } @@ -95,5 +106,5 @@ function assertOptions(options, schema, allowUnknown) { export default { assertOptions, - validators + validators, }; diff --git a/lib/platform/browser/classes/Blob.js b/lib/platform/browser/classes/Blob.js index 6c506c48..9ec4af87 100644 --- a/lib/platform/browser/classes/Blob.js +++ b/lib/platform/browser/classes/Blob.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -export default typeof Blob !== 'undefined' ? Blob : null +export default typeof Blob !== 'undefined' ? Blob : null; diff --git a/lib/platform/browser/index.js b/lib/platform/browser/index.js index 08c206f3..8e5f99cf 100644 --- a/lib/platform/browser/index.js +++ b/lib/platform/browser/index.js @@ -1,13 +1,13 @@ -import URLSearchParams from './classes/URLSearchParams.js' -import FormData from './classes/FormData.js' -import Blob from './classes/Blob.js' +import URLSearchParams from './classes/URLSearchParams.js'; +import FormData from './classes/FormData.js'; +import Blob from './classes/Blob.js'; export default { isBrowser: true, classes: { URLSearchParams, FormData, - Blob + Blob, }, - protocols: ['http', 'https', 'file', 'blob', 'url', 'data'] + protocols: ['http', 'https', 'file', 'blob', 'url', 'data'], }; diff --git a/lib/platform/common/utils.js b/lib/platform/common/utils.js index 52a3186e..e4dfe469 100644 --- a/lib/platform/common/utils.js +++ b/lib/platform/common/utils.js @@ -1,6 +1,6 @@ const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; -const _navigator = typeof navigator === 'object' && navigator || undefined; +const _navigator = (typeof navigator === 'object' && navigator) || undefined; /** * Determine if we're running in a standard browser environment @@ -19,7 +19,8 @@ const _navigator = typeof navigator === 'object' && navigator || undefined; * * @returns {boolean} */ -const hasStandardBrowserEnv = hasBrowserEnv && +const hasStandardBrowserEnv = + hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); /** @@ -40,12 +41,12 @@ const hasStandardBrowserWebWorkerEnv = (() => { ); })(); -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; +const origin = (hasBrowserEnv && window.location.href) || 'http://localhost'; export { hasBrowserEnv, hasStandardBrowserWebWorkerEnv, hasStandardBrowserEnv, _navigator as navigator, - origin -} + origin, +}; diff --git a/lib/platform/index.js b/lib/platform/index.js index 860ba21a..e1094abf 100644 --- a/lib/platform/index.js +++ b/lib/platform/index.js @@ -3,5 +3,5 @@ import * as utils from './common/utils.js'; export default { ...utils, - ...platform -} + ...platform, +}; diff --git a/lib/platform/node/index.js b/lib/platform/node/index.js index cd1ca0c4..9979a715 100644 --- a/lib/platform/node/index.js +++ b/lib/platform/node/index.js @@ -1,20 +1,20 @@ import crypto from 'crypto'; -import URLSearchParams from './classes/URLSearchParams.js' -import FormData from './classes/FormData.js' +import URLSearchParams from './classes/URLSearchParams.js'; +import FormData from './classes/FormData.js'; -const ALPHA = 'abcdefghijklmnopqrstuvwxyz' +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; const DIGIT = '0123456789'; const ALPHABET = { DIGIT, ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -} + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT, +}; const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { let str = ''; - const {length} = alphabet; + const { length } = alphabet; const randomValues = new Uint32Array(size); crypto.randomFillSync(randomValues); for (let i = 0; i < size; i++) { @@ -22,17 +22,16 @@ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { } return str; -} - +}; export default { isNode: true, classes: { URLSearchParams, FormData, - Blob: typeof Blob !== 'undefined' && Blob || null + Blob: (typeof Blob !== 'undefined' && Blob) || null, }, ALPHABET, generateString, - protocols: [ 'http', 'https', 'file', 'data' ] + protocols: ['http', 'https', 'file', 'data'], }; diff --git a/lib/utils.js b/lib/utils.js index b464a623..239a3d74 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; -import bind from "./helpers/bind.js"; +import bind from './helpers/bind.js'; // utils is a library of generic helper functions non-specific to axios @@ -36,7 +36,7 @@ const { isArray } = Array; * * @returns {boolean} True if the value is undefined, otherwise false */ -const isUndefined = typeOfTest("undefined"); +const isUndefined = typeOfTest('undefined'); /** * Determine if a value is a Buffer @@ -63,7 +63,7 @@ function isBuffer(val) { * * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ -const isArrayBuffer = kindOfTest("ArrayBuffer"); +const isArrayBuffer = kindOfTest('ArrayBuffer'); /** * Determine if a value is a view on an ArrayBuffer @@ -74,7 +74,7 @@ const isArrayBuffer = kindOfTest("ArrayBuffer"); */ function isArrayBufferView(val) { let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { result = ArrayBuffer.isView(val); } else { result = val && val.buffer && isArrayBuffer(val.buffer); @@ -89,7 +89,7 @@ function isArrayBufferView(val) { * * @returns {boolean} True if value is a String, otherwise false */ -const isString = typeOfTest("string"); +const isString = typeOfTest('string'); /** * Determine if a value is a Function @@ -97,7 +97,7 @@ const isString = typeOfTest("string"); * @param {*} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ -const isFunction = typeOfTest("function"); +const isFunction = typeOfTest('function'); /** * Determine if a value is a Number @@ -106,7 +106,7 @@ const isFunction = typeOfTest("function"); * * @returns {boolean} True if value is a Number, otherwise false */ -const isNumber = typeOfTest("number"); +const isNumber = typeOfTest('number'); /** * Determine if a value is an Object @@ -115,7 +115,7 @@ const isNumber = typeOfTest("number"); * * @returns {boolean} True if value is an Object, otherwise false */ -const isObject = (thing) => thing !== null && typeof thing === "object"; +const isObject = (thing) => thing !== null && typeof thing === 'object'; /** * Determine if a value is a Boolean @@ -133,7 +133,7 @@ const isBoolean = (thing) => thing === true || thing === false; * @returns {boolean} True if value is a plain Object, otherwise false */ const isPlainObject = (val) => { - if (kindOf(val) !== "object") { + if (kindOf(val) !== 'object') { return false; } @@ -161,10 +161,7 @@ const isEmptyObject = (val) => { } try { - return ( - Object.keys(val).length === 0 && - Object.getPrototypeOf(val) === Object.prototype - ); + return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; } catch (e) { // Fallback for any other objects that might cause RangeError with Object.keys() return false; @@ -178,7 +175,7 @@ const isEmptyObject = (val) => { * * @returns {boolean} True if value is a Date, otherwise false */ -const isDate = kindOfTest("Date"); +const isDate = kindOfTest('Date'); /** * Determine if a value is a File @@ -187,7 +184,7 @@ const isDate = kindOfTest("Date"); * * @returns {boolean} True if value is a File, otherwise false */ -const isFile = kindOfTest("File"); +const isFile = kindOfTest('File'); /** * Determine if a value is a Blob @@ -196,7 +193,7 @@ const isFile = kindOfTest("File"); * * @returns {boolean} True if value is a Blob, otherwise false */ -const isBlob = kindOfTest("Blob"); +const isBlob = kindOfTest('Blob'); /** * Determine if a value is a FileList @@ -205,7 +202,7 @@ const isBlob = kindOfTest("Blob"); * * @returns {boolean} True if value is a File, otherwise false */ -const isFileList = kindOfTest("FileList"); +const isFileList = kindOfTest('FileList'); /** * Determine if a value is a Stream @@ -227,13 +224,13 @@ const isFormData = (thing) => { let kind; return ( thing && - ((typeof FormData === "function" && thing instanceof FormData) || + ((typeof FormData === 'function' && thing instanceof FormData) || (isFunction(thing.append) && - ((kind = kindOf(thing)) === "formdata" || + ((kind = kindOf(thing)) === 'formdata' || // detect form-data instance - (kind === "object" && + (kind === 'object' && isFunction(thing.toString) && - thing.toString() === "[object FormData]")))) + thing.toString() === '[object FormData]')))) ); }; @@ -244,13 +241,13 @@ const isFormData = (thing) => { * * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ -const isURLSearchParams = kindOfTest("URLSearchParams"); +const isURLSearchParams = kindOfTest('URLSearchParams'); const [isReadableStream, isRequest, isResponse, isHeaders] = [ - "ReadableStream", - "Request", - "Response", - "Headers", + 'ReadableStream', + 'Request', + 'Response', + 'Headers', ].map(kindOfTest); /** @@ -260,9 +257,9 @@ const [isReadableStream, isRequest, isResponse, isHeaders] = [ * * @returns {String} The String freed of excess whitespace */ -const trim = (str) => - str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); - +const trim = (str) => { + return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); +}; /** * Iterate over an Array or an Object invoking a function for each item. * @@ -281,7 +278,7 @@ const trim = (str) => */ function forEach(obj, fn, { allOwnKeys = false } = {}) { // Don't bother if no value provided - if (obj === null || typeof obj === "undefined") { + if (obj === null || typeof obj === 'undefined') { return; } @@ -289,7 +286,7 @@ function forEach(obj, fn, { allOwnKeys = false } = {}) { let l; // Force an array if not already something iterable - if (typeof obj !== "object") { + if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } @@ -306,9 +303,7 @@ function forEach(obj, fn, { allOwnKeys = false } = {}) { } // Iterate over object keys - const keys = allOwnKeys - ? Object.getOwnPropertyNames(obj) - : Object.keys(obj); + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); const len = keys.length; let key; @@ -339,16 +334,11 @@ function findKey(obj, key) { const _global = (() => { /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" - ? self - : typeof window !== "undefined" - ? window - : global; + if (typeof globalThis !== 'undefined') return globalThis; + return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; })(); -const isContextDefined = (context) => - !isUndefined(context) && context !== _global; +const isContextDefined = (context) => !isUndefined(context) && context !== _global; /** * Accepts varargs expecting each argument to be an object, then @@ -373,7 +363,7 @@ function merge(/* obj1, obj2, obj3, ... */) { const result = {}; const assignValue = (val, key) => { // Skip dangerous property names to prevent prototype pollution - if (key === "__proto__" || key === "constructor" || key === "prototype") { + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return; } @@ -426,7 +416,7 @@ const extend = (a, b, thisArg, { allOwnKeys } = {}) => { }); } }, - { allOwnKeys }, + { allOwnKeys } ); return a; }; @@ -455,17 +445,14 @@ const stripBOM = (content) => { * @returns {void} */ const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create( - superConstructor.prototype, - descriptors, - ); - Object.defineProperty(constructor.prototype, "constructor", { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + Object.defineProperty(constructor.prototype, 'constructor', { value: constructor, writable: true, enumerable: false, configurable: true, }); - Object.defineProperty(constructor, "super", { + Object.defineProperty(constructor, 'super', { value: superConstructor.prototype, }); props && Object.assign(constructor.prototype, props); @@ -495,20 +482,13 @@ const toFlatObject = (sourceObj, destObj, filter, propFilter) => { i = props.length; while (i-- > 0) { prop = props[i]; - if ( - (!propFilter || propFilter(prop, sourceObj, destObj)) && - !merged[prop] - ) { + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while ( - sourceObj && - (!filter || filter(sourceObj, destObj)) && - sourceObj !== Object.prototype - ); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; }; @@ -565,7 +545,7 @@ const isTypedArray = ((TypedArray) => { return (thing) => { return TypedArray && thing instanceof TypedArray; }; -})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); /** * For each entry in the object, call the function with the key and value. @@ -608,14 +588,12 @@ const matchAll = (regExp, str) => { }; /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ -const isHTMLForm = kindOfTest("HTMLFormElement"); +const isHTMLForm = kindOfTest('HTMLFormElement'); const toCamelCase = (str) => { - return str - .toLowerCase() - .replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - }); + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; + }); }; /* Creating a function that will check if an object has a property. */ @@ -632,7 +610,7 @@ const hasOwnProperty = ( * * @returns {boolean} True if value is a RegExp object, otherwise false */ -const isRegExp = kindOfTest("RegExp"); +const isRegExp = kindOfTest('RegExp'); const reduceDescriptors = (obj, reducer) => { const descriptors = Object.getOwnPropertyDescriptors(obj); @@ -656,10 +634,7 @@ const reduceDescriptors = (obj, reducer) => { const freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { // skip restricted props in strict mode - if ( - isFunction(obj) && - ["arguments", "caller", "callee"].indexOf(name) !== -1 - ) { + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { return false; } @@ -669,7 +644,7 @@ const freezeMethods = (obj) => { descriptor.enumerable = false; - if ("writable" in descriptor) { + if ('writable' in descriptor) { descriptor.writable = false; return; } @@ -691,9 +666,7 @@ const toObjectSet = (arrayOrString, delimiter) => { }); }; - isArray(arrayOrString) - ? define(arrayOrString) - : define(String(arrayOrString).split(delimiter)); + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); return obj; }; @@ -701,9 +674,7 @@ const toObjectSet = (arrayOrString, delimiter) => { const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite((value = +value)) - ? value - : defaultValue; + return value != null && Number.isFinite((value = +value)) ? value : defaultValue; }; /** @@ -717,7 +688,7 @@ function isSpecCompliantForm(thing) { return !!( thing && isFunction(thing.append) && - thing[toStringTag] === "FormData" && + thing[toStringTag] === 'FormData' && thing[iterator] ); } @@ -736,7 +707,7 @@ const toJSONObject = (obj) => { return source; } - if (!("toJSON" in source)) { + if (!('toJSON' in source)) { stack[i] = source; const target = isArray(source) ? [] : {}; @@ -757,7 +728,7 @@ const toJSONObject = (obj) => { return visit(obj, 0); }; -const isAsyncFn = kindOfTest("AsyncFunction"); +const isAsyncFn = kindOfTest('AsyncFunction'); const isThenable = (thing) => thing && @@ -776,27 +747,27 @@ const _setImmediate = ((setImmediateSupported, postMessageSupported) => { return postMessageSupported ? ((token, callbacks) => { _global.addEventListener( - "message", + 'message', ({ source, data }) => { if (source === _global && data === token) { callbacks.length && callbacks.shift()(); } }, - false, + false ); return (cb) => { callbacks.push(cb); - _global.postMessage(token, "*"); + _global.postMessage(token, '*'); }; })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})(typeof setImmediate === "function", isFunction(_global.postMessage)); +})(typeof setImmediate === 'function', isFunction(_global.postMessage)); const asap = - typeof queueMicrotask !== "undefined" + typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) - : (typeof process !== "undefined" && process.nextTick) || _setImmediate; + : (typeof process !== 'undefined' && process.nextTick) || _setImmediate; // ********************* diff --git a/package-lock.json b/package-lock.json index b08ddd68..6de93ff0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -54,11 +54,13 @@ "karma-sauce-launcher": "^4.3.6", "karma-sinon": "^1.0.5", "karma-sourcemap-loader": "^0.4.0", + "lint-staged": "^15.2.10", "memoizee": "^0.4.17", "minimist": "^1.2.8", "mocha": "^10.8.2", "multer": "^1.4.4", "pacote": "^20.0.0", + "prettier": "^3.8.1", "pretty-bytes": "^6.1.1", "rollup": "^2.79.2", "rollup-plugin-auto-external": "^2.0.0", @@ -103,6 +105,7 @@ "integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/generator": "^7.28.6", @@ -3069,6 +3072,7 @@ "integrity": "sha512-t7frlewr6+cbx+9Ohpl0NOTKXZNV9xHRmNOvql47BFJKcEG1CxtxlPEEe+gR9uhVWM4DwhnvTF110mIL4yP9RA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -3228,7 +3232,6 @@ "integrity": "sha512-C6wW5L+b7ogSDVqymbkkvuW9kruN//YisMED04xzeBBqjHa2FYnmvOlS6Xj68xWQRgWvI9cIglsjFowH/RJyEA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/helper-module-context": "1.9.0", "@webassemblyjs/helper-wasm-bytecode": "1.9.0", @@ -3240,24 +3243,21 @@ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.9.0.tgz", "integrity": "sha512-TG5qcFsS8QB4g4MhrxK5TqfdNe7Ey/7YL/xN+36rRjl/BlGE/NcBvJcqsRgCP6Z92mRE+7N50pRIi8SmKUbcQA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-api-error": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.9.0.tgz", "integrity": "sha512-NcMLjoFMXpsASZFxJ5h2HZRcEhDkvnNFOAKneP5RbKRzaWJN36NC4jqQHKwStIhGXu5mUWlUUk7ygdtrO8lbmw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-buffer": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.9.0.tgz", "integrity": "sha512-qZol43oqhq6yBPx7YM3m9Bv7WMV9Eevj6kMi6InKOuZxhw+q9hOkvq5e/PpKSiLfyetpaBnogSbNCfBwyB00CA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-code-frame": { "version": "1.9.0", @@ -3265,7 +3265,6 @@ "integrity": "sha512-ERCYdJBkD9Vu4vtjUYe8LZruWuNIToYq/ME22igL+2vj2dQ2OOujIZr3MEFvfEaqKoVqpsFKAGsRdBSBjrIvZA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/wast-printer": "1.9.0" } @@ -3275,8 +3274,7 @@ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.9.0.tgz", "integrity": "sha512-OPRowhGbshCb5PxJ8LocpdX9Kl0uB4XsAjl6jH/dWKlk/mzsANvhwbiULsaiqT5GZGT9qinTICdj6PLuM5gslw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/@webassemblyjs/helper-module-context": { "version": "1.9.0", @@ -3284,7 +3282,6 @@ "integrity": "sha512-MJCW8iGC08tMk2enck1aPW+BE5Cw8/7ph/VGZxwyvGbJwjktKkDK7vy7gAmMDx88D7mhDTCNKAW5tED+gZ0W8g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0" } @@ -3294,8 +3291,7 @@ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.9.0.tgz", "integrity": "sha512-R7FStIzyNcd7xKxCZH5lE0Bqy+hGTwS3LJjuv1ZVxd9O7eHCedSdrId/hMOd20I+v8wDXEn+bjfKDLzTepoaUw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-wasm-section": { "version": "1.9.0", @@ -3303,7 +3299,6 @@ "integrity": "sha512-XnMB8l3ek4tvrKUUku+IVaXNHz2YsJyOOmz+MMkZvh8h1uSJpSen6vYnw3IoQ7WwEuAhL8Efjms1ZWjqh2agvw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-buffer": "1.9.0", @@ -3317,7 +3312,6 @@ "integrity": "sha512-dcX8JuYU/gvymzIHc9DgxTzUUTLexWwt8uCTWP3otys596io0L5aW02Gb1RjYpx2+0Jus1h4ZFqjla7umFniTg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@xtuc/ieee754": "^1.2.0" } @@ -3328,7 +3322,6 @@ "integrity": "sha512-ENVzM5VwV1ojs9jam6vPys97B/S65YQtv/aanqnU7D8aSoHFX8GyhGg0CMfyKNIHBuAVjy3tlzd5QMMINa7wpw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@xtuc/long": "4.2.2" } @@ -3338,8 +3331,7 @@ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.9.0.tgz", "integrity": "sha512-GZbQlWtopBTP0u7cHrEx+73yZKrQoBMpwkGEIqlacljhXCkVM1kMQge/Mf+csMJAjEdSwhOyLAS0AoR3AG5P8w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/wasm-edit": { "version": "1.9.0", @@ -3347,7 +3339,6 @@ "integrity": "sha512-FgHzBm80uwz5M8WKnMTn6j/sVbqilPdQXTWraSjBwFXSYGirpkSWE2R9Qvz9tNiTKQvoKILpCuTjBKzOIm0nxw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-buffer": "1.9.0", @@ -3365,7 +3356,6 @@ "integrity": "sha512-cPE3o44YzOOHvlsb4+E9qSqjc9Qf9Na1OO/BHFy4OI91XDE14MjFN4lTMezzaIWdPqHnsTodGGNP+iRSYfGkjA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-wasm-bytecode": "1.9.0", @@ -3380,7 +3370,6 @@ "integrity": "sha512-Qkjgm6Anhm+OMbIL0iokO7meajkzQD71ioelnfPEj6r4eOFuqm4YC3VBPqXjFyyNwowzbMD+hizmprP/Fwkl2A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-buffer": "1.9.0", @@ -3394,7 +3383,6 @@ "integrity": "sha512-9+wkMowR2AmdSWQzsPEjFU7njh8HTO5MqO8vjwEHuM+AMHioNqSBONRdr0NQQ3dVQrzp0s8lTcYqzUdb7YgELA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-api-error": "1.9.0", @@ -3410,7 +3398,6 @@ "integrity": "sha512-qsqSAP3QQ3LyZjNC/0jBJ/ToSxfYJ8kYyuiGvtn/8MK89VrNEfwj7BPQzJVHi0jGTRK2dGdJ5PRqhtjzoww+bw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/floating-point-hex-parser": "1.9.0", @@ -3426,7 +3413,6 @@ "integrity": "sha512-2J0nE95rHXHyQ24cWjMKJ1tqB/ds8z/cyeOZxJhcb+rW+SQASVjuznUSmdz5GpVJTzU8JkhYut0D3siFDD6wsA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/wast-parser": "1.9.0", @@ -3438,16 +3424,14 @@ "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", "dev": true, - "license": "BSD-3-Clause", - "peer": true + "license": "BSD-3-Clause" }, "node_modules/@xtuc/long": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true, - "license": "Apache-2.0", - "peer": true + "license": "Apache-2.0" }, "node_modules/abbrev": { "version": "3.0.1", @@ -3486,6 +3470,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3519,6 +3504,7 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -3536,7 +3522,6 @@ "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "ajv": ">=5.0.0" } @@ -3554,6 +3539,22 @@ "node": ">=0.10.0" } }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/ansi-gray": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ansi-gray/-/ansi-gray-0.1.1.tgz", @@ -3652,8 +3653,7 @@ "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/arch": { "version": "2.2.0", @@ -4003,7 +4003,6 @@ "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", @@ -4015,8 +4014,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/assert": { "version": "1.5.1", @@ -4024,7 +4022,6 @@ "integrity": "sha512-zzw1uCAgLbsKwBfFc8CX78DDg+xZeBksSO3vwVIDDN5i94eOrPsSSyiVhmsSABFDM/OcpE2aagCat9dnWQLG1A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "object.assign": "^4.1.4", "util": "^0.10.4" @@ -4045,8 +4042,7 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/assert/node_modules/util": { "version": "0.10.4", @@ -4054,7 +4050,6 @@ "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "2.0.3" } @@ -4878,16 +4873,14 @@ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/bn.js": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.2.tgz", "integrity": "sha512-v2YAxEmKaBLahNwE1mjp4WON6huMNeuDvagFZW+ASCuA/ku0bXR9hSMw0XpiqMoA3+rmnyck/tPRSFQkoC9Cuw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/body-parser": { "version": "1.20.4", @@ -4976,8 +4969,7 @@ "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", "integrity": "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/browser-stdout": { "version": "1.3.1", @@ -4992,7 +4984,6 @@ "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "buffer-xor": "^1.0.3", "cipher-base": "^1.0.0", @@ -5008,7 +4999,6 @@ "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "browserify-aes": "^1.0.4", "browserify-des": "^1.0.0", @@ -5021,7 +5011,6 @@ "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cipher-base": "^1.0.1", "des.js": "^1.0.0", @@ -5035,7 +5024,6 @@ "integrity": "sha512-YBjSAiTqM04ZVei6sXighu679a3SqWORA3qZTEqZImnlkDIFtKc6pNutpjyZ8RJTjQtuYfeetkxM11GwoYXMIQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^5.2.1", "randombytes": "^2.1.0", @@ -5051,7 +5039,6 @@ "integrity": "sha512-C2AUdAJg6rlM2W5QMp2Q4KGQMVBwR1lIimTsUnutJ8bMpW5B52pGpR2gEnNBNwijumDo5FojQ0L9JrXA8m4YEw==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "bn.js": "^5.2.2", "browserify-rsa": "^4.1.1", @@ -5072,8 +5059,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/browserify-sign/node_modules/readable-stream": { "version": "2.3.8", @@ -5081,7 +5067,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -5097,8 +5082,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/browserify-sign/node_modules/string_decoder": { "version": "1.1.1", @@ -5106,7 +5090,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -5116,8 +5099,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/browserify-zlib": { "version": "0.2.0", @@ -5125,7 +5107,6 @@ "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "pako": "~1.0.5" } @@ -5150,6 +5131,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -5249,8 +5231,7 @@ "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", "integrity": "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/builtin-modules": { "version": "3.3.0", @@ -5270,8 +5251,7 @@ "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", "integrity": "sha512-HpGFw18DgFWlncDfjTa2rcQ4W88O1mC8e8yZ2AvQY5KDaktSTwo+KRf6nHK6FRI5FyRyb/5T6+TSxfP7QyGsmQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/builtins": { "version": "2.0.1", @@ -5895,7 +5875,6 @@ "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6.0" } @@ -5906,7 +5885,6 @@ "integrity": "sha512-Mz9QMT5fJe7bKI7MH31UilT5cEK5EHHRCccw/YRFsRY47AuNgaV6HY3rscp0/I4Q+tTW/5zoqpSeRRI54TkDWA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1", @@ -5959,6 +5937,93 @@ "node": ">= 0.4" } }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -6171,6 +6236,13 @@ "color-support": "bin.js" } }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -6351,8 +6423,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz", "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==", - "dev": true, - "peer": true + "dev": true }, "node_modules/constant-case": { "version": "3.0.4", @@ -6371,8 +6442,7 @@ "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", "integrity": "sha512-xFxOwqIzR/e1k1gLiWEophSCMqXcwVHIH7akf7b/vxcUeGunlj3hvZaaqxwHsTgn+IndtkQJgSztIDWeumWJDQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/content-disposition": { "version": "0.5.4", @@ -6473,7 +6543,6 @@ "deprecated": "This package is no longer supported.", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "aproba": "^1.1.1", "fs-write-stream-atomic": "^1.0.8", @@ -6490,7 +6559,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -6573,6 +6641,7 @@ "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", @@ -6678,7 +6747,6 @@ "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.1.0", "elliptic": "^6.5.3" @@ -6689,8 +6757,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/create-hash": { "version": "1.2.0", @@ -6698,7 +6765,6 @@ "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cipher-base": "^1.0.1", "inherits": "^2.0.1", @@ -6713,7 +6779,6 @@ "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cipher-base": "^1.0.3", "create-hash": "^1.1.0", @@ -6763,7 +6828,6 @@ "integrity": "sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "browserify-cipher": "^1.0.1", "browserify-sign": "^4.2.3", @@ -6810,8 +6874,7 @@ "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.2.tgz", "integrity": "sha512-0sVXIohTfLqVIW3kb/0n6IiWF3Ifj5nm2XaSrLq2DI6fKIGa2fYAZdk917rUneaeLVpYfFcyXE2ft0fe3remsA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/d": { "version": "1.0.2", @@ -7315,7 +7378,6 @@ "integrity": "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" @@ -7481,7 +7543,6 @@ "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.1.0", "miller-rabin": "^4.0.0", @@ -7493,8 +7554,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/doctrine": { "version": "3.0.0", @@ -7528,7 +7588,6 @@ "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.4", "npm": ">=1.2" @@ -7919,7 +7978,6 @@ "integrity": "sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.11.9", "brorand": "^1.1.0", @@ -7935,8 +7993,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/emoji-regex": { "version": "8.0.0", @@ -7965,31 +8022,6 @@ "node": ">= 0.8" } }, - "node_modules/encoding": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", - "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "iconv-lite": "^0.6.2" - } - }, - "node_modules/encoding/node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/end-of-stream": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", @@ -8036,7 +8068,6 @@ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.5.0.tgz", "integrity": "sha512-Nv9m36S/vxpsI+Hc4/ZGRs0n9mXqSWGGq49zxb/cJfPAQMbUtttJAlNPS4AQzaBdw/pKskw5bMbekT/Y7W/Wlg==", "dev": true, - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "memory-fs": "^0.5.0", @@ -8051,8 +8082,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/enhanced-resolve/node_modules/memory-fs": { "version": "0.5.0", @@ -8060,7 +8090,6 @@ "integrity": "sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "errno": "^0.1.3", "readable-stream": "^2.0.1" @@ -8075,7 +8104,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -8091,8 +8119,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/enhanced-resolve/node_modules/string_decoder": { "version": "1.1.1", @@ -8100,7 +8127,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -8131,6 +8157,19 @@ "node": ">=6" } }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/err-code": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", @@ -8144,7 +8183,6 @@ "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "prr": "~1.0.1" }, @@ -8314,6 +8352,7 @@ "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -8682,7 +8721,6 @@ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.8.x" } @@ -8703,7 +8741,6 @@ "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "md5.js": "^1.3.4", "safe-buffer": "^5.1.1" @@ -9206,8 +9243,7 @@ "integrity": "sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==", "deprecated": "This module is no longer supported.", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/figures": { "version": "1.7.0", @@ -9347,7 +9383,6 @@ "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "commondir": "^1.0.1", "make-dir": "^2.0.0", @@ -9363,7 +9398,6 @@ "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "locate-path": "^3.0.0" }, @@ -9377,7 +9411,6 @@ "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" @@ -9392,7 +9425,6 @@ "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "pify": "^4.0.1", "semver": "^5.6.0" @@ -9407,7 +9439,6 @@ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "p-try": "^2.0.0" }, @@ -9424,7 +9455,6 @@ "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "p-limit": "^2.0.0" }, @@ -9438,7 +9468,6 @@ "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=4" } @@ -9449,7 +9478,6 @@ "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -9460,7 +9488,6 @@ "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "find-up": "^3.0.0" }, @@ -9474,7 +9501,6 @@ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", "dev": true, "license": "ISC", - "peer": true, "bin": { "semver": "bin/semver" } @@ -9921,7 +9947,6 @@ "deprecated": "This package is no longer supported.", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "iferr": "^0.1.5", @@ -9934,8 +9959,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/fs-write-stream-atomic/node_modules/readable-stream": { "version": "2.3.8", @@ -9943,7 +9967,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -9959,8 +9982,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/fs-write-stream-atomic/node_modules/string_decoder": { "version": "1.1.1", @@ -9968,7 +9990,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -10029,6 +10050,19 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", + "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -11000,7 +11034,6 @@ "integrity": "sha512-vXm0l45VbcHEVlTCzs8M+s0VeYsB2lnlAaThoLKGXr3bE/VWDOelNUnycUPEhKEaXARL2TEFjBOyUiM6+55KBg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1" @@ -11059,7 +11092,6 @@ "integrity": "sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "hash.js": "^1.0.3", "minimalistic-assert": "^1.0.0", @@ -11178,8 +11210,7 @@ "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", "integrity": "sha512-J+FkSdyD+0mA0N+81tMotaRMfSL9SGi+xpD3T6YApKsc3bGSXJlfXri3VyFOeYkfLRQisDk1W+jIFFKBeUBbBg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/https-proxy-agent": { "version": "7.0.6", @@ -11195,6 +11226,16 @@ "node": ">= 14" } }, + "node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=16.17.0" + } + }, "node_modules/husky": { "version": "8.0.3", "resolved": "https://registry.npmjs.org/husky/-/husky-8.0.3.tgz", @@ -11250,8 +11291,7 @@ "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", "integrity": "sha512-DUNFN5j7Tln0D+TxzloUjKB+CtVu6myn0JEFak6dG18mNt9YkQ6lzGCdafwofISZ1lLF3xRHJ98VKy9ynkcFaA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/ignore": { "version": "5.3.2", @@ -11365,8 +11405,7 @@ "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz", "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/inflight": { "version": "1.0.6", @@ -12101,7 +12140,8 @@ "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-2.99.1.tgz", "integrity": "sha512-ra97U4qu3OCcIxvN6eg3kyy8bLrID/TgxafSGMMICg3SFx5C/sUfDPpiOh7yoIsHdtjrOVdtT9rieYhqOsh9Ww==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/jest-worker": { "version": "26.6.2", @@ -12309,6 +12349,7 @@ "integrity": "sha512-LrtUxbdvt1gOpo3gxG+VAJlJAEMhbWlM4YrFQgql98FwF7+K8K12LYO4hnDdUkNjeztYrOXEMqgTajSWgmtI/w==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@colors/colors": "1.5.0", "body-parser": "^1.19.0", @@ -13082,6 +13123,19 @@ "dev": true, "license": "MIT" }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, "node_modules/limiter": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz", @@ -13095,6 +13149,312 @@ "dev": true, "license": "MIT" }, + "node_modules/lint-staged": { + "version": "15.5.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.5.2.tgz", + "integrity": "sha512-YUSOLq9VeRNAo/CTaVmhGDKG+LBtA8KF1X4K5+ykMSwWST1vDxJRB2kv2COgLb1fvpCo+A/y9A0G0znNVmdx4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.4.1", + "commander": "^13.1.0", + "debug": "^4.4.0", + "execa": "^8.0.1", + "lilconfig": "^3.1.3", + "listr2": "^8.2.5", + "micromatch": "^4.0.8", + "pidtree": "^0.6.0", + "string-argv": "^0.3.2", + "yaml": "^2.7.0" + }, + "bin": { + "lint-staged": "bin/lint-staged.js" + }, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://opencollective.com/lint-staged" + } + }, + "node_modules/lint-staged/node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lint-staged/node_modules/commander": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", + "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/lint-staged/node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/lint-staged/node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lint-staged/node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lint-staged/node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/lint-staged/node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lint-staged/node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/lint-staged/node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lint-staged/node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lint-staged/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lint-staged/node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/listr2": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.3.3.tgz", + "integrity": "sha512-LWzX2KsqcB1wqQ4AHgYb4RsDXauQiqhjLk+6hjbaeHG4zpjjVAB6wC/gz6X0l+Du1cN3pUB5ZlrvTbhGSNnUQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "cli-truncate": "^4.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.1.0", + "rfdc": "^1.4.1", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/listr2/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/listr2/node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/listr2/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", @@ -13131,7 +13491,6 @@ "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=4.3.0 <5.0.0 || >=5.10" } @@ -13358,6 +13717,144 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/log-update/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-update/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/log4js": { "version": "6.9.1", "resolved": "https://registry.npmjs.org/log4js/-/log4js-6.9.1.tgz", @@ -13783,7 +14280,6 @@ "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "hash-base": "^3.0.0", "inherits": "^2.0.1", @@ -13826,7 +14322,6 @@ "integrity": "sha512-cda4JKCxReDXFXRqOHPQscuIYg1PvxbE2S2GP45rnwfEK+vZaXC8C1OFvdHIbgw0DLzowXGVoxLaAmlgRy14GQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "errno": "^0.1.3", "readable-stream": "^2.0.1" @@ -13837,8 +14332,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/memory-fs/node_modules/readable-stream": { "version": "2.3.8", @@ -13846,7 +14340,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -13862,8 +14355,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/memory-fs/node_modules/string_decoder": { "version": "1.1.1", @@ -13871,7 +14363,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -13997,7 +14488,6 @@ "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.0.0", "brorand": "^1.0.1" @@ -14011,8 +14501,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/mime": { "version": "2.6.0", @@ -14048,6 +14537,32 @@ "node": ">= 0.6" } }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/mimic-response": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", @@ -14070,8 +14585,7 @@ "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", "integrity": "sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/minimatch": { "version": "9.0.5", @@ -14258,7 +14772,6 @@ "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "concat-stream": "^1.5.0", "duplexify": "^3.4.2", @@ -14284,7 +14797,6 @@ "node >= 0.8" ], "license": "MIT", - "peer": true, "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", @@ -14297,8 +14809,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/mississippi/node_modules/pump": { "version": "3.0.3", @@ -14306,7 +14817,6 @@ "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" @@ -14318,7 +14828,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -14334,8 +14843,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/mississippi/node_modules/string_decoder": { "version": "1.1.1", @@ -14343,7 +14851,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -14820,7 +15327,6 @@ "deprecated": "This package is no longer supported.", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "aproba": "^1.1.1", "copy-concurrently": "^1.0.0", @@ -14837,7 +15343,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -15280,7 +15785,6 @@ "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "assert": "^1.1.1", "browserify-zlib": "^0.2.0", @@ -15313,7 +15817,6 @@ "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "base64-js": "^1.0.2", "ieee754": "^1.1.4", @@ -15325,8 +15828,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/node-libs-browser/node_modules/readable-stream": { "version": "2.3.8", @@ -15334,7 +15836,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -15350,8 +15851,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/node-libs-browser/node_modules/string_decoder": { "version": "1.1.1", @@ -15359,7 +15859,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -15898,6 +16397,22 @@ "wrappy": "1" } }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -15971,8 +16486,7 @@ "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", "integrity": "sha512-gjcpUc3clBf9+210TRaDWbf+rZZZEshZ+DlXMRCeAjp0xhTrnQsKHypIy1J3d5hKdUzj69t708EHtU8P6bUn0A==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/os-filter-obj": { "version": "2.0.0", @@ -16227,8 +16741,7 @@ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", "dev": true, - "license": "(MIT AND Zlib)", - "peer": true + "license": "(MIT AND Zlib)" }, "node_modules/parallel-transform": { "version": "1.2.0", @@ -16236,7 +16749,6 @@ "integrity": "sha512-P2vSmIu38uIlvdcU7fDkyrxj33gTUy/ABO5ZUbGowxNCopBq/OoD42bP4UmMrJoPyk4Uqf0mu3mtWBhHCZD8yg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cyclist": "^1.0.1", "inherits": "^2.0.3", @@ -16248,8 +16760,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/parallel-transform/node_modules/readable-stream": { "version": "2.3.8", @@ -16257,7 +16768,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -16273,8 +16783,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/parallel-transform/node_modules/string_decoder": { "version": "1.1.1", @@ -16282,7 +16791,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -16317,7 +16825,6 @@ "integrity": "sha512-fIYNuZ/HastSb80baGOuPRo1O9cf4baWw5WsAp7dBuUzeTD/BoaG8sVTdlPFksBE2lF21dN+A1AnrpIjSWqHHg==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "asn1.js": "^4.10.1", "browserify-aes": "^1.2.0", @@ -16439,8 +16946,7 @@ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz", "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/path-case": { "version": "3.0.4", @@ -16570,7 +17076,6 @@ "integrity": "sha512-Q3CG/cYvCO1ye4QKkuH7EXxs3VC/rI1/trd+qX2+PolbaKG0H+bgcZzrTt96mMyRtejk+JMCiLUn3y29W8qmFQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "create-hash": "^1.2.0", "create-hmac": "^1.1.7", @@ -16617,6 +17122,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", + "dev": true, + "license": "MIT", + "bin": { + "pidtree": "bin/pidtree.js" + }, + "engines": { + "node": ">=0.10" + } + }, "node_modules/pify": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", @@ -16769,6 +17287,22 @@ "node": ">=4" } }, + "node_modules/prettier": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/pretty-bytes": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz", @@ -16808,7 +17342,6 @@ "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 0.6.0" } @@ -16835,8 +17368,7 @@ "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", "integrity": "sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/promise-retry": { "version": "2.0.1", @@ -16884,8 +17416,7 @@ "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", "integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/pseudomap": { "version": "1.0.2", @@ -16923,7 +17454,6 @@ "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "bn.js": "^4.1.0", "browserify-rsa": "^4.0.0", @@ -16938,8 +17468,7 @@ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/pump": { "version": "2.0.1", @@ -17087,7 +17616,6 @@ "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", "integrity": "sha512-773xhDQnZBMFobEiztv8LIl70ch5MSF/jUQVlhwFyBILqq96anmoctVIYz+ZRp0qbCKATTn6ev02M3r7Ga5vqA==", "dev": true, - "peer": true, "engines": { "node": ">=0.4.x" } @@ -17142,7 +17670,6 @@ "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "randombytes": "^2.0.5", "safe-buffer": "^5.1.0" @@ -17879,6 +18406,23 @@ "dev": true, "license": "MIT" }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", @@ -17947,7 +18491,6 @@ "integrity": "sha512-5Di9UC0+8h1L6ZD2d7awM7E/T4uA1fJRlx6zk/NvdCCVEoAnFqvHmCuNeIKoCeIixBX/q8uM+6ycDvF8woqosA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "hash-base": "^3.1.2", "inherits": "^2.0.4" @@ -17962,7 +18505,6 @@ "integrity": "sha512-Bb33KbowVTIj5s7Ked1OsqHUeCpz//tPwR+E2zJgJKo9Z5XolZ9b6bdUgjmYlwnWhoOQKoTd1TYToZGn5mAYOg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "^2.0.4", "readable-stream": "^2.3.8", @@ -17978,8 +18520,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/ripemd160/node_modules/readable-stream": { "version": "2.3.8", @@ -17987,7 +18528,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -18003,8 +18543,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/ripemd160/node_modules/string_decoder": { "version": "1.1.1", @@ -18012,7 +18551,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -18022,8 +18560,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/roarr": { "version": "2.15.4", @@ -18049,6 +18586,7 @@ "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -18241,7 +18779,6 @@ "integrity": "sha512-ntymy489o0/QQplUDnpYAYUsO50K9SBrIVaKCWDOJzYJts0f9WH9RFJkyagebkw5+y1oi00R7ynNW/d12GBumg==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "aproba": "^1.1.1" } @@ -18737,8 +19274,7 @@ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/setprototypeof": { "version": "1.2.0", @@ -18753,7 +19289,6 @@ "integrity": "sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w==", "dev": true, "license": "(MIT AND BSD-3-Clause)", - "peer": true, "dependencies": { "inherits": "^2.0.4", "safe-buffer": "^5.2.1", @@ -18907,6 +19442,7 @@ "dev": true, "hasInstallScript": true, "license": "BSD-3-Clause", + "peer": true, "dependencies": { "@sinonjs/formatio": "^2.0.0", "diff": "^3.1.0", @@ -18950,6 +19486,49 @@ "node": ">=4" } }, + "node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", @@ -19205,8 +19784,7 @@ "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/source-map": { "version": "0.6.1", @@ -19469,7 +20047,6 @@ "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "~2.0.1", "readable-stream": "^2.0.2" @@ -19480,8 +20057,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/stream-browserify/node_modules/readable-stream": { "version": "2.3.8", @@ -19489,7 +20065,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -19505,8 +20080,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/stream-browserify/node_modules/string_decoder": { "version": "1.1.1", @@ -19514,7 +20088,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -19525,7 +20098,6 @@ "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "end-of-stream": "^1.1.0", "stream-shift": "^1.0.0" @@ -19544,7 +20116,6 @@ "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "builtin-status-codes": "^3.0.0", "inherits": "^2.0.1", @@ -19558,8 +20129,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/stream-http/node_modules/readable-stream": { "version": "2.3.8", @@ -19567,7 +20137,6 @@ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", @@ -19583,8 +20152,7 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/stream-http/node_modules/string_decoder": { "version": "1.1.1", @@ -19592,7 +20160,6 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "~5.1.0" } @@ -19719,6 +20286,16 @@ "safe-buffer": "~5.2.0" } }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, "node_modules/string-replace-async": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/string-replace-async/-/string-replace-async-3.0.2.tgz", @@ -19850,6 +20427,19 @@ "node": ">=0.10.0" } }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -19929,7 +20519,6 @@ "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -20121,7 +20710,6 @@ "integrity": "sha512-2lBVf/VMVIddjSn3GqbT90GvIJ/eYXJkt8cTzU7NbjKqK8fwv18Ftr4PlbF46b/e88743iZFL5Dtr/rC4hjIeA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cacache": "^12.0.2", "find-cache-dir": "^2.1.0", @@ -20164,7 +20752,6 @@ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "ajv": "^6.9.1" } @@ -20175,7 +20762,6 @@ "integrity": "sha512-a0tMB40oefvuInr4Cwb3GerbL9xTj1D5yg0T5xrjGCGyfvbxseIXX7BAO/u/hIXdafzOI5JC3wDwHyf24buOAQ==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "bluebird": "^3.5.5", "chownr": "^1.1.1", @@ -20199,16 +20785,14 @@ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/terser-webpack-plugin/node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/terser-webpack-plugin/node_modules/is-wsl": { "version": "1.1.0", @@ -20216,7 +20800,6 @@ "integrity": "sha512-gfygJYZ2gLTDlmbWMI0CE2MwnFzSN/2SZfkMlItC4K/JBlsWVDB0bO6XhqcY13YXE7iMcAJnzTCJjPiTeJJ0Mw==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=4" } @@ -20226,8 +20809,7 @@ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/terser-webpack-plugin/node_modules/rimraf": { "version": "2.7.1", @@ -20236,7 +20818,6 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -20250,7 +20831,6 @@ "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ajv": "^6.1.0", "ajv-errors": "^1.0.0", @@ -20266,7 +20846,6 @@ "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "dependencies": { "randombytes": "^2.1.0" } @@ -20277,7 +20856,6 @@ "integrity": "sha512-cepbSq/neFK7xB6A50KHN0xHDotYzq58wWCa5LeWqnPrHG8GzfEjO/4O8kpmcGW+oaxkvhEJCWgbgNk4/ZV93Q==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "figgy-pudding": "^3.5.1" } @@ -20288,7 +20866,6 @@ "integrity": "sha512-4GnLC0x667eJG0ewJTa6z/yXrbLGv80D9Ru6HIpCQmO+Q4PfEtBFi0ObSckqwL6VyQv/7ENJieXHo2ANmdQwgw==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "commander": "^2.20.0", "source-map": "~0.6.1", @@ -20307,7 +20884,6 @@ "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "unique-slug": "^2.0.0" } @@ -20318,7 +20894,6 @@ "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "imurmurhash": "^0.1.4" } @@ -20328,8 +20903,7 @@ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/terser/node_modules/commander": { "version": "2.20.3", @@ -20499,7 +21073,6 @@ "integrity": "sha512-9phl76Cqm6FhSX9Xe1ZUAMLtm1BLkKj2Qd5ApyWkXzsMRaA7dgr81kf4wJmQf/hAvg8EEyJxDo3du/0KlhPiKQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "setimmediate": "^1.0.4" }, @@ -20572,6 +21145,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -20608,8 +21182,7 @@ "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", "integrity": "sha512-okFlQcoGTi4LQBG/PgSYblw9VOyptsz2KJZqc6qtgGdes8VktzUQkj4BI2blit072iS8VODNcMA+tvnS9dnuMA==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/to-buffer": { "version": "1.2.2", @@ -20831,8 +21404,7 @@ "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", "integrity": "sha512-JVa5ijo+j/sOoHGjw0sxw734b1LhBkQ3bvUGNdxnVXDCX81Yx7TFgnZygxrIIWn23hbfTaMYLwRmAxFyDuFmIw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tuf-js": { "version": "3.1.0", @@ -20964,6 +21536,7 @@ "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -21365,7 +21938,6 @@ "integrity": "sha512-oCwdVC7mTuWiPyjLUz/COz5TLk6wgp0RCsN+wHZ2Ekneac9w8uuV0njcbbie2ME+Vs+d6duwmYuR3HgQXs1fOg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "punycode": "^1.4.1", "qs": "^6.12.3" @@ -21413,7 +21985,6 @@ "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "inherits": "2.0.3" } @@ -21430,8 +22001,7 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/utils-merge": { "version": "1.0.1", @@ -21659,8 +22229,7 @@ "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/void-elements": { "version": "2.0.1", @@ -21678,7 +22247,6 @@ "integrity": "sha512-9P3MWk6SrKjHsGkLT2KHXdQ/9SNkyoJbabxnKOoJepsvJjJG8uYTR3yTPxPQvNDI3w4Nz1xnE0TLHK4RIVe/MQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "graceful-fs": "^4.1.2", "neo-async": "^2.5.0" @@ -21695,7 +22263,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "chokidar": "^2.1.8" } @@ -21707,7 +22274,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -21723,7 +22289,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=8" }, @@ -21738,7 +22303,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "fill-range": "^7.1.1" }, @@ -21753,7 +22317,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -21780,7 +22343,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "to-regex-range": "^5.0.1" }, @@ -21799,7 +22361,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } @@ -21811,7 +22372,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -21826,7 +22386,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "binary-extensions": "^2.0.0" }, @@ -21841,7 +22400,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.12.0" } @@ -21853,7 +22411,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "picomatch": "^2.2.1" }, @@ -21868,7 +22425,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "is-number": "^7.0.0" }, @@ -22008,7 +22564,6 @@ "integrity": "sha512-td7fYwgLSrky3fI1EuU5cneU4+pbH6GgOfuKNS1tNPcfdGinGELAqsb/BP4nnvZyKSG2i/xFGU7+n2PvZA8HJQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.9.0", "@webassemblyjs/helper-module-context": "1.9.0", @@ -22059,7 +22614,6 @@ "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "source-list-map": "^2.0.0", "source-map": "~0.6.1" @@ -22071,7 +22625,6 @@ "integrity": "sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -22103,7 +22656,6 @@ "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "ajv": "^6.9.1" } @@ -22114,7 +22666,6 @@ "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "esrecurse": "^4.1.0", "estraverse": "^4.1.1" @@ -22129,7 +22680,6 @@ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "engines": { "node": ">=4.0" } @@ -22139,8 +22689,7 @@ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/webpack/node_modules/schema-utils": { "version": "1.0.0", @@ -22148,7 +22697,6 @@ "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ajv": "^6.1.0", "ajv-errors": "^1.0.0", @@ -22230,7 +22778,6 @@ "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "errno": "~0.1.7" } @@ -22385,6 +22932,22 @@ "dev": true, "license": "ISC" }, + "node_modules/yaml": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz", + "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/yargs": { "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", diff --git a/package.json b/package.json index 57df1d57..5029d92c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "axios", "version": "1.13.5", "description": "Promise based HTTP client for the browser and node.js", - "main": "./dist/node/axios.cjs", + "main": "./index.js", "module": "./index.js", "exports": { ".": { @@ -63,7 +63,6 @@ "prepublishOnly": "npm run test:build:version", "build": "gulp clear && cross-env NODE_ENV=production rollup -c -m", "examples": "node ./examples/server.js", - "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", "fix": "eslint --fix lib/**/*.js", "prepare": "husky install && npm run prepare:hooks", "prepare:hooks": "npx husky set .husky/commit-msg \"npx commitlint --edit $1\"" @@ -131,11 +130,13 @@ "karma-sauce-launcher": "^4.3.6", "karma-sinon": "^1.0.5", "karma-sourcemap-loader": "^0.4.0", + "lint-staged": "^15.2.10", "memoizee": "^0.4.17", "minimist": "^1.2.8", "mocha": "^10.8.2", "multer": "^1.4.4", "pacote": "^20.0.0", + "prettier": "^3.8.1", "pretty-bytes": "^6.1.1", "rollup": "^2.79.2", "rollup-plugin-auto-external": "^2.0.0", @@ -202,6 +203,9 @@ "@commitlint/config-conventional" ] }, + "lint-staged": { + "*.{js,cjs,mjs,ts,json,md,yml,yaml}": "prettier --write" + }, "c8": { "all": true, "include": [ @@ -219,4 +223,4 @@ ], "report-dir": "./coverage" } -} \ No newline at end of file +} diff --git a/rollup.config.js b/rollup.config.js index 3deab308..b2741a05 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,6 +1,6 @@ import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; -import {terser} from "rollup-plugin-terser"; +import { terser } from 'rollup-plugin-terser'; import json from '@rollup/plugin-json'; import { babel } from '@rollup/plugin-babel'; import autoExternal from 'rollup-plugin-auto-external'; @@ -8,51 +8,52 @@ import bundleSize from 'rollup-plugin-bundle-size'; import aliasPlugin from '@rollup/plugin-alias'; import path from 'path'; -const lib = require("./package.json"); +const lib = require('./package.json'); const outputFileName = 'axios'; -const name = "axios"; +const name = 'axios'; const namedInput = './index.js'; const defaultInput = './lib/axios.js'; -const buildConfig = ({es5, browser = true, minifiedVersion = true, alias, ...config}) => { - const {file} = config.output; +const buildConfig = ({ es5, browser = true, minifiedVersion = true, alias, ...config }) => { + const { file } = config.output; const ext = path.extname(file); const basename = path.basename(file, ext); const extArr = ext.split('.'); extArr.shift(); - - const build = ({minified}) => ({ + const build = ({ minified }) => ({ input: namedInput, ...config, output: { ...config.output, - file: `${path.dirname(file)}/${basename}.${(minified ? ['min', ...extArr] : extArr).join('.')}` + file: `${path.dirname(file)}/${basename}.${(minified ? ['min', ...extArr] : extArr).join('.')}`, }, plugins: [ aliasPlugin({ - entries: alias || [] + entries: alias || [], }), json(), - resolve({browser}), + resolve({ browser }), commonjs(), minified && terser(), minified && bundleSize(), - ...(es5 ? [babel({ - babelHelpers: 'bundled', - presets: ['@babel/preset-env'] - })] : []), + ...(es5 + ? [ + babel({ + babelHelpers: 'bundled', + presets: ['@babel/preset-env'], + }), + ] + : []), ...(config.plugins || []), - ] + ], }); - const configs = [ - build({minified: false}), - ]; + const configs = [build({ minified: false })]; if (minifiedVersion) { - configs.push(build({minified: true})) + configs.push(build({ minified: true })); } return configs; @@ -68,15 +69,15 @@ export default async () => { input: namedInput, output: { file: `dist/esm/${outputFileName}.js`, - format: "esm", + format: 'esm', preferConst: true, - exports: "named", - banner - } + exports: 'named', + banner, + }, }), // browser ESM bundle for CDN with fetch adapter only // Downsizing from 12.97 kB (gzip) to 12.23 kB (gzip) -/* ...buildConfig({ + /* ...buildConfig({ input: namedInput, output: { file: `dist/esm/${outputFileName}-fetch.js`, @@ -97,10 +98,10 @@ export default async () => { output: { file: `dist/${outputFileName}.js`, name, - format: "umd", - exports: "default", - banner - } + format: 'umd', + exports: 'default', + banner, + }, }), // Browser CJS bundle @@ -111,10 +112,10 @@ export default async () => { output: { file: `dist/browser/${name}.cjs`, name, - format: "cjs", - exports: "default", - banner - } + format: 'cjs', + exports: 'default', + banner, + }, }), // Node.js commonjs bundle @@ -122,16 +123,12 @@ export default async () => { input: defaultInput, output: { file: `dist/node/${name}.cjs`, - format: "cjs", + format: 'cjs', preferConst: true, - exports: "default", - banner + exports: 'default', + banner, }, - plugins: [ - autoExternal(), - resolve(), - commonjs() - ] - } - ] + plugins: [autoExternal(), resolve(), commonjs()], + }, + ]; }; diff --git a/sandbox/client.html b/sandbox/client.html index 6b13ae2f..210585c8 100644 --- a/sandbox/client.html +++ b/sandbox/client.html @@ -1,499 +1,522 @@ + AXIOS | Sandbox - - + } + + -
              -
              - axios -

               | Sandbox

              -
              - -
              - -
              -
              -

              Input

              -
              -
              - - -
              -
              - - -
              -
              - - -
              - -
              - - -
              - -
              +
              +
              + axios +

               | Sandbox

              +
              +
              -
              +
              -

              Request

              -
              No Data
              +

              Input

              +
              +
              + + +
              +
              + + +
              +
              + + +
              + +
              + + +
              + +
              -
              -

              Response

              -
              No Data
              -
              +
              +
              +

              Request

              +
              No Data
              +
              -
              -

              Error

              -
              None
              +
              +

              Response

              +
              No Data
              +
              + +
              +

              Error

              +
              None
              +
              -
              -
              +
              -
              +
              - - + + yearSpan.textContent = new Date().getFullYear(); + })(); + - + + \ No newline at end of file diff --git a/sandbox/client.js b/sandbox/client.js index f091a88e..d7208ec9 100644 --- a/sandbox/client.js +++ b/sandbox/client.js @@ -3,18 +3,18 @@ import axios from '../index.js'; const URL = 'http://127.0.0.1:3000/api'; const BODY = { foo: 'bar', - baz: 1234 + baz: 1234, }; -function handleSuccess(data) { console.log(data); } -function handleFailure(data) { console.log('error', data); } +function handleSuccess(data) { + console.log(data); +} +function handleFailure(data) { + console.log('error', data); +} // GET -axios.get(URL, { params: BODY }) - .then(handleSuccess) - .catch(handleFailure); +axios.get(URL, { params: BODY }).then(handleSuccess).catch(handleFailure); // POST -axios.post(URL, BODY) - .then(handleSuccess) - .catch(handleFailure); +axios.post(URL, BODY).then(handleSuccess).catch(handleFailure); diff --git a/sandbox/server.js b/sandbox/server.js index 8b5693f4..401f8750 100644 --- a/sandbox/server.js +++ b/sandbox/server.js @@ -15,7 +15,7 @@ let server; function pipeFileToResponse(res, file, type) { if (type) { res.writeHead(200, { - 'Content-Type': type + 'Content-Type': type, }); } @@ -47,18 +47,18 @@ function handleApiRequest(req, res) { url: req.url, data: data ? JSON.parse(data) : undefined, method: req.method, - headers: req.headers + headers: req.headers, }; } catch (e) { console.error('Error:', e.message); status = 400; result = { - error: e.message + error: e.message, }; } res.writeHead(status, { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }); res.end(JSON.stringify(result)); }); diff --git a/test/helpers/retry.js b/test/helpers/retry.js index a4ccfbdc..b89c6001 100644 --- a/test/helpers/retry.js +++ b/test/helpers/retry.js @@ -1,18 +1,20 @@ - export const retryNetwork = async (fn, retries = 3, delay = 1000) => { - let attempt = 0, sleep; + let attempt = 0, + sleep; do { try { - return await fn() + return await fn(); } catch (err) { if (err.code === 'ERR_NETWORK' && attempt++ < retries) { sleep = attempt * attempt * delay; - console.warn(`[ERR_NETWORK]: Attempt ${attempt}/${retries}${err.config ? ' [' + err.config.url + ']' : ''} sleep [${sleep}ms]`); - await new Promise(resolve => setTimeout(resolve, sleep)); + console.warn( + `[ERR_NETWORK]: Attempt ${attempt}/${retries}${err.config ? ' [' + err.config.url + ']' : ''} sleep [${sleep}ms]` + ); + await new Promise((resolve) => setTimeout(resolve, sleep)); } else { throw err; } } } while (true); -} +}; diff --git a/test/helpers/server.js b/test/helpers/server.js index 698b2b7f..3ec489fb 100644 --- a/test/helpers/server.js +++ b/test/helpers/server.js @@ -1,22 +1,20 @@ -import http from "http"; -import http2 from "http2"; -import stream from "stream"; -import getStream from "get-stream"; -import {Throttle} from "stream-throttle"; -import formidable from "formidable"; +import http from 'http'; +import http2 from 'http2'; +import stream from 'stream'; +import getStream from 'get-stream'; +import { Throttle } from 'stream-throttle'; +import formidable from 'formidable'; import selfsigned from 'selfsigned'; - export const LOCAL_SERVER_URL = 'http://localhost:4444'; export const SERVER_HANDLER_STREAM_ECHO = (req, res) => req.pipe(res); -export const setTimeoutAsync = (ms) => new Promise(resolve=> setTimeout(resolve, ms)); +export const setTimeoutAsync = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const certificate = selfsigned.generate(null, { keySize: 2048 }); export const startHTTPServer = (handlerOrOptions, options) => { - const { handler, useBuffering = false, @@ -26,45 +24,52 @@ export const startHTTPServer = (handlerOrOptions, options) => { useHTTP2, key = certificate.private, cert = certificate.cert, - } = - Object.assign(typeof handlerOrOptions === 'function' ? { - handler: handlerOrOptions - } : handlerOrOptions || {}, options); + } = Object.assign( + typeof handlerOrOptions === 'function' + ? { + handler: handlerOrOptions, + } + : handlerOrOptions || {}, + options + ); return new Promise((resolve, reject) => { - const serverHandler = handler || async function (req, res) { - try { - req.headers['content-length'] && res.setHeader('content-length', req.headers['content-length']); + const serverHandler = + handler || + async function (req, res) { + try { + req.headers['content-length'] && + res.setHeader('content-length', req.headers['content-length']); - let dataStream = req; + let dataStream = req; - if (useBuffering) { - dataStream = stream.Readable.from(await getStream(req)); + if (useBuffering) { + dataStream = stream.Readable.from(await getStream(req)); + } + + let streams = [dataStream]; + + if (rate) { + streams.push(new Throttle({ rate })); + } + + streams.push(res); + + stream.pipeline(streams, (err) => { + err && console.log('Server warning: ' + err.message); + }); + } catch (err) { + console.warn('HTTP server error:', err); } + }; - let streams = [dataStream]; - - if (rate) { - streams.push(new Throttle({rate})) - } - - streams.push(res); - - stream.pipeline(streams, (err) => { - err && console.log('Server warning: ' + err.message) - }); - } catch (err){ - console.warn('HTTP server error:', err); - } - } - - const server = useHTTP2 ? - http2.createSecureServer({key, cert} , serverHandler) : - http.createServer(serverHandler); + const server = useHTTP2 + ? http2.createSecureServer({ key, cert }, serverHandler) + : http.createServer(serverHandler); const sessions = new Set(); - if(useHTTP2) { + if (useHTTP2) { server.on('session', (session) => { sessions.add(session); @@ -77,7 +82,7 @@ export const startHTTPServer = (handlerOrOptions, options) => { for (const session of sessions) { session.destroy(); } - } + }; } else { server.keepAliveTimeout = keepAlive; } @@ -85,9 +90,8 @@ export const startHTTPServer = (handlerOrOptions, options) => { server.listen(port, function (err) { err ? reject(err) : resolve(this); }); - }); -} +}; export const stopHTTPServer = async (server, timeout = 10000) => { if (server) { @@ -99,9 +103,9 @@ export const stopHTTPServer = async (server, timeout = 10000) => { server.closeAllSessions(); } - await Promise.race([new Promise(resolve => server.close(resolve)), setTimeoutAsync(timeout)]); + await Promise.race([new Promise((resolve) => server.close(resolve)), setTimeoutAsync(timeout)]); } -} +}; export const handleFormData = (req) => { return new Promise((resolve, reject) => { @@ -112,52 +116,55 @@ export const handleFormData = (req) => { return reject(err); } - resolve({fields, files}); + resolve({ fields, files }); }); }); -} +}; -export const nodeVersion = process.versions.node.split('.').map(v => parseInt(v, 10)); +export const nodeVersion = process.versions.node.split('.').map((v) => parseInt(v, 10)); export const generateReadable = (length = 1024 * 1024, chunkSize = 10 * 1024, sleep = 50) => { - return stream.Readable.from(async function* (){ - let dataLength = 0; + return stream.Readable.from( + (async function* () { + let dataLength = 0; - while(dataLength < length) { - const leftBytes = length - dataLength; + while (dataLength < length) { + const leftBytes = length - dataLength; - const chunk = Buffer.alloc(leftBytes > chunkSize? chunkSize : leftBytes); + const chunk = Buffer.alloc(leftBytes > chunkSize ? chunkSize : leftBytes); - dataLength += chunk.length; + dataLength += chunk.length; - yield chunk; + yield chunk; - if (sleep) { - await setTimeoutAsync(sleep); + if (sleep) { + await setTimeoutAsync(sleep); + } } - } - }()); -} + })() + ); +}; export const makeReadableStream = (chunk = 'chunk', n = 10, timeout = 100) => { - return new ReadableStream({ + return new ReadableStream( + { async pull(controller) { await setTimeoutAsync(timeout); n-- ? controller.enqueue(chunk) : controller.close(); - } + }, }, { - highWaterMark: 1 + highWaterMark: 1, } - ) -} - -export const makeEchoStream = (echo) => new WritableStream({ - write(chunk) { - echo && console.log(`Echo chunk`, chunk); - } -}) + ); +}; +export const makeEchoStream = (echo) => + new WritableStream({ + write(chunk) { + echo && console.log(`Echo chunk`, chunk); + }, + }); export const startTestServer = async (port) => { const handler = async (req) => { @@ -171,11 +178,11 @@ export const startTestServer = async (port) => { params, method: req.method, headers: req.headers, - } + }; const contentType = req.headers['content-type'] || ''; - const {delay = 0} = params; + const { delay = 0 } = params; if (+delay) { await setTimeoutAsync(+delay); @@ -185,44 +192,46 @@ export const startTestServer = async (port) => { case '/echo/json': default: if (contentType.startsWith('multipart/')) { - let {fields, files} = await handleFormData(req); + let { fields, files } = await handleFormData(req); response.form = fields; response.files = files; } else { - response.body = (await getStream(req, {encoding: 'buffer'})).toString('hex'); + response.body = (await getStream(req, { encoding: 'buffer' })).toString('hex'); } return { - body: response - } + body: response, + }; } }; - return await startHTTPServer((req, res) => { - // Set CORS headers - res.setHeader('Access-Control-Allow-Origin', `*`); // Allows all origins, or specify a domain like 'http://example.com' - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // Allowed HTTP methods - res.setHeader('Access-Control-Allow-Headers', '*'); // Allowed request headers - res.setHeader('Access-Control-Max-Age', '86400'); // Cache preflight requests for 24 hours + return await startHTTPServer( + (req, res) => { + // Set CORS headers + res.setHeader('Access-Control-Allow-Origin', `*`); // Allows all origins, or specify a domain like 'http://example.com' + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // Allowed HTTP methods + res.setHeader('Access-Control-Allow-Headers', '*'); // Allowed request headers + res.setHeader('Access-Control-Max-Age', '86400'); // Cache preflight requests for 24 hours - // Handle preflight requests (OPTIONS method) - if (req.method === 'OPTIONS') { - res.writeHead(204); // No content - res.end(); - return; - } + // Handle preflight requests (OPTIONS method) + if (req.method === 'OPTIONS') { + res.writeHead(204); // No content + res.end(); + return; + } - Promise.resolve(handler(req, res)).then(response=>{ - const {status = 200, headers = {}, body} = response || {}; + Promise.resolve(handler(req, res)).then((response) => { + const { status = 200, headers = {}, body } = response || {}; + res.statusCode = status; - res.statusCode = status; + Object.entries(headers).forEach((header, value) => { + res.setHeader(header, value); + }); - Object.entries(headers).forEach((header, value) => { - res.setHeader(header, value); + res.end(JSON.stringify(body, null, 2)); }); - - res.end(JSON.stringify(body, null, 2)) - }) - }, {port}); -} + }, + { port } + ); +}; diff --git a/test/manual/basic.html b/test/manual/basic.html index 35fa6490..7affac08 100644 --- a/test/manual/basic.html +++ b/test/manual/basic.html @@ -1,21 +1,24 @@ + + -An alert should be shown with the {"name":"axios"} + An alert should be shown with the {"name":"axios"} - - - + + + + \ No newline at end of file diff --git a/test/manual/cors.html b/test/manual/cors.html index da6e946f..4a85c37d 100644 --- a/test/manual/cors.html +++ b/test/manual/cors.html @@ -1,20 +1,23 @@ + + -An alert should be shown with {"status":"ok"} + An alert should be shown with {"status":"ok"} - - - + + + + \ No newline at end of file diff --git a/test/manual/progress.html b/test/manual/progress.html index e651b126..84f3a96b 100644 --- a/test/manual/progress.html +++ b/test/manual/progress.html @@ -1,37 +1,40 @@ + + -See your console - - + + - + + \ No newline at end of file diff --git a/test/module/cjs/index.js b/test/module/cjs/index.js index 7eb5dc03..57e34a62 100644 --- a/test/module/cjs/index.js +++ b/test/module/cjs/index.js @@ -1,7 +1,7 @@ const axios = require('axios'); const assert = require('assert'); -const {CanceledError, AxiosError, AxiosHeaders} = axios; +const { CanceledError, AxiosError, AxiosHeaders } = axios; assert.strictEqual(typeof axios, 'function'); assert.strictEqual(typeof CanceledError, 'function'); diff --git a/test/module/cjs/package.json b/test/module/cjs/package.json index 1b198f46..17dba005 100644 --- a/test/module/cjs/package.json +++ b/test/module/cjs/package.json @@ -12,4 +12,4 @@ "dependencies": { "axios": "file:../../.." } -} +} \ No newline at end of file diff --git a/test/module/esm/index.js b/test/module/esm/index.js index dd887617..3d60ebb3 100644 --- a/test/module/esm/index.js +++ b/test/module/esm/index.js @@ -1,5 +1,5 @@ import assert from 'assert'; -import axios, {CanceledError, AxiosError, AxiosHeaders} from 'axios'; +import axios, { CanceledError, AxiosError, AxiosHeaders } from 'axios'; import settle from 'axios/unsafe/core/settle.js'; assert.strictEqual(typeof axios, 'function'); diff --git a/test/module/esm/package.json b/test/module/esm/package.json index 16271506..084ab82f 100644 --- a/test/module/esm/package.json +++ b/test/module/esm/package.json @@ -13,4 +13,4 @@ "dependencies": { "axios": "file:../../.." } -} +} \ No newline at end of file diff --git a/test/module/test.js b/test/module/test.js index ca6e1f8b..ee957850 100644 --- a/test/module/test.js +++ b/test/module/test.js @@ -1,11 +1,11 @@ import assert from 'assert'; import * as axios from '../../index.js'; import axiosFactory from '../../lib/axios.js'; -import utils from "../../lib/utils.js"; -import {fileURLToPath} from 'url'; +import utils from '../../lib/utils.js'; +import { fileURLToPath } from 'url'; import path from 'path'; -import util from "util"; -import cp from "child_process"; +import util from 'util'; +import cp from 'child_process'; import fs from 'fs-extra'; const BACKUP_PATH = './backup/'; @@ -14,23 +14,23 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); const exec = util.promisify(cp.exec); -const spawn = (command, args) => new Promise((resolve, reject) => { - cp.spawn(command, args, { - shell : true, - stdio: 'inherit' - }).once('error', reject).on( - 'close', - (code) => code ? reject(new Error(`Exit code ${code}`)) : resolve() - ); -}); +const spawn = (command, args) => + new Promise((resolve, reject) => { + cp.spawn(command, args, { + shell: true, + stdio: 'inherit', + }) + .once('error', reject) + .on('close', (code) => (code ? reject(new Error(`Exit code ${code}`)) : resolve())); + }); -const {Axios} = axiosFactory; +const { Axios } = axiosFactory; const ignoreList = ['default']; const instance = axiosFactory.create({}); -const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const remove = async (file) => { console.log(`✓ Remove entry '${file}'...`); @@ -40,10 +40,9 @@ const remove = async (file) => { } catch (err) { console.warn(err.message); } -} +}; describe('module', function () { - before(async () => { console.log('✓ Creating build backup...'); await fs.copy('./dist/', BACKUP_PATH); @@ -59,7 +58,6 @@ describe('module', function () { }); describe('export', function () { - it('should have consistent ESM export', function () { const namedExport = {}; const factoryExport = {}; @@ -119,7 +117,7 @@ describe('module', function () { }); }); - describe('TS require(\'axios\')', () => { + describe("TS require('axios')", () => { const pkgPath = path.join(__dirname, './ts-require'); after(async () => { @@ -133,7 +131,7 @@ describe('module', function () { }); }); - describe('TS require(\'axios\').default', () => { + describe("TS require('axios').default", () => { const pkgPath = path.join(__dirname, './ts-require-default'); after(async () => { @@ -160,8 +158,8 @@ describe('module', function () { this.timeout(30000); await spawn(`npm test --prefix ${pkgPath}`, [], { - shell : true, - stdio: 'pipe' + shell: true, + stdio: 'pipe', }); }); }); @@ -177,8 +175,8 @@ describe('module', function () { this.timeout(30000); await spawn(`npm test --prefix ${pkgPath}`, [], { - shell : true, - stdio: 'pipe' + shell: true, + stdio: 'pipe', }); }); }); diff --git a/test/module/ts-require-default/index.js b/test/module/ts-require-default/index.js index 493f088c..196f1d32 100644 --- a/test/module/ts-require-default/index.js +++ b/test/module/ts-require-default/index.js @@ -1,7 +1,7 @@ "use strict"; const assert = require('assert'); const axios = require('axios').default; -const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData } = axios; +const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData, } = axios; assert.strictEqual(typeof axios, 'function'); assert.strictEqual(typeof CanceledError, 'function'); assert.strictEqual(typeof AxiosError, 'function'); diff --git a/test/module/ts-require-default/index.ts b/test/module/ts-require-default/index.ts index 408a7112..fe3a19d7 100644 --- a/test/module/ts-require-default/index.ts +++ b/test/module/ts-require-default/index.ts @@ -1,6 +1,16 @@ const assert = require('assert'); const axios = require('axios').default; -const {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} = axios; +const { + CanceledError, + AxiosError, + AxiosHeaders, + formToJSON, + spread, + isAxiosError, + isCancel, + all, + toFormData, +} = axios; assert.strictEqual(typeof axios, 'function'); diff --git a/test/module/ts-require-default/package.json b/test/module/ts-require-default/package.json index 23c39f3d..e69da691 100644 --- a/test/module/ts-require-default/package.json +++ b/test/module/ts-require-default/package.json @@ -17,4 +17,4 @@ "devDependencies": { "typescript": "^4.8.4" } -} +} \ No newline at end of file diff --git a/test/module/ts-require-default/tsconfig.json b/test/module/ts-require-default/tsconfig.json index ac1c5dbc..0e68f666 100644 --- a/test/module/ts-require-default/tsconfig.json +++ b/test/module/ts-require-default/tsconfig.json @@ -11,7 +11,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ @@ -25,9 +25,9 @@ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ + "module": "commonjs" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ @@ -71,12 +71,12 @@ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ @@ -98,6 +98,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } diff --git a/test/module/ts-require/index.js b/test/module/ts-require/index.js index 15bda4d5..38b7c444 100644 --- a/test/module/ts-require/index.js +++ b/test/module/ts-require/index.js @@ -1,7 +1,7 @@ "use strict"; const assert = require('assert'); const axios = require('axios'); -const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData } = axios; +const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData, } = axios; assert.strictEqual(typeof axios, 'function'); assert.strictEqual(typeof CanceledError, 'function'); assert.strictEqual(typeof AxiosError, 'function'); diff --git a/test/module/ts-require/index.ts b/test/module/ts-require/index.ts index 41829ef5..097b6f41 100644 --- a/test/module/ts-require/index.ts +++ b/test/module/ts-require/index.ts @@ -1,6 +1,16 @@ const assert = require('assert'); const axios = require('axios'); -const {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} = axios; +const { + CanceledError, + AxiosError, + AxiosHeaders, + formToJSON, + spread, + isAxiosError, + isCancel, + all, + toFormData, +} = axios; assert.strictEqual(typeof axios, 'function'); diff --git a/test/module/ts-require/package.json b/test/module/ts-require/package.json index 23c39f3d..e69da691 100644 --- a/test/module/ts-require/package.json +++ b/test/module/ts-require/package.json @@ -17,4 +17,4 @@ "devDependencies": { "typescript": "^4.8.4" } -} +} \ No newline at end of file diff --git a/test/module/ts-require/tsconfig.json b/test/module/ts-require/tsconfig.json index ac1c5dbc..0e68f666 100644 --- a/test/module/ts-require/tsconfig.json +++ b/test/module/ts-require/tsconfig.json @@ -11,7 +11,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ @@ -25,9 +25,9 @@ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ + "module": "commonjs" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ @@ -71,12 +71,12 @@ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ @@ -98,6 +98,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } diff --git a/test/module/ts/index.ts b/test/module/ts/index.ts index ce88fb5e..57dc9cd1 100644 --- a/test/module/ts/index.ts +++ b/test/module/ts/index.ts @@ -1,5 +1,15 @@ import assert from 'assert'; -import axios, {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} from 'axios'; +import axios, { + CanceledError, + AxiosError, + AxiosHeaders, + formToJSON, + spread, + isAxiosError, + isCancel, + all, + toFormData, +} from 'axios'; assert.strictEqual(typeof axios, 'function'); diff --git a/test/module/ts/package.json b/test/module/ts/package.json index 23c39f3d..e69da691 100644 --- a/test/module/ts/package.json +++ b/test/module/ts/package.json @@ -17,4 +17,4 @@ "devDependencies": { "typescript": "^4.8.4" } -} +} \ No newline at end of file diff --git a/test/module/ts/tsconfig.json b/test/module/ts/tsconfig.json index ac1c5dbc..0e68f666 100644 --- a/test/module/ts/tsconfig.json +++ b/test/module/ts/tsconfig.json @@ -11,7 +11,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "jsx": "preserve", /* Specify what JSX code is generated. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ @@ -25,9 +25,9 @@ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ + "module": "commonjs" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ @@ -71,12 +71,12 @@ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ @@ -98,6 +98,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } diff --git a/test/module/typings/cjs/index.ts b/test/module/typings/cjs/index.ts index 0304f054..e4ee57f9 100644 --- a/test/module/typings/cjs/index.ts +++ b/test/module/typings/cjs/index.ts @@ -6,22 +6,21 @@ const config: axios.AxiosRequestConfig = { allowAbsoluteUrls: false, baseURL: 'https://api.example.com/', transformRequest: (data: any) => '{"foo":"bar"}', - transformResponse: [ - (data: any) => ({ baz: 'qux' }) - ], + transformResponse: [(data: any) => ({ baz: 'qux' })], headers: { 'X-FOO': 'bar' }, params: { id: 12345 }, paramsSerializer: { indexes: true, encode: (value: any) => value, - serialize: (value: Record, options?: axios.ParamsSerializerOptions) => String(value) + serialize: (value: Record, options?: axios.ParamsSerializerOptions) => + String(value), }, data: { foo: 'bar' }, timeout: 10000, withCredentials: true, auth: { username: 'janedoe', - password: 's00pers3cret' + password: 's00pers3cret', }, responseType: 'json', xsrfCookieName: 'XSRF-TOKEN', @@ -34,17 +33,17 @@ const config: axios.AxiosRequestConfig = { maxRedirects: 5, proxy: { host: '127.0.0.1', - port: 9000 + port: 9000, }, - cancelToken: new axios.CancelToken((cancel: axios.Canceler) => {}) + cancelToken: new axios.CancelToken((cancel: axios.Canceler) => {}), }; const nullValidateStatusConfig: axios.AxiosRequestConfig = { - validateStatus: null + validateStatus: null, }; const undefinedValidateStatusConfig: axios.AxiosRequestConfig = { - validateStatus: undefined + validateStatus: undefined, }; const handleResponse = (response: axios.AxiosResponse) => { @@ -65,45 +64,31 @@ const handleError = (error: axios.AxiosError) => { } }; -axios(config) - .then(handleResponse) - .catch(handleError); +axios(config).then(handleResponse).catch(handleError); -axios.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); -axios.head('/user') - .then(handleResponse) - .catch(handleError); +axios.head('/user').then(handleResponse).catch(handleError); -axios.options('/user') - .then(handleResponse) - .catch(handleError); +axios.options('/user').then(handleResponse).catch(handleError); -axios.delete('/user') - .then(handleResponse) - .catch(handleError); +axios.delete('/user').then(handleResponse).catch(handleError); -axios.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.post('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); +axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); -axios.put('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.put('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -axios.patch('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.patch('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); // Typed methods interface UserCreationDef { @@ -130,46 +115,35 @@ const handleUserResponse = (response: axios.AxiosResponse) => { console.log(response.config); }; -axios.get('/user?id=12345') - .then(handleUserResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleUserResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleUserResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); -axios.head('/user') - .then(handleUserResponse) - .catch(handleError); +axios.head('/user').then(handleUserResponse).catch(handleError); -axios.options('/user') - .then(handleUserResponse) - .catch(handleError); +axios.options('/user').then(handleUserResponse).catch(handleError); -axios.delete('/user') - .then(handleUserResponse) - .catch(handleError); +axios.delete('/user').then(handleUserResponse).catch(handleError); -axios.post('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); +axios.post('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); -axios.post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) - .then(handleUserResponse) - .catch(handleError); +axios + .post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) + .then(handleUserResponse) + .catch(handleError); -axios.put('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); - -axios.patch('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); +axios.put('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); +axios.patch('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); // with custom response headers axios.AxiosResponse result -const handleUserResponseWithCustomHeaders = (response: axios.AxiosResponse) => { +const handleUserResponseWithCustomHeaders = ( + response: axios.AxiosResponse +) => { console.log(response.data.id); console.log(response.data.name); console.log(response.status); @@ -178,41 +152,54 @@ const handleUserResponseWithCustomHeaders = (response: axios.AxiosResponse>('/user?id=12345') -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .get>('/user?id=12345') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.get>('/user', { params: { id: 12345 } }) -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .get>('/user', { params: { id: 12345 } }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.head>('/user') -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .head>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.options>('/user') -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .options>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.delete>('/user') -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .delete>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.post>('/user', { name: 'foo', id: 1 }) -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .post>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.post>('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .post>( + '/user', + { name: 'foo', id: 1 }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.put>('/user', { name: 'foo', id: 1 }) -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .put>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.patch>('/user', { name: 'foo', id: 1 }) -.then(handleUserResponseWithCustomHeaders) -.catch(handleError); +axios + .patch>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); // (Typed methods) with custom response type @@ -220,81 +207,71 @@ const handleStringResponse = (response: string) => { console.log(response); }; -axios.get('/user?id=12345') - .then(handleStringResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleStringResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleStringResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleStringResponse) + .catch(handleError); -axios.head('/user') - .then(handleStringResponse) - .catch(handleError); +axios.head('/user').then(handleStringResponse).catch(handleError); -axios.options('/user') - .then(handleStringResponse) - .catch(handleError); +axios.options('/user').then(handleStringResponse).catch(handleError); -axios.delete('/user') - .then(handleStringResponse) - .catch(handleError); +axios.delete('/user').then(handleStringResponse).catch(handleError); -axios.post, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .post, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleStringResponse) - .catch(handleError); +axios + .post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleStringResponse) + .catch(handleError); -axios.put, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .put, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.patch, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .patch, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.request({ - method: 'get', - url: '/user?id=12345' -}) - .then(handleStringResponse) - .catch(handleError); +axios + .request({ + method: 'get', + url: '/user?id=12345', + }) + .then(handleStringResponse) + .catch(handleError); // Instances const instance1: axios.AxiosInstance = axios.create(); const instance2: axios.AxiosInstance = axios.create(config); -instance1(config) - .then(handleResponse) - .catch(handleError); +instance1(config).then(handleResponse).catch(handleError); -instance1.request(config) - .then(handleResponse) - .catch(handleError); +instance1.request(config).then(handleResponse).catch(handleError); -instance1.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); +instance1.get('/user?id=12345').then(handleResponse).catch(handleError); -instance1.options('/user') - .then(handleResponse) - .catch(handleError); +instance1.options('/user').then(handleResponse).catch(handleError); -instance1.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); +instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); -instance1.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +instance1.post('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); +instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); // Defaults @@ -329,33 +306,35 @@ axios.create({ // Interceptors const requestInterceptorId: number = axios.interceptors.request.use( - (config: axios.InternalAxiosRequestConfig) => config, - (error: any) => Promise.reject(error) + (config: axios.InternalAxiosRequestConfig) => config, + (error: any) => Promise.reject(error) ); axios.interceptors.request.eject(requestInterceptorId); axios.interceptors.request.use( - (config: axios.InternalAxiosRequestConfig) => Promise.resolve(config), - (error: any) => Promise.reject(error) + (config: axios.InternalAxiosRequestConfig) => Promise.resolve(config), + (error: any) => Promise.reject(error) ); axios.interceptors.request.use((config: axios.InternalAxiosRequestConfig) => config); -axios.interceptors.request.use((config: axios.InternalAxiosRequestConfig) => Promise.resolve(config)); +axios.interceptors.request.use((config: axios.InternalAxiosRequestConfig) => + Promise.resolve(config) +); const responseInterceptorId: number = axios.interceptors.response.use( - (response: axios.AxiosResponse) => response, - (error: any) => Promise.reject(error) + (response: axios.AxiosResponse) => response, + (error: any) => Promise.reject(error) ); axios.interceptors.response.eject(responseInterceptorId); axios.interceptors.response.use( - (response: axios.AxiosResponse) => Promise.resolve(response), - (error: any) => Promise.reject(error) + (response: axios.AxiosResponse) => Promise.resolve(response), + (error: any) => Promise.reject(error) ); -axios.interceptors.request.use(req => { +axios.interceptors.request.use((req) => { // https://github.com/axios/axios/issues/5415 req.headers.set('foo', 'bar'); req.headers['Content-Type'] = 123; @@ -363,14 +342,14 @@ axios.interceptors.request.use(req => { }); const voidRequestInterceptorId = axios.interceptors.request.use( - // @ts-expect-error -- Must return an axios.AxiosRequestConfig (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) + // @ts-expect-error -- Must return an axios.AxiosRequestConfig (or throw) + (_response) => {}, + (error: any) => Promise.reject(error) ); const voidResponseInterceptorId = axios.interceptors.response.use( - // @ts-expect-error -- Must return an axios.AxiosResponse (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) + // @ts-expect-error -- Must return an axios.AxiosResponse (or throw) + (_response) => {}, + (error: any) => Promise.reject(error) ); axios.interceptors.request.eject(voidRequestInterceptorId); axios.interceptors.response.eject(voidResponseInterceptorId); @@ -389,7 +368,7 @@ const adapter: axios.AxiosAdapter = (config: axios.InternalAxiosRequestConfig) = status: 200, statusText: 'OK', headers: { 'X-FOO': 'bar' }, - config + config, }; return Promise.resolve(response); }; @@ -398,10 +377,7 @@ axios.defaults.adapter = adapter; // axios.all -const promises = [ - Promise.resolve(1), - Promise.resolve(2) -]; +const promises = [Promise.resolve(1), Promise.resolve(2)]; const promise: Promise = axios.all(promises); @@ -412,61 +388,75 @@ const fn2: (arr: number[]) => string = axios.spread(fn1); // Promises -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo') - .then((value: string) => {}); +axios + .get('/user') + .then((response: axios.AxiosResponse) => 'foo') + .then((value: string) => {}); -axios.get('/user') - .then((response: axios.AxiosResponse) => Promise.resolve('foo')) - .then((value: string) => {}); +axios + .get('/user') + .then((response: axios.AxiosResponse) => Promise.resolve('foo')) + .then((value: string) => {}); -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo', (error: any) => 'bar') - .then((value: string) => {}); +axios + .get('/user') + .then( + (response: axios.AxiosResponse) => 'foo', + (error: any) => 'bar' + ) + .then((value: string) => {}); -axios.get('/user') - .then((response: axios.AxiosResponse) => 'foo', (error: any) => 123) - .then((value: string | number) => {}); +axios + .get('/user') + .then( + (response: axios.AxiosResponse) => 'foo', + (error: any) => 123 + ) + .then((value: string | number) => {}); -axios.get('/user') - .catch((error: any) => 'foo') - .then((value) => {}); +axios + .get('/user') + .catch((error: any) => 'foo') + .then((value) => {}); -axios.get('/user') - .catch((error: any) => Promise.resolve('foo')) - .then((value) => {}); +axios + .get('/user') + .catch((error: any) => Promise.resolve('foo')) + .then((value) => {}); // axios.Cancellation const source: axios.CancelTokenSource = axios.CancelToken.source(); -axios.get('/user', { - cancelToken: source.token -}).catch((thrown: axios.AxiosError | axios.Cancel) => { - if (axios.isCancel(thrown)) { - const cancel: axios.Cancel = thrown; - console.log(cancel.message); - } -}); +axios + .get('/user', { + cancelToken: source.token, + }) + .catch((thrown: axios.AxiosError | axios.Cancel) => { + if (axios.isCancel(thrown)) { + const cancel: axios.Cancel = thrown; + console.log(cancel.message); + } + }); source.cancel('Operation has been axios.Canceled.'); // axios.AxiosError -axios.get('/user') - .catch((error) => { - if (axios.isAxiosError(error)) { - const axiosError: axios.AxiosError = error; - } - }); +axios.get('/user').catch((error) => { + if (axios.isAxiosError(error)) { + const axiosError: axios.AxiosError = error; + console.log(axiosError.message); + } +}); // FormData -axios.toFormData({x: 1}, new FormData()); +axios.toFormData({ x: 1 }, new FormData()); // AbortSignal -axios.get('/user', {signal: new AbortController().signal}); +axios.get('/user', { signal: new AbortController().signal }); // AxiosHeaders methods @@ -478,13 +468,13 @@ axios.get('/user', { transformResponse: (data, headers) => { headers.has('foo'); - } + }, }); // Max Rate axios.get('/user', { - maxRate: 1000 + maxRate: 1000, }); axios.get('/user', { @@ -499,14 +489,14 @@ axios.get('/user', { console.log(e.total); console.log(e.progress); console.log(e.rate); - } + }, }); // AxiosHeaders // iterator -const headers = new axios.AxiosHeaders({foo: "bar"}) +const headers = new axios.AxiosHeaders({ foo: 'bar' }); for (const [header, value] of headers) { console.log(header, value); @@ -514,17 +504,16 @@ for (const [header, value] of headers) { // index signature -(()=>{ - const headers = new axios.AxiosHeaders({x:1}); +(() => { + const headers = new axios.AxiosHeaders({ x: 1 }); headers.y = 2; })(); - // AxiosRequestHeaders -(()=>{ - const headers:axios.AxiosRequestHeaders = new axios.AxiosHeaders({x:1}); +(() => { + const headers: axios.AxiosRequestHeaders = new axios.AxiosHeaders({ x: 1 }); headers.y = 2; @@ -535,28 +524,28 @@ for (const [header, value] of headers) { { const requestInterceptorId: number = axios.interceptors.request.use( - async (config) => { - config.headers.Accept ="foo"; - config.headers.setAccept("foo"); - config.headers = new axios.AxiosHeaders({x:1}); - config.headers.foo = "1"; - config.headers.set('bar', '2'); - config.headers.set({myHeader: "myValue"}) - config.headers = new axios.AxiosHeaders({myHeader: "myValue"}); - config.headers = {...config.headers} as axios.AxiosRequestHeaders; - return config; - }, - (error: any) => Promise.reject(error) + async (config) => { + config.headers.Accept = 'foo'; + config.headers.setAccept('foo'); + config.headers = new axios.AxiosHeaders({ x: 1 }); + config.headers.foo = '1'; + config.headers.set('bar', '2'); + config.headers.set({ myHeader: 'myValue' }); + config.headers = new axios.AxiosHeaders({ myHeader: 'myValue' }); + config.headers = { ...config.headers } as axios.AxiosRequestHeaders; + return config; + }, + (error: any) => Promise.reject(error) ); } { - const config: axios.AxiosRequestConfig = {headers: new axios.AxiosHeaders({foo: 1})}; + const config: axios.AxiosRequestConfig = { headers: new axios.AxiosHeaders({ foo: 1 }) }; axios.get('', { headers: { bar: 2, - ...config.headers - } + ...config.headers, + }, }); } diff --git a/test/module/typings/cjs/package.json b/test/module/typings/cjs/package.json index 58c4caf8..6fbe5f3f 100644 --- a/test/module/typings/cjs/package.json +++ b/test/module/typings/cjs/package.json @@ -17,4 +17,4 @@ "devDependencies": { "typescript": "^4.9.4" } -} +} \ No newline at end of file diff --git a/test/module/typings/esm/index.ts b/test/module/typings/esm/index.ts index e44e3ec0..fd59a10b 100644 --- a/test/module/typings/esm/index.ts +++ b/test/module/typings/esm/index.ts @@ -19,7 +19,8 @@ import axios, { all, isCancel, isAxiosError, - spread, AddressFamily + spread, + AddressFamily, } from 'axios'; const config: AxiosRequestConfig = { @@ -28,22 +29,20 @@ const config: AxiosRequestConfig = { baseURL: 'https://api.example.com/', allowAbsoluteUrls: false, transformRequest: (data: any) => '{"foo":"bar"}', - transformResponse: [ - (data: any) => ({ baz: 'qux' }) - ], + transformResponse: [(data: any) => ({ baz: 'qux' })], headers: { 'X-FOO': 'bar' }, params: { id: 12345 }, paramsSerializer: { indexes: true, encode: (value: any) => value, - serialize: (value: Record, options?: ParamsSerializerOptions) => String(value) + serialize: (value: Record, options?: ParamsSerializerOptions) => String(value), }, data: { foo: 'bar' }, timeout: 10000, withCredentials: true, auth: { username: 'janedoe', - password: 's00pers3cret' + password: 's00pers3cret', }, responseType: 'json', xsrfCookieName: 'XSRF-TOKEN', @@ -56,17 +55,17 @@ const config: AxiosRequestConfig = { maxRedirects: 5, proxy: { host: '127.0.0.1', - port: 9000 + port: 9000, }, - cancelToken: new axios.CancelToken((cancel: Canceler) => {}) + cancelToken: new axios.CancelToken((cancel: Canceler) => {}), }; const nullValidateStatusConfig: AxiosRequestConfig = { - validateStatus: null + validateStatus: null, }; const undefinedValidateStatusConfig: AxiosRequestConfig = { - validateStatus: undefined + validateStatus: undefined, }; const handleResponse = (response: AxiosResponse) => { @@ -87,45 +86,31 @@ const handleError = (error: AxiosError) => { } }; -axios(config) - .then(handleResponse) - .catch(handleError); +axios(config).then(handleResponse).catch(handleError); -axios.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); -axios.head('/user') - .then(handleResponse) - .catch(handleError); +axios.head('/user').then(handleResponse).catch(handleError); -axios.options('/user') - .then(handleResponse) - .catch(handleError); +axios.options('/user').then(handleResponse).catch(handleError); -axios.delete('/user') - .then(handleResponse) - .catch(handleError); +axios.delete('/user').then(handleResponse).catch(handleError); -axios.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.post('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); +axios + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); -axios.put('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.put('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -axios.patch('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +axios.patch('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); // Typed methods interface UserCreationDef { @@ -152,88 +137,91 @@ const handleUserResponse = (response: AxiosResponse) => { console.log(response.config); }; -axios.get('/user?id=12345') - .then(handleUserResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleUserResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleUserResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleUserResponse) + .catch(handleError); -axios.head('/user') - .then(handleUserResponse) - .catch(handleError); +axios.head('/user').then(handleUserResponse).catch(handleError); -axios.options('/user') - .then(handleUserResponse) - .catch(handleError); +axios.options('/user').then(handleUserResponse).catch(handleError); -axios.delete('/user') - .then(handleUserResponse) - .catch(handleError); +axios.delete('/user').then(handleUserResponse).catch(handleError); -axios.post('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); +axios.post('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); -axios.post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) - .then(handleUserResponse) - .catch(handleError); +axios + .post('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) + .then(handleUserResponse) + .catch(handleError); -axios.put('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); +axios.put('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); -axios.patch('/user', { name: 'foo', id: 1 }) - .then(handleUserResponse) - .catch(handleError); +axios.patch('/user', { name: 'foo', id: 1 }).then(handleUserResponse).catch(handleError); // with custom response headers AxiosResponse result -const handleUserResponseWithCustomHeaders = (response: AxiosResponse) => { - console.log(response.data.id); - console.log(response.data.name); - console.log(response.status); - console.log(response.statusText); - console.log(response.headers); - console.log(response.config); - }; +const handleUserResponseWithCustomHeaders = ( + response: AxiosResponse +) => { + console.log(response.data.id); + console.log(response.data.name); + console.log(response.status); + console.log(response.statusText); + console.log(response.headers); + console.log(response.config); +}; -axios.get>('/user?id=12345') - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .get>('/user?id=12345') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.get>('/user', { params: { id: 12345 } }) - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .get>('/user', { params: { id: 12345 } }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.head>('/user') - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .head>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.options>('/user') - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .options>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.delete>('/user') - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .delete>('/user') + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.post>('/user', { name: 'foo', id: 1 }) - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .post>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.post>('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .post>( + '/user', + { name: 'foo', id: 1 }, + { headers: { 'X-FOO': 'bar' } } + ) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.put>('/user', { name: 'foo', id: 1 }) - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .put>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); -axios.patch>('/user', { name: 'foo', id: 1 }) - .then(handleUserResponseWithCustomHeaders) - .catch(handleError); +axios + .patch>('/user', { name: 'foo', id: 1 }) + .then(handleUserResponseWithCustomHeaders) + .catch(handleError); // (Typed methods) with custom response type @@ -241,81 +229,71 @@ const handleStringResponse = (response: string) => { console.log(response); }; -axios.get('/user?id=12345') - .then(handleStringResponse) - .catch(handleError); +axios.get('/user?id=12345').then(handleStringResponse).catch(handleError); -axios.get('/user', { params: { id: 12345 } }) - .then(handleStringResponse) - .catch(handleError); +axios + .get('/user', { params: { id: 12345 } }) + .then(handleStringResponse) + .catch(handleError); -axios.head('/user') - .then(handleStringResponse) - .catch(handleError); +axios.head('/user').then(handleStringResponse).catch(handleError); -axios.options('/user') - .then(handleStringResponse) - .catch(handleError); +axios.options('/user').then(handleStringResponse).catch(handleError); -axios.delete('/user') - .then(handleStringResponse) - .catch(handleError); +axios.delete('/user').then(handleStringResponse).catch(handleError); -axios.post, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .post, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleStringResponse) - .catch(handleError); +axios + .post, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleStringResponse) + .catch(handleError); -axios.put, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .put, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.patch, string>('/user', { name: 'foo' }) - .then(handleStringResponse) - .catch(handleError); +axios + .patch, string>('/user', { name: 'foo' }) + .then(handleStringResponse) + .catch(handleError); -axios.request({ - method: 'get', - url: '/user?id=12345' -}) - .then(handleStringResponse) - .catch(handleError); +axios + .request({ + method: 'get', + url: '/user?id=12345', + }) + .then(handleStringResponse) + .catch(handleError); // Instances const instance1: AxiosInstance = axios.create(); const instance2: AxiosInstance = instance1.create(config); -instance1(config) - .then(handleResponse) - .catch(handleError); +instance1(config).then(handleResponse).catch(handleError); -instance1.request(config) - .then(handleResponse) - .catch(handleError); +instance1.request(config).then(handleResponse).catch(handleError); -instance1.get('/user?id=12345') - .then(handleResponse) - .catch(handleError); +instance1.get('/user?id=12345').then(handleResponse).catch(handleError); -instance1.options('/user') - .then(handleResponse) - .catch(handleError); +instance1.options('/user').then(handleResponse).catch(handleError); -instance1.get('/user', { params: { id: 12345 } }) - .then(handleResponse) - .catch(handleError); +instance1 + .get('/user', { params: { id: 12345 } }) + .then(handleResponse) + .catch(handleError); -instance1.post('/user', { foo: 'bar' }) - .then(handleResponse) - .catch(handleError); +instance1.post('/user', { foo: 'bar' }).then(handleResponse).catch(handleError); -instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) - .then(handleResponse) - .catch(handleError); +instance1 + .post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) + .then(handleResponse) + .catch(handleError); // Defaults @@ -350,39 +328,39 @@ axios.create({ // Interceptors const requestInterceptorId: number = axios.interceptors.request.use( - async (config) => { - await axios.get('/foo', { - headers: config.headers - }); - return config; - }, - (error: any) => Promise.reject(error), - {synchronous: false} + async (config) => { + await axios.get('/foo', { + headers: config.headers, + }); + return config; + }, + (error: any) => Promise.reject(error), + { synchronous: false } ); axios.interceptors.request.eject(requestInterceptorId); axios.interceptors.request.use( - (config) => Promise.resolve(config), - (error: any) => Promise.reject(error) + (config) => Promise.resolve(config), + (error: any) => Promise.reject(error) ); axios.interceptors.request.use((config) => config); axios.interceptors.request.use((config) => Promise.resolve(config)); const responseInterceptorId: number = axios.interceptors.response.use( - (response: AxiosResponse) => response, - (error: any) => Promise.reject(error) + (response: AxiosResponse) => response, + (error: any) => Promise.reject(error) ); axios.interceptors.response.eject(responseInterceptorId); axios.interceptors.response.use( - (response: AxiosResponse) => Promise.resolve(response), - (error: any) => Promise.reject(error) + (response: AxiosResponse) => Promise.resolve(response), + (error: any) => Promise.reject(error) ); -axios.interceptors.request.use(req => { +axios.interceptors.request.use((req) => { // https://github.com/axios/axios/issues/5415 req.headers.set('foo', 'bar'); req.headers['Content-Type'] = 123; @@ -390,14 +368,14 @@ axios.interceptors.request.use(req => { }); const voidRequestInterceptorId = axios.interceptors.request.use( - // @ts-expect-error -- Must return an AxiosRequestConfig (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) + // @ts-expect-error -- Must return an AxiosRequestConfig (or throw) + (_response) => {}, + (error: any) => Promise.reject(error) ); const voidResponseInterceptorId = axios.interceptors.response.use( - // @ts-expect-error -- Must return an AxiosResponse (or throw) - (_response) => {}, - (error: any) => Promise.reject(error) + // @ts-expect-error -- Must return an AxiosResponse (or throw) + (_response) => {}, + (error: any) => Promise.reject(error) ); axios.interceptors.request.eject(voidRequestInterceptorId); axios.interceptors.response.eject(voidResponseInterceptorId); @@ -416,7 +394,7 @@ const adapter: AxiosAdapter = (config) => { status: 200, statusText: 'OK', headers: { 'X-FOO': 'bar' }, - config + config, }; return Promise.resolve(response); }; @@ -425,20 +403,14 @@ axios.defaults.adapter = adapter; // axios.all -const promises = [ - Promise.resolve(1), - Promise.resolve(2) -]; +const promises = [Promise.resolve(1), Promise.resolve(2)]; const promise: Promise = axios.all(promises); // axios.all named export (() => { - const promises = [ - Promise.resolve(1), - Promise.resolve(2) - ]; + const promises = [Promise.resolve(1), Promise.resolve(2)]; const promise: Promise = all(promises); })(); @@ -456,72 +428,87 @@ const fn2: (arr: number[]) => string = axios.spread(fn1); // Promises -axios.get('/user') - .then((response: AxiosResponse) => 'foo') - .then((value: string) => {}); +axios + .get('/user') + .then((response: AxiosResponse) => 'foo') + .then((value: string) => {}); -axios.get('/user') - .then((response: AxiosResponse) => Promise.resolve('foo')) - .then((value: string) => {}); +axios + .get('/user') + .then((response: AxiosResponse) => Promise.resolve('foo')) + .then((value: string) => {}); -axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 'bar') - .then((value: string) => {}); +axios + .get('/user') + .then( + (response: AxiosResponse) => 'foo', + (error: any) => 'bar' + ) + .then((value: string) => {}); -axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 123) - .then((value: string | number) => {}); +axios + .get('/user') + .then( + (response: AxiosResponse) => 'foo', + (error: any) => 123 + ) + .then((value: string | number) => {}); -axios.get('/user') - .catch((error: any) => 'foo') - .then((value: any) => {}); +axios + .get('/user') + .catch((error: any) => 'foo') + .then((value: any) => {}); -axios.get('/user') - .catch((error: any) => Promise.resolve('foo')) - .then((value: any) => {}); +axios + .get('/user') + .catch((error: any) => Promise.resolve('foo')) + .then((value: any) => {}); // Cancellation const source: CancelTokenSource = axios.CancelToken.source(); -axios.get('/user', { - cancelToken: source.token -}).catch((thrown: AxiosError | Cancel) => { - if (axios.isCancel(thrown)) { - const cancel: Cancel = thrown; - console.log(cancel.message); - } +axios + .get('/user', { + cancelToken: source.token, + }) + .catch((thrown: AxiosError | Cancel) => { + if (axios.isCancel(thrown)) { + const cancel: Cancel = thrown; + console.log(cancel.message); + } - // named export - if (isCancel(thrown)) { - const cancel: Cancel = thrown; - console.log(cancel.message); - } -}); + // named export + if (isCancel(thrown)) { + const cancel: Cancel = thrown; + console.log(cancel.message); + } + }); source.cancel('Operation has been canceled.'); // AxiosError -axios.get('/user') - .catch((error: AxiosError) => { - if (axios.isAxiosError(error)) { - const axiosError: AxiosError = error; - } +axios.get('/user').catch((error: AxiosError) => { + if (axios.isAxiosError(error)) { + const axiosError: AxiosError = error; + console.log(axiosError.message); + } - // named export + // named export - if (isAxiosError(error)) { - const axiosError: AxiosError = error; - } - }); + if (isAxiosError(error)) { + const axiosError: AxiosError = error; + console.log(axiosError.message); + } +}); // FormData -axios.toFormData({x: 1}, new FormData()); +axios.toFormData({ x: 1 }, new FormData()); // named export -toFormData({x: 1}, new FormData()); +toFormData({ x: 1 }, new FormData()); // formToJSON @@ -532,7 +519,7 @@ formToJSON(new FormData()); // AbortSignal -axios.get('/user', {signal: new AbortController().signal}); +axios.get('/user', { signal: new AbortController().signal }); // AxiosHeaders methods @@ -544,25 +531,27 @@ axios.get('/user', { }, (data: any, headers) => { headers['foo'] = 'bar'; - return 'baz' - } + return 'baz'; + }, ], - transformResponse: [(data: any, headers: AxiosResponseHeaders) => { - headers.has('foo'); - }] + transformResponse: [ + (data: any, headers: AxiosResponseHeaders) => { + headers.has('foo'); + }, + ], }); // config headers axios.get('/user', { - headers: new AxiosHeaders({x:1}) + headers: new AxiosHeaders({ x: 1 }), }); axios.get('/user', { headers: { - foo : 1 - } + foo: 1, + }, }); // issue #5034 @@ -590,7 +579,7 @@ function getRequestConfig2(options: AxiosRequestConfig): AxiosRequestConfig { // Max Rate axios.get('/user', { - maxRate: 1000 + maxRate: 1000, }); axios.get('/user', { @@ -605,24 +594,23 @@ axios.get('/user', { console.log(e.total); console.log(e.progress); console.log(e.rate); - } + }, }); // adapters axios.get('/user', { - adapter: 'xhr' + adapter: 'xhr', }); axios.get('/user', { - adapter: 'http' + adapter: 'http', }); axios.get('/user', { - adapter: ['xhr', 'http'] + adapter: ['xhr', 'http'], }); - { // getAdapter @@ -653,7 +641,7 @@ axios.get('/user', { // iterator -const headers = new AxiosHeaders({foo: "bar"}) +const headers = new AxiosHeaders({ foo: 'bar' }); for (const [header, value] of headers) { console.log(header, value); @@ -661,16 +649,16 @@ for (const [header, value] of headers) { // index signature -(()=>{ - const headers = new AxiosHeaders({x:1}); +(() => { + const headers = new AxiosHeaders({ x: 1 }); headers.y = 2; })(); // AxiosRequestHeaders -(()=>{ - const headers:AxiosRequestHeaders = new AxiosHeaders({x:1}); +(() => { + const headers: AxiosRequestHeaders = new AxiosHeaders({ x: 1 }); headers.y = 2; @@ -681,44 +669,48 @@ for (const [header, value] of headers) { { const requestInterceptorId: number = axios.interceptors.request.use( - async (config) => { - config.headers.Accept ="foo"; - config.headers.setAccept("foo"); - config.headers = new AxiosHeaders({x:1}); - config.headers.foo = "1"; - config.headers.set('bar', '2'); - config.headers.set({myHeader: "myValue"}) - config.headers = new AxiosHeaders({myHeader: "myValue"}); - config.headers = {...config.headers} as AxiosRequestHeaders; - return config; - }, - (error: any) => Promise.reject(error) + async (config) => { + config.headers.Accept = 'foo'; + config.headers.setAccept('foo'); + config.headers = new AxiosHeaders({ x: 1 }); + config.headers.foo = '1'; + config.headers.set('bar', '2'); + config.headers.set({ myHeader: 'myValue' }); + config.headers = new AxiosHeaders({ myHeader: 'myValue' }); + config.headers = { ...config.headers } as AxiosRequestHeaders; + return config; + }, + (error: any) => Promise.reject(error) ); } { - const config: AxiosRequestConfig = {headers: new AxiosHeaders({foo: 1})}; + const config: AxiosRequestConfig = { headers: new AxiosHeaders({ foo: 1 }) }; axios.get('', { headers: { bar: 2, - ...config.headers - } + ...config.headers, + }, }); } // lookup axios.get('/user', { - lookup: (hostname: string, opt: object, cb: (err: Error | null, address: string, family: AddressFamily) => void) => { + lookup: ( + hostname: string, + opt: object, + cb: (err: Error | null, address: string, family: AddressFamily) => void + ) => { cb(null, '127.0.0.1', 4); - } + }, }); // lookup async axios.get('/user', { lookup: (hostname: string, opt: object) => { return ['127.0.0.1', 4]; - } + }, }); // AxiosError.cause should be typed as Error to allow accessing .message diff --git a/test/module/typings/esm/package.json b/test/module/typings/esm/package.json index 744077a3..02cf3798 100644 --- a/test/module/typings/esm/package.json +++ b/test/module/typings/esm/package.json @@ -18,4 +18,4 @@ "devDependencies": { "typescript": "^4.9.4" } -} +} \ No newline at end of file diff --git a/test/specs/__helpers.js b/test/specs/__helpers.js index 235f8589..94ace3d8 100644 --- a/test/specs/__helpers.js +++ b/test/specs/__helpers.js @@ -6,7 +6,7 @@ window.axios = _axios; jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000; jasmine.getEnv().defaultTimeoutInterval = 60000; -window.TEST_SERVER_URL = "http://localhost:3000"; +window.TEST_SERVER_URL = 'http://localhost:3000'; // Get Ajax request using an increasing timeout to retry window.getAjaxRequest = (function () { diff --git a/test/specs/adapter.spec.js b/test/specs/adapter.spec.js index 85b23eb0..4a5bc1ea 100644 --- a/test/specs/adapter.spec.js +++ b/test/specs/adapter.spec.js @@ -1,4 +1,3 @@ - describe('adapter', function () { beforeEach(function () { jasmine.Ajax.install(); @@ -18,16 +17,16 @@ describe('adapter', function () { request.onreadystatechange = function () { resolve({ config: config, - request: request + request: request, }); }; request.send(null); }); - } + }, }).catch(done); - getAjaxRequest().then(function(request) { + getAjaxRequest().then(function (request) { expect(request.url).toBe('/bar'); done(); }); @@ -44,19 +43,19 @@ describe('adapter', function () { request.onreadystatechange = function () { resolve({ config: config, - request: request + request: request, }); }; expect(asyncFlag).toBe(false); request.send(null); }); - } + }, }).catch(done); asyncFlag = true; - getAjaxRequest().then(function() { + getAjaxRequest().then(function () { done(); }); }); @@ -78,19 +77,19 @@ describe('adapter', function () { request.onreadystatechange = function () { resolve({ config: config, - request: request + request: request, }); }; expect(asyncFlag).toBe(true); request.send(null); }); - } + }, }).catch(done); asyncFlag = true; - getAjaxRequest().then(function() { + getAjaxRequest().then(function () { done(); }); }); diff --git a/test/specs/api.spec.js b/test/specs/api.spec.js index eab50e7a..11a3be51 100644 --- a/test/specs/api.spec.js +++ b/test/specs/api.spec.js @@ -1,4 +1,3 @@ - describe('static api', function () { it('should have request method helpers', function () { expect(typeof axios.request).toEqual('function'); @@ -43,7 +42,7 @@ describe('static api', function () { expect(typeof axios.isCancel).toEqual('function'); }); - it('should have getUri method', function() { + it('should have getUri method', function () { expect(typeof axios.getUri).toEqual('function'); }); diff --git a/test/specs/basicAuth.spec.js b/test/specs/basicAuth.spec.js index d453f83a..ccdef213 100644 --- a/test/specs/basicAuth.spec.js +++ b/test/specs/basicAuth.spec.js @@ -1,8 +1,8 @@ -import axios from "../../index"; +import axios from '../../index'; function validateInvalidCharacterError(error) { expect(/character/i.test(error.message)).toEqual(true); -}; +} describe('basicAuth', function () { // Validate an invalid character error @@ -18,8 +18,8 @@ describe('basicAuth', function () { axios('/foo', { auth: { username: 'Aladdin', - password: 'open sesame' - } + password: 'open sesame', + }, }); setTimeout(function () { @@ -33,8 +33,8 @@ describe('basicAuth', function () { it('should accept HTTP Basic auth credentials without the password parameter', function (done) { axios('/foo', { auth: { - username: 'Aladdin' - } + username: 'Aladdin', + }, }); setTimeout(function () { @@ -49,14 +49,16 @@ describe('basicAuth', function () { axios('/foo', { auth: { username: 'Aladdin', - password: 'open ßç£☃sesame' - } + password: 'open ßç£☃sesame', + }, }); setTimeout(function () { const request = jasmine.Ajax.requests.mostRecent(); - expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ=='); + expect(request.requestHeaders['Authorization']).toEqual( + 'Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ==' + ); done(); }, 100); }); @@ -65,13 +67,19 @@ describe('basicAuth', function () { axios('/foo', { auth: { username: 'Aladßç£☃din', - password: 'open sesame' - } - }).then(function (response) { - done(new Error('Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.')); - }).catch(function (error) { - validateInvalidCharacterError(error); - done(); - }); + password: 'open sesame', + }, + }) + .then(function (response) { + done( + new Error( + 'Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.' + ) + ); + }) + .catch(function (error) { + validateInvalidCharacterError(error); + done(); + }); }); }); diff --git a/test/specs/cancel.spec.js b/test/specs/cancel.spec.js index ac85769b..d91d0c68 100644 --- a/test/specs/cancel.spec.js +++ b/test/specs/cancel.spec.js @@ -1,65 +1,72 @@ const Cancel = axios.Cancel; const CancelToken = axios.CancelToken; -import {AbortController as _AbortController} from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; +import { AbortController as _AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; -const envAbortController = typeof AbortController === 'function' ? AbortController : _AbortController; +const envAbortController = + typeof AbortController === 'function' ? AbortController : _AbortController; -describe('cancel', function() { - beforeEach(function() { +describe('cancel', function () { + beforeEach(function () { jasmine.Ajax.install(); }); - afterEach(function() { + afterEach(function () { jasmine.Ajax.uninstall(); }); - describe('when called before sending request', function() { - it('rejects Promise with a CanceledError object', function(done) { + describe('when called before sending request', function () { + it('rejects Promise with a CanceledError object', function (done) { const source = CancelToken.source(); source.cancel('Operation has been canceled.'); - axios.get('/foo', { - cancelToken: source.token - }).catch(function(thrown) { - expect(thrown).toEqual(jasmine.any(Cancel)); - expect(thrown.message).toBe('Operation has been canceled.'); - done(); - }); + axios + .get('/foo', { + cancelToken: source.token, + }) + .catch(function (thrown) { + expect(thrown).toEqual(jasmine.any(Cancel)); + expect(thrown.message).toBe('Operation has been canceled.'); + done(); + }); }); }); - describe('when called after request has been sent', function() { - it('rejects Promise with a CanceledError object', function(done) { + describe('when called after request has been sent', function () { + it('rejects Promise with a CanceledError object', function (done) { const source = CancelToken.source(); - axios.get('/foo/bar', { - cancelToken: source.token - }).catch(function(thrown) { - expect(thrown).toEqual(jasmine.any(Cancel)); - expect(thrown.message).toBe('Operation has been canceled.'); - done(); - }); + axios + .get('/foo/bar', { + cancelToken: source.token, + }) + .catch(function (thrown) { + expect(thrown).toEqual(jasmine.any(Cancel)); + expect(thrown.message).toBe('Operation has been canceled.'); + done(); + }); - getAjaxRequest().then(function(request) { + getAjaxRequest().then(function (request) { // call cancel() when the request has been sent, but a response has not been received source.cancel('Operation has been canceled.'); request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); }); }); - it('calls abort on request object', function(done) { + it('calls abort on request object', function (done) { const source = CancelToken.source(); let request; - axios.get('/foo/bar', { - cancelToken: source.token - }).catch(function() { - // jasmine-ajax sets statusText to 'abort' when request.abort() is called - expect(request.statusText).toBe('abort'); - done(); - }); + axios + .get('/foo/bar', { + cancelToken: source.token, + }) + .catch(function () { + // jasmine-ajax sets statusText to 'abort' when request.abort() is called + expect(request.statusText).toBe('abort'); + done(); + }); - getAjaxRequest().then(function(req) { + getAjaxRequest().then(function (req) { // call cancel() when the request has been sent, but a response has not been received source.cancel(); request = req; @@ -90,27 +97,30 @@ describe('cancel', function() { // }); // }); - it('it should support cancellation using AbortController signal', function(done) { + it('it should support cancellation using AbortController signal', function (done) { const controller = new envAbortController(); - axios.get('/foo/bar', { - signal: controller.signal - }).then(function() { - done.fail('Has not been canceled'); - }, - function(thrown) { - expect(thrown).toEqual(jasmine.any(Cancel)); - done(); - } - ); + axios + .get('/foo/bar', { + signal: controller.signal, + }) + .then( + function () { + done.fail('Has not been canceled'); + }, + function (thrown) { + expect(thrown).toEqual(jasmine.any(Cancel)); + done(); + } + ); getAjaxRequest().then(function (request) { // call cancel() when the request has been sent, but a response has not been received controller.abort(); - setTimeout(function(){ + setTimeout(function () { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); }, 0); }); diff --git a/test/specs/cancel/CancelToken.spec.js b/test/specs/cancel/CancelToken.spec.js index d3901c54..9264a0c8 100644 --- a/test/specs/cancel/CancelToken.spec.js +++ b/test/specs/cancel/CancelToken.spec.js @@ -1,25 +1,25 @@ import CancelToken from '../../../lib/cancel/CancelToken'; import CanceledError from '../../../lib/cancel/CanceledError'; -describe('CancelToken', function() { - describe('constructor', function() { - it('throws when executor is not specified', function() { - expect(function() { +describe('CancelToken', function () { + describe('constructor', function () { + it('throws when executor is not specified', function () { + expect(function () { new CancelToken(); }).toThrowError(TypeError, 'executor must be a function.'); }); - it('throws when executor is not a function', function() { - expect(function() { + it('throws when executor is not a function', function () { + expect(function () { new CancelToken(123); }).toThrowError(TypeError, 'executor must be a function.'); }); }); - describe('reason', function() { - it('returns a CanceledError if cancellation has been requested', function() { + describe('reason', function () { + it('returns a CanceledError if cancellation has been requested', function () { let cancel; - const token = new CancelToken(function(c) { + const token = new CancelToken(function (c) { cancel = c; }); cancel('Operation has been canceled.'); @@ -27,16 +27,16 @@ describe('CancelToken', function() { expect(token.reason.message).toBe('Operation has been canceled.'); }); - it('returns undefined if cancellation has not been requested', function() { - const token = new CancelToken(function() {}); + it('returns undefined if cancellation has not been requested', function () { + const token = new CancelToken(function () {}); expect(token.reason).toBeUndefined(); }); }); - describe('promise', function() { - it('returns a Promise that resolves when cancellation is requested', function(done) { + describe('promise', function () { + it('returns a Promise that resolves when cancellation is requested', function (done) { let cancel; - const token = new CancelToken(function(c) { + const token = new CancelToken(function (c) { cancel = c; }); token.promise.then(function onFulfilled(value) { @@ -48,11 +48,11 @@ describe('CancelToken', function() { }); }); - describe('throwIfRequested', function() { - it('throws if cancellation has been requested', function() { + describe('throwIfRequested', function () { + it('throws if cancellation has been requested', function () { // Note: we cannot use expect.toThrowError here as CanceledError does not inherit from Error let cancel; - const token = new CancelToken(function(c) { + const token = new CancelToken(function (c) { cancel = c; }); cancel('Operation has been canceled.'); @@ -67,14 +67,14 @@ describe('CancelToken', function() { } }); - it('does not throw if cancellation has not been requested', function() { - const token = new CancelToken(function() {}); + it('does not throw if cancellation has not been requested', function () { + const token = new CancelToken(function () {}); token.throwIfRequested(); }); }); - describe('source', function() { - it('returns an object containing token and cancel function', function() { + describe('source', function () { + it('returns an object containing token and cancel function', function () { const source = CancelToken.source(); expect(source.token).toEqual(jasmine.any(CancelToken)); expect(source.cancel).toEqual(jasmine.any(Function)); diff --git a/test/specs/cancel/CanceledError.spec.js b/test/specs/cancel/CanceledError.spec.js index 57839ca2..df470c4c 100644 --- a/test/specs/cancel/CanceledError.spec.js +++ b/test/specs/cancel/CanceledError.spec.js @@ -1,21 +1,21 @@ import CanceledError from '../../../lib/cancel/CanceledError'; -describe('Cancel', function() { - describe('toString', function() { - it('returns correct result when message is not specified', function() { +describe('Cancel', function () { + describe('toString', function () { + it('returns correct result when message is not specified', function () { const cancel = new CanceledError(); expect(cancel.toString()).toBe('CanceledError: canceled'); }); - it('returns correct result when message is specified', function() { + it('returns correct result when message is specified', function () { const cancel = new CanceledError('Operation has been canceled.'); expect(cancel.toString()).toBe('CanceledError: Operation has been canceled.'); }); }); - it('should be a native error as checked by the NodeJS `isNativeError` function', function (){ - if((typeof process !== 'undefined') && (process.release.name === 'node')){ - let {isNativeError} = require('node:util/types'); - expect(isNativeError(new CanceledError("My Canceled Error"))).toBeTruthy(); + it('should be a native error as checked by the NodeJS `isNativeError` function', function () { + if (typeof process !== 'undefined' && process.release.name === 'node') { + let { isNativeError } = require('node:util/types'); + expect(isNativeError(new CanceledError('My Canceled Error'))).toBeTruthy(); } }); }); diff --git a/test/specs/cancel/isCancel.spec.js b/test/specs/cancel/isCancel.spec.js index 540c121f..4e685487 100644 --- a/test/specs/cancel/isCancel.spec.js +++ b/test/specs/cancel/isCancel.spec.js @@ -1,12 +1,12 @@ import isCancel from '../../../lib/cancel/isCancel'; import CanceledError from '../../../lib/cancel/CanceledError'; -describe('isCancel', function() { - it('returns true if value is a CanceledError', function() { +describe('isCancel', function () { + it('returns true if value is a CanceledError', function () { expect(isCancel(new CanceledError())).toBe(true); }); - it('returns false if value is not a CanceledError', function() { + it('returns false if value is not a CanceledError', function () { expect(isCancel({ foo: 'bar' })).toBe(false); }); }); diff --git a/test/specs/core/AxiosError.spec.js b/test/specs/core/AxiosError.spec.js index 3f4f594b..92576b69 100644 --- a/test/specs/core/AxiosError.spec.js +++ b/test/specs/core/AxiosError.spec.js @@ -1,8 +1,7 @@ import AxiosError from '../../../lib/core/AxiosError'; - -describe('core::AxiosError', function() { - it('should create an Error with message, config, code, request, response, stack and isAxiosError', function() { +describe('core::AxiosError', function () { + it('should create an Error with message, config, code, request, response, stack and isAxiosError', function () { const request = { path: '/foo' }; const response = { status: 200, data: { foo: 'bar' } }; const error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response); @@ -15,7 +14,7 @@ describe('core::AxiosError', function() { expect(error.isAxiosError).toBe(true); expect(error.stack).toBeDefined(); }); - it('should create an Error that can be serialized to JSON', function() { + it('should create an Error that can be serialized to JSON', function () { // Attempting to serialize request and response results in // TypeError: Converting circular structure to JSON const request = { path: '/foo' }; @@ -30,8 +29,8 @@ describe('core::AxiosError', function() { expect(json.response).toBe(undefined); }); - describe('core::createError.from', function() { - it('should add config, config, request and response to error', function() { + describe('core::createError.from', function () { + it('should add config, config, request and response to error', function () { const error = new Error('Boom!'); const request = { path: '/foo' }; const response = { status: 200, data: { foo: 'bar' } }; @@ -44,26 +43,28 @@ describe('core::AxiosError', function() { expect(axiosError.isAxiosError).toBe(true); }); - it('should return error', function() { + it('should return error', function () { const error = new Error('Boom!'); - expect(AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError).toBeTruthy(); + expect( + AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError + ).toBeTruthy(); }); }); - it('should be a native error as checked by the NodeJS `isNativeError` function', function (){ - if((typeof process !== 'undefined') && (process.release.name === 'node')){ - let {isNativeError} = require('node:util/types'); - expect(isNativeError(new AxiosError("My Axios Error"))).toBeTruthy(); + it('should be a native error as checked by the NodeJS `isNativeError` function', function () { + if (typeof process !== 'undefined' && process.release.name === 'node') { + let { isNativeError } = require('node:util/types'); + expect(isNativeError(new AxiosError('My Axios Error'))).toBeTruthy(); } }); - it('should create an error using one of the static class properties as an error code', function (){ - const myError = new AxiosError("My Axios Error", AxiosError.ECONNABORTED); + it('should create an error using one of the static class properties as an error code', function () { + const myError = new AxiosError('My Axios Error', AxiosError.ECONNABORTED); expect(myError.code).toEqual(AxiosError.ECONNABORTED); }); it('should have status property when response was passed to the constructor', () => { - const err = new AxiosError('test', 'foo', {}, {}, {status: 400}); - expect(err.status).toBe(400); + const err = new AxiosError('test', 'foo', {}, {}, { status: 400 }); + expect(err.status).toBe(400); }); }); diff --git a/test/specs/core/buildFullPath.spec.js b/test/specs/core/buildFullPath.spec.js index 19319cb8..ea3ed101 100644 --- a/test/specs/core/buildFullPath.spec.js +++ b/test/specs/core/buildFullPath.spec.js @@ -6,15 +6,21 @@ describe('helpers::buildFullPath', function () { }); it('should not combine the URLs when the requestedURL is absolute', function () { - expect(buildFullPath('https://api.github.com', 'https://api.example.com/users')).toBe('https://api.example.com/users'); + expect(buildFullPath('https://api.github.com', 'https://api.example.com/users')).toBe( + 'https://api.example.com/users' + ); }); it('should combine the URLs when the requestedURL is absolute and allowAbsoluteUrls is false', function () { - expect(buildFullPath('https://api.github.com', 'https://api.example.com/users', false)).toBe('https://api.github.com/https://api.example.com/users'); + expect(buildFullPath('https://api.github.com', 'https://api.example.com/users', false)).toBe( + 'https://api.github.com/https://api.example.com/users' + ); }); it('should not combine the URLs when the requestedURL is absolute, allowAbsoluteUrls is false, and the baseURL is not configured', function () { - expect(buildFullPath(undefined, 'https://api.example.com/users', false)).toBe('https://api.example.com/users'); + expect(buildFullPath(undefined, 'https://api.example.com/users', false)).toBe( + 'https://api.example.com/users' + ); }); it('should not combine URLs when the baseURL is not configured', function () { @@ -24,5 +30,4 @@ describe('helpers::buildFullPath', function () { it('should combine URLs when the baseURL and requestedURL are relative', function () { expect(buildFullPath('/api', '/users')).toBe('/api/users'); }); - }); diff --git a/test/specs/core/mergeConfig.spec.js b/test/specs/core/mergeConfig.spec.js index 465b6a0d..4add0b0e 100644 --- a/test/specs/core/mergeConfig.spec.js +++ b/test/specs/core/mergeConfig.spec.js @@ -1,28 +1,28 @@ import defaults from '../../../lib/defaults'; import mergeConfig from '../../../lib/core/mergeConfig'; -import {AxiosHeaders} from "../../../index.js"; +import { AxiosHeaders } from '../../../index.js'; -describe('core::mergeConfig', function() { - it('should accept undefined for second argument', function() { +describe('core::mergeConfig', function () { + it('should accept undefined for second argument', function () { expect(mergeConfig(defaults, undefined)).toEqual(defaults); }); - it('should accept an object for second argument', function() { + it('should accept an object for second argument', function () { expect(mergeConfig(defaults, {})).toEqual(defaults); }); - it('should not leave references', function() { + it('should not leave references', function () { const merged = mergeConfig(defaults, {}); expect(merged).not.toBe(defaults); expect(merged.headers).not.toBe(defaults.headers); }); - it('should allow setting request options', function() { + it('should allow setting request options', function () { const config = { url: '__sample url__', method: '__sample method__', params: '__sample params__', - data: { foo: true } + data: { foo: true }, }; const merged = mergeConfig(defaults, config); expect(merged.url).toEqual(config.url); @@ -31,28 +31,32 @@ describe('core::mergeConfig', function() { expect(merged.data).toEqual(config.data); }); - it('should not inherit request options', function() { + it('should not inherit request options', function () { const localDefaults = { method: '__sample method__', - data: { foo: true } + data: { foo: true }, }; const merged = mergeConfig(localDefaults, {}); expect(merged.method).toEqual(undefined); expect(merged.data).toEqual(undefined); }); - ['auth', 'headers', 'params', 'proxy'].forEach(function(key) { - it('should set new config for' + key + ' without default', function() { - const a = {}, b = {}, c = {}; - a[key] = undefined - b[key] = { user: 'foo', pass: 'test' } - c[key] = { user: 'foo', pass: 'test' } + ['auth', 'headers', 'params', 'proxy'].forEach(function (key) { + it('should set new config for' + key + ' without default', function () { + const a = {}, + b = {}, + c = {}; + a[key] = undefined; + b[key] = { user: 'foo', pass: 'test' }; + c[key] = { user: 'foo', pass: 'test' }; expect(mergeConfig(a, b)).toEqual(c); }); - it('should merge ' + key + ' with defaults', function() { - const a = {}, b = {}, c = {}; + it('should merge ' + key + ' with defaults', function () { + const a = {}, + b = {}, + c = {}; a[key] = { user: 'foo', pass: 'bar' }; b[key] = { pass: 'test' }; c[key] = { user: 'foo', pass: 'test' }; @@ -60,9 +64,11 @@ describe('core::mergeConfig', function() { expect(mergeConfig(a, b)).toEqual(c); }); - it('should overwrite default ' + key + ' with a non-object value', function() { - [false, null, 123].forEach(function(value) { - const a = {}, b = {}, c = {}; + it('should overwrite default ' + key + ' with a non-object value', function () { + [false, null, 123].forEach(function (value) { + const a = {}, + b = {}, + c = {}; a[key] = { user: 'foo', pass: 'test' }; b[key] = value; c[key] = value; @@ -72,261 +78,270 @@ describe('core::mergeConfig', function() { }); }); - it('should allow setting other options', function() { + it('should allow setting other options', function () { const merged = mergeConfig(defaults, { timeout: 123 }); expect(merged.timeout).toEqual(123); }); - it('should allow setting custom options', function() { + it('should allow setting custom options', function () { const merged = mergeConfig(defaults, { foo: 'bar' }); expect(merged.foo).toEqual('bar'); }); - it('should allow setting custom default options', function() { + it('should allow setting custom default options', function () { const merged = mergeConfig({ foo: 'bar' }, {}); expect(merged.foo).toEqual('bar'); }); - it('should allow merging custom objects in the config', function() { - const merged = mergeConfig({ - nestedConfig: { - propertyOnDefaultConfig: true + it('should allow merging custom objects in the config', function () { + const merged = mergeConfig( + { + nestedConfig: { + propertyOnDefaultConfig: true, + }, + }, + { + nestedConfig: { + propertyOnRequestConfig: true, + }, } - }, { - nestedConfig: { - propertyOnRequestConfig: true - } - }); + ); expect(merged.nestedConfig.propertyOnDefaultConfig).toEqual(true); expect(merged.nestedConfig.propertyOnRequestConfig).toEqual(true); }); describe('headers', () => { it('should allow merging with AxiosHeaders instances', () => { - const merged = mergeConfig({ - headers: new AxiosHeaders({ - x: 1, - y: 2 - }) - }, { - headers: new AxiosHeaders({ - X: 1, - Y: 2 - }) - }); + const merged = mergeConfig( + { + headers: new AxiosHeaders({ + x: 1, + y: 2, + }), + }, + { + headers: new AxiosHeaders({ + X: 1, + Y: 2, + }), + } + ); expect(merged.headers).toEqual({ x: '1', - y: '2' + y: '2', }); }); }); + describe('valueFromConfig2Keys', function () { + const config1 = { url: '/foo', method: 'post', data: { a: 3 } }; - describe('valueFromConfig2Keys', function() { - const config1 = {url: '/foo', method: 'post', data: {a: 3}}; - - it('should skip if config2 is undefined', function() { + it('should skip if config2 is undefined', function () { expect(mergeConfig(config1, {})).toEqual({}); }); - it('should clone config2 if is plain object', function() { - const data = {a: 1, b: 2}; - const merged = mergeConfig(config1, {data: data}); + it('should clone config2 if is plain object', function () { + const data = { a: 1, b: 2 }; + const merged = mergeConfig(config1, { data: data }); expect(merged.data).toEqual(data); expect(merged.data).not.toBe(data); }); - it('should clone config2 if is array', function() { + it('should clone config2 if is array', function () { const data = [1, 2, 3]; - const merged = mergeConfig(config1, {data: data}); + const merged = mergeConfig(config1, { data: data }); expect(merged.data).toEqual(data); expect(merged.data).not.toBe(data); }); - it('should set as config2 in other cases', function() { + it('should set as config2 in other cases', function () { const obj = Object.create({}); - expect(mergeConfig(config1, {data: 1}).data).toBe(1); - expect(mergeConfig(config1, {data: 'str'}).data).toBe('str'); - expect(mergeConfig(config1, {data: obj}).data).toBe(obj); - expect(mergeConfig(config1, {data: null}).data).toBe(null); + expect(mergeConfig(config1, { data: 1 }).data).toBe(1); + expect(mergeConfig(config1, { data: 'str' }).data).toBe('str'); + expect(mergeConfig(config1, { data: obj }).data).toBe(obj); + expect(mergeConfig(config1, { data: null }).data).toBe(null); }); }); - describe('mergeDeepPropertiesKeys', function() { - it('should skip if both config1 and config2 are undefined', function() { - expect(mergeConfig({headers: undefined}, {headers: undefined})).toEqual({}); + describe('mergeDeepPropertiesKeys', function () { + it('should skip if both config1 and config2 are undefined', function () { + expect(mergeConfig({ headers: undefined }, { headers: undefined })).toEqual({}); }); - it('should merge if both config1 and config2 are plain object', function() { - expect(mergeConfig({headers: {a: 1, b: 1}}, {headers: {b: 2, c: 2}})) - .toEqual({headers: {a: 1, b: 2, c: 2}}); + it('should merge if both config1 and config2 are plain object', function () { + expect(mergeConfig({ headers: { a: 1, b: 1 } }, { headers: { b: 2, c: 2 } })).toEqual({ + headers: { a: 1, b: 2, c: 2 }, + }); }); - it('should clone config2 if is plain object', function() { - const config1 = {headers: [1, 2, 3]}; - const config2 = {headers: {a: 1, b: 2}}; + it('should clone config2 if is plain object', function () { + const config1 = { headers: [1, 2, 3] }; + const config2 = { headers: { a: 1, b: 2 } }; const merged = mergeConfig(config1, config2); expect(merged.headers).toEqual(config2.headers); expect(merged.headers).not.toBe(config2.headers); }); - it('should clone config2 if is array', function() { - const config1 = {headers: {a: 1, b: 1}}; - const config2 = {headers: [1, 2, 3]}; + it('should clone config2 if is array', function () { + const config1 = { headers: { a: 1, b: 1 } }; + const config2 = { headers: [1, 2, 3] }; const merged = mergeConfig(config1, config2); expect(merged.headers).toEqual(config2.headers); expect(merged.headers).not.toBe(config2.headers); }); - it('should set as config2 in other cases', function() { - const config1 = {headers: {a: 1, b: 1}}; + it('should set as config2 in other cases', function () { + const config1 = { headers: { a: 1, b: 1 } }; const obj = Object.create({}); - expect(mergeConfig(config1, {headers: 1}).headers).toBe(1); - expect(mergeConfig(config1, {headers: 'str'}).headers).toBe('str'); - expect(mergeConfig(config1, {headers: obj}).headers).toBe(obj); - expect(mergeConfig(config1, {headers: null}).headers).toBe(null); + expect(mergeConfig(config1, { headers: 1 }).headers).toBe(1); + expect(mergeConfig(config1, { headers: 'str' }).headers).toBe('str'); + expect(mergeConfig(config1, { headers: obj }).headers).toBe(obj); + expect(mergeConfig(config1, { headers: null }).headers).toBe(null); }); - it('should clone config1 if is plain object', function() { - const config1 = {headers: {a: 1, b: 2}}; + it('should clone config1 if is plain object', function () { + const config1 = { headers: { a: 1, b: 2 } }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.headers).toEqual(config1.headers); expect(merged.headers).not.toBe(config1.headers); }); - it('should clone config1 if is array', function() { - const config1 = {headers: [1, 2, 3]}; + it('should clone config1 if is array', function () { + const config1 = { headers: [1, 2, 3] }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.headers).toEqual(config1.headers); expect(merged.headers).not.toBe(config1.headers); }); - it('should set as config1 in other cases', function() { + it('should set as config1 in other cases', function () { const config2 = {}; const obj = Object.create({}); - expect(mergeConfig({headers: 1}, config2).headers).toBe(1); - expect(mergeConfig({headers: 'str'}, config2).headers).toBe('str'); - expect(mergeConfig({headers: obj}, config2).headers).toBe(obj); - expect(mergeConfig({headers: null}, config2).headers).toBe(null); + expect(mergeConfig({ headers: 1 }, config2).headers).toBe(1); + expect(mergeConfig({ headers: 'str' }, config2).headers).toBe('str'); + expect(mergeConfig({ headers: obj }, config2).headers).toBe(obj); + expect(mergeConfig({ headers: null }, config2).headers).toBe(null); }); }); - describe('defaultToConfig2Keys', function() { - it('should skip if both config1 and config2 are undefined', function() { - expect(mergeConfig({transformRequest: undefined}, {transformRequest: undefined})).toEqual({}); + describe('defaultToConfig2Keys', function () { + it('should skip if both config1 and config2 are undefined', function () { + expect(mergeConfig({ transformRequest: undefined }, { transformRequest: undefined })).toEqual( + {} + ); }); - it('should clone config2 if both config1 and config2 are plain object', function() { - const config1 = {transformRequest: {a: 1, b: 1}}; - const config2 = {transformRequest: {b: 2, c: 2}}; + it('should clone config2 if both config1 and config2 are plain object', function () { + const config1 = { transformRequest: { a: 1, b: 1 } }; + const config2 = { transformRequest: { b: 2, c: 2 } }; const merged = mergeConfig(config1, config2); expect(merged.transformRequest).toEqual(config2.transformRequest); expect(merged.transformRequest).not.toBe(config2.transformRequest); }); - it('should clone config2 if is array', function() { - const config1 = {transformRequest: {a: 1, b: 1}}; - const config2 = {transformRequest: [1, 2, 3]}; + it('should clone config2 if is array', function () { + const config1 = { transformRequest: { a: 1, b: 1 } }; + const config2 = { transformRequest: [1, 2, 3] }; const merged = mergeConfig(config1, config2); expect(merged.transformRequest).toEqual(config2.transformRequest); expect(merged.transformRequest).not.toBe(config2.transformRequest); }); - it('should set as config2 in other cases', function() { - const config1 = {transformRequest: {a: 1, b: 1}}; + it('should set as config2 in other cases', function () { + const config1 = { transformRequest: { a: 1, b: 1 } }; const obj = Object.create({}); - expect(mergeConfig(config1, {transformRequest: 1}).transformRequest).toBe(1); - expect(mergeConfig(config1, {transformRequest: 'str'}).transformRequest).toBe('str'); - expect(mergeConfig(config1, {transformRequest: obj}).transformRequest).toBe(obj); - expect(mergeConfig(config1, {transformRequest: null}).transformRequest).toBe(null); + expect(mergeConfig(config1, { transformRequest: 1 }).transformRequest).toBe(1); + expect(mergeConfig(config1, { transformRequest: 'str' }).transformRequest).toBe('str'); + expect(mergeConfig(config1, { transformRequest: obj }).transformRequest).toBe(obj); + expect(mergeConfig(config1, { transformRequest: null }).transformRequest).toBe(null); }); - it('should clone config1 if is plain object', function() { - const config1 = {transformRequest: {a: 1, b: 2}}; + it('should clone config1 if is plain object', function () { + const config1 = { transformRequest: { a: 1, b: 2 } }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.transformRequest).toEqual(config1.transformRequest); expect(merged.transformRequest).not.toBe(config1.transformRequest); }); - it('should clone config1 if is array', function() { - const config1 = {transformRequest: [1, 2, 3]}; + it('should clone config1 if is array', function () { + const config1 = { transformRequest: [1, 2, 3] }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.transformRequest).toEqual(config1.transformRequest); expect(merged.transformRequest).not.toBe(config1.transformRequest); }); - it('should set as config1 in other cases', function() { + it('should set as config1 in other cases', function () { const config2 = {}; const obj = Object.create({}); - expect(mergeConfig({transformRequest: 1}, config2).transformRequest).toBe(1); - expect(mergeConfig({transformRequest: 'str'}, config2).transformRequest).toBe('str'); - expect(mergeConfig({transformRequest: obj}, config2).transformRequest).toBe(obj); - expect(mergeConfig({transformRequest: null}, config2).transformRequest).toBe(null); + expect(mergeConfig({ transformRequest: 1 }, config2).transformRequest).toBe(1); + expect(mergeConfig({ transformRequest: 'str' }, config2).transformRequest).toBe('str'); + expect(mergeConfig({ transformRequest: obj }, config2).transformRequest).toBe(obj); + expect(mergeConfig({ transformRequest: null }, config2).transformRequest).toBe(null); }); }); - describe('directMergeKeys', function() { - it('should merge if config2 in keys', function() { - expect(mergeConfig({}, {validateStatus: undefined})).toEqual({validateStatus: undefined}); + describe('directMergeKeys', function () { + it('should merge if config2 in keys', function () { + expect(mergeConfig({}, { validateStatus: undefined })).toEqual({ validateStatus: undefined }); }); - it('should merge if both config1 and config2 are plain object', function() { - expect(mergeConfig({validateStatus: {a: 1, b: 1}}, {validateStatus: {b: 2, c: 2}})) - .toEqual({validateStatus: {a: 1, b: 2, c: 2}}); + it('should merge if both config1 and config2 are plain object', function () { + expect( + mergeConfig({ validateStatus: { a: 1, b: 1 } }, { validateStatus: { b: 2, c: 2 } }) + ).toEqual({ validateStatus: { a: 1, b: 2, c: 2 } }); }); - it('should clone config2 if is plain object', function() { - const config1 = {validateStatus: [1, 2, 3]}; - const config2 = {validateStatus: {a: 1, b: 2}}; + it('should clone config2 if is plain object', function () { + const config1 = { validateStatus: [1, 2, 3] }; + const config2 = { validateStatus: { a: 1, b: 2 } }; const merged = mergeConfig(config1, config2); expect(merged.validateStatus).toEqual(config2.validateStatus); expect(merged.validateStatus).not.toBe(config2.validateStatus); }); - it('should clone config2 if is array', function() { - const config1 = {validateStatus: {a: 1, b: 2}}; - const config2 = {validateStatus: [1, 2, 3]}; + it('should clone config2 if is array', function () { + const config1 = { validateStatus: { a: 1, b: 2 } }; + const config2 = { validateStatus: [1, 2, 3] }; const merged = mergeConfig(config1, config2); expect(merged.validateStatus).toEqual(config2.validateStatus); expect(merged.validateStatus).not.toBe(config2.validateStatus); }); - it('should set as config2 in other cases', function() { - const config1 = {validateStatus: {a: 1, b: 2}}; + it('should set as config2 in other cases', function () { + const config1 = { validateStatus: { a: 1, b: 2 } }; const obj = Object.create({}); - expect(mergeConfig(config1, {validateStatus: 1}).validateStatus).toBe(1); - expect(mergeConfig(config1, {validateStatus: 'str'}).validateStatus).toBe('str'); - expect(mergeConfig(config1, {validateStatus: obj}).validateStatus).toBe(obj); - expect(mergeConfig(config1, {validateStatus: null}).validateStatus).toBe(null); + expect(mergeConfig(config1, { validateStatus: 1 }).validateStatus).toBe(1); + expect(mergeConfig(config1, { validateStatus: 'str' }).validateStatus).toBe('str'); + expect(mergeConfig(config1, { validateStatus: obj }).validateStatus).toBe(obj); + expect(mergeConfig(config1, { validateStatus: null }).validateStatus).toBe(null); }); - it('should clone config1 if is plain object', function() { - const config1 = {validateStatus: {a: 1, b: 2}}; + it('should clone config1 if is plain object', function () { + const config1 = { validateStatus: { a: 1, b: 2 } }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.validateStatus).toEqual(config1.validateStatus); expect(merged.validateStatus).not.toBe(config1.validateStatus); }); - it('should clone config1 if is array', function() { - const config1 = {validateStatus: [1, 2, 3]}; + it('should clone config1 if is array', function () { + const config1 = { validateStatus: [1, 2, 3] }; const config2 = {}; const merged = mergeConfig(config1, config2); expect(merged.validateStatus).toEqual(config1.validateStatus); expect(merged.validateStatus).not.toBe(config1.validateStatus); }); - it('should set as config1 in other cases', function() { + it('should set as config1 in other cases', function () { const config2 = {}; const obj = Object.create({}); - expect(mergeConfig({validateStatus: 1}, config2).validateStatus).toBe(1); - expect(mergeConfig({validateStatus: 'str'}, config2).validateStatus).toBe('str'); - expect(mergeConfig({validateStatus: obj}, config2).validateStatus).toBe(obj); - expect(mergeConfig({validateStatus: null}, config2).validateStatus).toBe(null); + expect(mergeConfig({ validateStatus: 1 }, config2).validateStatus).toBe(1); + expect(mergeConfig({ validateStatus: 'str' }, config2).validateStatus).toBe('str'); + expect(mergeConfig({ validateStatus: obj }, config2).validateStatus).toBe(obj); + expect(mergeConfig({ validateStatus: null }, config2).validateStatus).toBe(null); }); }); }); diff --git a/test/specs/core/settle.spec.js b/test/specs/core/settle.spec.js index 87009bc6..7a13e965 100644 --- a/test/specs/core/settle.spec.js +++ b/test/specs/core/settle.spec.js @@ -1,64 +1,63 @@ import settle from '../../../lib/core/settle'; -describe('core::settle', function() { +describe('core::settle', function () { let resolve; let reject; - beforeEach(function() { + beforeEach(function () { resolve = jasmine.createSpy('resolve'); reject = jasmine.createSpy('reject'); }); - it('should resolve promise if status is not set', function() { + it('should resolve promise if status is not set', function () { const response = { config: { - validateStatus: function() { + validateStatus: function () { return true; - } - } - }; - settle(resolve, reject, response); - expect(resolve).toHaveBeenCalledWith(response); - expect(reject).not.toHaveBeenCalled(); - }); - - it('should resolve promise if validateStatus is not set', function() { - const response = { - status: 500, - config: { - } - }; - settle(resolve, reject, response); - expect(resolve).toHaveBeenCalledWith(response); - expect(reject).not.toHaveBeenCalled(); - }); - - it('should resolve promise if validateStatus returns true', function() { - const response = { - status: 500, - config: { - validateStatus: function() { - return true; - } - } - }; - settle(resolve, reject, response); - expect(resolve).toHaveBeenCalledWith(response); - expect(reject).not.toHaveBeenCalled(); - }); - - it('should reject promise if validateStatus returns false', function() { - const req = { - path: '/foo' - }; - const response = { - status: 500, - config: { - validateStatus: function() { - return false; - } + }, }, - request: req + }; + settle(resolve, reject, response); + expect(resolve).toHaveBeenCalledWith(response); + expect(reject).not.toHaveBeenCalled(); + }); + + it('should resolve promise if validateStatus is not set', function () { + const response = { + status: 500, + config: {}, + }; + settle(resolve, reject, response); + expect(resolve).toHaveBeenCalledWith(response); + expect(reject).not.toHaveBeenCalled(); + }); + + it('should resolve promise if validateStatus returns true', function () { + const response = { + status: 500, + config: { + validateStatus: function () { + return true; + }, + }, + }; + settle(resolve, reject, response); + expect(resolve).toHaveBeenCalledWith(response); + expect(reject).not.toHaveBeenCalled(); + }); + + it('should reject promise if validateStatus returns false', function () { + const req = { + path: '/foo', + }; + const response = { + status: 500, + config: { + validateStatus: function () { + return false; + }, + }, + request: req, }; settle(resolve, reject, response); expect(resolve).not.toHaveBeenCalled(); @@ -71,13 +70,13 @@ describe('core::settle', function() { expect(reason.response).toBe(response); }); - it('should pass status to validateStatus', function() { + it('should pass status to validateStatus', function () { const validateStatus = jasmine.createSpy('validateStatus'); const response = { status: 500, config: { - validateStatus: validateStatus - } + validateStatus: validateStatus, + }, }; settle(resolve, reject, response); expect(validateStatus).toHaveBeenCalledWith(500); diff --git a/test/specs/core/transformData.spec.js b/test/specs/core/transformData.spec.js index 5201c73f..dd3626ad 100644 --- a/test/specs/core/transformData.spec.js +++ b/test/specs/core/transformData.spec.js @@ -4,28 +4,30 @@ describe('core::transformData', function () { it('should support a single transformer', function () { let data; - data = transformData.call({ - - }, function (data) { + data = transformData.call({}, function (data) { data = 'foo'; return data; - }) + }); expect(data).toEqual('foo'); }); it('should support an array of transformers', function () { let data = ''; - data = transformData.call({data}, [function (data) { - data += 'f'; - return data; - }, function (data) { - data += 'o'; - return data; - }, function (data) { - data += 'o'; - return data; - }]); + data = transformData.call({ data }, [ + function (data) { + data += 'f'; + return data; + }, + function (data) { + data += 'o'; + return data; + }, + function (data) { + data += 'o'; + return data; + }, + ]); expect(data).toEqual('foo'); }); @@ -35,22 +37,29 @@ describe('core::transformData', function () { 'content-type': 'foo/bar', }; let data = ''; - data = transformData.call({data, headers}, [function (data, headers) { - data += headers['content-type']; - return data; - }]); + data = transformData.call({ data, headers }, [ + function (data, headers) { + data += headers['content-type']; + return data; + }, + ]); expect(data).toEqual('foo/bar'); }); it('should support reference status code in transformData', function () { let data = ''; - data = transformData.call({}, [function (data, headers, status) { - data += status; - return data; - }], {data, status: 200}); + data = transformData.call( + {}, + [ + function (data, headers, status) { + data += status; + return data; + }, + ], + { data, status: 200 } + ); expect(data).toEqual('200'); }); }); - diff --git a/test/specs/defaults.spec.js b/test/specs/defaults.spec.js index 55dfe494..53a94213 100644 --- a/test/specs/defaults.spec.js +++ b/test/specs/defaults.spec.js @@ -13,18 +13,23 @@ describe('defaults', function () { delete axios.defaults.baseURL; delete axios.defaults.headers.get['X-CUSTOM-HEADER']; delete axios.defaults.headers.post['X-CUSTOM-HEADER']; - document.cookie = XSRF_COOKIE_NAME + '=;expires=' + new Date(Date.now() - 86400000).toGMTString(); + document.cookie = + XSRF_COOKIE_NAME + '=;expires=' + new Date(Date.now() - 86400000).toGMTString(); }); it('should transform request json', function () { - expect(defaults.transformRequest[0]({foo: 'bar'}, new AxiosHeaders())).toEqual('{"foo":"bar"}'); + expect(defaults.transformRequest[0]({ foo: 'bar' }, new AxiosHeaders())).toEqual( + '{"foo":"bar"}' + ); }); it("should also transform request json when 'Content-Type' is 'application/json'", function () { const headers = new AxiosHeaders({ 'Content-Type': 'application/json', }); - expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}'); + expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual( + '{"foo":"bar"}' + ); expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]'); expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"'); expect(defaults.transformRequest[0](42, headers)).toEqual('42'); @@ -33,12 +38,12 @@ describe('defaults', function () { expect(defaults.transformRequest[0](null, headers)).toEqual('null'); }); - it("should transform the plain data object to a FormData instance 'Content-Type' if header is 'multipart/form-data'", function() { + it("should transform the plain data object to a FormData instance 'Content-Type' if header is 'multipart/form-data'", function () { const headers = new AxiosHeaders({ - 'Content-Type': 'multipart/form-data' + 'Content-Type': 'multipart/form-data', }); - const payload = {x: 1}; + const payload = { x: 1 }; const transformed = defaults.transformRequest[0](payload, headers); @@ -82,7 +87,7 @@ describe('defaults', function () { it('should use request config', function (done) { axios('/foo', { - baseURL: 'http://www.example.com' + baseURL: 'http://www.example.com', }); getAjaxRequest().then(function (request) { @@ -94,7 +99,7 @@ describe('defaults', function () { it('should use default config for custom instance', function (done) { const instance = axios.create({ xsrfCookieName: XSRF_COOKIE_NAME, - xsrfHeaderName: 'X-CUSTOM-XSRF-TOKEN' + xsrfHeaderName: 'X-CUSTOM-XSRF-TOKEN', }); document.cookie = instance.defaults.xsrfCookieName + '=foobarbaz'; @@ -130,22 +135,22 @@ describe('defaults', function () { const instance = axios.create({ headers: { common: { - 'X-COMMON-HEADER': 'commonHeaderValue' + 'X-COMMON-HEADER': 'commonHeaderValue', }, get: { - 'X-GET-HEADER': 'getHeaderValue' + 'X-GET-HEADER': 'getHeaderValue', }, post: { - 'X-POST-HEADER': 'postHeaderValue' - } - } + 'X-POST-HEADER': 'postHeaderValue', + }, + }, }); instance.get('/foo', { headers: { 'X-FOO-HEADER': 'fooHeaderValue', - 'X-BAR-HEADER': 'barHeaderValue' - } + 'X-BAR-HEADER': 'barHeaderValue', + }, }); getAjaxRequest().then(function (request) { @@ -154,7 +159,7 @@ describe('defaults', function () { 'X-COMMON-HEADER': 'commonHeaderValue', 'X-GET-HEADER': 'getHeaderValue', 'X-FOO-HEADER': 'fooHeaderValue', - 'X-BAR-HEADER': 'barHeaderValue' + 'X-BAR-HEADER': 'barHeaderValue', }).toJSON() ); done(); diff --git a/test/specs/formdata.spec.js b/test/specs/formdata.spec.js index a0dffe99..0b8c01c3 100644 --- a/test/specs/formdata.spec.js +++ b/test/specs/formdata.spec.js @@ -1,17 +1,19 @@ -import {retryNetwork} from "../helpers/retry.js"; +import { retryNetwork } from '../helpers/retry.js'; -describe('FormData', function() { +describe('FormData', function () { it('should allow FormData posting', async () => { await retryNetwork(() => { - return axios.postForm(TEST_SERVER_URL, { - a: 'foo', - b: 'bar' - }).then(({data}) => { - expect(data.form).toEqual({ + return axios + .postForm(TEST_SERVER_URL, { a: 'foo', - b: 'bar' + b: 'bar', + }) + .then(({ data }) => { + expect(data.form).toEqual({ + a: 'foo', + b: 'bar', + }); }); - }); }); }); -}) +}); diff --git a/test/specs/headers.spec.js b/test/specs/headers.spec.js index d55c06d7..a95e22b8 100644 --- a/test/specs/headers.spec.js +++ b/test/specs/headers.spec.js @@ -1,4 +1,4 @@ -const {AxiosHeaders} = axios; +const { AxiosHeaders } = axios; function testHeaderValue(headers, key, val) { let found = false; @@ -49,10 +49,10 @@ describe('headers', function () { instance.defaults.headers.common['Content-Type'] = 'application/custom'; - instance.patch('/foo', ""); + instance.patch('/foo', ''); const expectedHeaders = { - 'Content-Type': "application/custom" + 'Content-Type': 'application/custom', }; return getAjaxRequest().then(function (request) { @@ -71,43 +71,52 @@ describe('headers', function () { return getAjaxRequest().then(function (request) { for (const key in headers) { - expect(request.requestHeaders[key]).toEqual(headers[key]); + expect(request.requestHeaders[key]).toEqual(headers[key]); } }); }); it('should reset headers by null or explicit undefined', function (done) { - axios.create({ - headers: { - common: { - 'x-header-a': 'a', - 'x-header-b': 'b', - 'x-header-c': 'c' + axios + .create({ + headers: { + common: { + 'x-header-a': 'a', + 'x-header-b': 'b', + 'x-header-c': 'c', + }, + }, + }) + .post( + '/foo', + { fizz: 'buzz' }, + { + headers: { + 'Content-Type': null, + 'x-header-a': null, + 'x-header-b': undefined, + }, } - } - }).post('/foo', {fizz: 'buzz'}, { - headers: { - 'Content-Type': null, - 'x-header-a': null, - 'x-header-b': undefined - } - }).catch(function (err) { - done(err); - }); + ) + .catch(function (err) { + done(err); + }); - getAjaxRequest().then(function (request) { - testHeaderValue(request.requestHeaders, 'Content-Type', undefined); - testHeaderValue(request.requestHeaders, 'x-header-a', undefined); - testHeaderValue(request.requestHeaders, 'x-header-b', undefined); - testHeaderValue(request.requestHeaders, 'x-header-c', 'c'); - done(); - }).catch(done); + getAjaxRequest() + .then(function (request) { + testHeaderValue(request.requestHeaders, 'Content-Type', undefined); + testHeaderValue(request.requestHeaders, 'x-header-a', undefined); + testHeaderValue(request.requestHeaders, 'x-header-b', undefined); + testHeaderValue(request.requestHeaders, 'x-header-c', 'c'); + done(); + }) + .catch(done); }); it('should use application/json when posting an object', function (done) { axios.post('/foo/bar', { firstName: 'foo', - lastName: 'bar' + lastName: 'bar', }); getAjaxRequest().then(function (request) { @@ -137,15 +146,15 @@ describe('headers', function () { const instance = axios.create({ headers: new AxiosHeaders({ xFoo: 'foo', - xBar: 'bar' - }) + xBar: 'bar', + }), }); instance.get('/foo', { headers: { XFOO: 'foo2', - xBaz: 'baz' - } + xBaz: 'baz', + }, }); await getAjaxRequest().then(function (request) { @@ -154,6 +163,5 @@ describe('headers', function () { expect(request.requestHeaders.xBaz).toEqual('baz'); expect(request.requestHeaders.XFOO).toEqual(undefined); }); - }); }); diff --git a/test/specs/helpers/buildURL.spec.js b/test/specs/helpers/buildURL.spec.js index cee95c62..0f137baf 100644 --- a/test/specs/helpers/buildURL.spec.js +++ b/test/specs/helpers/buildURL.spec.js @@ -6,78 +6,94 @@ describe('helpers::buildURL', function () { }); it('should support params', function () { - expect(buildURL('/foo', { - foo: 'bar', - isUndefined: undefined, - isNull: null - })).toEqual('/foo?foo=bar'); + expect( + buildURL('/foo', { + foo: 'bar', + isUndefined: undefined, + isNull: null, + }) + ).toEqual('/foo?foo=bar'); }); it('should support sending raw params to custom serializer func', function () { - const serializer = sinon.stub(); - const params = { foo: "bar" }; - serializer.returns("foo=bar"); + const serializer = sinon.stub(); + const params = { foo: 'bar' }; + serializer.returns('foo=bar'); expect( buildURL( - "/foo", + '/foo', { - foo: "bar", + foo: 'bar', }, { serialize: serializer, } ) - ).toEqual("/foo?foo=bar"); + ).toEqual('/foo?foo=bar'); expect(serializer.calledOnce).toBe(true); expect(serializer.calledWith(params)).toBe(true); }); it('should support object params', function () { - expect(buildURL('/foo', { - foo: { - bar: 'baz' - } - })).toEqual('/foo?foo%5Bbar%5D=baz'); + expect( + buildURL('/foo', { + foo: { + bar: 'baz', + }, + }) + ).toEqual('/foo?foo%5Bbar%5D=baz'); }); it('should support date params', function () { const date = new Date(); - expect(buildURL('/foo', { - date: date - })).toEqual('/foo?date=' + date.toISOString()); + expect( + buildURL('/foo', { + date: date, + }) + ).toEqual('/foo?date=' + date.toISOString()); }); it('should support array params with encode', function () { - expect(buildURL('/foo', { - foo: ['bar', 'baz'] - })).toEqual('/foo?foo%5B%5D=bar&foo%5B%5D=baz'); + expect( + buildURL('/foo', { + foo: ['bar', 'baz'], + }) + ).toEqual('/foo?foo%5B%5D=bar&foo%5B%5D=baz'); }); it('should support special char params', function () { - expect(buildURL('/foo', { - foo: ':$, ' - })).toEqual('/foo?foo=:$,+'); + expect( + buildURL('/foo', { + foo: ':$, ', + }) + ).toEqual('/foo?foo=:$,+'); }); it('should support existing params', function () { - expect(buildURL('/foo?foo=bar', { - bar: 'baz' - })).toEqual('/foo?foo=bar&bar=baz'); + expect( + buildURL('/foo?foo=bar', { + bar: 'baz', + }) + ).toEqual('/foo?foo=bar&bar=baz'); }); it('should support "length" parameter', function () { - expect(buildURL('/foo', { - query: 'bar', - start: 0, - length: 5 - })).toEqual('/foo?query=bar&start=0&length=5'); + expect( + buildURL('/foo', { + query: 'bar', + start: 0, + length: 5, + }) + ).toEqual('/foo?query=bar&start=0&length=5'); }); it('should correct discard url hash mark', function () { - expect(buildURL('/foo?foo=bar#hash', { - query: 'baz' - })).toEqual('/foo?foo=bar&query=baz'); + expect( + buildURL('/foo?foo=bar#hash', { + query: 'baz', + }) + ).toEqual('/foo?foo=bar&query=baz'); }); it('should support URLSearchParams', function () { @@ -86,22 +102,22 @@ describe('helpers::buildURL', function () { it('should support custom serialize function', function () { const params = { - x: 1 - } + x: 1, + }; const options = { serialize: (thisParams, thisOptions) => { expect(thisParams).toEqual(params); expect(thisOptions).toEqual(options); - return "rendered" - } + return 'rendered'; + }, }; expect(buildURL('/foo', params, options)).toEqual('/foo?rendered'); const customSerializer = (thisParams) => { expect(thisParams).toEqual(params); - return "rendered" + return 'rendered'; }; expect(buildURL('/foo', params, customSerializer)).toEqual('/foo?rendered'); diff --git a/test/specs/helpers/cookies.spec.js b/test/specs/helpers/cookies.spec.js index 041f8552..812f6d06 100644 --- a/test/specs/helpers/cookies.spec.js +++ b/test/specs/helpers/cookies.spec.js @@ -3,12 +3,15 @@ import cookies from '../../../lib/helpers/cookies'; describe('helpers::cookies', function () { afterEach(function () { // Remove all the cookies - const expires = Date.now() - (60 * 60 * 24 * 7); - document.cookie.split(';').map(function (cookie) { - return cookie.split('=')[0]; - }).forEach(function (name) { - document.cookie = name + '=; expires=' + new Date(expires).toGMTString(); - }); + const expires = Date.now() - 60 * 60 * 24 * 7; + document.cookie + .split(';') + .map(function (cookie) { + return cookie.split('=')[0]; + }) + .forEach(function (name) { + document.cookie = name + '=; expires=' + new Date(expires).toGMTString(); + }); }); it('should write cookies', function () { diff --git a/test/specs/helpers/formDataToJSON.spec.js b/test/specs/helpers/formDataToJSON.spec.js index d49177e9..deb07802 100644 --- a/test/specs/helpers/formDataToJSON.spec.js +++ b/test/specs/helpers/formDataToJSON.spec.js @@ -9,9 +9,9 @@ describe('formDataToJSON', function () { expect(formDataToJSON(formData)).toEqual({ foo: { bar: { - baz: '123' - } - } + baz: '123', + }, + }, }); }); @@ -22,7 +22,7 @@ describe('formDataToJSON', function () { formData.append('foo', '2'); expect(formDataToJSON(formData)).toEqual({ - foo: ['1', '2'] + foo: ['1', '2'], }); }); @@ -33,7 +33,7 @@ describe('formDataToJSON', function () { formData.append('foo[]', '2'); expect(formDataToJSON(formData)).toEqual({ - foo: ['1', '2'] + foo: ['1', '2'], }); }); @@ -44,7 +44,7 @@ describe('formDataToJSON', function () { formData.append('foo[1]', '2'); expect(formDataToJSON(formData)).toEqual({ - foo: ['1', '2'] + foo: ['1', '2'], }); }); @@ -60,9 +60,9 @@ describe('formDataToJSON', function () { foo: ['1', '2'], constructor: { prototype: { - y: 'value' - } - } + y: 'value', + }, + }, }); expect({}.x).toEqual(undefined); diff --git a/test/specs/helpers/isAxiosError.spec.js b/test/specs/helpers/isAxiosError.spec.js index f818a86e..8dedea77 100644 --- a/test/specs/helpers/isAxiosError.spec.js +++ b/test/specs/helpers/isAxiosError.spec.js @@ -1,24 +1,20 @@ import AxiosError from '../../../lib/core/AxiosError'; import isAxiosError from '../../../lib/helpers/isAxiosError'; -describe('helpers::isAxiosError', function() { - it('should return true if the error is created by core::createError', function() { - expect(isAxiosError(new AxiosError('Boom!', null, { foo: 'bar' }))) - .toBe(true); +describe('helpers::isAxiosError', function () { + it('should return true if the error is created by core::createError', function () { + expect(isAxiosError(new AxiosError('Boom!', null, { foo: 'bar' }))).toBe(true); }); - it('should return true if the error is enhanced by core::enhanceError', function() { - expect(isAxiosError(AxiosError.from(new Error('Boom!'), null, { foo: 'bar' }))) - .toBe(true); + it('should return true if the error is enhanced by core::enhanceError', function () { + expect(isAxiosError(AxiosError.from(new Error('Boom!'), null, { foo: 'bar' }))).toBe(true); }); - it('should return false if the error is a normal Error instance', function() { - expect(isAxiosError(new Error('Boom!'))) - .toBe(false); + it('should return false if the error is a normal Error instance', function () { + expect(isAxiosError(new Error('Boom!'))).toBe(false); }); it('should return false if the error is null', function () { - expect(isAxiosError(null)) - .toBe(false); + expect(isAxiosError(null)).toBe(false); }); }); diff --git a/test/specs/helpers/parseHeaders.spec.js b/test/specs/helpers/parseHeaders.spec.js index 068fd5ee..60d3895f 100644 --- a/test/specs/helpers/parseHeaders.spec.js +++ b/test/specs/helpers/parseHeaders.spec.js @@ -4,10 +4,12 @@ describe('helpers::parseHeaders', function () { it('should parse headers', function () { const date = new Date(); const parsed = parseHeaders( - 'Date: ' + date.toISOString() + '\n' + - 'Content-Type: application/json\n' + - 'Connection: keep-alive\n' + - 'Transfer-Encoding: chunked' + 'Date: ' + + date.toISOString() + + '\n' + + 'Content-Type: application/json\n' + + 'Connection: keep-alive\n' + + 'Transfer-Encoding: chunked' ); expect(parsed['date']).toEqual(date.toISOString()); @@ -16,27 +18,22 @@ describe('helpers::parseHeaders', function () { expect(parsed['transfer-encoding']).toEqual('chunked'); }); - it('should use array for set-cookie', function() { + it('should use array for set-cookie', function () { const parsedZero = parseHeaders(''); - const parsedSingle = parseHeaders( - 'Set-Cookie: key=val;' - ); - const parsedMulti = parseHeaders( - 'Set-Cookie: key=val;\n' + - 'Set-Cookie: key2=val2;\n' - ); + const parsedSingle = parseHeaders('Set-Cookie: key=val;'); + const parsedMulti = parseHeaders('Set-Cookie: key=val;\n' + 'Set-Cookie: key2=val2;\n'); expect(parsedZero['set-cookie']).toBeUndefined(); expect(parsedSingle['set-cookie']).toEqual(['key=val;']); expect(parsedMulti['set-cookie']).toEqual(['key=val;', 'key2=val2;']); }); - it('should handle duplicates', function() { + it('should handle duplicates', function () { const parsed = parseHeaders( 'Age: age-a\n' + // age is in ignore duplicates blocklist - 'Age: age-b\n' + - 'Foo: foo-a\n' + - 'Foo: foo-b\n' + 'Age: age-b\n' + + 'Foo: foo-a\n' + + 'Foo: foo-b\n' ); expect(parsed['age']).toEqual('age-a'); diff --git a/test/specs/helpers/spread.spec.js b/test/specs/helpers/spread.spec.js index 9e465ec8..a9f98557 100644 --- a/test/specs/helpers/spread.spec.js +++ b/test/specs/helpers/spread.spec.js @@ -18,4 +18,3 @@ describe('helpers::spread', function () { expect(value).toEqual(50); }); }); - diff --git a/test/specs/helpers/toFormData.spec.js b/test/specs/helpers/toFormData.spec.js index 8e6265d8..246118e4 100644 --- a/test/specs/helpers/toFormData.spec.js +++ b/test/specs/helpers/toFormData.spec.js @@ -5,11 +5,11 @@ describe('toFormData', function () { const o = { val: 123, nested: { - arr: ['hello', 'world'] - } + arr: ['hello', 'world'], + }, }; - const form = toFormData(o, null, {dots: true}); + const form = toFormData(o, null, { dots: true }); expect(form instanceof FormData).toEqual(true); expect(Array.from(form.keys()).length).toEqual(3); expect(form.get('val')).toEqual('123'); @@ -18,12 +18,12 @@ describe('toFormData', function () { it('should respect metaTokens option', function () { const data = { - 'obj{}': {x: 1, y: 2} + 'obj{}': { x: 1, y: 2 }, }; const str = JSON.stringify(data['obj{}']); - const form = toFormData(data, null, {metaTokens: false}); + const form = toFormData(data, null, { metaTokens: false }); expect(Array.from(form.keys()).length).toEqual(1); expect(form.getAll('obj')).toEqual([str]); @@ -33,10 +33,10 @@ describe('toFormData', function () { it('should include full indexes when the `indexes` option is set to true', function () { const data = { arr: [1, 2, 3], - arr2: [1, [2], 3] + arr2: [1, [2], 3], }; - const form = toFormData(data, null, {indexes: true}); + const form = toFormData(data, null, { indexes: true }); expect(Array.from(form.keys()).length).toEqual(6); @@ -52,10 +52,10 @@ describe('toFormData', function () { it('should include brackets only when the `indexes` option is set to false', function () { const data = { arr: [1, 2, 3], - arr2: [1, [2], 3] + arr2: [1, [2], 3], }; - const form = toFormData(data, null, {indexes: false}); + const form = toFormData(data, null, { indexes: false }); expect(Array.from(form.keys()).length).toEqual(6); @@ -69,10 +69,10 @@ describe('toFormData', function () { it('should omit brackets when the `indexes` option is set to null', function () { const data = { arr: [1, 2, 3], - arr2: [1, [2], 3] + arr2: [1, [2], 3], }; - const form = toFormData(data, null, {indexes: null}); + const form = toFormData(data, null, { indexes: null }); expect(Array.from(form.keys()).length).toEqual(6); @@ -88,8 +88,8 @@ describe('toFormData', function () { const o = { val: 123, nested: { - arr: ['hello', 'world'] - } + arr: ['hello', 'world'], + }, }; const form = toFormData(o); @@ -101,7 +101,7 @@ describe('toFormData', function () { it('should append value whose key ends with [] as separate values with the same key', function () { const data = { - 'arr[]': [1, 2, 3] + 'arr[]': [1, 2, 3], }; const form = toFormData(data); @@ -112,7 +112,7 @@ describe('toFormData', function () { it('should append value whose key ends with {} as a JSON string', function () { const data = { - 'obj{}': {x: 1, y: 2} + 'obj{}': { x: 1, y: 2 }, }; const str = JSON.stringify(data['obj{}']); @@ -123,4 +123,3 @@ describe('toFormData', function () { expect(form.getAll('obj{}')).toEqual([str]); }); }); - diff --git a/test/specs/helpers/validator.spec.js b/test/specs/helpers/validator.spec.js index 6c53e4c9..1b7b194f 100644 --- a/test/specs/helpers/validator.spec.js +++ b/test/specs/helpers/validator.spec.js @@ -2,42 +2,54 @@ import validator from '../../../lib/helpers/validator'; -describe('validator::assertOptions', function() { - it('should throw only if unknown an option was passed', function() { - expect(function() { - validator.assertOptions({ - x: true - }, { - y: validator.validators.boolean - }); +describe('validator::assertOptions', function () { + it('should throw only if unknown an option was passed', function () { + expect(function () { + validator.assertOptions( + { + x: true, + }, + { + y: validator.validators.boolean, + } + ); }).toThrow(new Error('Unknown option x')); - expect(function() { - validator.assertOptions({ - x: true - }, { - x: validator.validators.boolean, - y: validator.validators.boolean - }); + expect(function () { + validator.assertOptions( + { + x: true, + }, + { + x: validator.validators.boolean, + y: validator.validators.boolean, + } + ); }).not.toThrow(new Error('Unknown option x')); }); - it('should throw TypeError only if option type doesn\'t match', function() { - expect(function() { - validator.assertOptions({ - x: 123 - }, { - x: validator.validators.boolean - }); + it("should throw TypeError only if option type doesn't match", function () { + expect(function () { + validator.assertOptions( + { + x: 123, + }, + { + x: validator.validators.boolean, + } + ); }).toThrow(new TypeError('option x must be a boolean')); - expect(function() { - validator.assertOptions({ - x: true - }, { - x: validator.validators.boolean, - y: validator.validators.boolean - }); + expect(function () { + validator.assertOptions( + { + x: true, + }, + { + x: validator.validators.boolean, + y: validator.validators.boolean, + } + ); }).not.toThrow(); }); }); diff --git a/test/specs/instance.spec.js b/test/specs/instance.spec.js index 46426e56..6fb6da07 100644 --- a/test/specs/instance.spec.js +++ b/test/specs/instance.spec.js @@ -11,27 +11,29 @@ describe('instance', function () { const instance = axios.create(); for (const prop in axios) { - if ([ - 'Axios', - 'AxiosError', - 'create', - 'Cancel', - 'CanceledError', - 'CancelToken', - 'isCancel', - 'all', - 'spread', - 'getUri', - 'isAxiosError', - 'mergeConfig', - 'getAdapter', - 'VERSION', - 'default', - 'toFormData', - 'formToJSON', - 'AxiosHeaders', - 'HttpStatusCode' - ].indexOf(prop) > -1) { + if ( + [ + 'Axios', + 'AxiosError', + 'create', + 'Cancel', + 'CanceledError', + 'CancelToken', + 'isCancel', + 'all', + 'spread', + 'getUri', + 'isAxiosError', + 'mergeConfig', + 'getAdapter', + 'VERSION', + 'default', + 'toFormData', + 'formToJSON', + 'AxiosHeaders', + 'HttpStatusCode', + ].indexOf(prop) > -1 + ) { continue; } expect(typeof instance[prop]).toBe(typeof axios[prop]); @@ -51,7 +53,7 @@ describe('instance', function () { it('should make an http request with url instead of baseURL', function (done) { const instance = axios.create({ - url: 'https://api.example.com' + url: 'https://api.example.com', }); instance('/foo'); @@ -86,7 +88,7 @@ describe('instance', function () { it('should have defaults.headers', function () { const instance = axios.create({ - baseURL: 'https://api.example.com' + baseURL: 'https://api.example.com', }); expect(typeof instance.defaults.headers, 'object'); @@ -112,7 +114,7 @@ describe('instance', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 200 + status: 200, }); setTimeout(function () { @@ -123,15 +125,15 @@ describe('instance', function () { }); }); - it('should have getUri on the instance', function() { + it('should have getUri on the instance', function () { const instance = axios.create({ - baseURL: 'https://api.example.com' + baseURL: 'https://api.example.com', }); const options = { url: 'foo/bar', params: { - name: 'axios' - } + name: 'axios', + }, }; expect(instance.getUri(options)).toBe('https://api.example.com/foo/bar?name=axios'); }); @@ -141,8 +143,8 @@ describe('instance', function () { const options = { url: 'foo/bar?foo=bar', params: { - name: 'axios' - } + name: 'axios', + }, }; expect(instance.getUri(options)).toBe('foo/bar?foo=bar&name=axios'); }); @@ -153,8 +155,8 @@ describe('instance', function () { baseURL: 'https://api.example.com', url: 'foo/bar?foo=bar#hash', params: { - name: 'axios' - } + name: 'axios', + }, }; expect(instance.getUri(options)).toBe('https://api.example.com/foo/bar?foo=bar&name=axios'); }); diff --git a/test/specs/interceptors.spec.js b/test/specs/interceptors.spec.js index 3ff4f367..07006be4 100644 --- a/test/specs/interceptors.spec.js +++ b/test/specs/interceptors.spec.js @@ -28,11 +28,15 @@ describe('interceptors', function () { it('should add a request interceptor (explicitly flagged as asynchronous)', function (done) { let asyncFlag = false; - axios.interceptors.request.use(function (config) { - config.headers.test = 'added by interceptor'; - expect(asyncFlag).toBe(true); - return config; - }, null, { synchronous: false }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'added by interceptor'; + expect(asyncFlag).toBe(true); + return config; + }, + null, + { synchronous: false } + ); axios('/foo'); asyncFlag = true; @@ -45,11 +49,15 @@ describe('interceptors', function () { it('should add a request interceptor that is executed synchronously when flag is provided', function (done) { let asyncFlag = false; - axios.interceptors.request.use(function (config) { - config.headers.test = 'added by synchronous interceptor'; - expect(asyncFlag).toBe(false); - return config; - }, null, { synchronous: true }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'added by synchronous interceptor'; + expect(asyncFlag).toBe(false); + return config; + }, + null, + { synchronous: true } + ); axios('/foo'); asyncFlag = true; @@ -68,11 +76,15 @@ describe('interceptors', function () { return config; }); - axios.interceptors.request.use(function (config) { - config.headers.test = 'added by synchronous interceptor'; - expect(asyncFlag).toBe(true); - return config; - }, null, { synchronous: true }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'added by synchronous interceptor'; + expect(asyncFlag).toBe(true); + return config; + }, + null, + { synchronous: true } + ); axios.interceptors.request.use(function (config) { config.headers.test = 'added by the async interceptor'; @@ -118,7 +130,7 @@ describe('interceptors', function () { }); }); - it('should execute request interceptor in order', function (done) { + it('should execute request interceptor in order', function (done) { let sequence = ''; axios.interceptors.request.use(function (config) { sequence += '1'; @@ -138,8 +150,8 @@ describe('interceptors', function () { axios({ url: '/foo', transitional: { - legacyInterceptorReqResOrdering: false - } + legacyInterceptorReqResOrdering: false, + }, }); getAjaxRequest().then(function (request) { @@ -152,10 +164,14 @@ describe('interceptors', function () { function onGetCall(config) { return config.method === 'get'; } - axios.interceptors.request.use(function (config) { - config.headers.test = 'special get headers'; - return config; - }, null, { runWhen: onGetCall }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'special get headers'; + return config; + }, + null, + { runWhen: onGetCall } + ); axios('/foo'); @@ -169,15 +185,19 @@ describe('interceptors', function () { function onPostCall(config) { return config.method === 'post'; } - axios.interceptors.request.use(function (config) { - config.headers.test = 'special get headers'; - return config; - }, null, { runWhen: onPostCall }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'special get headers'; + return config; + }, + null, + { runWhen: onPostCall } + ); axios('/foo'); getAjaxRequest().then(function (request) { - expect(request.requestHeaders.test).toBeUndefined() + expect(request.requestHeaders.test).toBeUndefined(); done(); }); }); @@ -188,23 +208,31 @@ describe('interceptors', function () { function onPostCall(config) { return config.method === 'post'; } - axios.interceptors.request.use(function (config) { - config.headers.test = 'special get headers'; - return config; - }, null, { synchronous: false, runWhen: onPostCall }); + axios.interceptors.request.use( + function (config) { + config.headers.test = 'special get headers'; + return config; + }, + null, + { synchronous: false, runWhen: onPostCall } + ); - axios.interceptors.request.use(function (config) { - config.headers.sync = 'hello world'; - expect(asyncFlag).toBe(false); - return config; - }, null, { synchronous: true }); + axios.interceptors.request.use( + function (config) { + config.headers.sync = 'hello world'; + expect(asyncFlag).toBe(false); + return config; + }, + null, + { synchronous: true } + ); axios('/foo'); - asyncFlag = true + asyncFlag = true; getAjaxRequest().then(function (request) { - expect(request.requestHeaders.test).toBeUndefined() - expect(request.requestHeaders.sync).toBe('hello world') + expect(request.requestHeaders.test).toBeUndefined(); + expect(request.requestHeaders.sync).toBe('hello world'); done(); }); }); @@ -212,9 +240,13 @@ describe('interceptors', function () { it('should add a request interceptor with an onRejected block that is called if interceptor code fails', function (done) { const rejectedSpy = jasmine.createSpy('rejectedSpy'); const error = new Error('deadly error'); - axios.interceptors.request.use(function () { - throw error; - }, rejectedSpy, { synchronous: true }); + axios.interceptors.request.use( + function () { + throw error; + }, + rejectedSpy, + { synchronous: true } + ); axios('/foo').catch(done); @@ -228,7 +260,7 @@ describe('interceptors', function () { axios.interceptors.request.use(function () { return { url: '/bar', - method: 'post' + method: 'post', }; }); @@ -299,7 +331,7 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { @@ -328,7 +360,7 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { @@ -343,7 +375,7 @@ describe('interceptors', function () { axios.interceptors.response.use(function () { return { - data: 'stuff' + data: 'stuff', }; }); @@ -354,7 +386,7 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { @@ -384,7 +416,7 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { @@ -395,9 +427,7 @@ describe('interceptors', function () { }); describe('given you add multiple response interceptors', function () { - describe('and when the response was fulfilled', function () { - function fireRequestAndExpect(expectation) { let response; axios('/foo').then(function (data) { @@ -406,11 +436,11 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { - expectation(response) + expectation(response); }, 100); }); } @@ -440,7 +470,7 @@ describe('interceptors', function () { }); }); - it('then only the last interceptor\'s result is returned', function (done) { + it("then only the last interceptor's result is returned", function (done) { axios.interceptors.response.use(function () { return 'response 1'; }); @@ -454,7 +484,7 @@ describe('interceptors', function () { }); }); - it('then every interceptor receives the result of it\'s predecessor', function (done) { + it("then every interceptor receives the result of it's predecessor", function (done) { axios.interceptors.response.use(function () { return 'response 1'; }); @@ -469,7 +499,6 @@ describe('interceptors', function () { }); describe('and when the fulfillment-interceptor throws', function () { - function fireRequestCatchAndExpect(expectation) { axios('/foo').catch(function (data) { // dont handle result @@ -477,11 +506,11 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { - expectation() + expectation(); }, 100); }); } @@ -503,7 +532,7 @@ describe('interceptors', function () { axios.interceptors.response.use(function () { throw Error('throwing interceptor'); }); - const unusedFulfillInterceptor = function () { }; + const unusedFulfillInterceptor = function () {}; const rejectIntercept = jasmine.createSpy('rejectIntercept'); axios.interceptors.response.use(unusedFulfillInterceptor, rejectIntercept); @@ -518,8 +547,8 @@ describe('interceptors', function () { throw Error('throwing interceptor'); }); - const unusedFulfillInterceptor = function () { }; - const catchingThrowingInterceptor = function () { }; + const unusedFulfillInterceptor = function () {}; + const catchingThrowingInterceptor = function () {}; axios.interceptors.response.use(unusedFulfillInterceptor, catchingThrowingInterceptor); const interceptor3 = jasmine.createSpy('interceptor3'); @@ -559,7 +588,7 @@ describe('interceptors', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: 'OK' + responseText: 'OK', }); setTimeout(function () { @@ -571,27 +600,34 @@ describe('interceptors', function () { it('should remove async interceptor before making request and execute synchronously', function (done) { let asyncFlag = false; - const asyncIntercept = axios.interceptors.request.use(function (config) { - config.headers.async = 'async it!'; - return config; - }, null, { synchronous: false }); - - const syncIntercept = axios.interceptors.request.use(function (config) { - config.headers.sync = 'hello world'; - expect(asyncFlag).toBe(false); - return config; - }, null, { synchronous: true }); + const asyncIntercept = axios.interceptors.request.use( + function (config) { + config.headers.async = 'async it!'; + return config; + }, + null, + { synchronous: false } + ); + axios.interceptors.request.use( + function (config) { + config.headers.sync = 'hello world'; + expect(asyncFlag).toBe(false); + return config; + }, + null, + { synchronous: true } + ); axios.interceptors.request.eject(asyncIntercept); - axios('/foo') - asyncFlag = true + axios('/foo'); + asyncFlag = true; getAjaxRequest().then(function (request) { expect(request.requestHeaders.async).toBeUndefined(); expect(request.requestHeaders.sync).toBe('hello world'); - done() + done(); }); }); @@ -602,7 +638,7 @@ describe('interceptors', function () { }); axios.post('/foo', { - foo: 'bar' + foo: 'bar', }); getAjaxRequest().then(function (request) { @@ -613,7 +649,7 @@ describe('interceptors', function () { it('should modify base URL in request interceptor', function (done) { const instance = axios.create({ - baseURL: 'http://test.com/' + baseURL: 'http://test.com/', }); instance.interceptors.request.use(function (config) { @@ -631,11 +667,11 @@ describe('interceptors', function () { it('should clear all request interceptors', function () { const instance = axios.create({ - baseURL: 'http://test.com/' + baseURL: 'http://test.com/', }); instance.interceptors.request.use(function (config) { - return config + return config; }); instance.interceptors.request.clear(); @@ -645,11 +681,11 @@ describe('interceptors', function () { it('should clear all response interceptors', function () { const instance = axios.create({ - baseURL: 'http://test.com/' + baseURL: 'http://test.com/', }); instance.interceptors.response.use(function (config) { - return config + return config; }); instance.interceptors.response.clear(); diff --git a/test/specs/options.spec.js b/test/specs/options.spec.js index 65b5e7bb..87eb1c42 100644 --- a/test/specs/options.spec.js +++ b/test/specs/options.spec.js @@ -22,8 +22,8 @@ describe('options', function () { it('should accept headers', function (done) { axios('/foo', { headers: { - 'X-Requested-With': 'XMLHttpRequest' - } + 'X-Requested-With': 'XMLHttpRequest', + }, }); getAjaxRequest().then(function (request) { @@ -36,8 +36,8 @@ describe('options', function () { axios('/foo', { params: { foo: 123, - bar: 456 - } + bar: 456, + }, }); getAjaxRequest().then(function (request) { @@ -49,8 +49,8 @@ describe('options', function () { it('should allow overriding default headers', function (done) { axios('/foo', { headers: { - 'Accept': 'foo/bar' - } + Accept: 'foo/bar', + }, }); getAjaxRequest().then(function (request) { @@ -61,10 +61,10 @@ describe('options', function () { it('should accept base URL', function (done) { const instance = axios.create({ - baseURL: 'http://test.com/' + baseURL: 'http://test.com/', }); - instance.get('/foo') + instance.get('/foo'); getAjaxRequest().then(function (request) { expect(request.url).toBe('http://test.com/foo'); done(); @@ -75,13 +75,15 @@ describe('options', function () { spyOn(window.console, 'warn'); const instance = axios.create({ - baseUrl: 'http://example.com/' + baseUrl: 'http://example.com/', }); instance.get('/foo'); getAjaxRequest().then(function (request) { - expect(window.console.warn).toHaveBeenCalledWith('baseUrl is likely a misspelling of baseURL'); + expect(window.console.warn).toHaveBeenCalledWith( + 'baseUrl is likely a misspelling of baseURL' + ); expect(request.url).toBe('/foo'); done(); }); @@ -89,7 +91,7 @@ describe('options', function () { it('should ignore base URL if request URL is absolute', function (done) { const instance = axios.create({ - baseURL: 'http://someurl.com/' + baseURL: 'http://someurl.com/', }); instance.get('http://someotherurl.com/'); @@ -103,7 +105,7 @@ describe('options', function () { it('should combine the URLs if base url and request url exist and allowAbsoluteUrls is false', function (done) { const instance = axios.create({ baseURL: 'http://someurl.com/', - allowAbsoluteUrls: false + allowAbsoluteUrls: false, }); instance.get('http://someotherurl.com/'); @@ -112,10 +114,9 @@ describe('options', function () { expect(request.url).toBe('http://someurl.com/http://someotherurl.com/'); done(); }); - }); - it('should change only the baseURL of the specified instance', function() { + it('should change only the baseURL of the specified instance', function () { const instance1 = axios.create(); const instance2 = axios.create(); @@ -124,7 +125,7 @@ describe('options', function () { expect(instance2.defaults.baseURL).not.toBe('http://instance1.example.com/'); }); - it('should change only the headers of the specified instance', function() { + it('should change only the headers of the specified instance', function () { const instance1 = axios.create(); const instance2 = axios.create(); @@ -140,6 +141,8 @@ describe('options', function () { expect(axios.defaults.headers.common['Content-Type']).toBe(undefined); expect(instance1.defaults.headers.common['Content-Type']).toBe('application/xml'); - expect(instance2.defaults.headers.common['Content-Type']).toBe('application/x-www-form-urlencoded'); + expect(instance2.defaults.headers.common['Content-Type']).toBe( + 'application/x-www-form-urlencoded' + ); }); }); diff --git a/test/specs/progress.spec.js b/test/specs/progress.spec.js index 9d7cb490..674615ed 100644 --- a/test/specs/progress.spec.js +++ b/test/specs/progress.spec.js @@ -10,12 +10,12 @@ describe('progress events', function () { it('should add a download progress handler', function (done) { const progressSpy = jasmine.createSpy('progress'); - axios('/foo', { onDownloadProgress: progressSpy } ); + axios('/foo', { onDownloadProgress: progressSpy }); getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: '{"foo": "bar"}' + responseText: '{"foo": "bar"}', }); expect(progressSpy).toHaveBeenCalled(); done(); @@ -25,7 +25,7 @@ describe('progress events', function () { it('should add a upload progress handler', function (done) { const progressSpy = jasmine.createSpy('progress'); - axios('/foo', { onUploadProgress: progressSpy } ); + axios('/foo', { onUploadProgress: progressSpy }); getAjaxRequest().then(function (request) { // Jasmine AJAX doesn't trigger upload events. Waiting for upstream fix @@ -45,7 +45,7 @@ describe('progress events', function () { expect(downloadProgressSpy).not.toHaveBeenCalled(); request.respondWith({ status: 200, - responseText: '{"foo": "bar"}' + responseText: '{"foo": "bar"}', }); expect(downloadProgressSpy).toHaveBeenCalled(); done(); @@ -64,7 +64,7 @@ describe('progress events', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: '{"foo": "bar"}' + responseText: '{"foo": "bar"}', }); expect(progressSpy).toHaveBeenCalled(); done(); @@ -102,7 +102,7 @@ describe('progress events', function () { expect(downloadProgressSpy).not.toHaveBeenCalled(); request.respondWith({ status: 200, - responseText: '{"foo": "bar"}' + responseText: '{"foo": "bar"}', }); expect(downloadProgressSpy).toHaveBeenCalled(); done(); diff --git a/test/specs/promise.spec.js b/test/specs/promise.spec.js index 7c8d85fe..fe046a69 100644 --- a/test/specs/promise.spec.js +++ b/test/specs/promise.spec.js @@ -17,7 +17,7 @@ describe('promise', function () { getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: '{"hello":"world"}' + responseText: '{"hello":"world"}', }); setTimeout(function () { @@ -51,14 +51,17 @@ describe('promise', function () { axios .all([123, 456]) - .then(axios.spread(function (a, b) { - sum = a + b; - fulfilled = true; - return 'hello world'; - })) + .then( + axios.spread(function (a, b) { + sum = a + b; + fulfilled = true; + return 'hello world'; + }) + ) .then(function (res) { result = res; - }).catch(done); + }) + .catch(done); setTimeout(function () { expect(fulfilled).toEqual(true); diff --git a/test/specs/requests.spec.js b/test/specs/requests.spec.js index a8dcc13e..97eeeae7 100644 --- a/test/specs/requests.spec.js +++ b/test/specs/requests.spec.js @@ -20,7 +20,7 @@ describe('requests', function () { it('should treat method value as lowercase string', function (done) { axios({ url: '/foo', - method: 'POST' + method: 'POST', }).then(function (response) { expect(response.config.method).toBe('post'); done(); @@ -28,7 +28,7 @@ describe('requests', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 200 + status: 200, }); }); }); @@ -45,7 +45,7 @@ describe('requests', function () { it('should allow data', function (done) { axios.delete('/foo', { - data: { foo: 'bar' } + data: { foo: 'bar' }, }); getAjaxRequest().then(function (request) { @@ -63,7 +63,7 @@ describe('requests', function () { }); }); - describe('timeouts', function(){ + describe('timeouts', function () { beforeEach(function () { jasmine.clock().install(); }); @@ -75,14 +75,17 @@ describe('requests', function () { it('should handle timeouts', function (done) { axios({ url: '/foo', - timeout: 100 - }).then(function () { - fail(new Error('timeout error not caught')); - }, function (err) { - expect(err instanceof Error).toBe(true); - expect(err.code).toEqual('ECONNABORTED'); - done(); - }); + timeout: 100, + }).then( + function () { + fail(new Error('timeout error not caught')); + }, + function (err) { + expect(err instanceof Error).toBe(true); + expect(err.code).toEqual('ECONNABORTED'); + done(); + } + ); jasmine.Ajax.requests.mostRecent().responseTimeout(); }); @@ -93,15 +96,18 @@ describe('requests', function () { url: '/foo', timeout: 100, transitional: { - clarifyTimeoutError: true + clarifyTimeoutError: true, + }, + }).then( + function () { + fail(new Error('timeout error not caught')); + }, + function (err) { + expect(err instanceof Error).toBe(true); + expect(err.code).toEqual('ETIMEDOUT'); + done(); } - }).then(function () { - fail(new Error('timeout error not caught')); - }, function (err) { - expect(err instanceof Error).toBe(true); - expect(err.code).toEqual('ETIMEDOUT'); - done(); - }); + ); jasmine.Ajax.requests.mostRecent().responseTimeout(); }); @@ -130,9 +136,7 @@ describe('requests', function () { done(); }; - axios('http://thisisnotaserver/foo') - .then(resolveSpy, rejectSpy) - .then(finish, finish); + axios('http://thisisnotaserver/foo').then(resolveSpy, rejectSpy).then(finish, finish); }); it('should reject on abort', function (done) { @@ -151,9 +155,7 @@ describe('requests', function () { done(); }; - axios('/foo') - .then(resolveSpy, rejectSpy) - .then(finish, finish); + axios('/foo').then(resolveSpy, rejectSpy).then(finish, finish); getAjaxRequest().then(function (request) { request.abort(); @@ -167,8 +169,9 @@ describe('requests', function () { axios('/foo', { validateStatus: function (status) { return status !== 500; - } - }).then(resolveSpy) + }, + }) + .then(resolveSpy) .catch(rejectSpy) .then(function () { expect(resolveSpy).not.toHaveBeenCalled(); @@ -185,7 +188,7 @@ describe('requests', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 500 + status: 500, }); }); }); @@ -197,8 +200,9 @@ describe('requests', function () { axios('/foo', { validateStatus: function (status) { return status === 500; - } - }).then(resolveSpy) + }, + }) + .then(resolveSpy) .catch(rejectSpy) .then(function () { expect(resolveSpy).toHaveBeenCalled(); @@ -208,7 +212,7 @@ describe('requests', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 500 + status: 500, }); }); }); @@ -217,7 +221,8 @@ describe('requests', function () { const resolveSpy = jasmine.createSpy('resolve'); const rejectSpy = jasmine.createSpy('reject'); - axios('file:///xxx').then(resolveSpy) + axios('file:///xxx') + .then(resolveSpy) .catch(rejectSpy) .then(function () { expect(resolveSpy).toHaveBeenCalled(); @@ -238,8 +243,9 @@ describe('requests', function () { const rejectSpy = jasmine.createSpy('reject'); axios('/foo', { - validateStatus: null - }).then(resolveSpy) + validateStatus: null, + }) + .then(resolveSpy) .catch(rejectSpy) .then(function () { expect(resolveSpy).toHaveBeenCalled(); @@ -249,7 +255,7 @@ describe('requests', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 500 + status: 500, }); }); }); @@ -259,8 +265,9 @@ describe('requests', function () { const rejectSpy = jasmine.createSpy('reject'); axios('/foo', { - validateStatus: undefined - }).then(resolveSpy) + validateStatus: undefined, + }) + .then(resolveSpy) .catch(rejectSpy) .then(function () { expect(resolveSpy).toHaveBeenCalled(); @@ -270,7 +277,7 @@ describe('requests', function () { getAjaxRequest().then(function (request) { request.respondWith({ - status: 500 + status: 500, }); }); }); @@ -279,16 +286,19 @@ describe('requests', function () { it('should return JSON when rejecting', function (done) { let response; - axios('/api/account/signup', { - username: null, - password: null - }, { - method: 'post', - headers: { - 'Accept': 'application/json' + axios( + '/api/account/signup', + { + username: null, + password: null, + }, + { + method: 'post', + headers: { + Accept: 'application/json', + }, } - }) - .catch(function (error) { + ).catch(function (error) { response = error.response; }); @@ -296,7 +306,7 @@ describe('requests', function () { request.respondWith({ status: 400, statusText: 'Bad Request', - responseText: '{"error": "BAD USERNAME", "code": 1}' + responseText: '{"error": "BAD USERNAME", "code": 1}', }); setTimeout(function () { @@ -311,7 +321,7 @@ describe('requests', function () { it('should make cross domain http request', function (done) { let response; - axios.post('www.someurl.com/foo').then(function(res){ + axios.post('www.someurl.com/foo').then(function (res) { response = res; }); @@ -321,8 +331,8 @@ describe('requests', function () { statusText: 'OK', responseText: '{"foo": "bar"}', headers: { - 'Content-Type': 'application/json' - } + 'Content-Type': 'application/json', + }, }); setTimeout(function () { @@ -335,7 +345,6 @@ describe('requests', function () { }); }); - it('should supply correct response', function (done) { let response; @@ -349,8 +358,8 @@ describe('requests', function () { statusText: 'OK', responseText: '{"foo": "bar"}', headers: { - 'Content-Type': 'application/json' - } + 'Content-Type': 'application/json', + }, }); setTimeout(function () { @@ -366,17 +375,19 @@ describe('requests', function () { it('should not modify the config url with relative baseURL', function (done) { let config; - axios.get('/foo', { - baseURL: '/api' - }).catch(function (error) { + axios + .get('/foo', { + baseURL: '/api', + }) + .catch(function (error) { config = error.config; - }); + }); getAjaxRequest().then(function (request) { request.respondWith({ status: 404, statusText: 'NOT FOUND', - responseText: 'Resource not found' + responseText: 'Resource not found', }); setTimeout(function () { @@ -391,13 +402,19 @@ describe('requests', function () { let response; const contentType = 'application/vnd.myapp.type+json'; - axios.post('/foo', { prop: 'value' }, { - headers: { - 'Content-Type': contentType - } - }).then(function (res) { - response = res; - }); + axios + .post( + '/foo', + { prop: 'value' }, + { + headers: { + 'Content-Type': contentType, + }, + } + ) + .then(function (res) { + response = res; + }); getAjaxRequest().then(function (request) { expect(request.requestHeaders['Content-Type']).toEqual(contentType); @@ -443,14 +460,14 @@ describe('requests', function () { function str2ab(str) { const buff = new ArrayBuffer(str.length * 2); const view = new Uint16Array(buff); - for ( let i=0, l=str.length; i { - expect(typeof response).toBe('object'); - done(); - }) - .catch(err => { - done(err); - }); - - getAjaxRequest().then(function (request){ + + instance + .get('my/endpoint', { responseType: 'json' }) + .then((response) => { + expect(typeof response).toBe('object'); + done(); + }) + .catch((err) => { + done(err); + }); + + getAjaxRequest().then(function (request) { request.respondWith({ status: 200, - responseText: '{"key1": "value1"}' + responseText: '{"key1": "value1"}', }); }); }); - }); diff --git a/test/specs/utils/endsWith.js b/test/specs/utils/endsWith.js index e6575223..3af65e1b 100644 --- a/test/specs/utils/endsWith.js +++ b/test/specs/utils/endsWith.js @@ -1,6 +1,6 @@ import utils from '../../../lib/utils'; -const {kindOf} = utils; +const { kindOf } = utils; describe('utils::kindOf', function () { it('should return object tag', function () { diff --git a/test/specs/utils/extend.spec.js b/test/specs/utils/extend.spec.js index e3b7e819..0f1d09fd 100644 --- a/test/specs/utils/extend.spec.js +++ b/test/specs/utils/extend.spec.js @@ -1,11 +1,11 @@ import utils from '../../../lib/utils'; -const {extend} = utils; +const { extend } = utils; describe('utils::extend', function () { it('should be mutable', function () { const a = {}; - const b = {foo: 123}; + const b = { foo: 123 }; extend(a, b); @@ -13,8 +13,8 @@ describe('utils::extend', function () { }); it('should extend properties', function () { - let a = {foo: 123, bar: 456}; - const b = {bar: 789}; + let a = { foo: 123, bar: 456 }; + const b = { bar: 789 }; a = extend(a, b); @@ -24,7 +24,11 @@ describe('utils::extend', function () { it('should bind to thisArg', function () { const a = {}; - const b = {getFoo: function getFoo() { return this.foo; }}; + const b = { + getFoo: function getFoo() { + return this.foo; + }, + }; const thisArg = { foo: 'barbaz' }; extend(a, b, thisArg); @@ -33,4 +37,3 @@ describe('utils::extend', function () { expect(a.getFoo()).toEqual(thisArg.foo); }); }); - diff --git a/test/specs/utils/forEach.spec.js b/test/specs/utils/forEach.spec.js index 3d3c5b31..dba64cf2 100644 --- a/test/specs/utils/forEach.spec.js +++ b/test/specs/utils/forEach.spec.js @@ -1,6 +1,6 @@ import utils from '../../../lib/utils'; -const {forEach} = utils; +const { forEach } = utils; describe('utils::forEach', function () { it('should loop over an array', function () { @@ -19,7 +19,7 @@ describe('utils::forEach', function () { const obj = { b: 1, a: 2, - r: 3 + r: 3, }; forEach(obj, function (v, k) { @@ -44,9 +44,12 @@ describe('utils::forEach', function () { it('should make an array out of non-array argument', function () { let count = 0; - forEach(function () {}, function () { - count++; - }); + forEach( + function () {}, + function () { + count++; + } + ); expect(count).toEqual(1); }); @@ -54,7 +57,7 @@ describe('utils::forEach', function () { it('should handle non object prototype gracefully', function () { let count = 0; const data = Object.create(null); - data.foo = 'bar' + data.foo = 'bar'; forEach(data, function () { count++; diff --git a/test/specs/utils/isX.spec.js b/test/specs/utils/isX.spec.js index 822e40e1..65710c8d 100644 --- a/test/specs/utils/isX.spec.js +++ b/test/specs/utils/isX.spec.js @@ -3,7 +3,7 @@ import utils from '../../../lib/utils'; describe('utils::isX', function () { it('should validate Array', function () { expect(utils.isArray([])).toEqual(true); - expect(utils.isArray({length: 5})).toEqual(false); + expect(utils.isArray({ length: 5 })).toEqual(false); }); it('should validate ArrayBuffer', function () { @@ -25,7 +25,13 @@ describe('utils::isX', function () { it('should validate String', function () { expect(utils.isString('')).toEqual(true); - expect(utils.isString({toString: function () { return ''; }})).toEqual(false); + expect( + utils.isString({ + toString: function () { + return ''; + }, + }) + ).toEqual(false); }); it('should validate Number', function () { diff --git a/test/specs/utils/kindOf.js b/test/specs/utils/kindOf.js index e6575223..3af65e1b 100644 --- a/test/specs/utils/kindOf.js +++ b/test/specs/utils/kindOf.js @@ -1,6 +1,6 @@ import utils from '../../../lib/utils'; -const {kindOf} = utils; +const { kindOf } = utils; describe('utils::kindOf', function () { it('should return object tag', function () { diff --git a/test/specs/utils/kindOfTest.js b/test/specs/utils/kindOfTest.js index b6211b5e..da9a743a 100644 --- a/test/specs/utils/kindOfTest.js +++ b/test/specs/utils/kindOfTest.js @@ -1,4 +1,4 @@ -import {kindOfTest} from '../../../lib/utils'; +import { kindOfTest } from '../../../lib/utils'; describe('utils::kindOfTest', function () { it('should return true if the type is matched', function () { diff --git a/test/specs/utils/merge.spec.js b/test/specs/utils/merge.spec.js index 83a8a0c2..053863c2 100644 --- a/test/specs/utils/merge.spec.js +++ b/test/specs/utils/merge.spec.js @@ -1,12 +1,12 @@ import utils from '../../../lib/utils'; -const {merge} = utils; +const { merge } = utils; describe('utils::merge', function () { it('should be immutable', function () { const a = {}; - const b = {foo: 123}; - const c = {bar: 456}; + const b = { foo: 123 }; + const c = { bar: 456 }; merge(a, b, c); @@ -17,9 +17,9 @@ describe('utils::merge', function () { }); it('should merge properties', function () { - const a = {foo: 123}; - const b = {bar: 456}; - const c = {foo: 789}; + const a = { foo: 123 }; + const b = { bar: 456 }; + const c = { foo: 789 }; const d = merge(a, b, c); expect(d.foo).toEqual(789); @@ -27,29 +27,29 @@ describe('utils::merge', function () { }); it('should merge recursively', function () { - const a = {foo: {bar: 123}}; - const b = {foo: {baz: 456}, bar: {qux: 789}}; + const a = { foo: { bar: 123 } }; + const b = { foo: { baz: 456 }, bar: { qux: 789 } }; expect(merge(a, b)).toEqual({ foo: { bar: 123, - baz: 456 + baz: 456, }, bar: { - qux: 789 - } + qux: 789, + }, }); }); it('should remove all references from nested objects', function () { - const a = {foo: {bar: 123}}; + const a = { foo: { bar: 123 } }; const b = {}; const d = merge(a, b); expect(d).toEqual({ foo: { - bar: 123 - } + bar: 123, + }, }); expect(d.foo).not.toBe(a.foo); @@ -57,40 +57,40 @@ describe('utils::merge', function () { it('handles null and undefined arguments', function () { expect(merge(undefined, undefined)).toEqual({}); - expect(merge(undefined, {foo: 123})).toEqual({foo: 123}); - expect(merge({foo: 123}, undefined)).toEqual({foo: 123}); + expect(merge(undefined, { foo: 123 })).toEqual({ foo: 123 }); + expect(merge({ foo: 123 }, undefined)).toEqual({ foo: 123 }); expect(merge(null, null)).toEqual({}); - expect(merge(null, {foo: 123})).toEqual({foo: 123}); - expect(merge({foo: 123}, null)).toEqual({foo: 123}); + expect(merge(null, { foo: 123 })).toEqual({ foo: 123 }); + expect(merge({ foo: 123 }, null)).toEqual({ foo: 123 }); }); it('should replace properties with null', function () { - expect(merge({}, {a: null})).toEqual({a: null}); - expect(merge({a: null}, {})).toEqual({a: null}); + expect(merge({}, { a: null })).toEqual({ a: null }); + expect(merge({ a: null }, {})).toEqual({ a: null }); }); it('should replace properties with arrays', function () { - expect(merge({}, {a: [1, 2, 3]})).toEqual({a: [1, 2, 3]}); - expect(merge({a: 2}, {a: [1, 2, 3]})).toEqual({a: [1, 2, 3]}); - expect(merge({a: {b: 2}}, {a: [1, 2, 3]})).toEqual({a: [1, 2, 3]}); + expect(merge({}, { a: [1, 2, 3] })).toEqual({ a: [1, 2, 3] }); + expect(merge({ a: 2 }, { a: [1, 2, 3] })).toEqual({ a: [1, 2, 3] }); + expect(merge({ a: { b: 2 } }, { a: [1, 2, 3] })).toEqual({ a: [1, 2, 3] }); }); it('should replace properties with cloned arrays', function () { const a = [1, 2, 3]; - const d = merge({}, {a: a}); + const d = merge({}, { a: a }); - expect(d).toEqual({a: [1, 2, 3]}); + expect(d).toEqual({ a: [1, 2, 3] }); expect(d.a).not.toBe(a); }); it('should support caseless option', () => { - const a = {x: 1}; - const b = {X: 2}; - const merged = merge.call({caseless: true}, a, b); + const a = { x: 1 }; + const b = { X: 2 }; + const merged = merge.call({ caseless: true }, a, b); expect(merged).toEqual({ - x: 2 + x: 2, }); }); }); diff --git a/test/specs/utils/toArray.js b/test/specs/utils/toArray.js index 1483cad4..4601436b 100644 --- a/test/specs/utils/toArray.js +++ b/test/specs/utils/toArray.js @@ -1,6 +1,6 @@ import utils from '../../../lib/utils'; -const {toArray} = utils; +const { toArray } = utils; describe('utils::kindOf', function () { it('should return object tag', function () { diff --git a/test/specs/utils/toFlatObject.js b/test/specs/utils/toFlatObject.js index d70f9f2c..4dbbf16c 100644 --- a/test/specs/utils/toFlatObject.js +++ b/test/specs/utils/toFlatObject.js @@ -1,12 +1,12 @@ import utils from '../../../lib/utils'; -const {toFlatObject} = utils; +const { toFlatObject } = utils; describe('utils::toFlatObject', function () { it('should resolve object proto chain to a flat object representation', function () { - const a = {x: 1}; - const b = Object.create(a, {y: {value: 2}}); - const c = Object.create(b, {z: {value: 3}}); - expect(toFlatObject(c)).toEqual({x: 1, y: 2, z: 3}); + const a = { x: 1 }; + const b = Object.create(a, { y: { value: 2 } }); + const c = Object.create(b, { z: { value: 3 } }); + expect(toFlatObject(c)).toEqual({ x: 1, y: 2, z: 3 }); }); }); diff --git a/test/specs/utils/trim.spec.js b/test/specs/utils/trim.spec.js index b89e5fe0..bbded1fb 100644 --- a/test/specs/utils/trim.spec.js +++ b/test/specs/utils/trim.spec.js @@ -9,4 +9,3 @@ describe('utils::trim', function () { expect(utils.trim('\tfoo\t')).toEqual('foo'); }); }); - diff --git a/test/specs/xsrf.spec.js b/test/specs/xsrf.spec.js index b05f70e3..83d58472 100644 --- a/test/specs/xsrf.spec.js +++ b/test/specs/xsrf.spec.js @@ -6,7 +6,8 @@ describe('xsrf', function () { }); afterEach(function () { - document.cookie = axios.defaults.xsrfCookieName + '=;expires=' + new Date(Date.now() - 86400000).toGMTString(); + document.cookie = + axios.defaults.xsrfCookieName + '=;expires=' + new Date(Date.now() - 86400000).toGMTString(); jasmine.Ajax.uninstall(); }); @@ -34,7 +35,7 @@ describe('xsrf', function () { document.cookie = axios.defaults.xsrfCookieName + '=12345'; axios('/foo', { - xsrfCookieName: null + xsrfCookieName: null, }); getAjaxRequest().then(function (request) { @@ -44,10 +45,10 @@ describe('xsrf', function () { }); it('should not read cookies at all if xsrfCookieName is null', function (done) { - spyOn(cookies, "read"); + spyOn(cookies, 'read'); axios('/foo', { - xsrfCookieName: null + xsrfCookieName: null, }); getAjaxRequest().then(function (request) { @@ -71,7 +72,7 @@ describe('xsrf', function () { document.cookie = axios.defaults.xsrfCookieName + '=12345'; axios('http://example.com/', { - withCredentials: true + withCredentials: true, }); getAjaxRequest().then(function (request) { @@ -80,15 +81,14 @@ describe('xsrf', function () { }); }); - describe('withXSRFToken option', function(){ - + describe('withXSRFToken option', function () { it('should set xsrf header for cross origin when withXSRFToken = true', function (done) { const token = '12345'; document.cookie = axios.defaults.xsrfCookieName + '=' + token; axios('http://example.com/', { - withXSRFToken: true + withXSRFToken: true, }); getAjaxRequest().then(function (request) { @@ -103,7 +103,7 @@ describe('xsrf', function () { document.cookie = axios.defaults.xsrfCookieName + '=' + token; axios('/foo', { - withXSRFToken: false + withXSRFToken: false, }); getAjaxRequest().then(function (request) { @@ -118,7 +118,7 @@ describe('xsrf', function () { document.cookie = axios.defaults.xsrfCookieName + '=' + token; axios('/foo', { - withXSRFToken: false + withXSRFToken: false, }); getAjaxRequest().then(function (request) { @@ -134,7 +134,7 @@ describe('xsrf', function () { axios('/foo', { withXSRFToken: (config) => config.userFlag === 'yes', - userFlag: 'yes' + userFlag: 'yes', }); getAjaxRequest().then(function (request) { diff --git a/test/unit/adapters/adapters.js b/test/unit/adapters/adapters.js index a6651367..28383018 100644 --- a/test/unit/adapters/adapters.js +++ b/test/unit/adapters/adapters.js @@ -1,9 +1,8 @@ import adapters from '../../../lib/adapters/adapters.js'; import assert from 'assert'; - describe('adapters', function () { - const store = {...adapters.adapters}; + const store = { ...adapters.adapters }; beforeEach(() => { Object.keys(adapters.adapters).forEach((name) => { @@ -26,12 +25,12 @@ describe('adapters', function () { it('should detect adapter unavailable status', function () { adapters.adapters['testadapter'] = null; - assert.throws(() => adapters.getAdapter('testAdapter'), /is not available in the build/) + assert.throws(() => adapters.getAdapter('testAdapter'), /is not available in the build/); }); it('should detect adapter unsupported status', function () { adapters.adapters['testadapter'] = false; - assert.throws(() => adapters.getAdapter('testAdapter'), /is not supported by the environment/) + assert.throws(() => adapters.getAdapter('testAdapter'), /is not supported by the environment/); }); it('should pick suitable adapter from the list', function () { @@ -40,7 +39,7 @@ describe('adapters', function () { Object.assign(adapters.adapters, { foo: false, bar: null, - baz: adapter + baz: adapter, }); assert.strictEqual(adapters.getAdapter(['foo', 'bar', 'baz']), adapter); diff --git a/test/unit/adapters/error-details.spec.js b/test/unit/adapters/error-details.spec.js index 909c677f..003a39d0 100644 --- a/test/unit/adapters/error-details.spec.js +++ b/test/unit/adapters/error-details.spec.js @@ -4,7 +4,7 @@ import https from 'https'; import net from 'net'; import fs from 'fs'; import path from 'path'; -import {fileURLToPath} from 'url'; +import { fileURLToPath } from 'url'; import axios from '../../../index.js'; /** __dirname replacement for ESM */ @@ -16,7 +16,7 @@ async function getClosedPort() { return await new Promise((resolve) => { const srv = net.createServer(); srv.listen(0, '127.0.0.1', () => { - const {port} = srv.address(); + const { port } = srv.address(); srv.close(() => resolve(port)); }); }); @@ -48,7 +48,7 @@ describe('adapters – network-error details', function () { it('should expose self-signed TLS error and set error.cause', async function () { // Use the same certs already present for adapter tests in this folder - const keyPath = path.join(__dirname, 'key.pem'); + const keyPath = path.join(__dirname, 'key.pem'); const certPath = path.join(__dirname, 'cert.pem'); const key = fs.readFileSync(keyPath); @@ -57,24 +57,30 @@ describe('adapters – network-error details', function () { const httpsServer = https.createServer({ key, cert }, (req, res) => res.end('ok')); await new Promise((resolve) => httpsServer.listen(0, '127.0.0.1', resolve)); - const {port} = httpsServer.address(); + const { port } = httpsServer.address(); try { await axios.get(`https://127.0.0.1:${port}`, { timeout: 500, - httpsAgent: new https.Agent({ rejectUnauthorized: true }) // Explicit: reject self-signed + httpsAgent: new https.Agent({ rejectUnauthorized: true }), // Explicit: reject self-signed }); assert.fail('request unexpectedly succeeded'); } catch (err) { const codeStr = String(err.code); // OpenSSL/Node variants: SELF_SIGNED_CERT_IN_CHAIN, DEPTH_ZERO_SELF_SIGNED_CERT, UNABLE_TO_VERIFY_LEAF_SIGNATURE - assert.ok(/SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|DEPTH_ZERO/.test(codeStr), 'unexpected TLS code: ' + codeStr); + assert.ok( + /SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|DEPTH_ZERO/.test(codeStr), + 'unexpected TLS code: ' + codeStr + ); assert.ok('cause' in err, 'error.cause should exist'); assert.ok(err.cause instanceof Error, 'cause should be an Error'); const causeCode = String(err.cause && err.cause.code); - assert.ok(/SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|DEPTH_ZERO/.test(causeCode), 'unexpected cause code: ' + causeCode); + assert.ok( + /SELF_SIGNED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|DEPTH_ZERO/.test(causeCode), + 'unexpected cause code: ' + causeCode + ); assert.strictEqual(typeof err.message, 'string'); } finally { diff --git a/test/unit/adapters/fetch.js b/test/unit/adapters/fetch.js index e7f000f8..1d995e02 100644 --- a/test/unit/adapters/fetch.js +++ b/test/unit/adapters/fetch.js @@ -6,18 +6,18 @@ import { setTimeoutAsync, makeReadableStream, generateReadable, - makeEchoStream + makeEchoStream, } from '../../helpers/server.js'; import axios from '../../../index.js'; -import stream from "stream"; -import { AbortController } from "abortcontroller-polyfill/dist/cjs-ponyfill.js"; -import util from "util"; +import stream from 'stream'; +import { AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; +import util from 'util'; const pipelineAsync = util.promisify(stream.pipeline); const fetchAxios = axios.create({ baseURL: LOCAL_SERVER_URL, - adapter: 'fetch' + adapter: 'fetch', }); let server; @@ -27,7 +27,7 @@ describe('supports fetch with nodejs', function () { if (typeof fetch !== 'function') { this.skip(); } - }) + }); afterEach(async function () { await stopHTTPServer(server); @@ -42,7 +42,7 @@ describe('supports fetch with nodejs', function () { server = await startHTTPServer((req, res) => res.end(originalData)); const { data } = await fetchAxios.get('/', { - responseType: 'text' + responseType: 'text', }); assert.deepStrictEqual(data, originalData); @@ -54,10 +54,13 @@ describe('supports fetch with nodejs', function () { server = await startHTTPServer((req, res) => res.end(originalData)); const { data } = await fetchAxios.get('/', { - responseType: 'arraybuffer' + responseType: 'arraybuffer', }); - assert.deepStrictEqual(data, Uint8Array.from(await new TextEncoder().encode(originalData)).buffer); + assert.deepStrictEqual( + data, + Uint8Array.from(await new TextEncoder().encode(originalData)).buffer + ); }); it(`should support blob response type`, async () => { @@ -66,7 +69,7 @@ describe('supports fetch with nodejs', function () { server = await startHTTPServer((req, res) => res.end(originalData)); const { data } = await fetchAxios.get('/', { - responseType: 'blob' + responseType: 'blob', }); assert.deepStrictEqual(data, new Blob([originalData])); @@ -78,7 +81,7 @@ describe('supports fetch with nodejs', function () { server = await startHTTPServer((req, res) => res.end(originalData)); const { data } = await fetchAxios.get('/', { - responseType: 'stream' + responseType: 'stream', }); assert.ok(data instanceof ReadableStream, 'data is not instanceof ReadableStream'); @@ -96,7 +99,6 @@ describe('supports fetch with nodejs', function () { originalData.append('x', '123'); server = await startHTTPServer(async (req, res) => { - const response = await new Response(originalData); res.setHeader('Content-Type', response.headers.get('Content-Type')); @@ -105,12 +107,15 @@ describe('supports fetch with nodejs', function () { }); const { data } = await fetchAxios.get('/', { - responseType: 'formdata' + responseType: 'formdata', }); assert.ok(data instanceof FormData, 'data is not instanceof FormData'); - assert.deepStrictEqual(Object.fromEntries(data.entries()), Object.fromEntries(originalData.entries())); + assert.deepStrictEqual( + Object.fromEntries(data.entries()), + Object.fromEntries(originalData.entries()) + ); }); it(`should support json response type`, async () => { @@ -119,82 +124,89 @@ describe('supports fetch with nodejs', function () { server = await startHTTPServer((req, res) => res.end(JSON.stringify(originalData))); const { data } = await fetchAxios.get('/', { - responseType: 'json' + responseType: 'json', }); assert.deepStrictEqual(data, originalData); }); }); - describe("progress", () => { + describe('progress', () => { describe('upload', function () { it('should support upload progress capturing', async function () { this.timeout(15000); server = await startHTTPServer({ - rate: 100 * 1024 + rate: 100 * 1024, }); let content = ''; const count = 10; - const chunk = "test"; + const chunk = 'test'; const chunkLength = Buffer.byteLength(chunk); const contentLength = count * chunkLength; - const readable = stream.Readable.from(async function* () { - let i = count; + const readable = stream.Readable.from( + (async function* () { + let i = count; - while (i-- > 0) { - await setTimeoutAsync(1100); - content += chunk; - yield chunk; - } - }()); + while (i-- > 0) { + await setTimeoutAsync(1100); + content += chunk; + yield chunk; + } + })() + ); const samples = []; const { data } = await fetchAxios.post('/', readable, { onUploadProgress: ({ loaded, total, progress, bytes, upload }) => { - console.log(`Upload Progress ${loaded} from ${total} bytes (${(progress * 100).toFixed(1)}%)`); + console.log( + `Upload Progress ${loaded} from ${total} bytes (${(progress * 100).toFixed(1)}%)` + ); samples.push({ loaded, total, progress, bytes, - upload + upload, }); }, headers: { - 'Content-Length': contentLength + 'Content-Length': contentLength, }, - responseType: 'text' + responseType: 'text', }); await setTimeoutAsync(500); assert.strictEqual(data, content); - assert.deepStrictEqual(samples, Array.from(function* () { - for (let i = 1; i <= 10; i++) { - yield ({ - loaded: chunkLength * i, - total: contentLength, - progress: (chunkLength * i) / contentLength, - bytes: 4, - upload: true - }); - } - }())); + assert.deepStrictEqual( + samples, + Array.from( + (function* () { + for (let i = 1; i <= 10; i++) { + yield { + loaded: chunkLength * i, + total: contentLength, + progress: (chunkLength * i) / contentLength, + bytes: 4, + upload: true, + }; + } + })() + ) + ); }); it('should not fail with get method', async () => { server = await startHTTPServer((req, res) => res.end('OK')); const { data } = await fetchAxios.get('/', { - onUploadProgress() { - - } + onUploadProgress() {}, }); assert.strictEqual(data, 'OK'); @@ -206,61 +218,70 @@ describe('supports fetch with nodejs', function () { this.timeout(15000); server = await startHTTPServer({ - rate: 100 * 1024 + rate: 100 * 1024, }); let content = ''; const count = 10; - const chunk = "test"; + const chunk = 'test'; const chunkLength = Buffer.byteLength(chunk); const contentLength = count * chunkLength; - const readable = stream.Readable.from(async function* () { - let i = count; + const readable = stream.Readable.from( + (async function* () { + let i = count; - while (i-- > 0) { - await setTimeoutAsync(1100); - content += chunk; - yield chunk; - } - }()); + while (i-- > 0) { + await setTimeoutAsync(1100); + content += chunk; + yield chunk; + } + })() + ); const samples = []; const { data } = await fetchAxios.post('/', readable, { onDownloadProgress: ({ loaded, total, progress, bytes, download }) => { - console.log(`Download Progress ${loaded} from ${total} bytes (${(progress * 100).toFixed(1)}%)`); + console.log( + `Download Progress ${loaded} from ${total} bytes (${(progress * 100).toFixed(1)}%)` + ); samples.push({ loaded, total, progress, bytes, - download + download, }); }, headers: { - 'Content-Length': contentLength + 'Content-Length': contentLength, }, responseType: 'text', - maxRedirects: 0 + maxRedirects: 0, }); await setTimeoutAsync(500); assert.strictEqual(data, content); - assert.deepStrictEqual(samples, Array.from(function* () { - for (let i = 1; i <= 10; i++) { - yield ({ - loaded: chunkLength * i, - total: contentLength, - progress: (chunkLength * i) / contentLength, - bytes: 4, - download: true - }); - } - }())); + assert.deepStrictEqual( + samples, + Array.from( + (function* () { + for (let i = 1; i <= 10; i++) { + yield { + loaded: chunkLength * i, + total: contentLength, + progress: (chunkLength * i) / contentLength, + bytes: 4, + download: true, + }; + } + })() + ) + ); }); }); }); @@ -276,7 +297,7 @@ describe('supports fetch with nodejs', function () { assert.equal(res.data, 'Basic ' + base64); }); - it("should support stream.Readable as a payload", async () => { + it('should support stream.Readable as a payload', async () => { server = await startHTTPServer(); const { data } = await fetchAxios.post('/', stream.Readable.from('OK')); @@ -288,7 +309,7 @@ describe('supports fetch with nodejs', function () { it('should be able to abort the request stream', async function () { server = await startHTTPServer({ rate: 100000, - useBuffering: true + useBuffering: true, }); const controller = new AbortController(); @@ -300,7 +321,7 @@ describe('supports fetch with nodejs', function () { await assert.rejects(async () => { await fetchAxios.post('/', makeReadableStream(), { responseType: 'stream', - signal: controller.signal + signal: controller.signal, }); }, /CanceledError/); }); @@ -318,7 +339,7 @@ describe('supports fetch with nodejs', function () { const { data } = await fetchAxios.get('/', { responseType: 'stream', - signal: controller.signal + signal: controller.signal, }); await assert.rejects(async () => { @@ -339,8 +360,8 @@ describe('supports fetch with nodejs', function () { await assert.rejects(async () => { await fetchAxios('/', { - timeout - }) + timeout, + }); }, /timeout/); const passed = Date.now() - ts; @@ -348,7 +369,6 @@ describe('supports fetch with nodejs', function () { assert.ok(passed >= timeout - 5, `early cancellation detected (${passed} ms)`); }); - it('should combine baseURL and url', async () => { server = await startHTTPServer(); @@ -364,8 +384,8 @@ describe('supports fetch with nodejs', function () { const { data } = await fetchAxios.get('/?test=1', { params: { foo: 1, - bar: 2 - } + bar: 2, + }, }); assert.strictEqual(data, '/?test=1&foo=1&bar=2'); @@ -384,11 +404,11 @@ describe('supports fetch with nodejs', function () { it('should get response headers', async () => { server = await startHTTPServer((req, res) => { res.setHeader('foo', 'bar'); - res.end(req.url) + res.end(req.url); }); const { headers } = await fetchAxios.get('/', { - responseType: 'stream' + responseType: 'stream', }); assert.strictEqual(headers.get('foo'), 'bar'); @@ -411,25 +431,25 @@ describe('supports fetch with nodejs', function () { }); describe('env config', () => { - it('should respect env fetch API configuration', async() => { + it('should respect env fetch API configuration', async () => { const { data, headers } = await fetchAxios.get('/', { env: { fetch() { return { headers: { - foo: '1' + foo: '1', }, - text: async () => 'test' - } - } - } + text: async () => 'test', + }; + }, + }, }); assert.strictEqual(headers.get('foo'), '1'); assert.strictEqual(data, 'test'); }); - it('should be able to request with lack of Request object', async() => { + it('should be able to request with lack of Request object', async () => { const form = new FormData(); form.append('x', '1'); @@ -443,19 +463,19 @@ describe('supports fetch with nodejs', function () { fetch() { return { headers: { - foo: '1' + foo: '1', }, - text: async () => 'test' - } - } - } + text: async () => 'test', + }; + }, + }, }); assert.strictEqual(headers.get('foo'), '1'); assert.strictEqual(data, 'test'); }); - it('should be able to handle response with lack of Response object', async() => { + it('should be able to handle response with lack of Response object', async () => { const { data, headers } = await fetchAxios.get('/', { onDownloadProgress() { // dummy listener to activate streaming @@ -466,49 +486,49 @@ describe('supports fetch with nodejs', function () { fetch() { return { headers: { - foo: '1' + foo: '1', }, - text: async () => 'test' - } - } - } + text: async () => 'test', + }; + }, + }, }); assert.strictEqual(headers.get('foo'), '1'); assert.strictEqual(data, 'test'); }); - it('should fallback to the global on undefined env value', async() => { + it('should fallback to the global on undefined env value', async () => { server = await startHTTPServer((req, res) => res.end('OK')); const { data } = await fetchAxios.get('/', { env: { - fetch: undefined - } + fetch: undefined, + }, }); assert.strictEqual(data, 'OK'); }); - it('should use current global fetch when env fetch is not specified', async() => { + it('should use current global fetch when env fetch is not specified', async () => { const globalFetch = fetch; fetch = async () => { return { headers: { - foo: '1' + foo: '1', }, - text: async () => 'global' - } + text: async () => 'global', + }; }; try { server = await startHTTPServer((req, res) => res.end('OK')); - const {data} = await fetchAxios.get('/', { + const { data } = await fetchAxios.get('/', { env: { - fetch: undefined - } + fetch: undefined, + }, }); assert.strictEqual(data, 'global'); diff --git a/test/unit/adapters/http.js b/test/unit/adapters/http.js index fc233c83..61fd883b 100644 --- a/test/unit/adapters/http.js +++ b/test/unit/adapters/http.js @@ -9,7 +9,7 @@ import util from 'util'; import assert from 'assert'; import fs from 'fs'; import path from 'path'; -import {lookup} from 'dns'; +import { lookup } from 'dns'; let server, server2, proxy; import AxiosError from '../../../lib/core/AxiosError.js'; import FormDataLegacy from 'form-data'; @@ -19,17 +19,21 @@ import multer from 'multer'; import bodyParser from 'body-parser'; const isBlobSupported = typeof Blob !== 'undefined'; import devNull from 'dev-null'; -import {AbortController} from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; -import {__setProxy} from "../../../lib/adapters/http.js"; -import {FormData as FormDataPolyfill, Blob as BlobPolyfill, File as FilePolyfill} from 'formdata-node'; -import getStream from "get-stream"; +import { AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; +import { __setProxy } from '../../../lib/adapters/http.js'; +import { + FormData as FormDataPolyfill, + Blob as BlobPolyfill, + File as FilePolyfill, +} from 'formdata-node'; +import getStream from 'get-stream'; import { startHTTPServer, stopHTTPServer, LOCAL_SERVER_URL, SERVER_HANDLER_STREAM_ECHO, handleFormData, - generateReadable + generateReadable, } from '../../helpers/server.js'; const LOCAL_SERVER_URL2 = 'https://localhost:5555'; @@ -44,7 +48,7 @@ const __filename = url.fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); function setTimeoutAsync(ms) { - return new Promise(resolve=> setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } const pipelineAsync = util.promisify(stream.pipeline); @@ -60,10 +64,10 @@ function toleranceRange(positive, negative) { return (actualValue, value) => { return actualValue > value ? actualValue <= value * p : actualValue >= value * n; - } + }; } -const nodeVersion = process.versions.node.split('.').map(v => parseInt(v, 10)); +const nodeVersion = process.versions.node.split('.').map((v) => parseInt(v, 10)); const nodeMajorVersion = nodeVersion[0]; var noop = () => {}; @@ -82,331 +86,402 @@ describe('supports http with nodejs', function () { }); it('should support IPv4 literal strings', function (done) { - var data = { firstName: 'Fred', lastName: 'Flintstone', - emailAddr: 'fred@example.com' + emailAddr: 'fred@example.com', }; - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(data)); - }).listen(4444, function () { - axios.get('http://127.0.0.1:4444/').then(function (res) { - assert.deepEqual(res.data, data); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(data)); + }) + .listen(4444, function () { + axios + .get('http://127.0.0.1:4444/') + .then(function (res) { + assert.deepEqual(res.data, data); + done(); + }) + .catch(done); + }); }); it('should support IPv6 literal strings', function (done) { - var data = { firstName: 'Fred', lastName: 'Flintstone', - emailAddr: 'fred@example.com' + emailAddr: 'fred@example.com', }; - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(data)); - }).listen(4444, function () { - axios.get('http://[::1]:4444/').then(function (res) { - assert.deepEqual(res.data, data); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(data)); + }) + .listen(4444, function () { + axios + .get('http://[::1]:4444/') + .then(function (res) { + assert.deepEqual(res.data, data); + done(); + }) + .catch(done); + }); }); it('should throw an error if the timeout property is not parsable as a number', function (done) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + var success = false, + failure = false; + var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - var success = false, failure = false; - var error; + axios + .get('http://localhost:4444/', { + timeout: { strangeTimeout: 250 }, + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - axios.get('http://localhost:4444/', { - timeout: { strangeTimeout: 250 } - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.code, AxiosError.ERR_BAD_OPTION_VALUE); + assert.equal(error.message, 'error trying to parse `config.timeout` to int'); + done(); + }, 300); }); - - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.code, AxiosError.ERR_BAD_OPTION_VALUE); - assert.equal(error.message, 'error trying to parse `config.timeout` to int'); - done(); - }, 300); - }); }); it('should parse the timeout property', function (done) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + var success = false, + failure = false; + var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - var success = false, failure = false; - var error; + axios + .get('http://localhost:4444/', { + timeout: '250', + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - axios.get('http://localhost:4444/', { - timeout: '250' - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.code, 'ECONNABORTED'); + assert.equal(error.message, 'timeout of 250ms exceeded'); + done(); + }, 300); }); - - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.code, 'ECONNABORTED'); - assert.equal(error.message, 'timeout of 250ms exceeded'); - done(); - }, 300); - }); }); it('should respect the timeout property', function (done) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + var success = false, + failure = false; + var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - var success = false, failure = false; - var error; + axios + .get('http://localhost:4444/', { + timeout: 250, + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - axios.get('http://localhost:4444/', { - timeout: 250 - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.code, 'ECONNABORTED'); + assert.equal(error.message, 'timeout of 250ms exceeded'); + done(); + }, 300); }); - - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.code, 'ECONNABORTED'); - assert.equal(error.message, 'timeout of 250ms exceeded'); - done(); - }, 300); - }); }); it('should respect the timeoutErrorMessage property', function (done) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + var success = false, + failure = false; + var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - var success = false, failure = false; - var error; + axios + .get('http://localhost:4444/', { + timeout: 250, + timeoutErrorMessage: 'oops, timeout', + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - axios.get('http://localhost:4444/', { - timeout: 250, - timeoutErrorMessage: 'oops, timeout', - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + setTimeout(function () { + assert.strictEqual(success, false, 'request should not succeed'); + assert.strictEqual(failure, true, 'request should fail'); + assert.strictEqual(error.code, 'ECONNABORTED'); + assert.strictEqual(error.message, 'oops, timeout'); + done(); + }, 300); }); - - setTimeout(function () { - assert.strictEqual(success, false, 'request should not succeed'); - assert.strictEqual(failure, true, 'request should fail'); - assert.strictEqual(error.code, 'ECONNABORTED'); - assert.strictEqual(error.message, 'oops, timeout'); - done(); - }, 300); - }); }); it('should allow passing JSON', function (done) { var data = { firstName: 'Fred', lastName: 'Flintstone', - emailAddr: 'fred@example.com' + emailAddr: 'fred@example.com', }; - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(data)); - }).listen(4444, function () { - axios.get('http://localhost:4444/').then(function (res) { - assert.deepEqual(res.data, data); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(data)); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.deepEqual(res.data, data); + done(); + }) + .catch(done); + }); }); it('should allow passing JSON with BOM', function (done) { var data = { firstName: 'Fred', lastName: 'Flintstone', - emailAddr: 'fred@example.com' + emailAddr: 'fred@example.com', }; - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'application/json'); - var bomBuffer = Buffer.from([0xEF, 0xBB, 0xBF]) - var jsonBuffer = Buffer.from(JSON.stringify(data)); - res.end(Buffer.concat([bomBuffer, jsonBuffer])); - }).listen(4444, function () { - axios.get('http://localhost:4444/').then(function (res) { - assert.deepEqual(res.data, data); - done(); - }).catch(done);; - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json'); + var bomBuffer = Buffer.from([0xef, 0xbb, 0xbf]); + var jsonBuffer = Buffer.from(JSON.stringify(data)); + res.end(Buffer.concat([bomBuffer, jsonBuffer])); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.deepEqual(res.data, data); + done(); + }) + .catch(done); + }); }); it('should redirect', function (done) { var str = 'test response'; - server = http.createServer(function (req, res) { - var parsed = url.parse(req.url); + server = http + .createServer(function (req, res) { + var parsed = url.parse(req.url); - if (parsed.pathname === '/one') { - res.setHeader('Location', '/two'); - res.statusCode = 302; - res.end(); - } else { - res.end(str); - } - }).listen(4444, function () { - axios.get('http://localhost:4444/one').then(function (res) { - assert.equal(res.data, str); - assert.equal(res.request.path, '/two'); - done(); - }).catch(done); - }); + if (parsed.pathname === '/one') { + res.setHeader('Location', '/two'); + res.statusCode = 302; + res.end(); + } else { + res.end(str); + } + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/one') + .then(function (res) { + assert.equal(res.data, str); + assert.equal(res.request.path, '/two'); + done(); + }) + .catch(done); + }); }); it('should not redirect', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Location', '/foo'); - res.statusCode = 302; - res.end(); - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - maxRedirects: 0, - validateStatus: function () { - return true; - } - }).then(function (res) { - assert.equal(res.status, 302); - assert.equal(res.headers['location'], '/foo'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Location', '/foo'); + res.statusCode = 302; + res.end(); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + maxRedirects: 0, + validateStatus: function () { + return true; + }, + }) + .then(function (res) { + assert.equal(res.status, 302); + assert.equal(res.headers['location'], '/foo'); + done(); + }) + .catch(done); + }); }); it('should support max redirects', function (done) { var i = 1; - server = http.createServer(function (req, res) { - res.setHeader('Location', '/' + i); - res.statusCode = 302; - res.end(); - i++; - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - maxRedirects: 3 - }).catch(function (error) { - assert.equal(error.code, AxiosError.ERR_FR_TOO_MANY_REDIRECTS); - assert.equal(error.message, 'Maximum number of redirects exceeded'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Location', '/' + i); + res.statusCode = 302; + res.end(); + i++; + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + maxRedirects: 3, + }) + .catch(function (error) { + assert.equal(error.code, AxiosError.ERR_FR_TOO_MANY_REDIRECTS); + assert.equal(error.message, 'Maximum number of redirects exceeded'); + done(); + }) + .catch(done); + }); }); it('should support beforeRedirect', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Location', '/foo'); - res.statusCode = 302; - res.end(); - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - maxRedirects: 3, - beforeRedirect: function (options, responseDetails) { - if (options.path === '/foo' && responseDetails.headers.location === '/foo') { - throw new Error( - 'Provided path is not allowed' - ); - } - } - }).catch(function (error) { - assert.equal(error.message, 'Redirected request failed: Provided path is not allowed'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Location', '/foo'); + res.statusCode = 302; + res.end(); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + maxRedirects: 3, + beforeRedirect: function (options, responseDetails) { + if (options.path === '/foo' && responseDetails.headers.location === '/foo') { + throw new Error('Provided path is not allowed'); + } + }, + }) + .catch(function (error) { + assert.equal(error.message, 'Redirected request failed: Provided path is not allowed'); + done(); + }) + .catch(done); + }); }); it('should support beforeRedirect and proxy with redirect', async () => { let requestCount = 0; let totalRedirectCount = 5; - server = await startHTTPServer(function (req, res) { - requestCount += 1; - if (requestCount <= totalRedirectCount) { - res.setHeader('Location', 'http://localhost:4444'); - res.writeHead(302); - } - res.end(); - }, {port: 4444}); + server = await startHTTPServer( + function (req, res) { + requestCount += 1; + if (requestCount <= totalRedirectCount) { + res.setHeader('Location', 'http://localhost:4444'); + res.writeHead(302); + } + res.end(); + }, + { port: 4444 } + ); let proxyUseCount = 0; - proxy = await startHTTPServer(function (req, res) { - proxyUseCount += 1; - const targetUrl = new URL(req.url, 'http://' + req.headers.host); - const opts = { - host: targetUrl.hostname, - port: targetUrl.port, - path: targetUrl.path, - method: req.method - }; + proxy = await startHTTPServer( + function (req, res) { + proxyUseCount += 1; + const targetUrl = new URL(req.url, 'http://' + req.headers.host); + const opts = { + host: targetUrl.hostname, + port: targetUrl.port, + path: targetUrl.path, + method: req.method, + }; - const request = http.get(opts, function (response) { - res.writeHead(response.statusCode, response.headers); - stream.pipeline(response, res, () => {}); - }); + const request = http.get(opts, function (response) { + res.writeHead(response.statusCode, response.headers); + stream.pipeline(response, res, () => {}); + }); - request.on('error', (err) => { - console.warn('request error', err); - res.statusCode = 500; - res.end(); - }) - - }, {port: 4000}); + request.on('error', (err) => { + console.warn('request error', err); + res.statusCode = 500; + res.end(); + }); + }, + { port: 4000 } + ); let configBeforeRedirectCount = 0; - await axios.get('http://localhost:4444/', { - proxy: { - host: 'localhost', - port: 4000 - }, - maxRedirects: totalRedirectCount, - beforeRedirect: function (options) { - configBeforeRedirectCount += 1; - } - }).then(function (res) { - assert.equal(totalRedirectCount, configBeforeRedirectCount, 'should invoke config.beforeRedirect option on every redirect'); - assert.equal(totalRedirectCount + 1, proxyUseCount, 'should go through proxy on every redirect'); - }); + await axios + .get('http://localhost:4444/', { + proxy: { + host: 'localhost', + port: 4000, + }, + maxRedirects: totalRedirectCount, + beforeRedirect: function (options) { + configBeforeRedirectCount += 1; + }, + }) + .then(function (res) { + assert.equal( + totalRedirectCount, + configBeforeRedirectCount, + 'should invoke config.beforeRedirect option on every redirect' + ); + assert.equal( + totalRedirectCount + 1, + proxyUseCount, + 'should go through proxy on every redirect' + ); + }); }); it('should wrap HTTP errors and keep stack', async function () { @@ -422,16 +497,16 @@ describe('supports http with nodejs', function () { return assert.rejects( async function findMeInStackTrace() { - await axios.head('http://localhost:4444/one') + await axios.head('http://localhost:4444/one'); }, function (err) { - assert.equal(err.name, 'AxiosError') - assert.equal(err.isAxiosError, true) - const matches = [...err.stack.matchAll(/findMeInStackTrace/g)] - assert.equal(matches.length, 1, err.stack) + assert.equal(err.name, 'AxiosError'); + assert.equal(err.isAxiosError, true); + const matches = [...err.stack.matchAll(/findMeInStackTrace/g)]; + assert.equal(matches.length, 1, err.stack); return true; } - ) + ); }); it('should wrap interceptor errors and keep stack', function (done) { @@ -441,48 +516,58 @@ describe('supports http with nodejs', function () { } const axiosInstance = axios.create(); axiosInstance.interceptors.request.use((res) => { - throw new Error('from request interceptor') - }); - server = http.createServer(function (req, res) { - res.end(); - }).listen(4444, function () { - void assert.rejects( - async function findMeInStackTrace() { - await axiosInstance.get('http://localhost:4444/one') - }, - function (err) { - assert.equal(err.name, 'Error') - assert.equal(err.message, 'from request interceptor') - const matches = [...err.stack.matchAll(/findMeInStackTrace/g)] - assert.equal(matches.length, 1, err.stack) - return true; - } - ).then(done).catch(done); + throw new Error('from request interceptor'); }); + server = http + .createServer(function (req, res) { + res.end(); + }) + .listen(4444, function () { + void assert + .rejects( + async function findMeInStackTrace() { + await axiosInstance.get('http://localhost:4444/one'); + }, + function (err) { + assert.equal(err.name, 'Error'); + assert.equal(err.message, 'from request interceptor'); + const matches = [...err.stack.matchAll(/findMeInStackTrace/g)]; + assert.equal(matches.length, 1, err.stack); + return true; + } + ) + .then(done) + .catch(done); + }); }); it('should preserve the HTTP verb on redirect', function (done) { - server = http.createServer(function (req, res) { - if (req.method.toLowerCase() !== "head") { - res.statusCode = 400; - res.end(); - return; - } + server = http + .createServer(function (req, res) { + if (req.method.toLowerCase() !== 'head') { + res.statusCode = 400; + res.end(); + return; + } - var parsed = url.parse(req.url); - if (parsed.pathname === '/one') { - res.setHeader('Location', '/two'); - res.statusCode = 302; - res.end(); - } else { - res.end(); - } - }).listen(4444, function () { - axios.head('http://localhost:4444/one').then(function (res) { - assert.equal(res.status, 200); - done(); - }).catch(done); - }); + var parsed = url.parse(req.url); + if (parsed.pathname === '/one') { + res.setHeader('Location', '/two'); + res.statusCode = 302; + res.end(); + } else { + res.end(); + } + }) + .listen(4444, function () { + axios + .head('http://localhost:4444/one') + .then(function (res) { + assert.equal(res.status, 200); + done(); + }) + .catch(done); + }); }); describe('compression', async () => { @@ -490,21 +575,25 @@ describe('supports http with nodejs', function () { var data = { firstName: 'Fred', lastName: 'Flintstone', - emailAddr: 'fred@example.com' + emailAddr: 'fred@example.com', }; zlib.gzip(JSON.stringify(data), function (err, zipped) { - - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Content-Encoding', 'gzip'); - res.end(zipped); - }).listen(4444, function () { - axios.get('http://localhost:4444/').then(function (res) { - assert.deepEqual(res.data, data); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Content-Encoding', 'gzip'); + res.end(zipped); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.deepEqual(res.data, data); + done(); + }) + .catch(done); + }); }); }); @@ -517,32 +606,36 @@ describe('supports http with nodejs', function () { await assert.rejects(async () => { await axios.get(LOCAL_SERVER_URL); - }) + }); }); - it('should support disabling automatic decompression of response data', function(done) { + it('should support disabling automatic decompression of response data', function (done) { var data = 'Test data'; - zlib.gzip(data, function(err, zipped) { - server = http.createServer(function(req, res) { - res.setHeader('Content-Type', 'text/html;charset=utf-8'); - res.setHeader('Content-Encoding', 'gzip'); - res.end(zipped); - }).listen(4444, function() { - axios.get('http://localhost:4444/', { - decompress: false, - responseType: 'arraybuffer' - - }).then(function(res) { - assert.equal(res.data.toString('base64'), zipped.toString('base64')); - done(); - }).catch(done); - }); + zlib.gzip(data, function (err, zipped) { + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html;charset=utf-8'); + res.setHeader('Content-Encoding', 'gzip'); + res.end(zipped); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + decompress: false, + responseType: 'arraybuffer', + }) + .then(function (res) { + assert.equal(res.data.toString('base64'), zipped.toString('base64')); + done(); + }) + .catch(done); + }); }); }); describe('algorithms', () => { - const responseBody ='str'; + const responseBody = 'str'; for (const [typeName, zipped] of Object.entries({ gzip: gzip(responseBody), @@ -550,7 +643,7 @@ describe('supports http with nodejs', function () { compress: gzip(responseBody), deflate: deflate(responseBody), 'deflate-raw': deflateRaw(responseBody), - br: brotliCompress(responseBody) + br: brotliCompress(responseBody), })) { const type = typeName.split('-')[0]; @@ -561,7 +654,7 @@ describe('supports http with nodejs', function () { res.end(await zipped); }); - const {data} = await axios.get(LOCAL_SERVER_URL); + const { data } = await axios.get(LOCAL_SERVER_URL); assert.strictEqual(data, responseBody); }); @@ -573,7 +666,7 @@ describe('supports http with nodejs', function () { res.end(await zipped); }); - const {data} = await axios.get(LOCAL_SERVER_URL); + const { data } = await axios.get(LOCAL_SERVER_URL); assert.strictEqual(data, responseBody); }); @@ -587,7 +680,7 @@ describe('supports http with nodejs', function () { res.end(); }); - const {data} = await axios.get(LOCAL_SERVER_URL); + const { data } = await axios.get(LOCAL_SERVER_URL); assert.strictEqual(data, responseBody); }); @@ -599,7 +692,7 @@ describe('supports http with nodejs', function () { res.end(); }); - const {data} = await axios.get(LOCAL_SERVER_URL); + const { data } = await axios.get(LOCAL_SERVER_URL); assert.strictEqual(data, ''); }); @@ -614,205 +707,265 @@ describe('supports http with nodejs', function () { }); }); } - }); }); it('should support UTF8', function (done) { var str = Array(100000).join('ж'); - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end(str); - }).listen(4444, function () { - axios.get('http://localhost:4444/').then(function (res) { - assert.equal(res.data, str); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end(str); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.equal(res.data, str); + done(); + }) + .catch(done); + }); }); it('should support basic auth', function (done) { - server = http.createServer(function (req, res) { - res.end(req.headers.authorization); - }).listen(4444, function () { - var user = 'foo'; - var headers = { Authorization: 'Bearer 1234' }; - axios.get('http://' + user + '@localhost:4444/', { headers: headers }).then(function (res) { - var base64 = Buffer.from(user + ':', 'utf8').toString('base64'); - assert.equal(res.data, 'Basic ' + base64); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.end(req.headers.authorization); + }) + .listen(4444, function () { + var user = 'foo'; + var headers = { Authorization: 'Bearer 1234' }; + axios + .get('http://' + user + '@localhost:4444/', { headers: headers }) + .then(function (res) { + var base64 = Buffer.from(user + ':', 'utf8').toString('base64'); + assert.equal(res.data, 'Basic ' + base64); + done(); + }) + .catch(done); + }); }); it('should support basic auth with a header', function (done) { - server = http.createServer(function (req, res) { - res.end(req.headers.authorization); - }).listen(4444, function () { - var auth = { username: 'foo', password: 'bar' }; - var headers = { AuThOrIzAtIoN: 'Bearer 1234' }; // wonky casing to ensure caseless comparison - axios.get('http://localhost:4444/', { auth: auth, headers: headers }).then(function (res) { - var base64 = Buffer.from('foo:bar', 'utf8').toString('base64'); - assert.equal(res.data, 'Basic ' + base64); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.end(req.headers.authorization); + }) + .listen(4444, function () { + var auth = { username: 'foo', password: 'bar' }; + var headers = { AuThOrIzAtIoN: 'Bearer 1234' }; // wonky casing to ensure caseless comparison + axios + .get('http://localhost:4444/', { auth: auth, headers: headers }) + .then(function (res) { + var base64 = Buffer.from('foo:bar', 'utf8').toString('base64'); + assert.equal(res.data, 'Basic ' + base64); + done(); + }) + .catch(done); + }); }); it('should provides a default User-Agent header', function (done) { - server = http.createServer(function (req, res) { - res.end(req.headers['user-agent']); - }).listen(4444, function () { - axios.get('http://localhost:4444/').then(function (res) { - assert.ok(/^axios\/[\d.]+[-]?[a-z]*[.]?[\d]+$/.test(res.data), `User-Agent header does not match: ${res.data}`); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.end(req.headers['user-agent']); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.ok( + /^axios\/[\d.]+[-]?[a-z]*[.]?[\d]+$/.test(res.data), + `User-Agent header does not match: ${res.data}` + ); + done(); + }) + .catch(done); + }); }); it('should allow the User-Agent header to be overridden', function (done) { - server = http.createServer(function (req, res) { - res.end(req.headers['user-agent']); - }).listen(4444, function () { - var headers = { 'UsEr-AgEnT': 'foo bar' }; // wonky casing to ensure caseless comparison - axios.get('http://localhost:4444/', { headers }).then(function (res) { - assert.equal(res.data, 'foo bar'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.end(req.headers['user-agent']); + }) + .listen(4444, function () { + var headers = { 'UsEr-AgEnT': 'foo bar' }; // wonky casing to ensure caseless comparison + axios + .get('http://localhost:4444/', { headers }) + .then(function (res) { + assert.equal(res.data, 'foo bar'); + done(); + }) + .catch(done); + }); }); it('should allow the Content-Length header to be overridden', function (done) { - server = http.createServer(function (req, res) { - assert.strictEqual(req.headers['content-length'], '42'); - res.end(); - }).listen(4444, function () { - var headers = { 'CoNtEnT-lEnGtH': '42' }; // wonky casing to ensure caseless comparison - axios.post('http://localhost:4444/', 'foo', { headers }).then(function () { - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + assert.strictEqual(req.headers['content-length'], '42'); + res.end(); + }) + .listen(4444, function () { + var headers = { 'CoNtEnT-lEnGtH': '42' }; // wonky casing to ensure caseless comparison + axios + .post('http://localhost:4444/', 'foo', { headers }) + .then(function () { + done(); + }) + .catch(done); + }); }); it('should support max content length', async function () { - server = await startHTTPServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end(Array(5000).join('#')); - }, {port: 4444}); + server = await startHTTPServer( + function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end(Array(5000).join('#')); + }, + { port: 4444 } + ); await assert.rejects(() => { return axios.get('http://localhost:4444/', { maxContentLength: 2000, - maxRedirects: 0 - }) - },/maxContentLength size of 2000 exceeded/); + maxRedirects: 0, + }); + }, /maxContentLength size of 2000 exceeded/); }); it('should support max content length for redirected', function (done) { var str = Array(100000).join('ж'); - server = http.createServer(function (req, res) { - var parsed = url.parse(req.url); + server = http + .createServer(function (req, res) { + var parsed = url.parse(req.url); - if (parsed.pathname === '/two') { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end(str); - } else { - res.setHeader('Location', '/two'); - res.statusCode = 302; - res.end(); - } - }).listen(4444, function () { - var success = false, failure = false, error; + if (parsed.pathname === '/two') { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end(str); + } else { + res.setHeader('Location', '/two'); + res.statusCode = 302; + res.end(); + } + }) + .listen(4444, function () { + var success = false, + failure = false, + error; - axios.get('http://localhost:4444/one', { - maxContentLength: 2000, - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + axios + .get('http://localhost:4444/one', { + maxContentLength: 2000, + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); + + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.message, 'maxContentLength size of 2000 exceeded'); + done(); + }, 100); }); - - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.message, 'maxContentLength size of 2000 exceeded'); - done(); - }, 100); - }); }); it('should support max body length', function (done) { var data = Array(100000).join('ж'); - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end(); - }).listen(4444, function () { - var success = false, failure = false, error; + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end(); + }) + .listen(4444, function () { + var success = false, + failure = false, + error; - axios.post('http://localhost:4444/', { - data: data - }, { - maxBodyLength: 2000 - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; + axios + .post( + 'http://localhost:4444/', + { + data: data, + }, + { + maxBodyLength: 2000, + } + ) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); + + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.message, 'Request body larger than maxBodyLength limit'); + done(); + }, 100); }); - - - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.message, 'Request body larger than maxBodyLength limit'); - done(); - }, 100); - }); }); it('should properly support default max body length (follow-redirects as well)', function (done) { // taken from https://github.com/follow-redirects/follow-redirects/blob/22e81fc37132941fb83939d1dc4c2282b5c69521/index.js#L461 - var followRedirectsMaxBodyDefaults = 10 * 1024 *1024; + var followRedirectsMaxBodyDefaults = 10 * 1024 * 1024; var data = Array(2 * followRedirectsMaxBodyDefaults).join('ж'); - server = http.createServer(function (req, res) { - // consume the req stream - req.on('data', noop); - // and wait for the end before responding, otherwise an ECONNRESET error will be thrown - req.on('end', () => { - res.end('OK'); + server = http + .createServer(function (req, res) { + // consume the req stream + req.on('data', noop); + // and wait for the end before responding, otherwise an ECONNRESET error will be thrown + req.on('end', () => { + res.end('OK'); + }); + }) + .listen(4444, function (err) { + if (err) { + return done(err); + } + // send using the default -1 (unlimited axios maxBodyLength) + axios + .post('http://localhost:4444/', { + data: data, + }) + .then(function (res) { + assert.equal(res.data, 'OK', 'should handle response'); + done(); + }) + .catch(done); }); - }).listen(4444, function (err) { - if (err) { - return done(err); - } - // send using the default -1 (unlimited axios maxBodyLength) - axios.post('http://localhost:4444/', { - data: data - }).then(function (res) { - assert.equal(res.data, 'OK', 'should handle response'); - done(); - }).catch(done); - }); }); it('should display error while parsing params', function (done) { - server = http.createServer(function () { - - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - params: { - errorParam: new Date(undefined), - }, - }).catch(function (err) { - assert.deepEqual(err.exists, true) - done(); - }).catch(done); - }); + server = http + .createServer(function () {}) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + params: { + errorParam: new Date(undefined), + }, + }) + .catch(function (err) { + assert.deepEqual(err.exists, true); + done(); + }) + .catch(done); + }); }); it('should support sockets', function (done) { @@ -823,43 +976,50 @@ describe('supports http with nodejs', function () { socketName = '\\\\.\\pipe\\libuv-test'; } - server = net.createServer(function (socket) { - socket.on('data', function () { - socket.end('HTTP/1.1 200 OK\r\n\r\n'); - }); - }).listen(socketName, function () { - axios({ - socketPath: socketName, - url: 'http://localhost:4444/socket' + server = net + .createServer(function (socket) { + socket.on('data', function () { + socket.end('HTTP/1.1 200 OK\r\n\r\n'); + }); }) - .then(function (resp) { - assert.equal(resp.status, 200); - assert.equal(resp.statusText, 'OK'); - done(); - }).catch(done); - }); + .listen(socketName, function () { + axios({ + socketPath: socketName, + url: 'http://localhost:4444/socket', + }) + .then(function (resp) { + assert.equal(resp.status, 200); + assert.equal(resp.statusText, 'OK'); + done(); + }) + .catch(done); + }); }); - describe('streams', function(){ + describe('streams', function () { it('should support streams', function (done) { - server = http.createServer(function (req, res) { - req.pipe(res); - }).listen(4444, function () { - axios.post('http://localhost:4444/', - fs.createReadStream(__filename), { - responseType: 'stream' - }).then(function (res) { - var stream = res.data; - var string = ''; - stream.on('data', function (chunk) { - string += chunk.toString('utf8'); - }); - stream.on('end', function () { - assert.equal(string, fs.readFileSync(__filename, 'utf8')); - done(); - }); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + req.pipe(res); + }) + .listen(4444, function () { + axios + .post('http://localhost:4444/', fs.createReadStream(__filename), { + responseType: 'stream', + }) + .then(function (res) { + var stream = res.data; + var string = ''; + stream.on('data', function (chunk) { + string += chunk.toString('utf8'); + }); + stream.on('end', function () { + assert.equal(string, fs.readFileSync(__filename, 'utf8')); + done(); + }); + }) + .catch(done); + }); }); it('should pass errors for a failed stream', async function () { @@ -868,9 +1028,7 @@ describe('supports http with nodejs', function () { var notExitPath = path.join(__dirname, 'does_not_exist'); try { - await axios.post(LOCAL_SERVER_URL, - fs.createReadStream(notExitPath) - ); + await axios.post(LOCAL_SERVER_URL, fs.createReadStream(notExitPath)); assert.fail('expected ENOENT error'); } catch (err) { assert.equal(err.message, `ENOENT: no such file or directory, open \'${notExitPath}\'`); @@ -886,18 +1044,18 @@ describe('supports http with nodejs', function () { stream.destroy(); }, 1000); - const {data} = await axios.post(LOCAL_SERVER_URL, stream, {responseType: 'stream'}); + const { data } = await axios.post(LOCAL_SERVER_URL, stream, { responseType: 'stream' }); let streamError; - data.on('error', function(err) { + data.on('error', function (err) { streamError = err; }); try { await pipelineAsync(data, devNull()); assert.fail('stream was not aborted'); - } catch(e) { + } catch (e) { console.log(`pipeline error: ${e}`); } finally { assert.strictEqual(streamError && streamError.code, 'ERR_CANCELED'); @@ -907,503 +1065,590 @@ describe('supports http with nodejs', function () { it('should support buffers', function (done) { var buf = Buffer.alloc(1024, 'x'); // Unsafe buffer < Buffer.poolSize (8192 bytes) - server = http.createServer(function (req, res) { - assert.equal(req.headers['content-length'], buf.length.toString()); - req.pipe(res); - }).listen(4444, function () { - axios.post('http://localhost:4444/', - buf, { - responseType: 'stream' - }).then(function (res) { - var stream = res.data; - var string = ''; - stream.on('data', function (chunk) { - string += chunk.toString('utf8'); - }); - stream.on('end', function () { - assert.equal(string, buf.toString()); - done(); - }); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + assert.equal(req.headers['content-length'], buf.length.toString()); + req.pipe(res); + }) + .listen(4444, function () { + axios + .post('http://localhost:4444/', buf, { + responseType: 'stream', + }) + .then(function (res) { + var stream = res.data; + var string = ''; + stream.on('data', function (chunk) { + string += chunk.toString('utf8'); + }); + stream.on('end', function () { + assert.equal(string, buf.toString()); + done(); + }); + }) + .catch(done); + }); }); it('should support HTTP proxies', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('12345'); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('12345'); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '6789'); + }); + }); + }) + .listen(4000, function () { + axios + .get('http://localhost:4444/', { + proxy: { + host: 'localhost', + port: 4000, + }, + }) + .then(function (res) { + assert.equal(res.data, '123456789', 'should pass through proxy'); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '6789'); - }); - }); - - }).listen(4000, function () { - axios.get('http://localhost:4444/', { - proxy: { - host: 'localhost', - port: 4000 - } - }).then(function (res) { - assert.equal(res.data, '123456789', 'should pass through proxy'); - done(); - }).catch(done); }); - }); }); it('should support HTTPS proxies', function (done) { var options = { key: fs.readFileSync(path.join(__dirname, 'key.pem')), - cert: fs.readFileSync(path.join(__dirname, 'cert.pem')) + cert: fs.readFileSync(path.join(__dirname, 'cert.pem')), }; - server = https.createServer(options, function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('12345'); - }).listen(4444, function () { - proxy = https.createServer(options, function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path, - protocol: parsed.protocol, - rejectUnauthorized: false - }; + server = https + .createServer(options, function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('12345'); + }) + .listen(4444, function () { + proxy = https + .createServer(options, function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + protocol: parsed.protocol, + rejectUnauthorized: false, + }; - https.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; - }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '6789'); - }); - }); - }).listen(4000, function () { - axios.get('https://localhost:4444/', { - proxy: { - host: 'localhost', - port: 4000, - protocol: 'https:' - }, - httpsAgent: new https.Agent({ - rejectUnauthorized: false + https.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '6789'); + }); + }); }) - }).then(function (res) { - assert.equal(res.data, '123456789', 'should pass through proxy'); - done(); - }).catch(done); + .listen(4000, function () { + axios + .get('https://localhost:4444/', { + proxy: { + host: 'localhost', + port: 4000, + protocol: 'https:', + }, + httpsAgent: new https.Agent({ + rejectUnauthorized: false, + }), + }) + .then(function (res) { + assert.equal(res.data, '123456789', 'should pass through proxy'); + done(); + }) + .catch(done); + }); }); - }); }); it('should not pass through disabled proxy', function (done) { // set the env variable process.env.http_proxy = 'http://does-not-exists.example.com:4242/'; - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('123456789'); - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - proxy: false - }).then(function (res) { - assert.equal(res.data, '123456789', 'should not pass through proxy'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('123456789'); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + proxy: false, + }) + .then(function (res) { + assert.equal(res.data, '123456789', 'should not pass through proxy'); + done(); + }) + .catch(done); + }); }); it('should support proxy set via env var', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('4567'); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('4567'); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '1234'); + }); + }); + }) + .listen(4000, function () { + // set the env variable + process.env.http_proxy = 'http://localhost:4000/'; + + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.equal( + res.data, + '45671234', + 'should use proxy set by process.env.http_proxy' + ); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '1234'); - }); - }); - - }).listen(4000, function () { - // set the env variable - process.env.http_proxy = 'http://localhost:4000/'; - - axios.get('http://localhost:4444/').then(function (res) { - assert.equal(res.data, '45671234', 'should use proxy set by process.env.http_proxy'); - done(); - }).catch(done); }); - }); }); it('should support HTTPS proxy set via env var', function (done) { var options = { key: fs.readFileSync(path.join(__dirname, 'key.pem')), - cert: fs.readFileSync(path.join(__dirname, 'cert.pem')) + cert: fs.readFileSync(path.join(__dirname, 'cert.pem')), }; - server = https.createServer(options, function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('12345'); - }).listen(4444, function () { - proxy = https.createServer(options, function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path, - protocol: parsed.protocol, - rejectUnauthorized: false - }; + server = https + .createServer(options, function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('12345'); + }) + .listen(4444, function () { + proxy = https + .createServer(options, function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + protocol: parsed.protocol, + rejectUnauthorized: false, + }; - https.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; - }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '6789'); - }); - }); - }).listen(4000, function () { - process.env.https_proxy = 'https://localhost:4000/'; - - axios.get('https://localhost:4444/', { - httpsAgent: new https.Agent({ - rejectUnauthorized: false + https.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '6789'); + }); + }); }) - }).then(function (res) { - assert.equal(res.data, '123456789', 'should pass through proxy'); - done(); - }).catch(done); + .listen(4000, function () { + process.env.https_proxy = 'https://localhost:4000/'; + + axios + .get('https://localhost:4444/', { + httpsAgent: new https.Agent({ + rejectUnauthorized: false, + }), + }) + .then(function (res) { + assert.equal(res.data, '123456789', 'should pass through proxy'); + done(); + }) + .catch(done); + }); }); - }); }); it('should re-evaluate proxy on redirect when proxy set via env var', function (done) { - process.env.http_proxy = 'http://localhost:4000' - process.env.no_proxy = 'localhost:4000' + process.env.http_proxy = 'http://localhost:4000'; + process.env.no_proxy = 'localhost:4000'; var proxyUseCount = 0; - server = http.createServer(function (req, res) { - res.setHeader('Location', 'http://localhost:4000/redirected'); - res.statusCode = 302; - res.end(); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - if (parsed.pathname === '/redirected') { - response.statusCode = 200; - response.end(); - return; - } + server = http + .createServer(function (req, res) { + res.setHeader('Location', 'http://localhost:4000/redirected'); + res.statusCode = 302; + res.end(); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + if (parsed.pathname === '/redirected') { + response.statusCode = 200; + response.end(); + return; + } - proxyUseCount += 1; + proxyUseCount += 1; - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path, - protocol: parsed.protocol, - rejectUnauthorized: false - }; + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + protocol: parsed.protocol, + rejectUnauthorized: false, + }; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.setHeader('Location', res.headers.location); + response.end(body); + }); + }); + }) + .listen(4000, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.equal(res.status, 200); + assert.equal(proxyUseCount, 1); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.setHeader('Location', res.headers.location); - response.end(body); - }); - }); - }).listen(4000, function () { - axios.get('http://localhost:4444/').then(function(res) { - assert.equal(res.status, 200); - assert.equal(proxyUseCount, 1); - done(); - }).catch(done); }); - }); }); it('should not use proxy for domains in no_proxy', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('4567'); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('4567'); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '1234'); + }); + }); + }) + .listen(4000, function () { + // set the env variable + process.env.http_proxy = 'http://localhost:4000/'; + process.env.no_proxy = 'foo.com, localhost,bar.net , , quix.co'; + + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.equal(res.data, '4567', 'should not use proxy for domains in no_proxy'); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '1234'); - }); - }); - - }).listen(4000, function () { - // set the env variable - process.env.http_proxy = 'http://localhost:4000/'; - process.env.no_proxy = 'foo.com, localhost,bar.net , , quix.co'; - - axios.get('http://localhost:4444/').then(function (res) { - assert.equal(res.data, '4567', 'should not use proxy for domains in no_proxy'); - done(); - }).catch(done); }); - }); }); it('should use proxy for domains not in no_proxy', function (done) { - server = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - res.end('4567'); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; + server = http + .createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end('4567'); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(body + '1234'); + }); + }); + }) + .listen(4000, function () { + // set the env variable + process.env.http_proxy = 'http://localhost:4000/'; + process.env.no_proxy = 'foo.com, ,bar.net , quix.co'; + + axios + .get('http://localhost:4444/') + .then(function (res) { + assert.equal(res.data, '45671234', 'should use proxy for domains not in no_proxy'); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(body + '1234'); - }); - }); - - }).listen(4000, function () { - // set the env variable - process.env.http_proxy = 'http://localhost:4000/'; - process.env.no_proxy = 'foo.com, ,bar.net , quix.co'; - - axios.get('http://localhost:4444/').then(function (res) { - assert.equal(res.data, '45671234', 'should use proxy for domains not in no_proxy'); - done(); - }).catch(done); }); - }); }); it('should support HTTP proxy auth', function (done) { - server = http.createServer(function (req, res) { - res.end(); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; - var proxyAuth = request.headers['proxy-authorization']; + server = http + .createServer(function (req, res) { + res.end(); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; + var proxyAuth = request.headers['proxy-authorization']; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(proxyAuth); + }); + }); + }) + .listen(4000, function () { + axios + .get('http://localhost:4444/', { + proxy: { + host: 'localhost', + port: 4000, + auth: { + username: 'user', + password: 'pass', + }, + }, + }) + .then(function (res) { + var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); + assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy'); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(proxyAuth); - }); - }); - - }).listen(4000, function () { - axios.get('http://localhost:4444/', { - proxy: { - host: 'localhost', - port: 4000, - auth: { - username: 'user', - password: 'pass' - } - } - }).then(function (res) { - var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); - assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy'); - done(); - }).catch(done); }); - }); }); it('should support proxy auth from env', function (done) { - server = http.createServer(function (req, res) { - res.end(); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; - var proxyAuth = request.headers['proxy-authorization']; + server = http + .createServer(function (req, res) { + res.end(); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; + var proxyAuth = request.headers['proxy-authorization']; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(proxyAuth); + }); + }); + }) + .listen(4000, function () { + process.env.http_proxy = 'http://user:pass@localhost:4000/'; + + axios + .get('http://localhost:4444/') + .then(function (res) { + var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); + assert.equal( + res.data, + 'Basic ' + base64, + 'should authenticate to the proxy set by process.env.http_proxy' + ); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(proxyAuth); - }); - }); - - }).listen(4000, function () { - process.env.http_proxy = 'http://user:pass@localhost:4000/'; - - axios.get('http://localhost:4444/').then(function (res) { - var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); - assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy set by process.env.http_proxy'); - done(); - }).catch(done); }); - }); }); it('should support proxy auth with header', function (done) { - server = http.createServer(function (req, res) { - res.end(); - }).listen(4444, function () { - proxy = http.createServer(function (request, response) { - var parsed = url.parse(request.url); - var opts = { - host: parsed.hostname, - port: parsed.port, - path: parsed.path - }; - var proxyAuth = request.headers['proxy-authorization']; + server = http + .createServer(function (req, res) { + res.end(); + }) + .listen(4444, function () { + proxy = http + .createServer(function (request, response) { + var parsed = url.parse(request.url); + var opts = { + host: parsed.hostname, + port: parsed.port, + path: parsed.path, + }; + var proxyAuth = request.headers['proxy-authorization']; - http.get(opts, function (res) { - var body = ''; - res.on('data', function (data) { - body += data; + http.get(opts, function (res) { + var body = ''; + res.on('data', function (data) { + body += data; + }); + res.on('end', function () { + response.setHeader('Content-Type', 'text/html; charset=UTF-8'); + response.end(proxyAuth); + }); + }); + }) + .listen(4000, function () { + axios + .get('http://localhost:4444/', { + proxy: { + host: 'localhost', + port: 4000, + auth: { + username: 'user', + password: 'pass', + }, + }, + headers: { + 'Proxy-Authorization': 'Basic abc123', + }, + }) + .then(function (res) { + var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); + assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy'); + done(); + }) + .catch(done); }); - res.on('end', function () { - response.setHeader('Content-Type', 'text/html; charset=UTF-8'); - response.end(proxyAuth); - }); - }); - - }).listen(4000, function () { - axios.get('http://localhost:4444/', { - proxy: { - host: 'localhost', - port: 4000, - auth: { - username: 'user', - password: 'pass' - } - }, - headers: { - 'Proxy-Authorization': 'Basic abc123' - } - }).then(function (res) { - var base64 = Buffer.from('user:pass', 'utf8').toString('base64'); - assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy'); - done(); - }).catch(done); }); - }); }); describe('when invalid proxy options are provided', function () { it('should throw error', function () { const proxy = { - protocol: "http:", - host: "hostname.abc.xyz", + protocol: 'http:', + host: 'hostname.abc.xyz', port: 3300, auth: { - username: "", - password: "", - } + username: '', + password: '', + }, }; - return axios.get('https://test-domain.abc', {proxy}) - .then(function(){ + return axios.get('https://test-domain.abc', { proxy }).then( + function () { assert.fail('Does not throw'); - }, function (error) { + }, + function (error) { assert.strictEqual(error.message, 'Invalid proxy authorization'); assert.strictEqual(error.code, 'ERR_BAD_OPTION'); assert.deepStrictEqual(error.config.proxy, proxy); - }) + } + ); }); }); context('different options for direct proxy configuration (without env variables)', () => { const destination = 'www.example.com'; - const testCases = [{ - description: 'hostname and trailing colon in protocol', - proxyConfig: { hostname: '127.0.0.1', protocol: 'http:', port: 80 }, - expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination } - }, { - description: 'hostname and no trailing colon in protocol', - proxyConfig: { hostname: '127.0.0.1', protocol: 'http', port: 80 }, - expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination } - }, { - description: 'both hostname and host -> hostname takes precedence', - proxyConfig: { hostname: '127.0.0.1', host: '0.0.0.0', protocol: 'http', port: 80 }, - expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination } - }, { - description: 'only host and https protocol', - proxyConfig: { host: '0.0.0.0', protocol: 'https', port: 80 }, - expectedOptions: { host: '0.0.0.0', protocol: 'https:', port: 80, path: destination } - }]; + const testCases = [ + { + description: 'hostname and trailing colon in protocol', + proxyConfig: { hostname: '127.0.0.1', protocol: 'http:', port: 80 }, + expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination }, + }, + { + description: 'hostname and no trailing colon in protocol', + proxyConfig: { hostname: '127.0.0.1', protocol: 'http', port: 80 }, + expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination }, + }, + { + description: 'both hostname and host -> hostname takes precedence', + proxyConfig: { hostname: '127.0.0.1', host: '0.0.0.0', protocol: 'http', port: 80 }, + expectedOptions: { host: '127.0.0.1', protocol: 'http:', port: 80, path: destination }, + }, + { + description: 'only host and https protocol', + proxyConfig: { host: '0.0.0.0', protocol: 'https', port: 80 }, + expectedOptions: { host: '0.0.0.0', protocol: 'https:', port: 80, path: destination }, + }, + ]; for (const test of testCases) { it(test.description, () => { @@ -1418,207 +1663,251 @@ describe('supports http with nodejs', function () { it('should support cancel', function (done) { var source = axios.CancelToken.source(); - server = http.createServer(function (req, res) { - // call cancel() when the request has been sent, but a response has not been received - source.cancel('Operation has been canceled.'); - }).listen(4444, function () { - void assert.rejects( - async function findMeInStackTrace() { - await axios.get('http://localhost:4444/', { - cancelToken: source.token - }); - }, - function (thrown) { - assert.ok(thrown instanceof axios.Cancel, 'Promise must be rejected with a CanceledError object'); - assert.equal(thrown.message, 'Operation has been canceled.'); - if (nodeMajorVersion > 12) { - assert.match(thrown.stack, /findMeInStackTrace/); - } - return true; - }, - ).then(done).catch(done); - }); + server = http + .createServer(function (req, res) { + // call cancel() when the request has been sent, but a response has not been received + source.cancel('Operation has been canceled.'); + }) + .listen(4444, function () { + void assert + .rejects( + async function findMeInStackTrace() { + await axios.get('http://localhost:4444/', { + cancelToken: source.token, + }); + }, + function (thrown) { + assert.ok( + thrown instanceof axios.Cancel, + 'Promise must be rejected with a CanceledError object' + ); + assert.equal(thrown.message, 'Operation has been canceled.'); + if (nodeMajorVersion > 12) { + assert.match(thrown.stack, /findMeInStackTrace/); + } + return true; + } + ) + .then(done) + .catch(done); + }); }); it('should combine baseURL and url', function (done) { - server = http.createServer(function (req, res) { - res.end(); - }).listen(4444, function () { - axios.get('/foo', { - baseURL: 'http://localhost:4444/', - }).then(function (res) { - assert.equal(res.config.baseURL, 'http://localhost:4444/'); - assert.equal(res.config.url, '/foo'); - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + res.end(); + }) + .listen(4444, function () { + axios + .get('/foo', { + baseURL: 'http://localhost:4444/', + }) + .then(function (res) { + assert.equal(res.config.baseURL, 'http://localhost:4444/'); + assert.equal(res.config.url, '/foo'); + done(); + }) + .catch(done); + }); }); it('should support HTTP protocol', function (done) { - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - axios.get('http://localhost:4444') - .then(function (res) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + axios.get('http://localhost:4444').then(function (res) { assert.equal(res.request.agent.protocol, 'http:'); done(); - }) - }) + }); + }); }); it('should support HTTPS protocol', function (done) { - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - axios.get('https://www.google.com') - .then(function (res) { + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + axios.get('https://www.google.com').then(function (res) { assert.equal(res.request.agent.protocol, 'https:'); done(); - }) - }) + }); + }); }); it('should return malformed URL', function (done) { - var success = false, failure = false; + var success = false, + failure = false; var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - axios.get('tel:484-695-3408') - .then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; - }) + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + axios + .get('tel:484-695-3408') + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.message, 'Unsupported protocol tel:'); - done(); - }, 300); - }) + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.message, 'Unsupported protocol tel:'); + done(); + }, 300); + }); }); it('should return unsupported protocol', function (done) { - var success = false, failure = false; + var success = false, + failure = false; var error; - server = http.createServer(function (req, res) { - setTimeout(function () { - res.end(); - }, 1000); - }).listen(4444, function () { - axios.get('ftp:google.com') - .then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; - }) + server = http + .createServer(function (req, res) { + setTimeout(function () { + res.end(); + }, 1000); + }) + .listen(4444, function () { + axios + .get('ftp:google.com') + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }); - setTimeout(function () { - assert.equal(success, false, 'request should not succeed'); - assert.equal(failure, true, 'request should fail'); - assert.equal(error.message, 'Unsupported protocol ftp:'); - done(); - }, 300); - }) + setTimeout(function () { + assert.equal(success, false, 'request should not succeed'); + assert.equal(failure, true, 'request should fail'); + assert.equal(error.message, 'Unsupported protocol ftp:'); + done(); + }, 300); + }); }); it('should supply a user-agent if one is not specified', function (done) { - server = http.createServer(function (req, res) { - assert.equal(req.headers["user-agent"], 'axios/' + axios.VERSION); - res.end(); - }).listen(4444, function () { - axios.get('http://localhost:4444/' - ).then(function (res) { - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + assert.equal(req.headers['user-agent'], 'axios/' + axios.VERSION); + res.end(); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/') + .then(function (res) { + done(); + }) + .catch(done); + }); }); it('should omit a user-agent if one is explicitly disclaimed', function (done) { - server = http.createServer(function (req, res) { - assert.equal("user-agent" in req.headers, false); - assert.equal("User-Agent" in req.headers, false); - res.end(); - }).listen(4444, function () { - axios.get('http://localhost:4444/', { - headers: { - "User-Agent": null - } - }).then(function (res) { - done(); - }).catch(done); - }); + server = http + .createServer(function (req, res) { + assert.equal('user-agent' in req.headers, false); + assert.equal('User-Agent' in req.headers, false); + res.end(); + }) + .listen(4444, function () { + axios + .get('http://localhost:4444/', { + headers: { + 'User-Agent': null, + }, + }) + .then(function (res) { + done(); + }) + .catch(done); + }); }); it('should throw an error if http server that aborts a chunked request', function (done) { - server = http.createServer(function (req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.write('chunk 1'); - setTimeout(function () { - res.write('chunk 2'); - }, 100); - setTimeout(function() { - res.destroy(); - }, 200); - }).listen(4444, function () { - var success = false, failure = false; - var error; + server = http + .createServer(function (req, res) { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.write('chunk 1'); + setTimeout(function () { + res.write('chunk 2'); + }, 100); + setTimeout(function () { + res.destroy(); + }, 200); + }) + .listen(4444, function () { + var success = false, + failure = false; + var error; - axios.get('http://localhost:4444/aborted', { - timeout: 500 - }).then(function (res) { - success = true; - }).catch(function (err) { - error = err; - failure = true; - }).then(function () { - assert.strictEqual(success, false, 'request should not succeed'); - assert.strictEqual(failure, true, 'request should fail'); - assert.strictEqual(error.code, 'ERR_BAD_RESPONSE'); - assert.strictEqual(error.message, 'stream has been aborted'); - done(); - }).catch(done); - }); + axios + .get('http://localhost:4444/aborted', { + timeout: 500, + }) + .then(function (res) { + success = true; + }) + .catch(function (err) { + error = err; + failure = true; + }) + .then(function () { + assert.strictEqual(success, false, 'request should not succeed'); + assert.strictEqual(failure, true, 'request should fail'); + assert.strictEqual(error.code, 'ERR_BAD_RESPONSE'); + assert.strictEqual(error.message, 'stream has been aborted'); + done(); + }) + .catch(done); + }); }); - it('should able to cancel multiple requests with CancelToken', function(done){ - server = http.createServer(function (req, res) { - res.end('ok'); - }).listen(4444, function () { - var CancelToken = axios.CancelToken; - var source = CancelToken.source(); - var canceledStack = []; + it('should able to cancel multiple requests with CancelToken', function (done) { + server = http + .createServer(function (req, res) { + res.end('ok'); + }) + .listen(4444, function () { + var CancelToken = axios.CancelToken; + var source = CancelToken.source(); + var canceledStack = []; - var requests = [1, 2, 3, 4, 5].map(function(id){ - return axios - .get('/foo/bar', { cancelToken: source.token }) - .catch(function (e) { + var requests = [1, 2, 3, 4, 5].map(function (id) { + return axios.get('/foo/bar', { cancelToken: source.token }).catch(function (e) { if (!axios.isCancel(e)) { throw e; } canceledStack.push(id); }); + }); + + source.cancel('Aborted by user'); + + Promise.all(requests) + .then(function () { + assert.deepStrictEqual(canceledStack.sort(), [1, 2, 3, 4, 5]); + }) + .then(done, done); }); - - source.cancel("Aborted by user"); - - Promise.all(requests).then(function () { - assert.deepStrictEqual(canceledStack.sort(), [1, 2, 3, 4, 5]) - }).then(done, done); - }); }); describe('FormData', function () { @@ -1631,87 +1920,100 @@ describe('supports http with nodejs', function () { const stat = fs.statSync(image); - form.append('foo', "bar"); + form.append('foo', 'bar'); form.append('file1', file1, { filename: 'bar.jpg', filepath: 'temp/bar.jpg', - contentType: 'image/jpeg' + contentType: 'image/jpeg', }); form.append('fileStream', fileStream); - server = http.createServer(function (req, res) { - var receivedForm = new formidable.IncomingForm(); + server = http + .createServer(function (req, res) { + var receivedForm = new formidable.IncomingForm(); - assert.ok(req.rawHeaders.find(header => header.toLowerCase() === 'content-length')); + assert.ok(req.rawHeaders.find((header) => header.toLowerCase() === 'content-length')); - receivedForm.parse(req, function (err, fields, files) { - if (err) { - return done(err); - } + receivedForm.parse(req, function (err, fields, files) { + if (err) { + return done(err); + } - res.end(JSON.stringify({ - fields: fields, - files: files - })); + res.end( + JSON.stringify({ + fields: fields, + files: files, + }) + ); + }); + }) + .listen(4444, function () { + axios + .post('http://localhost:4444/', form, { + headers: { + 'Content-Type': 'multipart/form-data', + }, + }) + .then(function (res) { + assert.deepStrictEqual(res.data.fields, { foo: 'bar' }); + + assert.strictEqual(res.data.files.file1.mimetype, 'image/jpeg'); + assert.strictEqual(res.data.files.file1.originalFilename, 'temp/bar.jpg'); + assert.strictEqual(res.data.files.file1.size, 3); + + assert.strictEqual(res.data.files.fileStream.mimetype, 'image/png'); + assert.strictEqual(res.data.files.fileStream.originalFilename, 'axios.png'); + assert.strictEqual(res.data.files.fileStream.size, stat.size); + + done(); + }) + .catch(done); }); - }).listen(4444, function () { - axios.post('http://localhost:4444/', form, { - headers: { - 'Content-Type': 'multipart/form-data' - } - }).then(function (res) { - assert.deepStrictEqual(res.data.fields, {foo: 'bar'}); - - assert.strictEqual(res.data.files.file1.mimetype, 'image/jpeg'); - assert.strictEqual(res.data.files.file1.originalFilename, 'temp/bar.jpg'); - assert.strictEqual(res.data.files.file1.size, 3); - - assert.strictEqual(res.data.files.fileStream.mimetype, 'image/png'); - assert.strictEqual(res.data.files.fileStream.originalFilename, 'axios.png'); - assert.strictEqual(res.data.files.fileStream.size, stat.size); - - done(); - }).catch(done); - }); }); }); describe('SpecCompliant FormData', (done) => { it('should allow passing FormData', async function () { server = await startHTTPServer(async (req, res) => { - const {fields, files} = await handleFormData(req); + const { fields, files } = await handleFormData(req); - res.end(JSON.stringify({ - fields, - files - })); + res.end( + JSON.stringify({ + fields, + files, + }) + ); }); const form = new FormDataSpecCompliant(); const blobContent = 'blob-content'; - const blob = new BlobSpecCompliant([blobContent], {type: 'image/jpeg'}) + const blob = new BlobSpecCompliant([blobContent], { type: 'image/jpeg' }); form.append('foo1', 'bar1'); form.append('foo2', 'bar2'); form.append('file1', blob); - const {data} = await axios.post(LOCAL_SERVER_URL, form, { - maxRedirects: 0 + const { data } = await axios.post(LOCAL_SERVER_URL, form, { + maxRedirects: 0, }); - assert.deepStrictEqual(data.fields, {foo1: 'bar1' ,'foo2': 'bar2'}); + assert.deepStrictEqual(data.fields, { foo1: 'bar1', foo2: 'bar2' }); assert.deepStrictEqual(typeof data.files.file1, 'object'); - const {size, mimetype, originalFilename} = data.files.file1; + const { size, mimetype, originalFilename } = data.files.file1; assert.deepStrictEqual( - {size, mimetype, originalFilename}, - {mimetype: 'image/jpeg', originalFilename: 'blob', size: Buffer.from(blobContent).byteLength} + { size, mimetype, originalFilename }, + { + mimetype: 'image/jpeg', + originalFilename: 'blob', + size: Buffer.from(blobContent).byteLength, + } ); }); }); @@ -1723,8 +2025,11 @@ describe('supports http with nodejs', function () { var obj = { arr1: ['1', '2', '3'], arr2: ['1', ['2'], '3'], - obj: {x: '1', y: {z: '1'}}, - users: [{name: 'Peter', surname: 'griffin'}, {name: 'Thomas', surname: 'Anderson'}] + obj: { x: '1', y: { z: '1' } }, + users: [ + { name: 'Peter', surname: 'griffin' }, + { name: 'Thomas', surname: 'Anderson' }, + ], }; app.post('/', multer().none(), function (req, res, next) { @@ -1742,14 +2047,17 @@ describe('supports http with nodejs', function () { // arr[0]: '1' // arr[1]: '2' // ------------- - Promise.all([null, false, true].map(function (mode) { - return axios.postForm('http://localhost:3001/', obj, {formSerializer: {indexes: mode}}) - .then(function (res) { - assert.deepStrictEqual(res.data, obj, 'Index mode ' + mode); - }); - })).then(function (){ + Promise.all( + [null, false, true].map(function (mode) { + return axios + .postForm('http://localhost:3001/', obj, { formSerializer: { indexes: mode } }) + .then(function (res) { + assert.deepStrictEqual(res.data, obj, 'Index mode ' + mode); + }); + }) + ).then(function () { done(); - }, done) + }, done); }); }); }); @@ -1763,10 +2071,10 @@ describe('supports http with nodejs', function () { const blobContent = 'blob-content'; - const blob = new BlobSpecCompliant([blobContent], {type: 'image/jpeg'}) + const blob = new BlobSpecCompliant([blobContent], { type: 'image/jpeg' }); - const {data} = await axios.post(LOCAL_SERVER_URL, blob, { - maxRedirects: 0 + const { data } = await axios.post(LOCAL_SERVER_URL, blob, { + maxRedirects: 0, }); assert.deepStrictEqual(data, blobContent); @@ -1780,8 +2088,11 @@ describe('supports http with nodejs', function () { var obj = { arr1: ['1', '2', '3'], arr2: ['1', ['2'], '3'], - obj: {x: '1', y: {z: '1'}}, - users: [{name: 'Peter', surname: 'griffin'}, {name: 'Thomas', surname: 'Anderson'}] + obj: { x: '1', y: { z: '1' } }, + users: [ + { name: 'Peter', surname: 'griffin' }, + { name: 'Thomas', surname: 'Anderson' }, + ], }; app.use(bodyParser.urlencoded({ extended: true })); @@ -1791,15 +2102,17 @@ describe('supports http with nodejs', function () { }); server = app.listen(3001, function () { - return axios.post('http://localhost:3001/', obj, { - headers: { - 'content-type': 'application/x-www-form-urlencoded' - } - }) + return axios + .post('http://localhost:3001/', obj, { + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + }) .then(function (res) { assert.deepStrictEqual(res.data, obj); done(); - }).catch(done); + }) + .catch(done); }); }); }); @@ -1820,22 +2133,26 @@ describe('supports http with nodejs', function () { form.append('arr2[1][0]', '2'); form.append('arr2[2]', '3'); - server = http.createServer(function (req, res) { - req.pipe(res); - }).listen(3001, () => { - return axios.post('http://localhost:3001/', obj, { - headers: { - 'content-type': 'application/x-www-form-urlencoded' - }, - formSerializer: { - indexes: true - } + server = http + .createServer(function (req, res) { + req.pipe(res); }) - .then(function (res) { - assert.strictEqual(res.data, form.toString()); - done(); - }).catch(done); - }); + .listen(3001, () => { + return axios + .post('http://localhost:3001/', obj, { + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + formSerializer: { + indexes: true, + }, + }) + .then(function (res) { + assert.strictEqual(res.data, form.toString()); + done(); + }) + .catch(done); + }); }); describe('Data URL', function () { @@ -1844,14 +2161,16 @@ describe('supports http with nodejs', function () { const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64'); - axios.get(dataURI).then(({data}) => { - assert.deepStrictEqual(data, buffer); - done(); - }).catch(done); + axios + .get(dataURI) + .then(({ data }) => { + assert.deepStrictEqual(data, buffer); + done(); + }) + .catch(done); }); it('should support requesting data URL as a Blob (if supported by the environment)', function (done) { - if (!isBlobSupported) { this.skip(); return; @@ -1861,11 +2180,14 @@ describe('supports http with nodejs', function () { const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64'); - axios.get(dataURI, {responseType: 'blob'}).then(async ({data}) => { - assert.strictEqual(data.type, 'application/octet-stream'); - assert.deepStrictEqual(await data.text(), '123'); - done(); - }).catch(done); + axios + .get(dataURI, { responseType: 'blob' }) + .then(async ({ data }) => { + assert.strictEqual(data.type, 'application/octet-stream'); + assert.deepStrictEqual(await data.text(), '123'); + done(); + }) + .catch(done); }); it('should support requesting data URL as a String (text)', function (done) { @@ -1873,10 +2195,13 @@ describe('supports http with nodejs', function () { const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64'); - axios.get(dataURI, {responseType: "text"}).then(({data}) => { - assert.deepStrictEqual(data, '123'); - done(); - }).catch(done); + axios + .get(dataURI, { responseType: 'text' }) + .then(({ data }) => { + assert.deepStrictEqual(data, '123'); + done(); + }) + .catch(done); }); it('should support requesting data URL as a Stream', function (done) { @@ -1884,18 +2209,21 @@ describe('supports http with nodejs', function () { const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64'); - axios.get(dataURI, {responseType: "stream"}).then(({data}) => { - var str = ''; + axios + .get(dataURI, { responseType: 'stream' }) + .then(({ data }) => { + var str = ''; - data.on('data', function(response){ - str += response.toString(); - }); + data.on('data', function (response) { + str += response.toString(); + }); - data.on('end', function(){ - assert.strictEqual(str, '123'); - done(); - }); - }).catch(done); + data.on('end', function () { + assert.strictEqual(str, '123'); + done(); + }); + }) + .catch(done); }); }); @@ -1904,57 +2232,64 @@ describe('supports http with nodejs', function () { it('should support upload progress capturing', async function () { this.timeout(15000); server = await startHTTPServer({ - rate: 100 * 1024 + rate: 100 * 1024, }); let content = ''; const count = 10; - const chunk = "test"; + const chunk = 'test'; const chunkLength = Buffer.byteLength(chunk); const contentLength = count * chunkLength; - var readable = stream.Readable.from(async function* () { - let i = count; + var readable = stream.Readable.from( + (async function* () { + let i = count; - while (i-- > 0) { - await setTimeoutAsync(1100); - content += chunk; - yield chunk; - } - }()); + while (i-- > 0) { + await setTimeoutAsync(1100); + content += chunk; + yield chunk; + } + })() + ); const samples = []; - const {data} = await axios.post(LOCAL_SERVER_URL, readable, { - onUploadProgress: ({loaded, total, progress, bytes, upload}) => { + const { data } = await axios.post(LOCAL_SERVER_URL, readable, { + onUploadProgress: ({ loaded, total, progress, bytes, upload }) => { console.log('onUploadProgress', loaded, '/', total); samples.push({ loaded, total, progress, bytes, - upload + upload, }); }, headers: { - 'Content-Length': contentLength + 'Content-Length': contentLength, }, - responseType: 'text' + responseType: 'text', }); assert.strictEqual(data, content); - assert.deepStrictEqual(samples, Array.from(function* () { - for (let i = 1; i <= 10; i++) { - yield ({ - loaded: chunkLength * i, - total: contentLength, - progress: (chunkLength * i) / contentLength, - bytes: 4, - upload: true - }); - } - }())); + assert.deepStrictEqual( + samples, + Array.from( + (function* () { + for (let i = 1; i <= 10; i++) { + yield { + loaded: chunkLength * i, + total: contentLength, + progress: (chunkLength * i) / contentLength, + bytes: 4, + upload: true, + }; + } + })() + ) + ); }); }); @@ -1963,58 +2298,65 @@ describe('supports http with nodejs', function () { this.timeout(15000); server = await startHTTPServer({ - rate: 100 * 1024 + rate: 100 * 1024, }); let content = ''; const count = 10; - const chunk = "test"; + const chunk = 'test'; const chunkLength = Buffer.byteLength(chunk); const contentLength = count * chunkLength; - var readable = stream.Readable.from(async function* () { - let i = count; + var readable = stream.Readable.from( + (async function* () { + let i = count; - while (i-- > 0) { - await setTimeoutAsync(1100); - content += chunk; - yield chunk; - } - }()); + while (i-- > 0) { + await setTimeoutAsync(1100); + content += chunk; + yield chunk; + } + })() + ); const samples = []; - const {data} = await axios.post(LOCAL_SERVER_URL, readable, { - onDownloadProgress: ({loaded, total, progress, bytes, download}) => { + const { data } = await axios.post(LOCAL_SERVER_URL, readable, { + onDownloadProgress: ({ loaded, total, progress, bytes, download }) => { console.log('onDownloadProgress', loaded, '/', total); samples.push({ loaded, total, progress, bytes, - download + download, }); }, headers: { - 'Content-Length': contentLength + 'Content-Length': contentLength, }, responseType: 'text', - maxRedirects: 0 + maxRedirects: 0, }); assert.strictEqual(data, content); - assert.deepStrictEqual(samples, Array.from(function* () { - for (let i = 1; i <= 10; i++) { - yield ({ - loaded: chunkLength * i, - total: contentLength, - progress: (chunkLength * i) / contentLength, - bytes: 4, - download: true - }); - } - }())); + assert.deepStrictEqual( + samples, + Array.from( + (function* () { + for (let i = 1; i <= 10; i++) { + yield { + loaded: chunkLength * i, + total: contentLength, + progress: (chunkLength * i) / contentLength, + bytes: 4, + download: true, + }; + } + })() + ) + ); }); }); }); @@ -2034,36 +2376,37 @@ describe('supports http with nodejs', function () { const skip = 4; const compareValues = toleranceRange(50, 50); - const {data} = await axios.post(LOCAL_SERVER_URL, buf, { - onUploadProgress: ({loaded, total, progress, bytes, rate}) => { + const { data } = await axios.post(LOCAL_SERVER_URL, buf, { + onUploadProgress: ({ loaded, total, progress, bytes, rate }) => { samples.push({ loaded, total, progress, bytes, - rate + rate, }); }, maxRate: [configRate], responseType: 'text', - maxRedirects: 0 + maxRedirects: 0, }); - samples.slice(skip).forEach(({rate, progress}, i, _samples) => { - assert.ok(compareValues(rate, configRate), - `Rate sample at index ${i} is out of the expected range (${rate} / ${configRate}) [${ - _samples.map(({rate}) => rate).join(', ') - }]` + samples.slice(skip).forEach(({ rate, progress }, i, _samples) => { + assert.ok( + compareValues(rate, configRate), + `Rate sample at index ${i} is out of the expected range (${rate} / ${configRate}) [${_samples + .map(({ rate }) => rate) + .join(', ')}]` ); const progressTicksRate = 2; - const expectedProgress = ((i + skip) / secs) / progressTicksRate; + const expectedProgress = (i + skip) / secs / progressTicksRate; assert.ok( Math.abs(expectedProgress - progress) < 0.25, - `Progress sample at index ${i} is out of the expected range (${progress} / ${expectedProgress}) [${ - _samples.map(({progress}) => progress).join(', ') - }]` + `Progress sample at index ${i} is out of the expected range (${progress} / ${expectedProgress}) [${_samples + .map(({ progress }) => progress) + .join(', ')}]` ); }); @@ -2082,36 +2425,37 @@ describe('supports http with nodejs', function () { const skip = 4; const compareValues = toleranceRange(50, 50); - const {data} = await axios.post(LOCAL_SERVER_URL, buf, { - onDownloadProgress: ({loaded, total, progress, bytes, rate}) => { + const { data } = await axios.post(LOCAL_SERVER_URL, buf, { + onDownloadProgress: ({ loaded, total, progress, bytes, rate }) => { samples.push({ loaded, total, progress, bytes, - rate + rate, }); }, maxRate: [0, configRate], responseType: 'text', - maxRedirects: 0 + maxRedirects: 0, }); - samples.slice(skip).forEach(({rate, progress}, i, _samples) => { - assert.ok(compareValues(rate, configRate), - `Rate sample at index ${i} is out of the expected range (${rate} / ${configRate}) [${ - _samples.map(({rate}) => rate).join(', ') - }]` + samples.slice(skip).forEach(({ rate, progress }, i, _samples) => { + assert.ok( + compareValues(rate, configRate), + `Rate sample at index ${i} is out of the expected range (${rate} / ${configRate}) [${_samples + .map(({ rate }) => rate) + .join(', ')}]` ); const progressTicksRate = 3; - const expectedProgress = ((i + skip) / secs) / progressTicksRate; + const expectedProgress = (i + skip) / secs / progressTicksRate; assert.ok( Math.abs(expectedProgress - progress) < 0.25, - `Progress sample at index ${i} is out of the expected range (${progress} / ${expectedProgress}) [${ - _samples.map(({progress}) => progress).join(', ') - }]` + `Progress sample at index ${i} is out of the expected range (${progress} / ${expectedProgress}) [${_samples + .map(({ progress }) => progress) + .join(', ')}]` ); }); @@ -2119,23 +2463,23 @@ describe('supports http with nodejs', function () { }); }); - describe('request aborting', function() { + describe('request aborting', function () { //this.timeout(5000); it('should be able to abort the response stream', async () => { server = await startHTTPServer({ rate: 100_000, - useBuffering: true + useBuffering: true, }); const buf = Buffer.alloc(1024 * 1024); const controller = new AbortController(); - const {data} = await axios.post(LOCAL_SERVER_URL, buf, { + const { data } = await axios.post(LOCAL_SERVER_URL, buf, { responseType: 'stream', signal: controller.signal, - maxRedirects: 0 + maxRedirects: 0, }); setTimeout(() => { @@ -2144,7 +2488,7 @@ describe('supports http with nodejs', function () { let streamError; - data.on('error', function(err) { + data.on('error', function (err) { streamError = err; }); @@ -2152,7 +2496,7 @@ describe('supports http with nodejs', function () { assert.strictEqual(streamError && streamError.code, 'ERR_CANCELED'); }); - }) + }); it('should properly handle synchronous errors inside the adapter', function () { return assert.rejects(() => axios.get('http://192.168.0.285'), /Invalid URL/); @@ -2161,18 +2505,18 @@ describe('supports http with nodejs', function () { it('should support function as paramsSerializer value', async () => { server = await startHTTPServer((req, res) => res.end(req.url)); - const {data} = await axios.post(LOCAL_SERVER_URL, 'test', { + const { data } = await axios.post(LOCAL_SERVER_URL, 'test', { params: { - x: 1 + x: 1, }, paramsSerializer: () => 'foo', - maxRedirects: 0 + maxRedirects: 0, }); assert.strictEqual(data, '/?foo'); }); - describe('DNS', function() { + describe('DNS', function () { it('should support a custom DNS lookup function', async function () { server = await startHTTPServer(SERVER_HANDLER_STREAM_ECHO); @@ -2180,11 +2524,11 @@ describe('supports http with nodejs', function () { let isCalled = false; - const {data} = await axios.post(`http://fake-name.axios:4444`, payload,{ - lookup: (hostname, opt, cb) => { + const { data } = await axios.post(`http://fake-name.axios:4444`, payload, { + lookup: (hostname, opt, cb) => { isCalled = true; cb(null, '127.0.0.1', 4); - } + }, }); assert.ok(isCalled); @@ -2199,11 +2543,11 @@ describe('supports http with nodejs', function () { let isCalled = false; - const {data} = await axios.post(`http://fake-name.axios:4444`, payload,{ - lookup: (hostname, opt, cb) => { + const { data } = await axios.post(`http://fake-name.axios:4444`, payload, { + lookup: (hostname, opt, cb) => { isCalled = true; - cb(null, {address: '127.0.0.1', family: 4}); - } + cb(null, { address: '127.0.0.1', family: 4 }); + }, }); assert.ok(isCalled); @@ -2218,11 +2562,11 @@ describe('supports http with nodejs', function () { let isCalled = false; - const {data} = await axios.post(`http://fake-name.axios:4444`, payload,{ - lookup: async (hostname, opt) => { + const { data } = await axios.post(`http://fake-name.axios:4444`, payload, { + lookup: async (hostname, opt) => { isCalled = true; return ['127.0.0.1', 4]; - } + }, }); assert.ok(isCalled); @@ -2237,11 +2581,11 @@ describe('supports http with nodejs', function () { let isCalled = false; - const {data} = await axios.post(`http://fake-name.axios:4444`, payload,{ - lookup: async (hostname, opt) => { + const { data } = await axios.post(`http://fake-name.axios:4444`, payload, { + lookup: async (hostname, opt) => { isCalled = true; - return {address: '127.0.0.1', family: 4}; - } + return { address: '127.0.0.1', family: 4 }; + }, }); assert.ok(isCalled); @@ -2256,11 +2600,11 @@ describe('supports http with nodejs', function () { let isCalled = false; - const {data} = await axios.post(`http://fake-name.axios:4444`, payload,{ - lookup: async (hostname, opt) => { + const { data } = await axios.post(`http://fake-name.axios:4444`, payload, { + lookup: async (hostname, opt) => { isCalled = true; return '127.0.0.1'; - } + }, }); assert.ok(isCalled); @@ -2271,27 +2615,29 @@ describe('supports http with nodejs', function () { it('should handle errors', () => { return assert.rejects(async () => { await axios.get('https://no-such-domain-987654.com', { - lookup + lookup, }); }, /ENOTFOUND/); }); }); - describe('JSON', function() { + describe('JSON', function () { it('should support reviver on JSON.parse', async function () { server = await startHTTPServer(async (_, res) => { - res.end(JSON.stringify({ - foo: 'bar' - })); + res.end( + JSON.stringify({ + foo: 'bar', + }) + ); }); - const {data} = await axios.get(LOCAL_SERVER_URL, { + const { data } = await axios.get(LOCAL_SERVER_URL, { parseReviver: (key, value) => { return key === 'foo' ? 'success' : value; }, }); - assert.deepStrictEqual(data, {foo: 'success'}); + assert.deepStrictEqual(data, { foo: 'success' }); }); }); @@ -2302,52 +2648,53 @@ describe('supports http with nodejs', function () { baseURL: LOCAL_SERVER_URL, httpVersion: 2, http2Options: { - rejectUnauthorized: false - } + rejectUnauthorized: false, + }, }); it('should merge request http2Options with its instance config', async () => { - const {data} = await http2Axios.get('/', { + const { data } = await http2Axios.get('/', { http2Options: { - foo : 'test' + foo: 'test', }, adapter: async (config) => { return { - data: config.http2Options - } - } + data: config.http2Options, + }; + }, }); assert.deepStrictEqual(data, { rejectUnauthorized: false, - foo : 'test' + foo: 'test', }); }); it('should support http2 transport', async () => { - server = await startHTTPServer((req, res) => { - res.end('OK'); - }, { - useHTTP2: true - }); + server = await startHTTPServer( + (req, res) => { + res.end('OK'); + }, + { + useHTTP2: true, + } + ); - const {data} = await http2Axios.get(LOCAL_SERVER_URL); + const { data } = await http2Axios.get(LOCAL_SERVER_URL); assert.deepStrictEqual(data, 'OK'); - }); it(`should support request payload`, async () => { server = await startHTTPServer(null, { - useHTTP2: true + useHTTP2: true, }); const payload = 'DATA'; - const {data} = await http2Axios.post(LOCAL_SERVER_URL, payload); + const { data } = await http2Axios.post(LOCAL_SERVER_URL, payload); assert.deepStrictEqual(data, payload); - }); it(`should support FormData as a payload`, async function () { @@ -2355,55 +2702,61 @@ describe('supports http with nodejs', function () { this.skip(); } + server = await startHTTPServer( + async (req, res) => { + const { fields, files } = await handleFormData(req); - server = await startHTTPServer(async (req, res) => { - const {fields, files} = await handleFormData(req); - - res.end(JSON.stringify({ - fields, - files - })); - }, { - useHTTP2: true - }); + res.end( + JSON.stringify({ + fields, + files, + }) + ); + }, + { + useHTTP2: true, + } + ); const form = new FormData(); form.append('x', 'foo'); form.append('y', 'bar'); - const {data} = await http2Axios.post(LOCAL_SERVER_URL, form); + const { data } = await http2Axios.post(LOCAL_SERVER_URL, form); assert.deepStrictEqual(data, { fields: { x: 'foo', - y: 'bar' + y: 'bar', }, - files: {} + files: {}, }); - }); - describe("response types", () => { + describe('response types', () => { const originalData = '{"test": "OK"}'; const fixtures = { - 'text' : (v) => assert.strictEqual(v, originalData), - 'arraybuffer' : (v) => assert.deepStrictEqual(v, Buffer.from(originalData)), - 'stream': async (v) => assert.deepStrictEqual(await getStream(v), originalData), - 'json': async (v) => assert.deepStrictEqual(v, JSON.parse(originalData)) + text: (v) => assert.strictEqual(v, originalData), + arraybuffer: (v) => assert.deepStrictEqual(v, Buffer.from(originalData)), + stream: async (v) => assert.deepStrictEqual(await getStream(v), originalData), + json: async (v) => assert.deepStrictEqual(v, JSON.parse(originalData)), }; - for(let [responseType, assertValue] of Object.entries(fixtures)) { + for (let [responseType, assertValue] of Object.entries(fixtures)) { it(`should support ${responseType} response type`, async () => { - server = await startHTTPServer((req, res) => { - res.end(originalData); - }, { - useHTTP2: true - }); + server = await startHTTPServer( + (req, res) => { + res.end(originalData); + }, + { + useHTTP2: true, + } + ); - const {data} = await http2Axios.get(LOCAL_SERVER_URL, { - responseType + const { data } = await http2Axios.get(LOCAL_SERVER_URL, { + responseType, }); await assertValue(data); @@ -2411,21 +2764,22 @@ describe('supports http with nodejs', function () { } }); - - it('should support request timeout', async () => { - let isAborted= false; + let isAborted = false; let aborted; - const promise = new Promise(resolve => aborted = resolve); + const promise = new Promise((resolve) => (aborted = resolve)); - server = await startHTTPServer((req, res) => { - setTimeout(() => { - res.end('OK'); - }, 15000); - }, { - useHTTP2: true - }); + server = await startHTTPServer( + (req, res) => { + setTimeout(() => { + res.end('OK'); + }, 15000); + }, + { + useHTTP2: true, + } + ); server.on('stream', (stream) => { stream.once('aborted', () => { @@ -2436,7 +2790,7 @@ describe('supports http with nodejs', function () { await assert.rejects(async () => { await http2Axios.get(LOCAL_SERVER_URL, { - timeout: 500 + timeout: 500, }); }, /timeout/); @@ -2445,23 +2799,26 @@ describe('supports http with nodejs', function () { assert.ok(isAborted); }); - it('should support request cancellation', async function (){ + it('should support request cancellation', async function () { if (typeof AbortSignal !== 'function' || !AbortSignal.timeout) { this.skip(); } - let isAborted= false; + let isAborted = false; let aborted; - const promise = new Promise(resolve => aborted = resolve); + const promise = new Promise((resolve) => (aborted = resolve)); - server = await startHTTPServer((req, res) => { - setTimeout(() => { - res.end('OK'); - }, 15000); - }, { - useHTTP2: true - }); + server = await startHTTPServer( + (req, res) => { + setTimeout(() => { + res.end('OK'); + }, 15000); + }, + { + useHTTP2: true, + } + ); server.on('stream', (stream) => { stream.once('aborted', () => { @@ -2472,7 +2829,7 @@ describe('supports http with nodejs', function () { await assert.rejects(async () => { await http2Axios.get(LOCAL_SERVER_URL, { - signal: AbortSignal.timeout(500) + signal: AbortSignal.timeout(500), }); }, /CanceledError: canceled/); @@ -2482,17 +2839,20 @@ describe('supports http with nodejs', function () { }); it('should support stream response cancellation', async () => { - let isAborted= false; + let isAborted = false; var source = axios.CancelToken.source(); let aborted; - const promise = new Promise(resolve => aborted = resolve); + const promise = new Promise((resolve) => (aborted = resolve)); - server = await startHTTPServer((req, res) => { - generateReadable(10000, 100, 100).pipe(res); - }, { - useHTTP2: true - }); + server = await startHTTPServer( + (req, res) => { + generateReadable(10000, 100, 100).pipe(res); + }, + { + useHTTP2: true, + } + ); server.on('stream', (stream) => { stream.once('aborted', () => { @@ -2501,171 +2861,171 @@ describe('supports http with nodejs', function () { }); }); - const {data} = await http2Axios.get(LOCAL_SERVER_URL, { + const { data } = await http2Axios.get(LOCAL_SERVER_URL, { cancelToken: source.token, - responseType: 'stream' + responseType: 'stream', }); setTimeout(() => source.cancel()); - await assert.rejects( - () => pipelineAsync([data, devNull()]), - /CanceledError: canceled/ - ) + await assert.rejects(() => pipelineAsync([data, devNull()]), /CanceledError: canceled/); await promise; assert.ok(isAborted); }); - describe("session", () => { - it("should reuse session for the target authority", async() => { - server = await startHTTPServer((req, res) => { - setTimeout(() => res.end('OK'), 1000); - }, { - useHTTP2: true - }); + describe('session', () => { + it('should reuse session for the target authority', async () => { + server = await startHTTPServer( + (req, res) => { + setTimeout(() => res.end('OK'), 1000); + }, + { + useHTTP2: true, + } + ); const [response1, response2] = await Promise.all([ http2Axios.get(LOCAL_SERVER_URL, { - responseType: 'stream' + responseType: 'stream', }), http2Axios.get(LOCAL_SERVER_URL, { - responseType: 'stream' - }) + responseType: 'stream', + }), ]); assert.strictEqual(response1.data.session, response2.data.session); assert.deepStrictEqual( - await Promise.all([ - getStream(response1.data), - getStream(response2.data) - ]), + await Promise.all([getStream(response1.data), getStream(response2.data)]), ['OK', 'OK'] ); }); - it("should use different sessions for different authorities", async() => { - server = await startHTTPServer((req, res) => { - setTimeout(() => { - res.end('OK'); - }, 2000); - }, { - useHTTP2: true - }); + it('should use different sessions for different authorities', async () => { + server = await startHTTPServer( + (req, res) => { + setTimeout(() => { + res.end('OK'); + }, 2000); + }, + { + useHTTP2: true, + } + ); - server2 = await startHTTPServer((req, res) => { - setTimeout(() => { - res.end('OK'); - }, 2000); - }, { - useHTTP2: true, - port: SERVER_PORT2 - }); + server2 = await startHTTPServer( + (req, res) => { + setTimeout(() => { + res.end('OK'); + }, 2000); + }, + { + useHTTP2: true, + port: SERVER_PORT2, + } + ); const [response1, response2] = await Promise.all([ http2Axios.get(LOCAL_SERVER_URL, { - responseType: 'stream' + responseType: 'stream', }), http2Axios.get(LOCAL_SERVER_URL2, { - responseType: 'stream' - }) + responseType: 'stream', + }), ]); assert.notStrictEqual(response1.data.session, response2.data.session); assert.deepStrictEqual( - await Promise.all([ - getStream(response1.data), - getStream(response2.data) - ]), + await Promise.all([getStream(response1.data), getStream(response2.data)]), ['OK', 'OK'] ); }); - it("should use different sessions for requests with different http2Options set", async() => { - server = await startHTTPServer((req, res) => { - setTimeout(() => { - res.end('OK') - }, 1000); - }, { - useHTTP2: true - }); + it('should use different sessions for requests with different http2Options set', async () => { + server = await startHTTPServer( + (req, res) => { + setTimeout(() => { + res.end('OK'); + }, 1000); + }, + { + useHTTP2: true, + } + ); const [response1, response2] = await Promise.all([ http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', - http2Options: { - - } + http2Options: {}, }), http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', http2Options: { - foo: 'test' - } - }) + foo: 'test', + }, + }), ]); assert.notStrictEqual(response1.data.session, response2.data.session); assert.deepStrictEqual( - await Promise.all([ - getStream(response1.data), - getStream(response2.data) - ]), + await Promise.all([getStream(response1.data), getStream(response2.data)]), ['OK', 'OK'] ); }); - it("should use the same session for request with the same resolved http2Options set", async() => { - server = await startHTTPServer((req, res) => { - setTimeout(() => res.end('OK'), 1000); - }, { - useHTTP2: true - }); + it('should use the same session for request with the same resolved http2Options set', async () => { + server = await startHTTPServer( + (req, res) => { + setTimeout(() => res.end('OK'), 1000); + }, + { + useHTTP2: true, + } + ); const responses = await Promise.all([ http2Axios.get(LOCAL_SERVER_URL, { - responseType: 'stream' + responseType: 'stream', }), http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', - http2Options: undefined + http2Options: undefined, }), http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', - http2Options: { - - } - }) + http2Options: {}, + }), ]); - - assert.strictEqual(responses[1].data.session, responses[0].data.session); assert.strictEqual(responses[2].data.session, responses[0].data.session); - - assert.deepStrictEqual( - await Promise.all(responses.map(({data}) => getStream(data))), - ['OK', 'OK', 'OK'] - ); + assert.deepStrictEqual(await Promise.all(responses.map(({ data }) => getStream(data))), [ + 'OK', + 'OK', + 'OK', + ]); }); - it("should use different sessions after previous session timeout", async() => { - server = await startHTTPServer((req, res) => { - setTimeout(() => res.end('OK'), 100); - }, { - useHTTP2: true - }); + it('should use different sessions after previous session timeout', async () => { + server = await startHTTPServer( + (req, res) => { + setTimeout(() => res.end('OK'), 100); + }, + { + useHTTP2: true, + } + ); const response1 = await http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', http2Options: { - sessionTimeout: 1000 - } + sessionTimeout: 1000, + }, }); const data1 = await getStream(response1.data); @@ -2675,8 +3035,8 @@ describe('supports http with nodejs', function () { const response2 = await http2Axios.get(LOCAL_SERVER_URL, { responseType: 'stream', http2Options: { - sessionTimeout: 1000 - } + sessionTimeout: 1000, + }, }); const data2 = await getStream(response2.data); @@ -2697,11 +3057,11 @@ describe('supports http with nodejs', function () { try { await axios.get(LOCAL_SERVER_URL, { - responseType: 'stream' + responseType: 'stream', }); assert.fail('should be rejected'); - } catch(err) { + } catch (err) { assert.strictEqual(await getStream(err.response.data), 'OK'); } }); @@ -2710,16 +3070,14 @@ describe('supports http with nodejs', function () { it('should not fail with "socket hang up" when using timeouts', async () => { server = await startHTTPServer(async (req, res) => { if (req.url === '/wait') { - await new Promise(resolve => setTimeout(resolve, 5000)); + await new Promise((resolve) => setTimeout(resolve, 5000)); } res.end('ok'); - }) + }); const baseURL = LOCAL_SERVER_URL; - await axios.get('/1', {baseURL, timeout: 1000}); - await axios.get(`/wait`, {baseURL, timeout: 0}); + await axios.get('/1', { baseURL, timeout: 1000 }); + await axios.get(`/wait`, { baseURL, timeout: 0 }); }, 15000); }); }); - - diff --git a/test/unit/core/Axios.js b/test/unit/core/Axios.js index a4d62ac9..26451303 100644 --- a/test/unit/core/Axios.js +++ b/test/unit/core/Axios.js @@ -1,29 +1,29 @@ -import Axios from "../../../lib/core/Axios.js"; -import assert from "assert"; +import Axios from '../../../lib/core/Axios.js'; +import assert from 'assert'; describe('Axios', function () { - describe("handle un-writable error stack", function () { + describe('handle un-writable error stack', function () { async function testUnwritableErrorStack(stackAttributes) { const axios = new Axios({}); // mock axios._request to return an Error with an un-writable stack property axios._request = () => { - const mockError = new Error("test-error"); - Object.defineProperty(mockError, "stack", stackAttributes); + const mockError = new Error('test-error'); + Object.defineProperty(mockError, 'stack', stackAttributes); throw mockError; - } + }; try { - await axios.request("test-url", {}) + await axios.request('test-url', {}); } catch (e) { - assert.strictEqual(e.message, "test-error") + assert.strictEqual(e.message, 'test-error'); } } it('should support errors with a defined but un-writable stack', async function () { - await testUnwritableErrorStack({value: {}, writable: false}) + await testUnwritableErrorStack({ value: {}, writable: false }); }); it('should support errors with an undefined and un-writable stack', async function () { - await testUnwritableErrorStack({value: undefined, writable: false}) + await testUnwritableErrorStack({ value: undefined, writable: false }); }); it('should support errors with a custom getter/setter for the stack property', async function () { @@ -31,8 +31,8 @@ describe('Axios', function () { get: () => ({}), set: () => { throw new Error('read-only'); - } - }) + }, + }); }); it('should support errors with a custom getter/setter for the stack property (null case)', async function () { @@ -40,8 +40,8 @@ describe('Axios', function () { get: () => null, set: () => { throw new Error('read-only'); - } - }) + }, + }); }); }); diff --git a/test/unit/core/AxiosHeaders.js b/test/unit/core/AxiosHeaders.js index 46198749..b5c1c955 100644 --- a/test/unit/core/AxiosHeaders.js +++ b/test/unit/core/AxiosHeaders.js @@ -1,30 +1,29 @@ import AxiosHeaders from '../../../lib/core/AxiosHeaders.js'; import assert from 'assert'; -const [nodeMajorVersion] = process.versions.node.split('.').map(v => parseInt(v, 10)); +const [nodeMajorVersion] = process.versions.node.split('.').map((v) => parseInt(v, 10)); describe('AxiosHeaders', function () { it('should support headers argument', function () { const headers = new AxiosHeaders({ x: 1, - y: 2 + y: 2, }); assert.strictEqual(headers.get('x'), '1'); assert.strictEqual(headers.get('y'), '2'); - }) - + }); describe('set', function () { - it('should support adding a single header', function(){ + it('should support adding a single header', function () { const headers = new AxiosHeaders(); headers.set('foo', 'bar'); assert.strictEqual(headers.get('foo'), 'bar'); - }) + }); - it('should support adding multiple headers', function(){ + it('should support adding multiple headers', function () { const headers = new AxiosHeaders(); headers.set({ @@ -36,7 +35,7 @@ describe('AxiosHeaders', function () { assert.strictEqual(headers.get('bar'), 'value2'); }); - it('should support adding multiple headers from raw headers string', function(){ + it('should support adding multiple headers from raw headers string', function () { const headers = new AxiosHeaders(); headers.set(`foo:value1\nbar:value2`); @@ -45,7 +44,7 @@ describe('AxiosHeaders', function () { assert.strictEqual(headers.get('bar'), 'value2'); }); - it('should not rewrite header the header if the value is false', function(){ + it('should not rewrite header the header if the value is false', function () { const headers = new AxiosHeaders(); headers.set('foo', 'value1'); @@ -63,7 +62,7 @@ describe('AxiosHeaders', function () { assert.strictEqual(headers.get('foo'), 'value3'); }); - it('should not rewrite the header if its value is false, unless rewrite options is set to true', function(){ + it('should not rewrite the header if its value is false, unless rewrite options is set to true', function () { const headers = new AxiosHeaders(); headers.set('foo', false); @@ -108,7 +107,7 @@ describe('AxiosHeaders', function () { it('should support uppercase name mapping for names overlapped by class methods', () => { const headers = new AxiosHeaders({ - set: 'foo' + set: 'foo', }); headers.set('get', 'bar'); @@ -118,7 +117,7 @@ describe('AxiosHeaders', function () { }); describe('get', function () { - describe('filter', function() { + describe('filter', function () { it('should support RegExp', function () { const headers = new AxiosHeaders(); @@ -133,12 +132,18 @@ describe('AxiosHeaders', function () { headers.set('foo', 'bar=value1'); - assert.strictEqual(headers.get('foo', (value, header) => { - assert.strictEqual(value, 'bar=value1'); - assert.strictEqual(header, 'foo'); - return value; - }), 'bar=value1'); - assert.strictEqual(headers.get('foo', () => false), false); + assert.strictEqual( + headers.get('foo', (value, header) => { + assert.strictEqual(value, 'bar=value1'); + assert.strictEqual(header, 'foo'); + return value; + }), + 'bar=value1' + ); + assert.strictEqual( + headers.get('foo', () => false), + false + ); }); }); }); @@ -168,12 +173,18 @@ describe('AxiosHeaders', function () { headers.set('foo', 'bar=value1'); - assert.strictEqual(headers.has('foo', (value, header, headers) => { - assert.strictEqual(value, 'bar=value1'); - assert.strictEqual(header, 'foo'); - return true; - }), true); - assert.strictEqual(headers.has('foo', () => false), false); + assert.strictEqual( + headers.has('foo', (value, header, headers) => { + assert.strictEqual(value, 'bar=value1'); + assert.strictEqual(header, 'foo'); + return true; + }), + true + ); + assert.strictEqual( + headers.has('foo', () => false), + false + ); }); it('should support string pattern', function () { @@ -254,7 +265,10 @@ describe('AxiosHeaders', function () { assert.strictEqual(headers.has('foo'), true); - assert.strictEqual(headers.delete('foo', () => true), true); + assert.strictEqual( + headers.delete('foo', () => true), + true + ); assert.strictEqual(headers.has('foo'), false); }); @@ -279,21 +293,21 @@ describe('AxiosHeaders', function () { describe('clear', () => { it('should clear all headers', () => { - const headers = new AxiosHeaders({x: 1, y:2}); + const headers = new AxiosHeaders({ x: 1, y: 2 }); headers.clear(); - assert.deepStrictEqual({...headers.toJSON()}, {}); + assert.deepStrictEqual({ ...headers.toJSON() }, {}); }); it('should clear matching headers if a matcher was specified', () => { - const headers = new AxiosHeaders({foo: 1, 'x-foo': 2, bar: 3}); + const headers = new AxiosHeaders({ foo: 1, 'x-foo': 2, bar: 3 }); - assert.deepStrictEqual({...headers.toJSON()}, {foo: '1', 'x-foo': '2', bar: '3'}); + assert.deepStrictEqual({ ...headers.toJSON() }, { foo: '1', 'x-foo': '2', bar: '3' }); headers.clear(/^x-/); - assert.deepStrictEqual({...headers.toJSON()}, {foo: '1', bar: '3'}); + assert.deepStrictEqual({ ...headers.toJSON() }, { foo: '1', bar: '3' }); }); }); @@ -301,20 +315,23 @@ describe('AxiosHeaders', function () { it('should return headers object with original headers case', function () { const headers = new AxiosHeaders({ Foo: 'x', - bAr: 'y' + bAr: 'y', }); - assert.deepStrictEqual({...headers.toJSON()}, { - Foo: 'x', - bAr: 'y' - }); + assert.deepStrictEqual( + { ...headers.toJSON() }, + { + Foo: 'x', + bAr: 'y', + } + ); }); }); describe('accessors', function () { it('should support get accessor', function () { const headers = new AxiosHeaders({ - foo: 1 + foo: 1, }); headers.constructor.accessor('foo'); @@ -325,7 +342,7 @@ describe('AxiosHeaders', function () { it('should support set accessor', function () { const headers = new AxiosHeaders({ - foo: 1 + foo: 1, }); headers.constructor.accessor('foo'); @@ -337,7 +354,7 @@ describe('AxiosHeaders', function () { it('should support has accessor', function () { const headers = new AxiosHeaders({ - foo: 1 + foo: 1, }); headers.constructor.accessor('foo'); @@ -349,7 +366,7 @@ describe('AxiosHeaders', function () { it('should be caseless', function () { const headers = new AxiosHeaders({ - fOo: 1 + fOo: 1, }); assert.strictEqual(headers.get('Foo'), '1'); @@ -365,7 +382,6 @@ describe('AxiosHeaders', function () { headers.delete('FOO'); assert.strictEqual(headers.has('fOo'), false); - }); describe('normalize()', function () { @@ -373,54 +389,66 @@ describe('AxiosHeaders', function () { const headers = new AxiosHeaders({ fOo: 1, 'x-foo': 2, - 'y-bar-bAz': 3 + 'y-bar-bAz': 3, }); - assert.deepStrictEqual({...headers.normalize(true).toJSON()}, { - Foo: '1', - 'X-Foo': '2', - 'Y-Bar-Baz': '3' - }); + assert.deepStrictEqual( + { ...headers.normalize(true).toJSON() }, + { + Foo: '1', + 'X-Foo': '2', + 'Y-Bar-Baz': '3', + } + ); }); it('should support external defined values', function () { const headers = new AxiosHeaders({ - foo: '1' + foo: '1', }); headers['Foo'] = 2; headers['bar'] = 3; - assert.deepStrictEqual({...headers.normalize().toJSON()}, { - foo: '2', - bar: '3' - }); + assert.deepStrictEqual( + { ...headers.normalize().toJSON() }, + { + foo: '2', + bar: '3', + } + ); }); it('should support array values', function () { const headers = new AxiosHeaders({ - foo: [1,2,3] + foo: [1, 2, 3], }); - assert.deepStrictEqual({...headers.normalize().toJSON()}, { - foo: ['1','2','3'] - }); + assert.deepStrictEqual( + { ...headers.normalize().toJSON() }, + { + foo: ['1', '2', '3'], + } + ); }); }); describe('AxiosHeaders.concat', function () { it('should concatenate plain headers into an AxiosHeader instance', function () { - const a = {a: 1}; - const b = {b: 2}; - const c = {c: 3}; + const a = { a: 1 }; + const b = { b: 2 }; + const c = { c: 3 }; const headers = AxiosHeaders.concat(a, b, c); - assert.deepStrictEqual({...headers.toJSON()}, { - a: '1', - b: '2', - c: '3' - }); + assert.deepStrictEqual( + { ...headers.toJSON() }, + { + a: '1', + b: '2', + c: '3', + } + ); }); it('should concatenate raw headers into an AxiosHeader instance', function () { @@ -428,38 +456,41 @@ describe('AxiosHeaders', function () { const b = 'c:3\nx:4'; const headers = AxiosHeaders.concat(a, b); - assert.deepStrictEqual({...headers.toJSON()}, { - a: '1', - b: '2', - c: '3', - x: '4' - }); + assert.deepStrictEqual( + { ...headers.toJSON() }, + { + a: '1', + b: '2', + c: '3', + x: '4', + } + ); }); it('should concatenate Axios headers into a new AxiosHeader instance', function () { - const a = new AxiosHeaders({x: 1}); - const b = new AxiosHeaders({y: 2}); + const a = new AxiosHeaders({ x: 1 }); + const b = new AxiosHeaders({ y: 2 }); const headers = AxiosHeaders.concat(a, b); - assert.deepStrictEqual({...headers.toJSON()}, { - x: '1', - y: '2' - }); + assert.deepStrictEqual( + { ...headers.toJSON() }, + { + x: '1', + y: '2', + } + ); }); }); describe('toString', function () { it('should serialize AxiosHeader instance to a raw headers string', function () { - assert.deepStrictEqual(new AxiosHeaders({x:1, y:2}).toString(), 'x: 1\ny: 2'); + assert.deepStrictEqual(new AxiosHeaders({ x: 1, y: 2 }).toString(), 'x: 1\ny: 2'); }); }); describe('getSetCookie', function () { it('should return set-cookie', function () { - const headers = new AxiosHeaders( - 'Set-Cookie: key=val;\n' + - 'Set-Cookie: key2=val2;\n' - ); + const headers = new AxiosHeaders('Set-Cookie: key=val;\n' + 'Set-Cookie: key2=val2;\n'); assert.deepStrictEqual(headers.getSetCookie(), ['key=val;', 'key2=val2;']); }); diff --git a/test/unit/core/prototypePollution.js b/test/unit/core/prototypePollution.js index 28aa913f..eaf146b8 100644 --- a/test/unit/core/prototypePollution.js +++ b/test/unit/core/prototypePollution.js @@ -1,117 +1,105 @@ -"use strict"; +'use strict'; -import assert from "assert"; -import utils from "../../../lib/utils.js"; -import mergeConfig from "../../../lib/core/mergeConfig.js"; +import assert from 'assert'; +import utils from '../../../lib/utils.js'; +import mergeConfig from '../../../lib/core/mergeConfig.js'; -describe("Prototype Pollution Protection", function () { +describe('Prototype Pollution Protection', function () { afterEach(function () { // Clean up any pollution that might have occurred delete Object.prototype.polluted; }); - describe("utils.merge", function () { - it("should filter __proto__ key at top level", function () { - const result = utils.merge( - {}, - { __proto__: { polluted: "yes" }, safe: "value" }, - ); + describe('utils.merge', function () { + it('should filter __proto__ key at top level', function () { + const result = utils.merge({}, { __proto__: { polluted: 'yes' }, safe: 'value' }); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.safe, "value"); - assert.strictEqual(result.hasOwnProperty("__proto__"), false); + assert.strictEqual(result.safe, 'value'); + assert.strictEqual(result.hasOwnProperty('__proto__'), false); }); - it("should filter constructor key at top level", function () { - const result = utils.merge( - {}, - { constructor: { polluted: "yes" }, safe: "value" }, - ); + it('should filter constructor key at top level', function () { + const result = utils.merge({}, { constructor: { polluted: 'yes' }, safe: 'value' }); - assert.strictEqual(result.safe, "value"); - assert.strictEqual(result.hasOwnProperty("constructor"), false); + assert.strictEqual(result.safe, 'value'); + assert.strictEqual(result.hasOwnProperty('constructor'), false); }); - it("should filter prototype key at top level", function () { - const result = utils.merge( - {}, - { prototype: { polluted: "yes" }, safe: "value" }, - ); + it('should filter prototype key at top level', function () { + const result = utils.merge({}, { prototype: { polluted: 'yes' }, safe: 'value' }); - assert.strictEqual(result.safe, "value"); - assert.strictEqual(result.hasOwnProperty("prototype"), false); + assert.strictEqual(result.safe, 'value'); + assert.strictEqual(result.hasOwnProperty('prototype'), false); }); - it("should filter __proto__ key in nested objects", function () { + it('should filter __proto__ key in nested objects', function () { const result = utils.merge( {}, { headers: { - __proto__: { polluted: "nested" }, - "Content-Type": "application/json", + __proto__: { polluted: 'nested' }, + 'Content-Type': 'application/json', }, - }, + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.headers["Content-Type"], "application/json"); - assert.strictEqual(result.headers.hasOwnProperty("__proto__"), false); + assert.strictEqual(result.headers['Content-Type'], 'application/json'); + assert.strictEqual(result.headers.hasOwnProperty('__proto__'), false); }); - it("should filter constructor key in nested objects", function () { + it('should filter constructor key in nested objects', function () { const result = utils.merge( {}, { headers: { - constructor: { prototype: { polluted: "nested" } }, - "Content-Type": "application/json", + constructor: { prototype: { polluted: 'nested' } }, + 'Content-Type': 'application/json', }, - }, + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.headers["Content-Type"], "application/json"); - assert.strictEqual(result.headers.hasOwnProperty("constructor"), false); + assert.strictEqual(result.headers['Content-Type'], 'application/json'); + assert.strictEqual(result.headers.hasOwnProperty('constructor'), false); }); - it("should filter prototype key in nested objects", function () { + it('should filter prototype key in nested objects', function () { const result = utils.merge( {}, { headers: { - prototype: { polluted: "nested" }, - "Content-Type": "application/json", + prototype: { polluted: 'nested' }, + 'Content-Type': 'application/json', }, - }, + } ); - assert.strictEqual(result.headers["Content-Type"], "application/json"); - assert.strictEqual(result.headers.hasOwnProperty("prototype"), false); + assert.strictEqual(result.headers['Content-Type'], 'application/json'); + assert.strictEqual(result.headers.hasOwnProperty('prototype'), false); }); - it("should filter dangerous keys in deeply nested objects", function () { + it('should filter dangerous keys in deeply nested objects', function () { const result = utils.merge( {}, { level1: { level2: { - __proto__: { polluted: "deep" }, - prototype: { polluted: "deep" }, - safe: "value", + __proto__: { polluted: 'deep' }, + prototype: { polluted: 'deep' }, + safe: 'value', }, }, - }, + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.level1.level2.safe, "value"); - assert.strictEqual( - result.level1.level2.hasOwnProperty("__proto__"), - false, - ); + assert.strictEqual(result.level1.level2.safe, 'value'); + assert.strictEqual(result.level1.level2.hasOwnProperty('__proto__'), false); }); - it("should still merge regular properties correctly", function () { + it('should still merge regular properties correctly', function () { const result = utils.merge({ a: 1, b: { c: 2 } }, { b: { d: 3 }, e: 4 }); assert.strictEqual(result.a, 1); @@ -120,107 +108,104 @@ describe("Prototype Pollution Protection", function () { assert.strictEqual(result.e, 4); }); - it("should handle JSON.parse payloads safely", function () { + it('should handle JSON.parse payloads safely', function () { const malicious = JSON.parse('{"__proto__": {"polluted": "yes"}}'); const result = utils.merge({}, malicious); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.hasOwnProperty("__proto__"), false); + assert.strictEqual(result.hasOwnProperty('__proto__'), false); }); - it("should handle nested JSON.parse payloads safely", function () { + it('should handle nested JSON.parse payloads safely', function () { const malicious = JSON.parse( - '{"headers": {"constructor": {"prototype": {"polluted": "yes"}}}}', + '{"headers": {"constructor": {"prototype": {"polluted": "yes"}}}}' ); const result = utils.merge({}, malicious); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.headers.hasOwnProperty("constructor"), false); + assert.strictEqual(result.headers.hasOwnProperty('constructor'), false); }); }); - describe("mergeConfig", function () { - it("should filter dangerous keys at top level", function () { + describe('mergeConfig', function () { + it('should filter dangerous keys at top level', function () { const result = mergeConfig( {}, { - __proto__: { polluted: "yes" }, - constructor: { polluted: "yes" }, - prototype: { polluted: "yes" }, - url: "/api/test", - }, + __proto__: { polluted: 'yes' }, + constructor: { polluted: 'yes' }, + prototype: { polluted: 'yes' }, + url: '/api/test', + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.url, "/api/test"); - assert.strictEqual(result.hasOwnProperty("__proto__"), false); - assert.strictEqual(result.hasOwnProperty("constructor"), false); - assert.strictEqual(result.hasOwnProperty("prototype"), false); + assert.strictEqual(result.url, '/api/test'); + assert.strictEqual(result.hasOwnProperty('__proto__'), false); + assert.strictEqual(result.hasOwnProperty('constructor'), false); + assert.strictEqual(result.hasOwnProperty('prototype'), false); }); - it("should filter dangerous keys in headers", function () { + it('should filter dangerous keys in headers', function () { const result = mergeConfig( {}, { headers: { - __proto__: { polluted: "yes" }, - "Content-Type": "application/json", + __proto__: { polluted: 'yes' }, + 'Content-Type': 'application/json', }, - }, + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.headers["Content-Type"], "application/json"); - assert.strictEqual(result.headers.hasOwnProperty("__proto__"), false); + assert.strictEqual(result.headers['Content-Type'], 'application/json'); + assert.strictEqual(result.headers.hasOwnProperty('__proto__'), false); }); - it("should filter dangerous keys in custom config properties", function () { + it('should filter dangerous keys in custom config properties', function () { const result = mergeConfig( {}, { customProp: { - __proto__: { polluted: "yes" }, - safe: "value", + __proto__: { polluted: 'yes' }, + safe: 'value', }, - }, + } ); assert.strictEqual(Object.prototype.polluted, undefined); - assert.strictEqual(result.customProp.safe, "value"); - assert.strictEqual(result.customProp.hasOwnProperty("__proto__"), false); + assert.strictEqual(result.customProp.safe, 'value'); + assert.strictEqual(result.customProp.hasOwnProperty('__proto__'), false); }); - it("should still merge configs correctly", function () { + it('should still merge configs correctly', function () { const config1 = { - baseURL: "https://api.example.com", + baseURL: 'https://api.example.com', timeout: 1000, headers: { common: { - Accept: "application/json", + Accept: 'application/json', }, }, }; const config2 = { - url: "/users", + url: '/users', timeout: 5000, headers: { common: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, }, }; const result = mergeConfig(config1, config2); - assert.strictEqual(result.baseURL, "https://api.example.com"); - assert.strictEqual(result.url, "/users"); + assert.strictEqual(result.baseURL, 'https://api.example.com'); + assert.strictEqual(result.url, '/users'); assert.strictEqual(result.timeout, 5000); - assert.strictEqual(result.headers.common.Accept, "application/json"); - assert.strictEqual( - result.headers.common["Content-Type"], - "application/json", - ); + assert.strictEqual(result.headers.common.Accept, 'application/json'); + assert.strictEqual(result.headers.common['Content-Type'], 'application/json'); }); }); }); diff --git a/test/unit/defaults/transformResponse.js b/test/unit/defaults/transformResponse.js index 641d8835..6f6940c4 100644 --- a/test/unit/defaults/transformResponse.js +++ b/test/unit/defaults/transformResponse.js @@ -3,52 +3,64 @@ import transformData from '../../../lib/core/transformData.js'; import assert from 'assert'; describe('transformResponse', function () { - describe('200 request', function () { - it('parses json', function () { - const data = '{"message": "hello, world"}'; - const result = transformData.call({ - data, - response: { - headers: {'content-type': 'application/json'}, - status: 200 - } - }, defaults.transformResponse); - assert.strictEqual(result.message, 'hello, world'); - }); - it('ignores XML', function () { - const data = 'hello, world'; - const result = transformData.call({ - data, - response: { - headers: {'content-type': 'text/xml'}, - status: 200 - } - }, defaults.transformResponse); - assert.strictEqual(result, data); - }); + describe('200 request', function () { + it('parses json', function () { + const data = '{"message": "hello, world"}'; + const result = transformData.call( + { + data, + response: { + headers: { 'content-type': 'application/json' }, + status: 200, + }, + }, + defaults.transformResponse + ); + assert.strictEqual(result.message, 'hello, world'); }); - describe('204 request', function () { - it('does not parse the empty string', function () { - const data = ''; - const result = transformData.call({ - data, - response: { - headers: {'content-type': undefined}, - status: 204 - } - }, defaults.transformResponse); - assert.strictEqual(result, ''); - }); - it('does not parse undefined', function () { - const data = undefined; - const result = transformData.call({ - data, - response: { - headers: {'content-type': undefined}, - status: 200 - } - }, defaults.transformResponse); - assert.strictEqual(result, data); - }); + it('ignores XML', function () { + const data = 'hello, world'; + const result = transformData.call( + { + data, + response: { + headers: { 'content-type': 'text/xml' }, + status: 200, + }, + }, + defaults.transformResponse + ); + assert.strictEqual(result, data); }); + }); + describe('204 request', function () { + it('does not parse the empty string', function () { + const data = ''; + const result = transformData.call( + { + data, + response: { + headers: { 'content-type': undefined }, + status: 204, + }, + }, + defaults.transformResponse + ); + assert.strictEqual(result, ''); + }); + it('does not parse undefined', function () { + const data = undefined; + const result = transformData.call( + { + data, + response: { + headers: { 'content-type': undefined }, + status: 200, + }, + }, + defaults.transformResponse + ); + assert.strictEqual(result, data); + }); + }); }); diff --git a/test/unit/helpers/composeSignals.js b/test/unit/helpers/composeSignals.js index 89cfa11a..997082a4 100644 --- a/test/unit/helpers/composeSignals.js +++ b/test/unit/helpers/composeSignals.js @@ -28,7 +28,7 @@ describe('helpers::composeSignals', () => { it('should abort on timeout', async () => { const signal = composeSignals([], 100); - await new Promise(resolve => { + await new Promise((resolve) => { signal.addEventListener('abort', resolve); }); diff --git a/test/unit/helpers/fromDataURI.js b/test/unit/helpers/fromDataURI.js index d42dc865..434ab426 100644 --- a/test/unit/helpers/fromDataURI.js +++ b/test/unit/helpers/fromDataURI.js @@ -3,7 +3,7 @@ import fromDataURI from '../../../lib/helpers/fromDataURI.js'; describe('helpers::fromDataURI', function () { it('should return buffer from data uri', function () { - const buffer= Buffer.from('123'); + const buffer = Buffer.from('123'); const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64'); diff --git a/test/unit/helpers/parseProtocol.js b/test/unit/helpers/parseProtocol.js index 80c0646e..c3f8076b 100644 --- a/test/unit/helpers/parseProtocol.js +++ b/test/unit/helpers/parseProtocol.js @@ -4,21 +4,24 @@ import parseProtocol from '../../../lib/helpers/parseProtocol.js'; describe('helpers::parseProtocol', function () { it('should parse protocol part if it exists', function () { - utils.forEach({ - 'http://username:password@example.com/': 'http', - 'ftp:google.com': 'ftp', - 'sms:+15105550101?body=hello%20there': 'sms', - 'tel:0123456789' : 'tel', - '//google.com': '', - 'google.com': '', - 'admin://etc/default/grub' : 'admin', - 'stratum+tcp://server:port': 'stratum+tcp', - '/api/resource:customVerb': '', - 'https://stackoverflow.com/questions/': 'https', - 'mailto:jsmith@example.com' : 'mailto', - 'chrome-extension://1234/.html' : 'chrome-extension' - }, (expectedProtocol, url) => { - assert.strictEqual(parseProtocol(url), expectedProtocol); - }); + utils.forEach( + { + 'http://username:password@example.com/': 'http', + 'ftp:google.com': 'ftp', + 'sms:+15105550101?body=hello%20there': 'sms', + 'tel:0123456789': 'tel', + '//google.com': '', + 'google.com': '', + 'admin://etc/default/grub': 'admin', + 'stratum+tcp://server:port': 'stratum+tcp', + '/api/resource:customVerb': '', + 'https://stackoverflow.com/questions/': 'https', + 'mailto:jsmith@example.com': 'mailto', + 'chrome-extension://1234/.html': 'chrome-extension', + }, + (expectedProtocol, url) => { + assert.strictEqual(parseProtocol(url), expectedProtocol); + } + ); }); }); diff --git a/test/unit/helpers/toFormData.js b/test/unit/helpers/toFormData.js index 1b4bada5..c4416e71 100644 --- a/test/unit/helpers/toFormData.js +++ b/test/unit/helpers/toFormData.js @@ -6,11 +6,11 @@ describe('helpers::toFormData', function () { it('should convert a flat object to FormData', function () { const data = { foo: 'bar', - baz: 123 + baz: 123, }; const formData = toFormData(data, new FormData()); - + assert.ok(formData instanceof FormData); // form-data package specific checks assert.ok(formData._streams.length > 0); @@ -19,18 +19,18 @@ describe('helpers::toFormData', function () { it('should convert a nested object to FormData', function () { const data = { foo: { - bar: 'baz' - } + bar: 'baz', + }, }; const formData = toFormData(data, new FormData()); - + assert.ok(formData instanceof FormData); }); it('should throw Error on circular reference', function () { const data = { - foo: 'bar' + foo: 'bar', }; data.self = data; @@ -44,7 +44,7 @@ describe('helpers::toFormData', function () { it('should handle arrays', function () { const data = { - arr: [1, 2, 3] + arr: [1, 2, 3], }; const formData = toFormData(data, new FormData()); diff --git a/test/unit/platform/index.js b/test/unit/platform/index.js index ddef4215..27e388f6 100644 --- a/test/unit/platform/index.js +++ b/test/unit/platform/index.js @@ -1,5 +1,5 @@ -import platform from "../../../lib/platform/index.js"; -import assert from "assert"; +import platform from '../../../lib/platform/index.js'; +import assert from 'assert'; describe('generateString', function () { it('should generate a string of the specified length using the default alphabet', function () { diff --git a/test/unit/regression/SNYK-JS-AXIOS-1038255.js b/test/unit/regression/SNYK-JS-AXIOS-1038255.js index 1bdf5811..ffc4b115 100644 --- a/test/unit/regression/SNYK-JS-AXIOS-1038255.js +++ b/test/unit/regression/SNYK-JS-AXIOS-1038255.js @@ -9,28 +9,36 @@ import assert from 'assert'; const PROXY_PORT = 4777; const EVIL_PORT = 4666; - describe('Server-Side Request Forgery (SSRF)', () => { let fail = false; let proxy; let server; let location; beforeEach(() => { - server = http.createServer(function (req, res) { - fail = true; - res.end('rm -rf /'); - }).listen(EVIL_PORT); + server = http + .createServer(function (req, res) { + fail = true; + res.end('rm -rf /'); + }) + .listen(EVIL_PORT); - proxy = http.createServer(function (req, res) { - if (new URL(req.url, 'http://' + req.headers.host).toString() === 'http://localhost:' + EVIL_PORT + '/') { - return res.end(JSON.stringify({ - msg: 'Protected', - headers: req.headers, - })); - } - res.writeHead(302, { location }) - res.end() - }).listen(PROXY_PORT); + proxy = http + .createServer(function (req, res) { + if ( + new URL(req.url, 'http://' + req.headers.host).toString() === + 'http://localhost:' + EVIL_PORT + '/' + ) { + return res.end( + JSON.stringify({ + msg: 'Protected', + headers: req.headers, + }) + ); + } + res.writeHead(302, { location }); + res.end(); + }) + .listen(PROXY_PORT); }); afterEach(() => { server.close(); @@ -41,24 +49,26 @@ describe('Server-Side Request Forgery (SSRF)', () => { location = 'http://localhost:' + EVIL_PORT; let response = await axios({ - method: "get", - url: "http://www.google.com/", + method: 'get', + url: 'http://www.google.com/', proxy: { - host: "localhost", + host: 'localhost', port: PROXY_PORT, auth: { username: 'sam', password: 'password', - } + }, }, }); assert.strictEqual(fail, false); assert.strictEqual(response.data.msg, 'Protected'); assert.strictEqual(response.data.headers.host, 'localhost:' + EVIL_PORT); - assert.strictEqual(response.data.headers['proxy-authorization'], 'Basic ' + Buffer.from('sam:password').toString('base64')); + assert.strictEqual( + response.data.headers['proxy-authorization'], + 'Basic ' + Buffer.from('sam:password').toString('base64') + ); return response; - }); }); diff --git a/test/unit/regression/SNYK-JS-AXIOS-7361793.js b/test/unit/regression/SNYK-JS-AXIOS-7361793.js index ec7e54e7..fc2135ff 100644 --- a/test/unit/regression/SNYK-JS-AXIOS-7361793.js +++ b/test/unit/regression/SNYK-JS-AXIOS-7361793.js @@ -6,76 +6,82 @@ import http from 'http'; import assert from 'assert'; import platform from '../../../lib/platform/index.js'; - const GOOD_PORT = 4666; const BAD_PORT = 4667; describe('Server-Side Request Forgery (SSRF)', () => { - let goodServer, badServer; + let goodServer, badServer; - beforeEach(() => { - goodServer = http.createServer(function (req, res) { - res.write('good'); - res.end(); - }).listen(GOOD_PORT); - badServer = http.createServer(function (req, res) { - res.write('bad'); - res.end(); - }).listen(BAD_PORT); - }) + beforeEach(() => { + goodServer = http + .createServer(function (req, res) { + res.write('good'); + res.end(); + }) + .listen(GOOD_PORT); + badServer = http + .createServer(function (req, res) { + res.write('bad'); + res.end(); + }) + .listen(BAD_PORT); + }); - afterEach(() => { - goodServer.close(); - badServer.close(); + afterEach(() => { + goodServer.close(); + badServer.close(); + }); + + it('should not fetch in server-side mode', async () => { + const ssrfAxios = axios.create({ + baseURL: 'http://localhost:' + String(GOOD_PORT), }); - it('should not fetch in server-side mode', async () => { - const ssrfAxios = axios.create({ - baseURL: 'http://localhost:' + String(GOOD_PORT), - }); + // Good payload would be `userId = '12345'` + // Malicious payload is as below. + const userId = '/localhost:' + String(BAD_PORT); - // Good payload would be `userId = '12345'` - // Malicious payload is as below. - const userId = '/localhost:' + String(BAD_PORT); + try { + await ssrfAxios.get(`/${userId}`); + } catch (error) { + assert.ok(error.message.startsWith('Invalid URL')); + return; + } + assert.fail('Expected an error to be thrown'); + }); - try { - await ssrfAxios.get(`/${userId}`); - } catch (error) { - assert.ok(error.message.startsWith('Invalid URL')); - return; - } - assert.fail('Expected an error to be thrown'); + describe('should fetch in client-side mode', () => { + let hasBrowserEnv, origin; + + before(() => { + assert.ok(platform.hasBrowserEnv !== undefined); + hasBrowserEnv = platform.hasBrowserEnv; + origin = platform.origin; + platform.hasBrowserEnv = true; + platform.origin = 'http://localhost:' + String(GOOD_PORT); }); - - describe('should fetch in client-side mode', () => { - let hasBrowserEnv, origin; - - before(() => { - assert.ok(platform.hasBrowserEnv !== undefined); - hasBrowserEnv = platform.hasBrowserEnv; - origin = platform.origin; - platform.hasBrowserEnv = true; - platform.origin = 'http://localhost:' + String(GOOD_PORT); - }); - after(() => { - platform.hasBrowserEnv = hasBrowserEnv; - platform.origin = origin; - }); - it('should fetch in client-side mode', async () => { - platform.hasBrowserEnv = true; - const ssrfAxios = axios.create({ - baseURL: 'http://localhost:' + String(GOOD_PORT), - }); - - // Good payload would be `userId = '12345'` - // Malicious payload is as below. - const userId = '/localhost:' + String(BAD_PORT); - - const response = await ssrfAxios.get(`/${userId}`); - assert.strictEqual(response.data, 'bad'); - assert.strictEqual(response.config.baseURL, 'http://localhost:' + String(GOOD_PORT)); - assert.strictEqual(response.config.url, '//localhost:' + String(BAD_PORT)); - assert.strictEqual(response.request.res.responseUrl, 'http://localhost:' + String(BAD_PORT) + '/'); - }); + after(() => { + platform.hasBrowserEnv = hasBrowserEnv; + platform.origin = origin; }); + it('should fetch in client-side mode', async () => { + platform.hasBrowserEnv = true; + const ssrfAxios = axios.create({ + baseURL: 'http://localhost:' + String(GOOD_PORT), + }); + + // Good payload would be `userId = '12345'` + // Malicious payload is as below. + const userId = '/localhost:' + String(BAD_PORT); + + const response = await ssrfAxios.get(`/${userId}`); + assert.strictEqual(response.data, 'bad'); + assert.strictEqual(response.config.baseURL, 'http://localhost:' + String(GOOD_PORT)); + assert.strictEqual(response.config.url, '//localhost:' + String(BAD_PORT)); + assert.strictEqual( + response.request.res.responseUrl, + 'http://localhost:' + String(BAD_PORT) + '/' + ); + }); + }); }); diff --git a/test/unit/regression/bugs.js b/test/unit/regression/bugs.js index f975b162..dbdb77d3 100644 --- a/test/unit/regression/bugs.js +++ b/test/unit/regression/bugs.js @@ -5,7 +5,7 @@ import axios from '../../../index.js'; describe('issues', function () { describe('4999', function () { it('should not fail with query parsing', async function () { - const {data} = await axios.get('https://postman-echo.com/get?foo1=bar1&foo2=bar2'); + const { data } = await axios.get('https://postman-echo.com/get?foo1=bar1&foo2=bar2'); assert.strictEqual(data.args.foo1, 'bar1'); assert.strictEqual(data.args.foo2, 'bar2'); @@ -14,29 +14,31 @@ describe('issues', function () { describe('5028', function () { it('should handle set-cookie headers as an array', async function () { - const cookie1 = 'something=else; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly'; - const cookie2 = 'something-ssr.sig=n4MlwVAaxQAxhbdJO5XbUpDw-lA; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly'; + const cookie1 = + 'something=else; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly'; + const cookie2 = + 'something-ssr.sig=n4MlwVAaxQAxhbdJO5XbUpDw-lA; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly'; - const server = http.createServer((req, res) => { - //res.setHeader('Set-Cookie', 'my=value'); - res.setHeader('Set-Cookie', [cookie1, cookie2]); - res.writeHead(200); - res.write('Hi there'); - res.end(); - }).listen(0); + const server = http + .createServer((req, res) => { + //res.setHeader('Set-Cookie', 'my=value'); + res.setHeader('Set-Cookie', [cookie1, cookie2]); + res.writeHead(200); + res.write('Hi there'); + res.end(); + }) + .listen(0); const request = axios.create(); request.interceptors.response.use((res) => { - assert.deepStrictEqual(res.headers['set-cookie'], [ - cookie1, cookie2 - ]); + assert.deepStrictEqual(res.headers['set-cookie'], [cookie1, cookie2]); }); try { - await request({url: `http://localhost:${server.address().port}`}); + await request({ url: `http://localhost:${server.address().port}` }); } finally { - server.close() + server.close(); } }); }); @@ -48,20 +50,22 @@ describe('issues', function () { this.skip(); } - const server = http.createServer((req, res) => { - res.statusCode = 400; - res.end(); - }).listen(0); + const server = http + .createServer((req, res) => { + res.statusCode = 400; + res.end(); + }) + .listen(0); const instance = axios.create({ baseURL: `http://localhost:${server.address().port}`, - adapter: "fetch", + adapter: 'fetch', }); try { - await instance.get("/status/400"); + await instance.get('/status/400'); } catch (error) { - assert.equal(error.name, "AxiosError"); + assert.equal(error.name, 'AxiosError'); assert.equal(error.isAxiosError, true); assert.equal(error.status, 400); } finally { @@ -70,20 +74,22 @@ describe('issues', function () { }); it('http: should have status code in axios error', async function () { - const server = http.createServer((req, res) => { - res.statusCode = 400; - res.end(); - }).listen(0); + const server = http + .createServer((req, res) => { + res.statusCode = 400; + res.end(); + }) + .listen(0); const instance = axios.create({ baseURL: `http://localhost:${server.address().port}`, - adapter: "http", + adapter: 'http', }); try { - await instance.get("/status/400"); + await instance.get('/status/400'); } catch (error) { - assert.equal(error.name, "AxiosError"); + assert.equal(error.name, 'AxiosError'); assert.equal(error.isAxiosError, true); assert.equal(error.status, 400); } finally { @@ -91,5 +97,4 @@ describe('issues', function () { } }); }); - }); diff --git a/test/unit/utils/utils.js b/test/unit/utils/utils.js index 76eebcc1..908f4cff 100644 --- a/test/unit/utils/utils.js +++ b/test/unit/utils/utils.js @@ -3,16 +3,16 @@ import utils from '../../../lib/utils.js'; import FormData from 'form-data'; import stream from 'stream'; -describe('utils', function (){ +describe('utils', function () { it('should validate Stream', function () { - assert.strictEqual(utils.isStream(new stream.Readable()),true); - assert.strictEqual(utils.isStream({ foo: 'bar' }),false); + assert.strictEqual(utils.isStream(new stream.Readable()), true); + assert.strictEqual(utils.isStream({ foo: 'bar' }), false); }); it('should validate Buffer', function () { - assert.strictEqual(utils.isBuffer(Buffer.from('a')),true); - assert.strictEqual(utils.isBuffer(null),false); - assert.strictEqual(utils.isBuffer(undefined),false); + assert.strictEqual(utils.isBuffer(Buffer.from('a')), true); + assert.strictEqual(utils.isBuffer(null), false); + assert.strictEqual(utils.isBuffer(undefined), false); }); describe('utils::isFormData', function () { @@ -43,9 +43,7 @@ describe('utils', function (){ it('should detect custom FormData instances by toStringTag signature and append method presence', () => { class FormData { - append(){ - - } + append() {} get [Symbol.toStringTag]() { return 'FormData'; @@ -55,29 +53,37 @@ describe('utils', function (){ }); }); - describe('toJSON', function (){ + describe('toJSON', function () { it('should convert to a plain object without circular references', function () { - const obj= {a: [0]} - const source = {x:1, y:2, obj}; + const obj = { a: [0] }; + const source = { x: 1, y: 2, obj }; source.circular1 = source; obj.a[1] = obj; assert.deepStrictEqual(utils.toJSONObject(source), { - x: 1, y:2, obj: {a: [0]} + x: 1, + y: 2, + obj: { a: [0] }, }); }); it('should use objects with defined toJSON method without rebuilding', function () { const objProp = {}; - const obj= {objProp, toJSON(){ - return {ok: 1} - }}; - const source = {x:1, y:2, obj}; + const obj = { + objProp, + toJSON() { + return { ok: 1 }; + }, + }; + const source = { x: 1, y: 2, obj }; const jsonObject = utils.toJSONObject(source); assert.strictEqual(jsonObject.obj.objProp, objProp); - assert.strictEqual(JSON.stringify(jsonObject), JSON.stringify({x: 1, y:2, obj: {ok: 1}})) + assert.strictEqual( + JSON.stringify(jsonObject), + JSON.stringify({ x: 1, y: 2, obj: { ok: 1 } }) + ); }); }); @@ -85,11 +91,11 @@ describe('utils', function (){ it('should handle large Buffer in isEmptyObject without RangeError', function () { // Create a big buffer that used to cause the error const largeBuffer = Buffer.alloc(1024 * 1024 * 200); // 200MB - + // This used to throw: RangeError: Invalid array length // Now it should work fine const result = utils.isEmptyObject(largeBuffer); - + // Buffer should not be considered an empty object assert.strictEqual(result, false); }); @@ -97,20 +103,20 @@ describe('utils', function (){ it('should handle large Buffer in forEach without RangeError', function () { const largeBuffer = Buffer.alloc(1024 * 1024 * 200); // 200MB let count = 0; - + // This should skip the buffer (not iterate through it) utils.forEach(largeBuffer, () => count++); - + // Count should be 0 because forEach skips Buffers assert.strictEqual(count, 0); }); it('should handle large Buffer in findKey without RangeError', function () { const largeBuffer = Buffer.alloc(1024 * 1024 * 200); // 200MB - + // Should return null for Buffers const result = utils.findKey(largeBuffer, 'test'); - + assert.strictEqual(result, null); }); }); diff --git a/webpack.config.js b/webpack.config.js index 09b43d34..aae81aaa 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -10,11 +10,11 @@ function generateConfig(name) { sourceMapFilename: name + '.map', library: 'axios', libraryTarget: 'umd', - globalObject: 'this' + globalObject: 'this', }, node: false, devtool: 'source-map', - mode: compress ? 'production' : 'development' + mode: compress ? 'production' : 'development', }; return config; }