Comparing version 1.2.6 to 1.2.7
@@ -1,4 +0,4 @@ | ||
{ | ||
{ | ||
"name": "wrape", | ||
"version": "1.2.6", | ||
"version": "1.2.7", | ||
"description": "Easily generate API client's SDK — organize and simplify API Requests — OOP-ish way.", | ||
@@ -32,3 +32,2 @@ "main": "wrape.min.js", | ||
"dependencies": { | ||
"crypto-convert": "^1.0.0", | ||
"form-data": "^3.0.0", | ||
@@ -35,0 +34,0 @@ "node-fetch": "^2.6.1" |
@@ -7,2 +7,3 @@ | ||
Easily generate API client's SDK — organize and simplify API Requests. | ||
@@ -39,10 +40,9 @@ If you find yourself repeating HTTP requests code blocks, then this library is for you. | ||
- No dependencies, using Fetch API | ||
- Documentation Generator | ||
- Multiple API categories & subcategories | ||
- Elegant parameter handling | ||
- Universal support, small size (2.9KB) | ||
- For Browsers & Node.js | ||
@@ -54,6 +54,4 @@ ## Installation | ||
## Usage | ||
## Basic Example | ||
You start by writing a JSON schema of all your API endpoints. | ||
@@ -96,2 +94,8 @@ You can split requests into categories and subcategories. | ||
``` | ||
## Real-life Usages | ||
Some projects using Wrape: | ||
- https://github.com/tikapi-io/tiktok-api | ||
## Quick Documentaion | ||
@@ -103,2 +107,5 @@ | ||
An API category is an object consisting of [Endpoint Object](#endpoint-object)s or subcategories. | ||
A category can also contain special keys: | ||
- **`$options`**: Set options for this category, same object as [Gloabl Options](#global-options) | ||
- **`$help`**: A description used for endpoint generation | ||
@@ -116,2 +123,4 @@ #### Endpoint Object | ||
- **`request`**: A hook function for modifying the request. | ||
- **`help`**: A description used for documantaion generation | ||
- **`example_response`**: Example response used for documentation generation | ||
@@ -125,2 +134,3 @@ #### Params Object | ||
- A function, that returns a boolean. | ||
- **`in`**: Array of valid allowed values | ||
- **`help`** : An error message to throw if param is not valid, or required. | ||
@@ -132,3 +142,4 @@ - **`default`**: A default value for this param. | ||
- **`headers`** the param will be set in request headers | ||
- **`path`** the param will be set in request path, you must declare the named parameters in path, check [exmaple](#another-example) below. | ||
- **`path`** the param will be set in request path, you must declare the named parameters in path. | ||
- **``example``** : Example values used for documentation generation | ||
@@ -149,2 +160,12 @@ ### Global Options | ||
### Documentation Generator | ||
You can generate a Markdown reference of the API, just like this: | ||
```javascript | ||
api.$docs({ | ||
output: "API.md", | ||
}); | ||
``` | ||
@@ -204,14 +225,12 @@ ### Responses | ||
``` | ||
#### Alternative Category Options | ||
You can also set options for a category by initializing it with `set` function. This method doesn't work with subcategories. | ||
#### Setting Variables | ||
You can set enviroment variables for a category by initializing it with `set` function. | ||
```javascript | ||
const Profile = new api.user.profile.set({ | ||
values: { | ||
key: 'default_auth_token' | ||
} | ||
const User = new api.user.set({ | ||
authorization: 'default_auth_token' | ||
}); | ||
Profile.information({id: 1}).then((res) => { | ||
User.info({id: 1}).then((res) => { | ||
console.log(res.json); | ||
}); | ||
``` |
/*! | ||
* Wrape v1.2.6 | ||
* Wrape v1.2.7 | ||
* Author: Elis <contact@elis.cc> | ||
* License: MIT | ||
*/ | ||
function Wrape(e,t,n,r){n=n||{};r=Object.assign({base:"",headers:{},values:{},sender:!1,request_middleware:null,response_middleware:null,fetch_parse:!0,fetch_agent:!1,fetch_error_handler:!1},r);const a={form:"multipart/form-data",url:"application/x-www-form-urlencoded",json:"application/json",text:"text/plain"},o=Object.values(a),i=["headers","body","query","path"],s={POST:"body",GET:"query"},u={"multipart/form-data":function(){var e=new t;return e.toString=function(){return this},e},"application/x-www-form-urlencoded":function(){return new URLSearchParams},"application/json":function(){return{append:function(e,t){this.data=this.data||{},this.data[e]=t},toString:function(){return JSON.stringify(this.data)},isEmpty:function(){return!this.data||0==Object.keys(this.data).length}}},"text/plain":function(){return{append:function(e,t){return this.data=this.data||[],this.data.push(t)},toString:function(){return this.data.join("")},isEmpty:function(){return!this.data||0==this.data.length}}}};function f(e){return null==e}function c(e){for(var t of e)return!1;return!0}function d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p(t,n,r,a){return"function"==typeof r.sender?r.sender(t,n,a,r):e(t,n).then((async function(e){var o={},i=r.fetch_parse,s="function"==typeof a?a:null,u="function"==typeof r.fetch_error_handler?r.fetch_error_handler:null;try{if(i){var f=e.headers.get("Content-Type");o={status_code:e.status,status:e.status,statusText:e.statusText,headers:e.headers},f&&new RegExp("application/json").test(f)?o.json=await e.json():o.text=await e.text();var c=e.ok?"Success.":"Something went wrong.";o.message=o.json&&o.json.message?o.json.message:c}else o=e;if(!e.ok)throw new Error("Request failed.")}catch(e){return u?u(e,{url:t,options:n},o):Promise.reject(e)}return s?s(o):o}))}function l(e,t){var n={[t=t||"Wrape"]:function(a){if(!(this instanceof n[t]))throw new Error("You must initalize this object using 'new' command.");return Object.assign(this,e),this.set=function(e){this.$options=Object.assign({},r,e)}.bind(this),this.set(a),this}};return n[t]}function h(e,n){return e.method="string"==typeof e.method?e.method.toUpperCase():"GET",e.enctype=a[e.enctype]||(o.includes(e.enctype)?e.enctype:o[0]),n=Object.assign({},r,n),async function(a){var l=this.$options||n||r,h=`${l.base}${e.path}`,m={method:e.method,headers:l.headers,agent:l.fetch_agent},y=Object.keys(e.params),w=Array.from(arguments),g=e.request||l.request_middleware,v=e.response||l.response_middleware,b=u[e.enctype](),j=new URLSearchParams;for(var _ in w.length>1?a=w.reduce((function(e,t,n){return y[n]?(e[y[n]]=t,e):e}),{}):w[0]instanceof t?(a={},w[0].forEach((function(e,t){a[t]=e}))):a=1!=w.length||1!=y.length||!w[0]||w[0][y[0]]||w[0]instanceof t?a||{}:{[y[0]]:w[0]},e.params){var x=e.params[_],E=a[_]||x.default||l.values[_],S=x.name||_;if(x.required&&f(E))throw(q=new Error(x.help||`The '${_}' field is required.`)).field=q.param=_,q;if(!f(E)){if("function"==typeof x.formatter||"function"==typeof x.format){var $=x.format||x.formatter;E=$(E)}if(x.validate){var q,O="function"==typeof x.validate?x.validate(E):new RegExp(x.validate).test(E);if(!O)throw(q=new Error(x.help||`The '${_}' field is invalid.`)).field=q.param=_,q}var k="string"==typeof x.location?x.location.toLowerCase():s[m.method];if(!k||!i.includes(k))throw new Error(`Invalid location for '${_}' field.`);"headers"!=k?"body"!=k?"query"!=k?"path"==k&&(h=h.replace(new RegExp(":"+d(_)),E)):j.append(S,E):b.append(S,E):(m.headers=m.headers||{},m.headers[S]=E)}}var T=j.toString();T&&(h=`${h}?${T}`);var P=b.keys&&c(b.keys())||b.getLengthSync&&0==b.getLengthSync()||b.isEmpty&&b.isEmpty();if(P||(m.body=b.toString()),m.body&&e.enctype!==o[0]&&(m.headers=m.headers||{},m.headers["Content-Type"]=e.enctype),"function"==typeof g){var R=await Promise.resolve(g(h,m,j,b));if(!1===R)return!1;R&&R.url&&(h=R.url),R&&R.options&&(m=returns.options)}return p(h,m,l,v)}}return function e(t,n,r,a){for(var o in n){var i=n[o];if(i&&"object"==typeof i)if(i.hasOwnProperty("path")){var s=i;if(t._ne=!0,void 0!==t[o]){console.warn(`Skipping ${o} as it confilicts with another key in the object, avoid using keys like ('set') because they are reserved constructor words.`);continue}t[o]=h(s,a)}else"$options"===o&&(a=i),t[o]="$"===o.substr(0,1)?i:e({},i,o,a)}return t=t._ne?Object.assign(t,{set:l(t,r)}):t}({},n,!0)}!function(e,t){"function"==typeof define&&define.amd?define("wrape",[],t):"object"==typeof module&&module.exports?module.exports=t():e.Wrape=t()}("undefined"!=typeof self?self:this,(function(){const e="object"==typeof module&&module.exports?require("node-fetch"):window.fetch,t="object"==typeof module&&module.exports?require("form-data"):window.FormData;return e?t?Wrape.bind(null,e,t):(console.warn("FormData is not installed. If you are using Node please install form-data."),!1):(console.warn("Fetch API is not installed. If you are using Node please install node-fetch."),!1)})); | ||
function Wrape(e,t,n,r,a){r=r||{};a=Object.assign({base:"",headers:{},params:{},values:{},sender:!1,request_middleware:null,response_middleware:null,fetch_parse:!0,fetch_agent:!1,fetch_error_handler:!1},a);const o={form:"multipart/form-data",url:"application/x-www-form-urlencoded",json:"application/json",text:"text/plain"},i=Object.values(o),s=["headers","body","query","path"],u={POST:"body",GET:"query"},p={"multipart/form-data":function(){var e=new t;return e.toString=function(){return this},e},"application/x-www-form-urlencoded":function(){return new URLSearchParams},"application/json":function(){return{append:function(e,t){this.data=this.data||{},this.data[e]=t},toString:function(){return JSON.stringify(this.data)},isEmpty:function(){return!this.data||0==Object.keys(this.data).length}}},"text/plain":function(){return{append:function(e,t){return this.data=this.data||[],this.data.push(t)},toString:function(){return this.data.join("")},isEmpty:function(){return!this.data||0==this.data.length}}}};function l(e){return null==e}function c(e){for(var t of e)return!1;return!0}function f(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d(t,n,r,a){return"function"==typeof r.sender?r.sender(t,n,a,r):e(t,n).then((async function(e){var o={},i=r.fetch_parse,s="function"==typeof a?a:null,u="function"==typeof r.fetch_error_handler?r.fetch_error_handler:null;try{if(i){var p=e.headers.get("Content-Type");o={status_code:e.status,status:e.status,statusText:e.statusText,headers:e.headers},p&&new RegExp("application/json").test(p)?o.json=await e.json():o.text=await e.text();var l=e.ok?"Success.":"Something went wrong.";o.message=o.json&&o.json.message?o.json.message:l}else o=e;if(!e.ok)throw o}catch(e){return u?u(e,{url:t,options:n},o):Promise.reject(e)}return s?s(o):o}))}function h(e,t,n){var r={[t=t||"Wrape"]:function(a){if(!(this instanceof r[t]))throw new Error("You must initalize this object using 'new' command.");Object.assign(this,e);const o=function(e){if(this instanceof o)throw new Error("This object is already initialized.");if(e.$options){if("string"==typeof e.$options||"function"==typeof e.$options||"number"==typeof e.$options||"boolean"==typeof e.$options)throw new Error("Invalid $options object received.");Object.assign(n,e.$options),delete e.$options}n.values={...n.values,...e}}.bind(this);return this.set=o,this.set(a),this}};return r[t]}function m(e,n,r=!1){return e.method="string"==typeof e.method?e.method.toUpperCase():"GET",e.enctype=o[e.enctype]||(i.includes(e.enctype)?e.enctype:i[0]),e.params=e.params||{},async function(o){var h=n||a,m=`${h.base}${e.path}`,y={method:e.method,headers:{...h.headers},agent:h.fetch_agent},w=Object.assign({},h.params,e.params),v=Object.keys(w),g=Array.from(arguments),$=e.request||h.request_middleware,b=e.response||h.response_middleware,j=p[e.enctype](),x=new URLSearchParams;for(var O in g.length>1?o=g.reduce((function(e,t,n){return v[n]?(e[v[n]]=t,e):e}),{}):g[0]instanceof t?(o={},g[0].forEach((function(e,t){o[t]=e}))):o=1!=g.length||1!=v.length||!g[0]||g[0][v[0]]||g[0]instanceof t?o||{}:{[v[0]]:g[0]},w){var q=w[O],S=l(o[O])?q.hasOwnProperty("default")?q.default:h.values[O]||(r?q.example:void 0):o[O],E=q.name||O;if(q.required&&l(S))throw(k=new Error(q.help||`The '${O}' field is required.`)).field=k.param=O,k;if(!l(S)){if("function"==typeof q.formatter||"function"==typeof q.format){var _=q.format||q.formatter;S=_(S)}if(q.validate){var T="function"==typeof q.validate?q.validate(S):new RegExp(q.validate).test(S);if(!T)throw(k=new Error(q.help||`The '${O}' field is invalid.`)).field=k.param=O,k}var k;if(q.in&&Array.isArray(q.in)&&!q.in.includes(S))throw(k=new Error(q.help||`The '${O}' field is invalid.`)).field=k.param=O,k;var P="string"==typeof q.location?q.location.toLowerCase():u[y.method];if(!P||!s.includes(P))throw new Error(`Invalid location for '${O}' field.`);"headers"!=P?"body"!=P?"query"!=P?"path"==P&&(m=m.replace(new RegExp(":"+f(E)),S)):x.append(E,S):j.append(E,S):(y.headers=y.headers||{},y.headers[E]=S)}}var R=x.toString();R&&(m=`${m}?${R}`);var A=j.keys&&c(j.keys())||j.getLengthSync&&0==j.getLengthSync()||j.isEmpty&&j.isEmpty();if(A||(y.body=j.toString()),y.body&&e.enctype!==i[0]&&(y.headers=y.headers||{},y.headers["Content-Type"]=e.enctype),"function"==typeof $){var L=await Promise.resolve($(m,y,x,j));if(!1===L)return!1;L&&L.url&&(m=L.url),L&&L.options&&(y=returns.options)}return d(m,y,h,b)}}return function e(t,n,r,a){for(var o in n){var i=n[o];if(i&&"object"==typeof i)if(i.hasOwnProperty("path")){var s=i;if(t._ne=!0,void 0!==t[o]){console.warn(`Skipping ${o} as it confilicts with another key in the object, avoid using keys like ('set') because they are reserved constructor words.`);continue}t[o]=m(s,a)}else{if("$options"===o){var u=i;a=Object.assign({},a,u)}if("$"===o.substr(0,1))continue;t[o]=e({},i,o,a)}}return t=t._ne?Object.assign(t,{set:h(t,r,a)}):t}({$docs:async function(e,t){t={request:!0,response:!1,responseSleep:0,onlyExampleResponses:!0,showOptional:!0,commentOptional:!0,apiName:"api",headStartLevel:1,output:"./API.md",...t};const r={reference:"",body:""},o=["$options","$help"],i=function(e,n,r=!1){n=n||{};var a="";for(var o in e){var i=e[o],s=i.example||i.default||n[o]||i.type||"<any>";if(i.required||t.showOptional)if(!n[o]||!r)a+=`\t${t.commentOptional&&!i.required?"//":""}${o}: ${s="string"==typeof s?'"'+s+'"':s}, //${[i.required?"required":"optional",i.in&&Array.isArray(i.in)?"Allowed: "+i.in.join(", "):null,i.min?"Min: "+i.min:null,i.mix?"Max: "+i.max:null,i.validate?"Validate: "+("string"==typeof i.validate?i.validate:"<custom>"):null].filter((e=>e)).join(" | ")}\n`}return a},s=function(e,t,n,r){var a=n.params||{},o=Object.assign({},n.values,r.values),s="```javascript\n";return s+=`const ${e} = new ${t}.set({\n`,s+=i(a,o,!0),s+="})\n",s+="```\r\n\r\n"},u=function(e,t,n){var r="```javascript\n";return r+=e+"({\n",r+=i(t=t||{},n.values),r+="})\n",r+="```\r\n\r\n"},p=function(e,t){var n="<details>\n<summary>Request</summary>\r\n\r\n",r=(e.method||"get").toUpperCase(),a="GET"===r?"query":"body",o=e.params||{};(n+=`**${r}** ${e.path}\n`,0!==Object.keys(o))&&(n+="|Parameter|Location|Required|Description|\n|--|--|--|--|\n",n+=Object.keys(o).map((function(e){return[o[e].name||e,o[e].location||a,!!o[e].required,o[e].help].join("|")})).join("\n")+"\n");return n+="</details>\r\n\r\n"},l=async function(e,n){var r="<details>\n<summary>Response</summary>\r\n\r\n",a=e.example_response;if(!a){if(t.onlyExampleResponses)return"";var o=m(e,n,!0);try{console.log("[*] Generating response for "+e.path),await new Promise((function(e,n){setTimeout((function(){e(!0)}),t.responseSleep)})),a=(await o()).json}catch(e){return console.log(e),""}}return r+="```json\r\n",r+="string"==typeof a?a:JSON.stringify(a,null,"\t"),r+="\r\n```\r\n",r+="</details>\r\n\r\n"},c=async function(e,n,a,i,f,d=0){f+=1;var h,m=Math.min(f,6);for(var y in e)if(!o.includes(y)&&e[y]&&"object"==typeof e[y]){var w=`${i}.${y}`,v=`${a}-${y}`,g=n,$=e[y],b=$.path&&"string"==typeof $.path,j=`<h${m} id="${v}">${h=y,h.substr(0,1).toUpperCase()+h.substr(1,h.length)}</h${m}>\r\n\r\n`,x="\t".repeat(d)+`- [${y}](#${v})\r\n`,O=$.$help||$.help,q="string"==typeof O?O+"\r\n":"",S="",E="",_="",T="";$.$options&&($.$options.params&&(S=s(y,w,$.$options,n),w=y),g=Object.assign({},n,$.$options)),b&&(E=u(w,$.params,g),t.request&&(_=p($)),t.response&&(T=await l($,g))),r.reference+=x,r.body+=j+q+S+E+_+T,b||await c($,g,v,w,f,d+1)}};return await c(e,a,t.apiName,t.apiName,t.headStartLevel),n&&n.writeFileSync&&t.output&&n.writeFileSync(t.output,r.reference+"\r\n\r\n"+r.body),r}.bind(null,r)},r,!0,a)}!function(e,t){"function"==typeof define&&define.amd?define("wrape",[],t):"object"==typeof module&&module.exports?module.exports=t():e.Wrape=t()}("undefined"!=typeof self?self:this,(function(){const e="object"==typeof module&&module.exports?require("node-fetch"):window.fetch,t="object"==typeof module&&module.exports?require("form-data"):window.FormData,n="object"==typeof module&&module.exports?require("fs"):null;return e?t?Wrape.bind(null,e,t,n):(console.warn("FormData is not installed. If you are using Node please install form-data."),!1):(console.warn("Fetch API is not installed. If you are using Node please install node-fetch."),!1)})); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Invalid manifest file
QualityPackage has an invalid manifest file and can cause installation problems if you try to use it.
Found 1 instance in 1 package
Misc. License Issues
License(Experimental) A package's licensing information has fine-grained problems.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No tests
QualityPackage does not have any tests. This is a strong signal of a poorly maintained or low quality package.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
17509
0
0
0
1
226
1
2
1
- Removedcrypto-convert@^1.0.0
- Removedform-data@^3.0.0
- Removednode-fetch@^2.6.1
- Removed@types/node@17.0.45(transitive)
- Removedasynckit@0.4.0(transitive)
- Removedbalanced-match@1.0.2(transitive)
- Removedbrace-expansion@2.0.1(transitive)
- Removedcombined-stream@1.0.8(transitive)
- Removedcrypto-convert@1.1.6(transitive)
- Removeddelayed-stream@1.0.0(transitive)
- Removedform-data@3.0.2(transitive)
- Removedfs.realpath@1.0.0(transitive)
- Removedgetarg@0.0.5(transitive)
- Removedglob@8.1.0(transitive)
- Removedinflight@1.0.6(transitive)
- Removedinherits@2.0.4(transitive)
- Removedmime-db@1.52.0(transitive)
- Removedmime-types@2.1.35(transitive)
- Removedminimatch@5.1.6(transitive)
- Removednode-fetch@2.7.0(transitive)
- Removedonce@1.4.0(transitive)
- Removedrests@1.1.1(transitive)
- Removedtr46@0.0.3(transitive)
- Removedtypescript@4.9.5(transitive)
- Removedwebidl-conversions@3.0.1(transitive)
- Removedwhatwg-url@5.0.0(transitive)
- Removedwrappy@1.0.2(transitive)
- Removedyaml@2.6.1(transitive)