Socket
Socket
Sign inDemoInstall

mbta-client

Package Overview
Dependencies
5
Maintainers
2
Versions
35
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.2.9 to 0.3.0

lib/__tests__/data/alertsData.js

2

dist/mbta-client.min.js

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["mbta-client.min"]=t():e["mbta-client.min"]=t()}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=9)}([function(e,t,n){"use strict";var r=n(4),o=n(15),i=Object.prototype.toString;function s(e){return"[object Array]"===i.call(e)}function a(e){return null!==e&&"object"==typeof e}function u(e){return"[object Function]"===i.call(e)}function c(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),s(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}e.exports={isArray:s,isArrayBuffer:function(e){return"[object ArrayBuffer]"===i.call(e)},isBuffer:o,isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:a,isUndefined:function(e){return void 0===e},isDate:function(e){return"[object Date]"===i.call(e)},isFile:function(e){return"[object File]"===i.call(e)},isBlob:function(e){return"[object Blob]"===i.call(e)},isFunction:u,isStream:function(e){return a(e)&&u(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:c,merge:function e(){var t={};function n(n,r){"object"==typeof t[r]&&"object"==typeof n?t[r]=e(t[r],n):t[r]=n}for(var r=0,o=arguments.length;r<o;r++)c(arguments[r],n);return t},extend:function(e,t,n){return c(t,function(t,o){e[o]=n&&"function"==typeof t?r(t,n):t}),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}}},function(e,t,n){"use strict";(function(t){var r=n(0),o=n(18),i={"Content-Type":"application/x-www-form-urlencoded"};function s(e,t){!r.isUndefined(e)&&r.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var a,u={adapter:("undefined"!=typeof XMLHttpRequest?a=n(5):void 0!==t&&(a=n(5)),a),transformRequest:[function(e,t){return o(t,"Content-Type"),r.isFormData(e)||r.isArrayBuffer(e)||r.isBuffer(e)||r.isStream(e)||r.isFile(e)||r.isBlob(e)?e:r.isArrayBufferView(e)?e.buffer:r.isURLSearchParams(e)?(s(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):r.isObject(e)?(s(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};u.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],function(e){u.headers[e]={}}),r.forEach(["post","put","patch"],function(e){u.headers[e]=r.merge(i)}),e.exports=u}).call(this,n(17))},function(e,t,n){const{Attributes:r}=n(3),o=e=>t=>t&&t.data?t.data.map(t=>t.attributes[e]):(console.warn("No response data..."),[]),i=o(r.arrival_time),s=o(r.departure_time);e.exports={selectPage:(e,t)=>(e=>{if(!e)throw new Error("No response, fetch data before accessing this value");if(!e.links)throw new Error('response.links does not exist, "limit" must be in fetch options');return e.links})(t)[e],selectIncluded:(e,t)=>{if(!e)throw new Error("included() requires an MBTA response as an argument");return e.included?e.included.filter(e=>Array.isArray(t)?t.includes(e.type):t===e.type||null==t):(console.warn('response.included does not exist, "include" must be in fetch options'),[])},selectArrivalISOs:i,selectDepartureISOs:s}},function(e,t){e.exports={Attributes:{arrival_time:"arrival_time",departure_time:"departure_time"},Pagination:{first:"first",next:"next",prev:"prev",last:"last"}}},function(e,t,n){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t,n){"use strict";var r=n(0),o=n(19),i=n(21),s=n(22),a=n(23),u=n(6),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(24);e.exports=function(e){return new Promise(function(t,f){var l=e.data,p=e.headers;r.isFormData(l)&&delete p["Content-Type"];var d=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||a(e.url)||(d=new window.XDomainRequest,h="onload",m=!0,d.onprogress=function(){},d.ontimeout=function(){}),e.auth){var y=e.auth.username||"",w=e.auth.password||"";p.Authorization="Basic "+c(y+":"+w)}if(d.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d[h]=function(){if(d&&(4===d.readyState||m)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?s(d.getAllResponseHeaders()):null,r={data:e.responseType&&"text"!==e.responseType?d.response:d.responseText,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:n,config:e,request:d};o(t,f,r),d=null}},d.onerror=function(){f(u("Network Error",e,null,d)),d=null},d.ontimeout=function(){f(u("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var v=n(25),g=(e.withCredentials||a(e.url))&&e.xsrfCookieName?v.read(e.xsrfCookieName):void 0;g&&(p[e.xsrfHeaderName]=g)}if("setRequestHeader"in d&&r.forEach(p,function(e,t){void 0===l&&"content-type"===t.toLowerCase()?delete p[t]:d.setRequestHeader(t,e)}),e.withCredentials&&(d.withCredentials=!0),e.responseType)try{d.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){d&&(d.abort(),f(e),d=null)}),void 0===l&&(l=null),d.send(l)})}},function(e,t,n){"use strict";var r=n(20);e.exports=function(e,t,n,o,i){var s=new Error(e);return r(s,t,n,o,i)}},function(e,t,n){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t,n){"use strict";function r(e){this.message=e}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,e.exports=r},function(e,t,n){const r=n(10);e.exports=r},function(e,t,n){const{buildUrl:r,arrivalsWithConversion:o,departuresWithConversion:i}=n(11),{selectPage:s,selectIncluded:a}=n(2),u=n(12),{Pagination:c}=n(3);e.exports=class{constructor(e,t=u){this.apiKey=e,this.fetch=t}async fetchPredictions(e){return this.fetch(r("/predictions",e,this.apiKey))}async fetchStops(e){return this.fetch(r("/stops",e,this.apiKey))}async fetchTrips(e){return this.fetch(r("/trips",e,this.apiKey))}async fetchRoutes(e){return this.fetch(r("/routes",e,this.apiKey))}async fetchVehicles(e){return this.fetch(r("/vehicles",e,this.apiKey))}async fetchShapes(e){return this.fetch(r("/shapes",e,this.apiKey))}async fetchServices(e){return this.fetch(r("/services",e,this.apiKey))}async fetchSchedules(e){return this.fetch(r("/schedules",e,this.apiKey))}async fetchFacilities(e){return this.fetch(r("/facilities",e,this.apiKey))}selectArrivals(e,{convertTo:t,now:n}={}){return o({response:e,convertTo:t,now:n})}selectDepartures(e,{convertTo:t,now:n}={}){return i({response:e,convertTo:t,now:n})}selectIncluded(e,t){return a(e,t)}async fetchFirstPage(e){return this.fetch(s(c.first,e))}async fetchNextPage(e){return this.fetch(s(c.next,e))}async fetchPrevPage(e){return this.fetch(s(c.prev,e))}async fetchLastPage(e){return this.fetch(s(c.last,e))}}},function(e,t,n){const{selectArrivalISOs:r,selectDepartureISOs:o}=n(2),i=e=>null!=e&&""!==e,s=e=>Array.isArray(e)&&!e.filter(Boolean).length,a="https://api-v3.mbta.com",u=e=>[].concat(e).filter(Boolean).join(",").replace(/,\s/g,","),c=(e,t)=>{if(!i(t))return e;const n={"hours|hrs":36e5,"minutes|mins":6e4,"seconds|secs":1e3,"ms|milliseconds":1},r=Object.keys(n).find(e=>new RegExp(t,"i").test(e));if(!i(r))throw new Error(`Invalid 'convertTo' value: ${t}`);return e/n[r]},f=e=>t=>{const{response:n,max:r,convertTo:o,now:i=Date.now()}=t;return e(n).slice(0,r).map(e=>{if(null==o||null==e)return e;const t=new Date(e).valueOf()-i,n=Math.floor(c(t,o));return n>=0?n:0})},l=f(r),p=f(o),d=e=>new Date(e).toISOString(),h=e=>{const t=["tram|light rail|streetcar|trolley","subway|metro|train","rail|commuter|commuter rail","bus|autobus","ferry|boat","cable car","gondola|suspended cable car","funicular"],n=Number(e);if(!i(e)||n>=t.length)return console.warn(`Invalid type: ${e}`),null;if(n==n)return n;const r=t.findIndex(t=>new RegExp(e,"i").test(t));return r>-1?r:null},m=(e,t)=>{if(!i(t))return console.warn("API key is missing. Keys available at https://api-v3.mbta.com"),`${e}`;const n=e.includes("?")?"&":"?";return`${e}${n}api_key=${t}`};e.exports={exists:i,buildUrl:function(e,t,n){const r=a+e;if(!e)throw new Error("Please provide an endpoint. See https://api-v3.mbta.com/docs/swagger/index.html");if(!t||!Object.keys(t).length)return m(r,n);const{limit:o,offset:c,latitude:f,longitude:l,descending:p,min_time:y,max_time:w,radius:v,route:g,stop:x,sort:b,trip:T}=t,E=t=>t===e;!E("/predictions")&&!E("/schedules")||i(x)||i(T)||i(g)||console.warn('Please include "stop", "trip", or "route"'),E("/shapes")&&!i(g)&&console.warn('Shape requires a "route" param'),i(c)&&!i(o)&&console.warn('"offset" will have no effect without "limit"'),(i(f)&&!i(l)||!i(f)&&i(l))&&console.warn("Latitude and longitude must both be present"),!i(v)||i(f)&&i(l)||console.warn("Radius requires latitude and longitude"),i(p)&&!i(b)&&console.warn('"descending" has no effect without "sort"'),[y,w].forEach(e=>{i(e)&&!/^\d{2}:\d{2}/.test(e)&&console.warn("min_time and max_time format should be HH:MM")});const S=Object.entries(t).map(([e,n])=>{let r;switch(e){case"sort":return t.descending?`sort=-${n}`:`sort=${n}`;case"limit":case"offset":return`page[${e}]=${n}`;case"date":r=[].concat(n).map(d);break;case"route_type":case"type":r=[].concat(n).map(h);break;default:r=n}return!i(r)||s(r)?null:`${e}=${u(r)}`}).filter(e=>!!e&&!/descending/.test(e)).join("&");return m(`${r}?${S}`,n)},convertMs:c,convertTimes:f,isEmptyArray:s,normalizeType:h,normalizeDate:d,arrivalsWithConversion:l,departuresWithConversion:p}},function(e,t,n){const r=n(13);e.exports=(async(e,t=r)=>{try{const n=await t.get(e);if(!n||!n.data)throw new Error("No data from MBTA");return n.data}catch(e){const{response:t}=e;if(t&&t.data&&t.data.errors){const[e]=t.data.errors;throw console.error(`Error ${e.status||e.code} fetching MBTA data: ${e.detail||"(no details)"}`),e}throw console.error("Error fetching MBTA data:",e.message),e}})},function(e,t,n){e.exports=n(14)},function(e,t,n){"use strict";var r=n(0),o=n(4),i=n(16),s=n(1);function a(e){var t=new i(e),n=o(i.prototype.request,t);return r.extend(n,i.prototype,t),r.extend(n,t),n}var u=a(s);u.Axios=i,u.create=function(e){return a(r.merge(s,e))},u.Cancel=n(8),u.CancelToken=n(31),u.isCancel=n(7),u.all=function(e){return Promise.all(e)},u.spread=n(32),e.exports=u,e.exports.default=u},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["mbta-client.min"]=t():e["mbta-client.min"]=t()}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=9)}([function(e,t,n){"use strict";var r=n(4),o=n(15),i=Object.prototype.toString;function s(e){return"[object Array]"===i.call(e)}function a(e){return null!==e&&"object"==typeof e}function u(e){return"[object Function]"===i.call(e)}function c(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),s(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}e.exports={isArray:s,isArrayBuffer:function(e){return"[object ArrayBuffer]"===i.call(e)},isBuffer:o,isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:a,isUndefined:function(e){return void 0===e},isDate:function(e){return"[object Date]"===i.call(e)},isFile:function(e){return"[object File]"===i.call(e)},isBlob:function(e){return"[object Blob]"===i.call(e)},isFunction:u,isStream:function(e){return a(e)&&u(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:c,merge:function e(){var t={};function n(n,r){"object"==typeof t[r]&&"object"==typeof n?t[r]=e(t[r],n):t[r]=n}for(var r=0,o=arguments.length;r<o;r++)c(arguments[r],n);return t},extend:function(e,t,n){return c(t,function(t,o){e[o]=n&&"function"==typeof t?r(t,n):t}),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}}},function(e,t,n){"use strict";(function(t){var r=n(0),o=n(18),i={"Content-Type":"application/x-www-form-urlencoded"};function s(e,t){!r.isUndefined(e)&&r.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var a,u={adapter:("undefined"!=typeof XMLHttpRequest?a=n(5):void 0!==t&&(a=n(5)),a),transformRequest:[function(e,t){return o(t,"Content-Type"),r.isFormData(e)||r.isArrayBuffer(e)||r.isBuffer(e)||r.isStream(e)||r.isFile(e)||r.isBlob(e)?e:r.isArrayBufferView(e)?e.buffer:r.isURLSearchParams(e)?(s(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):r.isObject(e)?(s(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};u.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],function(e){u.headers[e]={}}),r.forEach(["post","put","patch"],function(e){u.headers[e]=r.merge(i)}),e.exports=u}).call(this,n(17))},function(e,t,n){const{Attributes:r}=n(3),o=e=>t=>t&&t.data?t.data.map(t=>t.attributes[e]):(console.warn("No response data..."),[]),i=o(r.arrival_time),s=o(r.departure_time);e.exports={selectPage:(e,t)=>(e=>{if(!e)throw new Error("No response, fetch data before accessing this value");if(!e.links)throw new Error('response.links does not exist, "limit" must be in fetch options');return e.links})(t)[e],selectIncluded:(e,t)=>{if(!e)throw new Error("included() requires an MBTA response as an argument");return e.included?e.included.filter(e=>Array.isArray(t)?t.includes(e.type):t===e.type||null==t):(console.warn('response.included does not exist, "include" must be in fetch options'),[])},selectArrivalISOs:i,selectDepartureISOs:s}},function(e,t){e.exports={Attributes:{arrival_time:"arrival_time",departure_time:"departure_time"},Pagination:{first:"first",next:"next",prev:"prev",last:"last"}}},function(e,t,n){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t,n){"use strict";var r=n(0),o=n(19),i=n(21),s=n(22),a=n(23),u=n(6),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(24);e.exports=function(e){return new Promise(function(t,f){var l=e.data,p=e.headers;r.isFormData(l)&&delete p["Content-Type"];var d=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||a(e.url)||(d=new window.XDomainRequest,h="onload",m=!0,d.onprogress=function(){},d.ontimeout=function(){}),e.auth){var y=e.auth.username||"",w=e.auth.password||"";p.Authorization="Basic "+c(y+":"+w)}if(d.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d[h]=function(){if(d&&(4===d.readyState||m)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?s(d.getAllResponseHeaders()):null,r={data:e.responseType&&"text"!==e.responseType?d.response:d.responseText,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:n,config:e,request:d};o(t,f,r),d=null}},d.onerror=function(){f(u("Network Error",e,null,d)),d=null},d.ontimeout=function(){f(u("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var v=n(25),g=(e.withCredentials||a(e.url))&&e.xsrfCookieName?v.read(e.xsrfCookieName):void 0;g&&(p[e.xsrfHeaderName]=g)}if("setRequestHeader"in d&&r.forEach(p,function(e,t){void 0===l&&"content-type"===t.toLowerCase()?delete p[t]:d.setRequestHeader(t,e)}),e.withCredentials&&(d.withCredentials=!0),e.responseType)try{d.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){d&&(d.abort(),f(e),d=null)}),void 0===l&&(l=null),d.send(l)})}},function(e,t,n){"use strict";var r=n(20);e.exports=function(e,t,n,o,i){var s=new Error(e);return r(s,t,n,o,i)}},function(e,t,n){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t,n){"use strict";function r(e){this.message=e}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,e.exports=r},function(e,t,n){const r=n(10);e.exports=r},function(e,t,n){const{buildUrl:r,arrivalsWithConversion:o,departuresWithConversion:i}=n(11),{selectPage:s,selectIncluded:a}=n(2),u=n(12),{Pagination:c}=n(3);e.exports=class{constructor(e,t=u){this.apiKey=e,this.fetch=t}async fetchPredictions(e){return this.fetch(r("/predictions",e,this.apiKey))}async fetchStops(e){return this.fetch(r("/stops",e,this.apiKey))}async fetchTrips(e){return this.fetch(r("/trips",e,this.apiKey))}async fetchRoutes(e){return this.fetch(r("/routes",e,this.apiKey))}async fetchVehicles(e){return this.fetch(r("/vehicles",e,this.apiKey))}async fetchShapes(e){return this.fetch(r("/shapes",e,this.apiKey))}async fetchServices(e){return this.fetch(r("/services",e,this.apiKey))}async fetchSchedules(e){return this.fetch(r("/schedules",e,this.apiKey))}async fetchFacilities(e){return this.fetch(r("/facilities",e,this.apiKey))}async fetchAlerts(e){return this.fetch(r("/alerts",e,this.apiKey))}selectArrivals(e,{convertTo:t,now:n}={}){return o({response:e,convertTo:t,now:n})}selectDepartures(e,{convertTo:t,now:n}={}){return i({response:e,convertTo:t,now:n})}selectIncluded(e,t){return a(e,t)}async fetchFirstPage(e){return this.fetch(s(c.first,e))}async fetchNextPage(e){return this.fetch(s(c.next,e))}async fetchPrevPage(e){return this.fetch(s(c.prev,e))}async fetchLastPage(e){return this.fetch(s(c.last,e))}}},function(e,t,n){const{selectArrivalISOs:r,selectDepartureISOs:o}=n(2),i=e=>null!=e&&""!==e,s=e=>Array.isArray(e)&&!e.filter(Boolean).length,a="https://api-v3.mbta.com",u=e=>[].concat(e).filter(Boolean).join(",").replace(/,\s/g,","),c=(e,t)=>{if(!i(t))return e;const n={"hours|hrs":36e5,"minutes|mins":6e4,"seconds|secs":1e3,"ms|milliseconds":1},r=Object.keys(n).find(e=>new RegExp(t,"i").test(e));if(!i(r))throw new Error(`Invalid 'convertTo' value: ${t}`);return e/n[r]},f=e=>t=>{const{response:n,max:r,convertTo:o,now:i=Date.now()}=t;return e(n).slice(0,r).map(e=>{if(null==o||null==e)return e;const t=new Date(e).valueOf()-i,n=Math.floor(c(t,o));return n>=0?n:0})},l=f(r),p=f(o),d=e=>new Date(e).toISOString(),h=e=>{const t=["tram|light rail|streetcar|trolley","subway|metro|train","rail|commuter|commuter rail","bus|autobus","ferry|boat","cable car","gondola|suspended cable car","funicular"],n=Number(e);if(!i(e)||n>=t.length)return console.warn(`Invalid type: ${e}`),null;if(n==n)return n;const r=t.findIndex(t=>new RegExp(e,"i").test(t));return r>-1?r:null},m=(e,t)=>{if(!i(t))return console.warn("API key is missing. Keys available at https://api-v3.mbta.com"),`${e}`;const n=e.includes("?")?"&":"?";return`${e}${n}api_key=${t}`};e.exports={exists:i,buildUrl:function(e,t,n){const r=a+e;if(!e)throw new Error("Please provide an endpoint. See https://api-v3.mbta.com/docs/swagger/index.html");if(!t||!Object.keys(t).length)return m(r,n);const{limit:o,offset:c,latitude:f,longitude:l,descending:p,min_time:y,max_time:w,radius:v,route:g,stop:x,sort:b,trip:T}=t,E=t=>t===e;!E("/predictions")&&!E("/schedules")||i(x)||i(T)||i(g)||console.warn('Please include "stop", "trip", or "route"'),E("/shapes")&&!i(g)&&console.warn('Shape requires a "route" param'),i(c)&&!i(o)&&console.warn('"offset" will have no effect without "limit"'),(i(f)&&!i(l)||!i(f)&&i(l))&&console.warn("Latitude and longitude must both be present"),!i(v)||i(f)&&i(l)||console.warn("Radius requires latitude and longitude"),i(p)&&!i(b)&&console.warn('"descending" has no effect without "sort"'),[y,w].forEach(e=>{i(e)&&!/^\d{2}:\d{2}/.test(e)&&console.warn("min_time and max_time format should be HH:MM")});const S=Object.entries(t).map(([e,n])=>{let r;switch(e){case"sort":return t.descending?`sort=-${n}`:`sort=${n}`;case"limit":case"offset":return`page[${e}]=${n}`;case"date":r=[].concat(n).map(d);break;case"route_type":case"type":r=[].concat(n).map(h);break;default:r=n}return!i(r)||s(r)?null:`${e}=${u(r)}`}).filter(e=>!!e&&!/descending/.test(e)).join("&");return m(`${r}?${S}`,n)},convertMs:c,convertTimes:f,isEmptyArray:s,normalizeType:h,normalizeDate:d,arrivalsWithConversion:l,departuresWithConversion:p}},function(e,t,n){const r=n(13);e.exports=(async(e,t=r)=>{try{const n=await t.get(e);if(!n||!n.data)throw new Error("No data from MBTA");return n.data}catch(e){const{response:t}=e;if(t&&t.data&&t.data.errors){const[e]=t.data.errors;throw console.error(`Error ${e.status||e.code} fetching MBTA data: ${e.detail||"(no details)"}`),e}throw console.error("Error fetching MBTA data:",e.message),e}})},function(e,t,n){e.exports=n(14)},function(e,t,n){"use strict";var r=n(0),o=n(4),i=n(16),s=n(1);function a(e){var t=new i(e),n=o(i.prototype.request,t);return r.extend(n,i.prototype,t),r.extend(n,t),n}var u=a(s);u.Axios=i,u.create=function(e){return a(r.merge(s,e))},u.Cancel=n(8),u.CancelToken=n(31),u.isCancel=n(7),u.all=function(e){return Promise.all(e)},u.spread=n(32),e.exports=u,e.exports.default=u},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}
/*!

@@ -3,0 +3,0 @@ * Determine if an object is a Buffer

@@ -5,2 +5,3 @@ const MBTA = require('../mbta');

const routesData = require('./data/routesData');
const alertsData = require('./data/alertsData');
const shapesData = require('./data/shapesData');

@@ -13,3 +14,3 @@ const servicesData = require('./data/servicesData');

const API_KEY = 'fakeApiKey';
const API_KEY = 'fake';

@@ -21,3 +22,3 @@ // // Uncomment to test live data

// const mbta = new MBTA();
// const pred = await mbta.fetchStops({ id: 'Back Bay' });
// const pred = await mbta.fetchAlerts({ limit: 3, banner: 'kiki' });
// console.log(util.inspect(pred, { showHidden: false, depth: null }));

@@ -28,12 +29,13 @@ // });

it.each([
['fetchStops', stopsData],
['fetchTrips', tripsData],
['fetchRoutes', routesData],
['fetchShapes', shapesData],
['fetchVehicles', vehiclesData],
['fetchServices', servicesData],
['fetchSchedules', schedulesData],
['fetchFacilities', facilitiesData],
['fetchPredictions', predictionData],
])('%s', async (methodName, data) => {
['fetchStops', stopsData, '/stops'],
['fetchTrips', tripsData, '/trips'],
['fetchAlerts', alertsData, '/alerts'],
['fetchRoutes', routesData, '/routes'],
['fetchShapes', shapesData, '/shapes'],
['fetchVehicles', vehiclesData, '/vehicles'],
['fetchServices', servicesData, '/services'],
['fetchSchedules', schedulesData, '/schedules'],
['fetchFacilities', facilitiesData, '/facilities'],
['fetchPredictions', predictionData, '/predictions'],
])('%s', async (methodName, data, endpoint) => {
const fetchService = jest.fn().mockResolvedValue(data);

@@ -43,2 +45,3 @@ const mbta = new MBTA(API_KEY, fetchService);

const fetched = await mbta[methodName]({});
expect(fetchService).toBeCalledWith(`https://api-v3.mbta.com${endpoint}?api_key=fake`);

@@ -45,0 +48,0 @@ expect(fetched).toEqual(data);

@@ -59,2 +59,6 @@ /* eslint-disable camelcase */

async fetchAlerts(queryParams) {
return this.fetch(buildUrl('/alerts', queryParams, this.apiKey));
}
// async fetchAllRoutesBasic({ type } = {}) {

@@ -61,0 +65,0 @@ // const routes = await this.fetchRoutes({ type });

{
"name": "mbta-client",
"version": "0.2.9",
"version": "0.3.0",
"description": "MBTA API v3 Node.js Client Library",

@@ -37,3 +37,4 @@ "main": "index.js",

"hooks": {
"pre-push": "npm t && npm run build"
"pre-commit": "npm run build",
"pre-push": "npm t -- --silent"
}

@@ -40,0 +41,0 @@ },

@@ -44,3 +44,3 @@ # MTBA API Client

// endpoint's sort options. `descending: true` will reverse sort order.
const sorted = mbta.fetchPredictions({
const sorted = await mbta.fetchPredictions({
stop: 42,

@@ -50,2 +50,10 @@ sort: 'arrival_time',

});
// Alerts have a number of extra filters. See MBTA docs for best practices.
const alerts = await mbta.fetchAlerts({
sort: 'cause',
activity: 'BOARD',
datetime: 'NOW',
severity: [2, 3],
});
```

@@ -89,3 +97,3 @@

These map to the endpoints listed at https://api-v3.mbta.com/docs/swagger/index.html. They return a promise that resolves to an MBTA response object. `options` for each function maps to the filters listed on that page. `options` that accept multiple values can be provided as an array or comma separated string.
These map to the endpoints listed in [the MBTA docs](https://api-v3.mbta.com/docs/swagger/index.html). They return a promise that resolves to an MBTA response object. `options` for each function maps to the filters listed on that page. `options` that accept multiple values can be provided as an array or comma separated string.

@@ -102,5 +110,8 @@ ```js

mbta.fetchPredictions(options);
// mbta.fetchAlerts(options) COMING SOON
mbta.fetchAlerts(options); // See note on alerts below
```
The MBTA docs say: "Displaying alerts is one of the trickiest features to get correct." See their [best practices](https://www.mbta.com/developers/v3-api/best-practices) and the [alerts API docs](https://api-v3.mbta.com/docs/swagger/index.html#/Alert/ApiWeb_AlertController_index) for more information.
### Helper functions

@@ -115,3 +126,3 @@

_Note: `arrival_time` could be null if it's the first stop on a route. If `departure_time` is not null, the MBTA recommends using that instead. Departure could be null if it's the final stop on a route. See https://www.mbta.com/developers/v3-api/best-practices for more info._
_Note: `arrival_time` could be null if it's the first stop on a route. If `departure_time` is not null, the MBTA recommends using that instead. Departure could be null if it's the final stop on a route. See [best practices](https://www.mbta.com/developers/v3-api/best-practices) for more info._

@@ -121,7 +132,7 @@ ```ts

// See the MBTA API docs for `include_value` options for each endpoint
// https://api-v3.mbta.com/docs/swagger/index.html
type TypeOptions = { type?: include_value | include_value[] };
```
_See the [MBTA API docs](https://api-v3.mbta.com/docs/swagger/index.html) for `include_value` options for each endpoint_
### Pagination helpers

@@ -128,0 +139,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc