index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var isPlainObject = require('is-plain-object');
  4. var universalUserAgent = require('universal-user-agent');
  5. function lowercaseKeys(object) {
  6. if (!object) {
  7. return {};
  8. }
  9. return Object.keys(object).reduce((newObj, key) => {
  10. newObj[key.toLowerCase()] = object[key];
  11. return newObj;
  12. }, {});
  13. }
  14. function mergeDeep(defaults, options) {
  15. const result = Object.assign({}, defaults);
  16. Object.keys(options).forEach(key => {
  17. if (isPlainObject.isPlainObject(options[key])) {
  18. if (!(key in defaults)) Object.assign(result, {
  19. [key]: options[key]
  20. });else result[key] = mergeDeep(defaults[key], options[key]);
  21. } else {
  22. Object.assign(result, {
  23. [key]: options[key]
  24. });
  25. }
  26. });
  27. return result;
  28. }
  29. function removeUndefinedProperties(obj) {
  30. for (const key in obj) {
  31. if (obj[key] === undefined) {
  32. delete obj[key];
  33. }
  34. }
  35. return obj;
  36. }
  37. function merge(defaults, route, options) {
  38. if (typeof route === "string") {
  39. let [method, url] = route.split(" ");
  40. options = Object.assign(url ? {
  41. method,
  42. url
  43. } : {
  44. url: method
  45. }, options);
  46. } else {
  47. options = Object.assign({}, route);
  48. } // lowercase header names before merging with defaults to avoid duplicates
  49. options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging
  50. removeUndefinedProperties(options);
  51. removeUndefinedProperties(options.headers);
  52. const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten
  53. if (defaults && defaults.mediaType.previews.length) {
  54. mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews);
  55. }
  56. mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, ""));
  57. return mergedOptions;
  58. }
  59. function addQueryParameters(url, parameters) {
  60. const separator = /\?/.test(url) ? "&" : "?";
  61. const names = Object.keys(parameters);
  62. if (names.length === 0) {
  63. return url;
  64. }
  65. return url + separator + names.map(name => {
  66. if (name === "q") {
  67. return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
  68. }
  69. return `${name}=${encodeURIComponent(parameters[name])}`;
  70. }).join("&");
  71. }
  72. const urlVariableRegex = /\{[^}]+\}/g;
  73. function removeNonChars(variableName) {
  74. return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
  75. }
  76. function extractUrlVariableNames(url) {
  77. const matches = url.match(urlVariableRegex);
  78. if (!matches) {
  79. return [];
  80. }
  81. return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
  82. }
  83. function omit(object, keysToOmit) {
  84. return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => {
  85. obj[key] = object[key];
  86. return obj;
  87. }, {});
  88. }
  89. // Based on https://github.com/bramstein/url-template, licensed under BSD
  90. // TODO: create separate package.
  91. //
  92. // Copyright (c) 2012-2014, Bram Stein
  93. // All rights reserved.
  94. // Redistribution and use in source and binary forms, with or without
  95. // modification, are permitted provided that the following conditions
  96. // are met:
  97. // 1. Redistributions of source code must retain the above copyright
  98. // notice, this list of conditions and the following disclaimer.
  99. // 2. Redistributions in binary form must reproduce the above copyright
  100. // notice, this list of conditions and the following disclaimer in the
  101. // documentation and/or other materials provided with the distribution.
  102. // 3. The name of the author may not be used to endorse or promote products
  103. // derived from this software without specific prior written permission.
  104. // THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
  105. // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  106. // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  107. // EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  108. // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  109. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  110. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  111. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  112. // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  113. // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  114. /* istanbul ignore file */
  115. function encodeReserved(str) {
  116. return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
  117. if (!/%[0-9A-Fa-f]/.test(part)) {
  118. part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
  119. }
  120. return part;
  121. }).join("");
  122. }
  123. function encodeUnreserved(str) {
  124. return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
  125. return "%" + c.charCodeAt(0).toString(16).toUpperCase();
  126. });
  127. }
  128. function encodeValue(operator, value, key) {
  129. value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
  130. if (key) {
  131. return encodeUnreserved(key) + "=" + value;
  132. } else {
  133. return value;
  134. }
  135. }
  136. function isDefined(value) {
  137. return value !== undefined && value !== null;
  138. }
  139. function isKeyOperator(operator) {
  140. return operator === ";" || operator === "&" || operator === "?";
  141. }
  142. function getValues(context, operator, key, modifier) {
  143. var value = context[key],
  144. result = [];
  145. if (isDefined(value) && value !== "") {
  146. if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
  147. value = value.toString();
  148. if (modifier && modifier !== "*") {
  149. value = value.substring(0, parseInt(modifier, 10));
  150. }
  151. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
  152. } else {
  153. if (modifier === "*") {
  154. if (Array.isArray(value)) {
  155. value.filter(isDefined).forEach(function (value) {
  156. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : ""));
  157. });
  158. } else {
  159. Object.keys(value).forEach(function (k) {
  160. if (isDefined(value[k])) {
  161. result.push(encodeValue(operator, value[k], k));
  162. }
  163. });
  164. }
  165. } else {
  166. const tmp = [];
  167. if (Array.isArray(value)) {
  168. value.filter(isDefined).forEach(function (value) {
  169. tmp.push(encodeValue(operator, value));
  170. });
  171. } else {
  172. Object.keys(value).forEach(function (k) {
  173. if (isDefined(value[k])) {
  174. tmp.push(encodeUnreserved(k));
  175. tmp.push(encodeValue(operator, value[k].toString()));
  176. }
  177. });
  178. }
  179. if (isKeyOperator(operator)) {
  180. result.push(encodeUnreserved(key) + "=" + tmp.join(","));
  181. } else if (tmp.length !== 0) {
  182. result.push(tmp.join(","));
  183. }
  184. }
  185. }
  186. } else {
  187. if (operator === ";") {
  188. if (isDefined(value)) {
  189. result.push(encodeUnreserved(key));
  190. }
  191. } else if (value === "" && (operator === "&" || operator === "?")) {
  192. result.push(encodeUnreserved(key) + "=");
  193. } else if (value === "") {
  194. result.push("");
  195. }
  196. }
  197. return result;
  198. }
  199. function parseUrl(template) {
  200. return {
  201. expand: expand.bind(null, template)
  202. };
  203. }
  204. function expand(template, context) {
  205. var operators = ["+", "#", ".", "/", ";", "?", "&"];
  206. return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
  207. if (expression) {
  208. let operator = "";
  209. const values = [];
  210. if (operators.indexOf(expression.charAt(0)) !== -1) {
  211. operator = expression.charAt(0);
  212. expression = expression.substr(1);
  213. }
  214. expression.split(/,/g).forEach(function (variable) {
  215. var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
  216. values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
  217. });
  218. if (operator && operator !== "+") {
  219. var separator = ",";
  220. if (operator === "?") {
  221. separator = "&";
  222. } else if (operator !== "#") {
  223. separator = operator;
  224. }
  225. return (values.length !== 0 ? operator : "") + values.join(separator);
  226. } else {
  227. return values.join(",");
  228. }
  229. } else {
  230. return encodeReserved(literal);
  231. }
  232. });
  233. }
  234. function parse(options) {
  235. // https://fetch.spec.whatwg.org/#methods
  236. let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible
  237. let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
  238. let headers = Object.assign({}, options.headers);
  239. let body;
  240. let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later
  241. const urlVariableNames = extractUrlVariableNames(url);
  242. url = parseUrl(url).expand(parameters);
  243. if (!/^http/.test(url)) {
  244. url = options.baseUrl + url;
  245. }
  246. const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl");
  247. const remainingParameters = omit(parameters, omittedParameters);
  248. const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
  249. if (!isBinaryRequest) {
  250. if (options.mediaType.format) {
  251. // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw
  252. headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(",");
  253. }
  254. if (options.mediaType.previews.length) {
  255. const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
  256. headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => {
  257. const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
  258. return `application/vnd.github.${preview}-preview${format}`;
  259. }).join(",");
  260. }
  261. } // for GET/HEAD requests, set URL query parameters from remaining parameters
  262. // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters
  263. if (["GET", "HEAD"].includes(method)) {
  264. url = addQueryParameters(url, remainingParameters);
  265. } else {
  266. if ("data" in remainingParameters) {
  267. body = remainingParameters.data;
  268. } else {
  269. if (Object.keys(remainingParameters).length) {
  270. body = remainingParameters;
  271. } else {
  272. headers["content-length"] = 0;
  273. }
  274. }
  275. } // default content-type for JSON if body is set
  276. if (!headers["content-type"] && typeof body !== "undefined") {
  277. headers["content-type"] = "application/json; charset=utf-8";
  278. } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body.
  279. // fetch does not allow to set `content-length` header, but we can set body to an empty string
  280. if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
  281. body = "";
  282. } // Only return body/request keys if present
  283. return Object.assign({
  284. method,
  285. url,
  286. headers
  287. }, typeof body !== "undefined" ? {
  288. body
  289. } : null, options.request ? {
  290. request: options.request
  291. } : null);
  292. }
  293. function endpointWithDefaults(defaults, route, options) {
  294. return parse(merge(defaults, route, options));
  295. }
  296. function withDefaults(oldDefaults, newDefaults) {
  297. const DEFAULTS = merge(oldDefaults, newDefaults);
  298. const endpoint = endpointWithDefaults.bind(null, DEFAULTS);
  299. return Object.assign(endpoint, {
  300. DEFAULTS,
  301. defaults: withDefaults.bind(null, DEFAULTS),
  302. merge: merge.bind(null, DEFAULTS),
  303. parse
  304. });
  305. }
  306. const VERSION = "6.0.12";
  307. const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url.
  308. // So we use RequestParameters and add method as additional required property.
  309. const DEFAULTS = {
  310. method: "GET",
  311. baseUrl: "https://api.github.com",
  312. headers: {
  313. accept: "application/vnd.github.v3+json",
  314. "user-agent": userAgent
  315. },
  316. mediaType: {
  317. format: "",
  318. previews: []
  319. }
  320. };
  321. const endpoint = withDefaults(null, DEFAULTS);
  322. exports.endpoint = endpoint;
  323. //# sourceMappingURL=index.js.map