Greasy Fork

GM Requests

Imitating Python's Requests library based on GM_xmlHttpRequest.

目前为 2023-07-03 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.cloud/scripts/470000/1214581/GM%20Requests.js

// ==UserScript==
// @name        GM Requests
// @description Imitating Python's Requests library based on GM_xmlHttpRequest.
// @version     0.0.3
// @author      大碗宽面wtw
// @homepage    https://github.com/bigbowl-wtw/TampermonkeyRequests/
// @supportURL  https://github.com/bigbowl-wtw/TampermonkeyRequests/issues
// @match       none
// @grant       GM_xmlhttpRequest
// @license     MIT
// @namespace   com.github.bigbowl-wtw
// ==/UserScript==

!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.requests=e():t.requests=e()}(self,(()=>(()=>{"use strict";var t,e={d:(t,o)=>{for(var i in o)e.o(o,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:o[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function i(t,...e){return(Object.assign||function(t,...e){for(let o,i=0,s=e.length;i<s;i++){o=e[i];for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=o[e])}return t}).call(this,t,...e)}e.r(o),e.d(o,{Session:()=>d,get:()=>l,post:()=>p,session:()=>f}),function(t){t[t.BadRequest=400]="BadRequest",t[t.Unauthorized=401]="Unauthorized",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.RequestTimeout=408]="RequestTimeout",t[t.TooManyRequests=429]="TooManyRequests",t[t.InternalServerError=500]="InternalServerError",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable"}(t||(t={}));class s{get empty(){return!Object.keys(this.cookies).length}constructor(t){var e;this.never=new Set,this.setCookies(null!==(e=t)&&void 0!==e?e:{})}update(t){i(this.cookies,this.normalizeCookie(t))}updateFromString(t){"string"==typeof t&&(t=[t]),this.update(t)}differenceUpdate(t){let e;e=Array.isArray(t)?t.map(this.stringToEntry):Object.entries(r(t)?t.cookies:t);const o=new Set(Object.keys(this.cookies));e=e.filter((([t])=>!o.has(t))),this.update(Object.fromEntries(e))}deleteFromString(t){"string"==typeof t&&(t=[t]);t.map(this.stringToEntry).map((([t])=>t)).forEach((t=>{this.never.add(t),delete this.cookies[t]}))}setCookies(t){this.cookies=new Proxy(this.normalizeCookie(t),{set:(t,e,o)=>(this.never.has(e)||(t[e]=o),!0)})}toString(){return Object.entries(this.cookies).map((([t,e])=>`${t}=${e}`)).join(";")}parseCookieString(t){return Object.fromEntries(t.map(this.stringToEntry))}normalizeCookie(t){return Array.isArray(t)?this.parseCookieString(t):r(t)?t.cookies:t}stringToEntry(t){return t.slice(0,t.indexOf(";")).split("=")}}function r(t){return"function"==typeof t.update}var n=function(t,e){var o={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(o[i[s]]=t[i[s]])}return o};class a{constructor(t){if(this.cookies=new s,!t)return void(this.headers={});const{cookie:e}=t,o=n(t,["cookie"]);this.headers=o,e&&this.cookies.update(e)}setFromString(t){const e=t.split("\r\n").map((t=>t.split(":"))).map((([t,e])=>[t.toLowerCase(),e.trim()]));for(const[t,o]of e){const e=this.headers[t];e?("string"==typeof e&&(this.headers[t]=[e]),this.headers[t].push(o)):this.headers[t]=o}return this}update(t){if("function"==typeof t.update)this.cookies.update(t.cookies),this.update(t.headers);else{const e=null!=t?t:{},{cookie:o}=e,s=n(e,["cookie"]);i(this.headers,s),o&&this.cookies.update(o)}}getHeaders(){if(!Object.keys(this.headers).length)return this.cookies.empty?{}:{cookie:this.cookies.toString()};const t={};for(const[e,o]of Object.entries(this.headers))t[e]=o.toString();return Object.assign(Object.assign({},t),{cookie:this.cookies.toString()})}append(t,e){"cookie"===t?this.cookies.update([t]):this[t]?Array.isArray(t)?this[t].concat(e):this[t]=[e].concat(this[t]):this[t]=e}get(t){return this.headers[t]}}var h=function(t,e,o,i){return new(o||(o=Promise))((function(s,r){function n(t){try{h(i.next(t))}catch(t){r(t)}}function a(t){try{h(i.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(n,a)}h((i=i.apply(t,e||[])).next())}))},u=function(t,e){var o={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(o[i[s]]=t[i[s]])}return o};class c{constructor(t,e,o){if(this.pendings=[],this.url=t,this.method=e,this.finalHeader=new a,o){const{query:t,json:e,data:i,cookie:s,auth:r,headers:n}=o,a=u(o,["query","json","data","cookie","auth","headers"]);this.query=t,this.json=e,this.data=i,this.cookie=s,this.auth=r,this.headers=n,this.others=a}}build(t){return h(this,void 0,void 0,(function*(){return this.buildURL().buildHeaderAndCookie(t).buildAuth(t),this.pendings.concat(t.buildHooks.map((e=>e.call(this,t)))),this.toDetails()}))}buildURL(){return this.parseQuery(this.query),this}buildHeaderAndCookie(t){const e=this.finalHeader.cookies;return t.cookies.empty||e.update(t.cookies),this.cookie&&e.update(this.cookie),this.finalHeader.update(t.headers),this.headers&&this.finalHeader.update(this.headers),this}buildAuth(t){var e;return this.pendings.push(null===(e=t.auth)||void 0===e?void 0:e.build(this.finalHeader)),this}buildBody(){if(this.json){const t="application/json";this.finalHeader.update({"Content-Type":t});const e=JSON.stringify(this.json);return this.finalData=e,this}if(this.data){if("string"==typeof this.data)return this.finalData=this.data,this;if(this.data instanceof FormData)return this;const t="application/x-www-form-urlencoded";return this.finalHeader.update({"Content-Type":t}),this.finalData=function(t){if(Object.values(t).some((t=>"function"!=typeof t.toString)))throw new TypeError("value must has `.toString`");return Object.entries(t).map((([t,e])=>`${t}=${encodeURIComponent(e.toString())}`)).join("&")}(this.data),this}return this}toDetails(){return h(this,void 0,void 0,(function*(){yield Promise.all(this.pendings);const t=this.url.toString();this.buildBody();const e=Object.assign({url:t,method:this.method,headers:this.finalHeader.getHeaders()},this.others);return this.finalData&&(e.data=this.finalData),e}))}parseQuery(t){let e;e="string"==typeof this.url?new URL(this.url):this.url,t&&Object.entries(t).filter((([t,e])=>"string"==typeof e)).forEach((([t,o])=>e.searchParams.append(t,o.toString()))),this.url=e}}class d{constructor(){this.buildHooks=[];const t=new a;Object.defineProperty(this,"headers",{get:()=>t,set(e){t.update(e)}}),Object.defineProperty(this,"cookies",{get:()=>t.cookies,set(e){t.cookies.setCookies(e)}})}get(t,e){return h(this,void 0,void 0,(function*(){return this.request("GET",t,e)}))}post(t,e){return h(this,void 0,void 0,(function*(){return this.request("POST",t,e)}))}request(e,o,i){return h(this,void 0,void 0,(function*(){const s=new c(o,e,i);return new Promise(((e,o)=>{i.onload||(s.others.onload=s=>{if(!this.cookies.empty){const t=(new a).setFromString(s.responseHeaders);this.cookies.deleteFromString(t["set-cookie"])}200!==s.status||s.status in t?o(s):e((null==i?void 0:i.responseType)?s.response:s)}),i.onerror||(s.others.onerror=t=>o(t)),s.build(this).then((t=>GM_xmlhttpRequest(t)))}))}))}registerBuildHook(t){this.buildHooks.push(t)}}function l(t,e,o){return(new d).get(t,Object.assign({query:e},o))}function p(t,e){return(new d).post(t,Object.assign({},e))}function f(){return new d}return o})()));