UNPKG

jsforce2

Version:

Salesforce API Library for JavaScript

1 lines 268 kB
!function(t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsforce=t()}(function(){return function n(i,o,s){function a(e,t){if(!o[e]){if(!i[e]){var r="function"==typeof require&&require;if(!t&&r)return r(e,!0);if(u)return u(e,!0);throw(r=new Error("Cannot find module '"+e+"'")).code="MODULE_NOT_FOUND",r}r=o[e]={exports:{}},i[e][0].call(r.exports,function(t){return a(i[e][1][t]||t)},r,r.exports,n,i,o,s)}return o[e].exports}for(var u="function"==typeof require&&require,t=0;t<s.length;t++)a(s[t]);return a}({1:[function(t,e,r){"use strict";var n=t("../core");n.browser=t("./client"),e.exports=n},{"../core":10,"./client":5}],2:[function(t,e,r){"use strict";e.exports="1.10.0"},{}],3:[function(t,e,r){"use strict";e.exports={inherits:t("inherits"),util:t("util"),events:t("events"),"lodash/core":t("lodash/core"),"readable-stream":t("readable-stream"),multistream:t("multistream"),"./VERSION":t("./VERSION"),"./cache":t("./cache"),"./connection":t("./connection"),"./core":t("./core"),"./csv":t("./csv"),"./date":t("./date"),"./http-api":t("./http-api"),"./logger":t("./logger"),"./oauth2":t("./oauth2"),"./process":t("./process"),"./promise":t("./promise"),"./query":t("./query"),"./quick-action":t("./quick-action"),"./record-stream":t("./record-stream"),"./record":t("./record"),"./soap":t("./soap"),"./sobject":t("./sobject"),"./soql-builder":t("./soql-builder"),"./transport":t("./transport")}},{"./VERSION":2,"./cache":8,"./connection":9,"./core":10,"./csv":11,"./date":12,"./http-api":13,"./logger":14,"./oauth2":15,"./process":16,"./promise":17,"./query":18,"./quick-action":19,"./record":21,"./record-stream":20,"./soap":23,"./sobject":24,"./soql-builder":25,"./transport":26,events:37,inherits:39,"lodash/core":43,multistream:44,"readable-stream":62,util:72}],4:[function(t,e,r){"use strict";var c=t("readable-stream").Duplex,l=t("lodash/core");e.exports={supported:"object"==typeof Sfdc&&void 0!==Sfdc.canvas,createRequest:function(u){return function(n,i){var o,s=new c;s._read=function(t){o&&s.push(o.body)};var a=[],t=!1;function e(t){var e={client:u.client,method:n.method,data:t};if(n.headers)for(var r in e.headers={},n.headers)"content-type"===r.toLowerCase()?e.contentType=n.headers[r]:e.headers[r]=n.headers[r];e.success=function(t){var r,e=(n=t.responseHeaders,r={},n.split(/\n/).forEach(function(t){var e=t.split(/\s*:\s*/),t=e[0].toLowerCase(),e=e[1];r[t]=e}),r),n=t.payload;l.isString(n)||(n=JSON.stringify(n)),o={statusCode:t.status,headers:e,body:n},i&&i(null,o,o.body),s.end()},e.failure=function(t){i&&i(t)},Sfdc.canvas.client.ajax(n.url,e)}return s._write=function(t,e,r){a.push(t.toString(e)),r()},s.on("finish",function(){t||(e(a.join("")),t=!0)}),!n.body&&""!==n.body&&/^(put|post|patch)$/i.test(n.method)||(e(n.body),t=!0),s}}}},{"lodash/core":43,"readable-stream":62}],5:[function(t,e,r){"use strict";var n=t("events"),i=t("inherits"),o=t("querystring"),s=t("lodash/core"),a=t("../connection"),d=t("../oauth2");function u(){var t=function(){var t;if(window.location.hash){if((t=o.parse(window.location.hash.substring(1))).access_token)return{success:!0,body:t}}else if(window.location.search&&(t=o.parse(window.location.search.substring(1))).error)return{success:!1,body:t}}(),e=localStorage.getItem("jsforce_state");if(t&&e&&t.body.state===e){localStorage.removeItem("jsforce_state");var r=e.split("."),e=r[0],r=r[1],e=new c(e);return t.success?(e._storeTokens(t.body),location.hash=""):e._storeError(t.body),"popup"===r&&window.close(),1}}function c(t){this._prefix=t||"jsforce"+l++,this.connection=null}var l=0;i(c,n.EventEmitter),c.prototype.init=function(t){var e;u()||(this.config=t,this.connection=new a(t),(t=this._getTokens())&&(this.connection.initialize(t),e=this,setTimeout(function(){e.emit("connect",e.connection)},10)))},c.prototype.login=function(t,e){s.isFunction(t)&&(e=t,t={}),t=t||{},e=e||function(){},s.extend(t,this.config);this._prompt(t,e)},c.prototype._prompt=function(t,e){var r=this,n=new d(t),i=Math.random().toString(36).substring(2),o=[this._prefix,"popup",i].join(".");localStorage.setItem("jsforce_state",o);var s,a,u,c,l=n.getAuthorizationUrl({response_type:"token",scope:t.scope,state:o}),h=t.size||{},f=(s=l,a=h.width||912,u=h.height||513,c=screen.width/2-a/2,h=screen.height/2-u/2,window.open(s,null,"location=yes,toolbar=no,status=no,menubar=no,width="+a+",height="+u+",top="+h+",left="+c));if(!f)return o=[this._prefix,"redirect",i].join("."),localStorage.setItem("jsforce_state",o),l=n.getAuthorizationUrl({response_type:"token",scope:t.scope,state:o}),void(location.href=l);r._removeTokens();var p=setInterval(function(){try{var t;f&&!f.closed||(clearInterval(p),(t=r._getTokens())?(r.connection.initialize(t),r.emit("connect",r.connection),e(null,{status:"connect"})):(t=r._getError())?e(new Error(t.error+": "+t.error_description)):e(null,{status:"cancel"}))}catch(t){}},1e3)},c.prototype.isLoggedIn=function(){return!(!this.connection||!this.connection.accessToken)},c.prototype.logout=function(){this.connection.logout(),this._removeTokens(),this.emit("disconnect")},c.prototype._getTokens=function(){var t=new RegExp("(^|;\\s*)"+this._prefix+"_loggedin=true(;|$)");if(document.cookie.match(t)){t=Number(localStorage.getItem(this._prefix+"_issued_at"));if(Date.now()<t+72e5){var e,t=localStorage.getItem(this._prefix+"_id");return t&&(e={id:(e=t.split("/")).pop(),organizationId:e.pop(),url:t}),{accessToken:localStorage.getItem(this._prefix+"_access_token"),instanceUrl:localStorage.getItem(this._prefix+"_instance_url"),userInfo:e}}}return null},c.prototype._storeTokens=function(t){localStorage.setItem(this._prefix+"_access_token",t.access_token),localStorage.setItem(this._prefix+"_instance_url",t.instance_url),localStorage.setItem(this._prefix+"_issued_at",t.issued_at),localStorage.setItem(this._prefix+"_id",t.id),document.cookie=this._prefix+"_loggedin=true;"},c.prototype._removeTokens=function(){localStorage.removeItem(this._prefix+"_access_token"),localStorage.removeItem(this._prefix+"_instance_url"),localStorage.removeItem(this._prefix+"_issued_at"),localStorage.removeItem(this._prefix+"_id"),document.cookie=this._prefix+"_loggedin="},c.prototype._getError=function(){try{var t=JSON.parse(localStorage.getItem(this._prefix+"_error"));return localStorage.removeItem(this._prefix+"_error"),t}catch(t){}},c.prototype._storeError=function(t){localStorage.setItem(this._prefix+"_error",JSON.stringify(t))},e.exports=new c,e.exports.Client=c},{"../connection":9,"../oauth2":15,events:37,inherits:39,"lodash/core":43,querystring:51}],6:[function(t,e,r){"use strict";var c=0;e.exports={supported:"undefined"!=typeof window&&"undefined"!=typeof document,createRequest:function(a,u){return a=a||"callback",u=u||1e4,function(t,e){if("GET"!==t.method.toUpperCase())return e(new Error("JSONP only supports GET request."));var r="_jsforce_jsonpCallback_"+ ++c,n=window,t=t.url;t+=0<t.indexOf("?")?"&":"?",t+=a+"="+r;var i=document.createElement("script");i.type="text/javascript",i.src=t,document.documentElement.appendChild(i);var o=setTimeout(function(){s(),e(new Error("JSONP call time out."))},u);n[r]=function(t){s(),e(null,{statusCode:200,headers:{"content-type":"application/json"},body:JSON.stringify(t)})};var s=function(){clearTimeout(o),document.documentElement.removeChild(i),delete n[r]}}}}},{}],7:[function(t,e,r){"use strict";var u=t("readable-stream").Duplex,c=t("lodash/core");e.exports=function(t,r){var n,i=new XMLHttpRequest;if(i.open(t.method,t.url),t.headers)for(var e in t.headers)i.setRequestHeader(e,t.headers[e]);i.setRequestHeader("Accept","*/*");var o=new u;o._read=function(t){n&&o.push(n.body)};var s=[],a=!1;return o._write=function(t,e,r){s.push(t.toString("buffer"===e?"binary":e)),r()},o.on("finish",function(){a||(i.send(s.join("")),a=!0)}),!t.body&&""!==t.body&&/^(put|post|patch)$/i.test(t.method)||(i.send(t.body),a=!0),i.onreadystatechange=function(){var t,e;4===i.readyState&&(t=function(t){t=(t.getAllResponseHeaders()||"").split(/[\r\n]+/);return c.map(t,function(t){return t.split(/\s*:/)[0].toLowerCase()})}(i),e={},c.forEach(t,function(t){t&&(e[t]=i.getResponseHeader(t))}),(n={statusCode:i.status,headers:e,body:i.response}).statusCode||(n.statusCode=400,n.body="Access Declined"),r&&r(null,n,n.body),o.end())},o}},{"lodash/core":43,"readable-stream":62}],8:[function(t,e,r){"use strict";function n(){this.fetching=!1}var i=t("events"),o=t("inherits"),l=t("lodash/core");o(n,i.EventEmitter),n.prototype.get=function(t){if(!t)return this._value;this.once("value",t),l.isUndefined(this._value)||this.emit("value",this._value)},n.prototype.set=function(t){this._value=t,this.emit("value",this._value)},n.prototype.clear=function(){this.fetching=!1,delete this._value};i=function(){this._entries={}};function h(t,e){return e=Array.prototype.slice.apply(e),t+"("+l.map(e,function(t){return JSON.stringify(t)}).join(",")+")"}i.prototype.get=function(t){if(t&&this._entries[t])return this._entries[t];var e=new n;return this._entries[t]=e},i.prototype.clear=function(t){for(var e in this._entries)t&&0!==e.indexOf(t)||this._entries[e].clear()},i.prototype.makeResponseCacheable=function(s,a,u){var c=this;return u=u||{},function(){var t=Array.prototype.slice.apply(arguments),e=t.pop();l.isFunction(e)||(t.push(e),e=null);var r=l.isString(u.key)?u.key:l.isFunction(u.key)?u.key.apply(a,t):h(u.namespace,t);Array.isArray(r)||(r=[r]);var n,i,o=[];r.forEach(function(t){t=c.get(t);t.fetching=!0,o.push(t)}),e&&t.push(function(r,n){Array.isArray(n)&&n.length==o.length?o.forEach(function(t,e){t.set({error:r,result:n[e]})}):o.forEach(function(t){t.set({error:r,result:n})}),e(r,n)});try{n=s.apply(a||this,t)}catch(t){i=t}if(n&&l.isFunction(n.then))return e?n:n.then(function(r){return Array.isArray(r)&&r.length==o.length?o.forEach(function(t,e){t.set({error:void 0,result:r[e]})}):o.forEach(function(t){t.set({error:void 0,result:r})}),r},function(r){throw Array.isArray(r)&&r.length==o.length?o.forEach(function(t,e){t.set({error:r[e],result:void 0})}):o.forEach(function(t){t.set({error:r,result:void 0})}),r});if(Array.isArray(n)&&n.length==o.length?o.forEach(function(t,e){t.set({error:i,result:n[e]})}):o.forEach(function(t){t.set({error:i,result:n})}),i)throw i;return n}},i.prototype.makeCacheable=function(i,o,s){var a=this;s=s||{};function t(){var t=Array.prototype.slice.apply(arguments),e=t.pop();l.isFunction(e)||t.push(e);var r=l.isString(s.key)?s.key:l.isFunction(s.key)?s.key.apply(o,t):h(s.namespace,t),n=a.get(r);if(!l.isFunction(e)){r=n.get();if(!r)throw new Error("Function call result is not cached yet.");if(r.error)throw r.error;return r.result}n.get(function(t){e(t.error,t.result)}),n.fetching||(n.fetching=!0,t.push(function(t,e){n.set({error:t,result:e})}),i.apply(o||this,t))}return t.clear=function(){var t=l.isString(s.key)?s.key:l.isFunction(s.key)?s.key.apply(o,arguments):h(s.namespace,arguments);a.clear(t)},t},e.exports=i},{events:37,inherits:39,"lodash/core":43}],9:[function(T,S,t){(function(r){"use strict";var t=T("events"),e=T("inherits"),u=T("lodash/core"),c=T("./promise"),n=T("./logger"),i=T("./oauth2"),o=T("./query"),s=T("./sobject"),a=T("./quick-action"),l=T("./http-api"),h=T("./transport"),f=T("./process"),p=T("./cache"),d="https://login.salesforce.com",y="",m="42.0",g=200,_=S.exports=function(t){t=t||{},this._logger=new n(t.logLevel);var e=t.oauth2||{loginUrl:t.loginUrl,clientId:t.clientId,clientSecret:t.clientSecret,redirectUri:t.redirectUri,proxyUrl:t.proxyUrl,httpProxy:t.httpProxy};this.oauth2=e=e instanceof i?e:new i(e),this.loginUrl=t.loginUrl||e.loginUrl||d,this.version=t.version||m,this.maxRequest=t.maxRequest||this.maxRequest||10,t.proxyUrl?this._transport=new h.ProxyTransport(t.proxyUrl):t.httpProxy?this._transport=new h.HttpProxyTransport(t.httpProxy):this._transport=new h,this.callOptions=t.callOptions,T("./core").emit("connection:new",this),this.process=new f(this),this.cache=new p;var r=t.refreshFn;!r&&this.oauth2.clientId&&(r=v),r&&(this._refreshDelegate=new l.SessionRefreshDelegate(this,r));e={key:function(t){return t?t.type?"describe."+t.type:"describe."+t:"describe"}};this.describe$=this.cache.makeCacheable(this.describe,this,e),this.describe=this.cache.makeResponseCacheable(this.describe,this,e),this.describeSObject$=this.describe$,this.describeSObject=this.describe;r={key:function(t){var e=t.types,t=t.autofetch||!1,e=!(25<e.length)||t?e:e.slice(0,25),r=[];return e.forEach(function(t){r.push("describe."+t)}),r}};this.batchDescribe=this.cache.makeResponseCacheable(this.batchDescribe,this,r),this.batchDescribeSObjects=this.batchDescribe,e={key:"describeGlobal"},this.describeGlobal$=this.cache.makeCacheable(this.describeGlobal,this,e),this.describeGlobal=this.cache.makeResponseCacheable(this.describeGlobal,this,e),this.initialize(t)};function v(r,n){r.oauth2.refreshToken(r.refreshToken,function(t,e){if(t)return n(t);t=w(e.id);r.initialize({instanceUrl:e.instance_url,accessToken:e.access_token,userInfo:t}),n(null,e.access_token,e)})}function b(t){function e(t){return t<10?"0"+t:t}return t.getUTCFullYear()+"-"+e(t.getUTCMonth()+1)+"-"+e(t.getUTCDate())+"T"+e(t.getUTCHours())+":"+e(t.getUTCMinutes())+":"+e(t.getUTCSeconds())+"+00:00"}function w(t){var e=t.split("/");return{id:e.pop(),organizationId:e.pop(),url:t}}function E(t){return t&&String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}e(_,t.EventEmitter),_.prototype.initialize=function(t){if(!t.instanceUrl&&t.serverUrl&&(t.instanceUrl=t.serverUrl.split("/").slice(0,3).join("/")),this.instanceUrl=t.instanceUrl||t.serverUrl||this.instanceUrl||y,this.accessToken=t.sessionId||t.accessToken||this.accessToken,this.refreshToken=t.refreshToken||this.refreshToken,this.refreshToken&&!this._refreshDelegate)throw new Error("Refresh token is specified without oauth2 client information or refresh function");this.signedRequest=t.signedRequest&&function(t){if(u.isString(t)){if("{"===t[0])return JSON.parse(t);var e=t.split(".").pop(),e=r.from(e,"base64").toString("utf-8");return JSON.parse(e)}return t}(t.signedRequest),this.signedRequest&&(this.accessToken=this.signedRequest.client.oauthToken,h.CanvasTransport.supported&&(this._transport=new h.CanvasTransport(this.signedRequest))),t.userInfo&&(this.userInfo=t.userInfo),this.limitInfo={},this.sobjects={},this.cache.clear(),this.cache.get("describeGlobal").removeAllListeners("value"),this.cache.get("describeGlobal").on("value",u.bind(function(t){t.result&&u.map(t.result.sobjects,function(t){return t.name}).forEach(this.sobject,this)},this)),this.tooling&&this.tooling.initialize(),this._sessionType=t.sessionId?"soap":"oauth2"},_.prototype._baseUrl=function(){return[this.instanceUrl,"services/data","v"+this.version].join("/")},_.prototype._normalizeUrl=function(t){return"/"===t[0]?0===t.indexOf("/services/")?this.instanceUrl+t:this._baseUrl()+t:t},_.prototype.request=function(t,e,r){"function"==typeof e&&(r=e,e=null),e=e||{};var n=this;u.isString(t)&&(t={method:"GET",url:t}),t.url=this._normalizeUrl(t.url);e=new l(this,e);return e.on("response",function(t){t.headers&&t.headers["sforce-limit-info"]&&((t=t.headers["sforce-limit-info"].match(/api\-usage=(\d+)\/(\d+)/))&&(n.limitInfo={apiUsage:{used:parseInt(t[1],10),limit:parseInt(t[2],10)}}))}),e.request(t).thenCall(r)},_.prototype.requestGet=function(t,e,r){t={method:"GET",url:t};return this.request(t,e,r)},_.prototype.requestPost=function(t,e,r,n){e={method:"POST",url:t,body:JSON.stringify(e),headers:{"content-type":"application/json"}};return this.request(e,r,n)},_.prototype.requestPut=function(t,e,r,n){e={method:"PUT",url:t,body:JSON.stringify(e),headers:{"content-type":"application/json"}};return this.request(e,r,n)},_.prototype.requestPatch=function(t,e,r,n){e={method:"PATCH",url:t,body:JSON.stringify(e),headers:{"content-type":"application/json"}};return this.request(e,r,n)},_.prototype.requestDelete=function(t,e,r){t={method:"DELETE",url:t};return this.request(t,e,r)},_.prototype.query=function(t,e,r){"function"==typeof e&&(r=e,e=void 0);e=new o(this,t,e);return r&&e.run(r),e},_.prototype.queryAll=function(t,e,r){"function"==typeof e&&(r=e,e=void 0);e=new o(this,t,e);return e.scanAll(!0),r&&e.run(r),e},_.prototype.queryMore=function(t,e,r){"function"==typeof e&&(r=e,e=void 0);e=new o(this,{locator:t},e);return r&&e.run(r),e},_.prototype._ensureVersion=function(t){var e=this.version.split(".");return parseInt(e[0],10)>=t},_.prototype._supports=function(t){return"sobject-collection"===t&&this._ensureVersion(42)},_.prototype.retrieve=function(t,e,r,n){return"function"==typeof r&&(n=r,r={}),r=r||{},(u.isArray(e)?this._supports("sobject-collection")?this._retrieveMany(t,e,r):this._retrieveParallel(t,e,r):this._retrieveSingle(t,e,r)).thenCall(n)},_.prototype._retrieveSingle=function(t,e,r){if(!e)return c.reject(new Error("Invalid record ID. Specify valid record ID value"));e=[this._baseUrl(),"sobjects",t,e].join("/");return r.fields&&(e+="?fields="+r.fields.join(",")),this.request({method:"GET",url:e,headers:r.headers})},_.prototype._retrieveParallel=function(e,t,r){if(t.length>this.maxRequest)return c.reject(new Error("Exceeded max limit of concurrent call"));var n=this;return c.all(t.map(function(t){return n._retrieveSingle(e,t,r).catch(function(t){if(r.allOrNone||"NOT_FOUND"!==t.errorCode)throw t;return null})}))},_.prototype._retrieveMany=function(t,e,r){if(0===e.length)return c.resolve([]);var n=[this._baseUrl(),"composite","sobjects",t].join("/"),i=this;return(r.fields?c.resolve(r.fields):new c(function(r,n){i.describe$(t,function(t,e){t?n(t):(e=e.fields.map(function(t){return t.name}),r(e))})})).then(function(t){return i.request({method:"POST",url:n,body:JSON.stringify({ids:e,fields:t}),headers:u.defaults(r.headers||{},{"Content-Type":"application/json"})})})},_.prototype._toRecordResult=function(t,e){var r={statusCode:e.errorCode,message:e.message};e.content&&(r.content=e.content),e.fields&&(r.fields=e.fields);r={success:!1,errors:[r]};return t&&(r.id=t),r},_.prototype.insert=_.prototype.create=function(t,e,r,n){return u.isString(t)||(n=r,r=e,e=t,t=null),"function"==typeof r&&(n=r,r={}),r=r||{},(u.isArray(e)?this._supports("sobject-collection")?this._createMany(t,e,r):this._createParallel(t,e,r):this._createSingle(t,e,r)).thenCall(n)},_.prototype._createSingle=function(t,e,r){t=t||e.attributes&&e.attributes.type||e.type;if(!t)return c.reject(new Error("No SObject Type defined in record"));delete(e=u.clone(e)).Id,delete e.type,delete e.attributes;t=[this._baseUrl(),"sobjects",t].join("/");return this.request({method:"POST",url:t,body:JSON.stringify(e),headers:u.defaults(r.headers||{},{"Content-Type":"application/json"})})},_.prototype._createParallel=function(e,t,r){if(t.length>this.maxRequest)return c.reject(new Error("Exceeded max limit of concurrent call"));var n=this;return c.all(t.map(function(t){return n._createSingle(e,t,r).catch(function(t){if(r.allOrNone||!t.errorCode)throw t;return this._toRecordResult(null,t)})}))},_.prototype._createMany=function(r,t,n){if(0===t.length)return c.resolve([]);if(t.length>g&&n.allowRecursive){var i=this;return i._createMany(r,t.slice(0,g),n).then(function(e){return i._createMany(r,t.slice(g),n).then(function(t){return e.concat(t)})})}t=u.map(t,function(t){var e=r||t.attributes&&t.attributes.type||t.type;return e?(delete(t=u.clone(t)).Id,delete t.type,t.attributes={type:e},t):c.reject(new Error("No SObject Type defined in record"))});var e=[this._baseUrl(),"composite","sobjects"].join("/");return this.request({method:"POST",url:e,body:JSON.stringify({allOrNone:n.allOrNone||!1,records:t}),headers:u.defaults(n.headers||{},{"Content-Type":"application/json"})})},_.prototype.update=function(t,e,r,n){return u.isString(t)||(n=r,r=e,e=t,t=null),"function"==typeof r&&(n=r,r={}),r=r||{},(u.isArray(e)?this._supports("sobject-collection")?this._updateMany(t,e,r):this._updateParallel(t,e,r):this._updateSingle(t,e,r)).thenCall(n)},_.prototype._updateSingle=function(t,e,r){var n=e.Id;if(!n)return c.reject(new Error("Record id is not found in record."));t=t||e.attributes&&e.attributes.type||e.type;if(!t)return c.reject(new Error("No SObject Type defined in record"));delete(e=u.clone(e)).Id,delete e.type,delete e.attributes;t=[this._baseUrl(),"sobjects",t,n].join("/");return this.request({method:"PATCH",url:t,body:JSON.stringify(e),headers:u.defaults(r.headers||{},{"Content-Type":"application/json"})},{noContentResponse:{id:n,success:!0,errors:[]}})},_.prototype._updateParallel=function(t,e,r){if(e.length>this.maxRequest)return c.reject(new Error("Exceeded max limit of concurrent call"));var n=this;return c.all(e.map(function(e){return n._updateSingle(t,e,r).catch(function(t){if(r.allOrNone||!t.errorCode)throw t;return this._toRecordResult(e.Id,t)})}))},_.prototype._updateMany=function(n,t,r){if(0===t.length)return c.resolve([]);if(t.length>g&&r.allowRecursive){var i=this;return i._updateMany(n,t.slice(0,g),r).then(function(e){return i._updateMany(n,t.slice(g),r).then(function(t){return e.concat(t)})})}t=u.map(t,function(t){var e=t.Id;if(!e)throw new Error("Record id is not found in record.");var r=n||t.attributes&&t.attributes.type||t.type;if(!r)throw new Error("No SObject Type defined in record");return delete(t=u.clone(t)).Id,t.id=e,delete t.type,t.attributes={type:r},t});var e=[this._baseUrl(),"composite","sobjects"].join("/");return this.request({method:"PATCH",url:e,body:JSON.stringify({allOrNone:r.allOrNone||!1,records:t}),headers:u.defaults(r.headers||{},{"Content-Type":"application/json"})})},_.prototype.upsert=function(n,t,i,o,e){u.isString(n)||(e=o,o=i,i=t,t=n,n=null),"function"==typeof o&&(e=o,o={}),o=o||{};var s=this,a=u.isArray(t);return((t=a?t:[t]).length>this.maxRequest?c.reject(new Error("Exceeded max limit of concurrent call")):c.all(u.map(t,function(t){var e=n||t.attributes&&t.attributes.type||t.type,r=t[i];delete(t=u.clone(t))[i],delete t.type,delete t.attributes;r=[s._baseUrl(),"sobjects",e,i,r].join("/");return s.request({method:"PATCH",url:r,body:JSON.stringify(t),headers:u.defaults(o.headers||{},{"Content-Type":"application/json"})},{noContentResponse:{success:!0,errors:[]}}).catch(function(t){if(!a||o.allOrNone||!t.errorCode)throw t;return s._toRecordResult(null,t)})})).then(function(t){return!a&&u.isArray(t)?t[0]:t})).thenCall(e)},_.prototype.delete=_.prototype.del=_.prototype.destroy=function(t,e,r,n){return"function"==typeof r&&(n=r,r={}),r=r||{},(u.isArray(e)?this._supports("sobject-collection")?this._destroyMany(t,e,r):this._destroyParallel(t,e,r):this._destroySingle(t,e,r)).thenCall(n)},_.prototype._destroySingle=function(t,e,r){t=[this._baseUrl(),"sobjects",t,e].join("/");return this.request({method:"DELETE",url:t,headers:r.headers||null},{noContentResponse:{id:e,success:!0,errors:[]}})},_.prototype._destroyParallel=function(t,e,r){if(e.length>this.maxRequest)return c.reject(new Error("Exceeded max limit of concurrent call"));var n=this;return c.all(e.map(function(e){return n._destroySingle(t,e,r).catch(function(t){if(r.allOrNone||!t.errorCode)throw t;return this._toRecordResult(e,t)})}))},_.prototype._destroyMany=function(t,r,n){if(0===r.length)return c.resolve([]);if(r.length>g&&n.allowRecursive){var i=this;return i._destroyMany(t,r.slice(0,g),n).then(function(e){return i._destroyMany(t,r.slice(g),n).then(function(t){return e.concat(t)})})}var e=[this._baseUrl(),"composite","sobjects?ids="].join("/")+r.join(",");return n.allOrNone&&(e+="&allOrNone=true"),this.request({method:"DELETE",url:e,headers:n.headers||null})},_.prototype.search=function(t,e){t=this._baseUrl()+"/search?q="+encodeURIComponent(t);return this.request(t).thenCall(e)},_.prototype.describe=_.prototype.describeSObject=function(t,e){var r=t.type||t,r=[this._baseUrl(),"sobjects",r,"describe"].join("/"),t=t.ifModifiedSince?{"If-Modified-Since":t.ifModifiedSince}:{};return this.request({method:"GET",url:r,headers:t}).then(function(t){return""===t?c.resolve(void 0):c.resolve(t)}).thenCall(e)},_.prototype.batchDescribe=_.prototype.batchDescribeSObjects=function(t,e){var r=t.types,n=t.autofetch||!1,i=Math.min(t.maxConcurrentRequests||15,15),o=[];do{var s=25<r.length?r.slice(0,25):r}while(o.push(s),0<(r=25<r.length?r.slice(25):[]).length&&n);var a=[];do{var u=o.length>i?o.slice(0,i):o}while(a.push(u),0<(o=o.length>i?o.slice(i):[]).length);return this.doBatchDescribeRequestBatches(a).thenCall(e)},_.prototype.doBatchDescribeRequestBatches=function(e){var r=this,n=[],t=e.shift();return r.doBatchOfBatchDescribeRequests(t).then(function(t){return t.forEach(function(t){n.push(t)}),0<e.length?r.doBatchDescribeRequestBatches(e).then(function(t){return t.forEach(function(t){n.push(t)}),c.resolve(n)}):c.resolve(n)})},_.prototype.doBatchOfBatchDescribeRequests=function(t){var e=this;return c.all(t.map(function(t){return e.doBatchDescribeRequest(t)})).then(function(t){var e=[];return t.forEach(function(t){t.forEach(function(t){e.push(t)})}),c.resolve(e)})},_.prototype.doBatchDescribeRequest=function(t){var n=[],e=[this._baseUrl(),"composite/batch"].join("/"),r="v"+this.version,i=[];return t.forEach(function(t){i.push({method:"GET",url:[r,"sobjects",t,"describe"].join("/")})}),this.request({method:"POST",url:e,body:JSON.stringify({batchRequests:i}),headers:{"Content-Type":"application/json"}}).then(function(t){if(t.results)for(var e=0,e=0;e<t.results.length;e++){var r=t.results[e];Array.isArray(r.result)?r.result[0].errorCode&&r.result[0].message&&this._logger.error("Error: "+r.result[0].errorCode+" "+r.result[0].message+" - "+typesToFetch[e]):n.push(r.result)}return c.resolve(n)})},_.prototype.describeGlobal=function(t){var e=this._baseUrl()+"/sobjects";return this.request(e).thenCall(t)},_.prototype.sobject=function(t){return this.sobjects=this.sobjects||{},this.sobjects[t]=this.sobjects[t]||new s(this,t)},_.prototype.identity=function(t,e){"function"==typeof t&&(e=t,t={}),t=t||{};var r=this,n=this.userInfo&&this.userInfo.url;return c.resolve(n?{identity:n}:this.request({method:"GET",url:this._baseUrl(),headers:t.headers})).then(function(t){t=t.identity;return r.request({method:"GET",url:t})}).then(function(t){return r.userInfo={id:t.user_id,organizationId:t.organization_id,url:t.id},t}).thenCall(e)},_.prototype.authorize=function(t,e,r){"function"==typeof e&&(r=e,e={});var n=this,i=this._logger;return this.oauth2.requestToken(t,e).then(function(t){var e=w(t.id);return n.initialize({instanceUrl:t.instance_url,accessToken:t.access_token,refreshToken:t.refresh_token,userInfo:e}),i.debug("<login> completed. user id = "+e.id+", org id = "+e.organizationId),e}).thenCall(r)},_.prototype.login=function(t,e,r){var n,i;return this._refreshDelegate=new l.SessionRefreshDelegate(this,(n=t,i=e,function(e,r){e.login(n,i,function(t){return t?r(t):void r(null,e.accessToken)})})),this.oauth2&&this.oauth2.clientId&&this.oauth2.clientSecret?this.loginByOAuth2(t,e,r):this.loginBySoap(t,e,r)},_.prototype.loginByOAuth2=function(t,e,r){var n=this,i=this._logger;return this.oauth2.authenticate(t,e).then(function(t){var e=w(t.id);return n.initialize({instanceUrl:t.instance_url,accessToken:t.access_token,userInfo:e}),i.debug("<login> completed. user id = "+e.id+", org id = "+e.organizationId),e}).thenCall(r)},_.prototype.loginBySoap=function(t,e,r){var o=this,s=this._logger,e=['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">',"<se:Header/>","<se:Body>",'<login xmlns="urn:partner.soap.sforce.com">',"<username>"+E(t)+"</username>","<password>"+E(e)+"</password>","</login>","</se:Body>","</se:Envelope>"].join(""),a=[this.loginUrl,"services/Soap/u",this.version].join("/");return this._transport.httpRequest({method:"POST",url:a,body:e,headers:{"Content-Type":"text/xml",SOAPAction:'""'}}).then(function(t){if(400<=t.statusCode){var e=(i=t.body.match(/<faultstring>([^<]+)<\/faultstring>/))&&i[1];throw new Error(e||t.body)}s.debug("SOAP response = "+t.body);var r=(i=t.body.match(/<serverUrl>([^<]+)<\/serverUrl>/))&&i[1],n=(i=t.body.match(/<sessionId>([^<]+)<\/sessionId>/))&&i[1],e=(i=t.body.match(/<userId>([^<]+)<\/userId>/))&&i[1],t=(i=t.body.match(/<organizationId>([^<]+)<\/organizationId>/))&&i[1],i=a.split("/").slice(0,3).join("/"),i={id:e,organizationId:t,url:i+="/id/"+t+"/"+e};return o.initialize({serverUrl:r.split("/").slice(0,3).join("/"),sessionId:n,userInfo:i}),s.debug("<login> completed. user id = "+e+", org id = "+t),i}).thenCall(r)},_.prototype.logout=function(t,e){return"function"==typeof t&&(e=t,t=!1),"oauth2"===this._sessionType?this.logoutByOAuth2(t,e):this.logoutBySoap(t,e)},_.prototype.logoutByOAuth2=function(t,e){"function"==typeof t&&(e=t,t=!1);var r=this;this._logger;return this.oauth2.revokeToken(t?this.refreshToken:this.accessToken).then(function(){r.accessToken=null,r.userInfo=null,r.refreshToken=null,r.instanceUrl=null,r.cache.clear()}).thenCall(e)},_.prototype.logoutBySoap=function(t,e){"function"==typeof t&&(e=t,t=!1);var r=this,n=this._logger,t=['<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/">',"<se:Header>",'<SessionHeader xmlns="urn:partner.soap.sforce.com">',"<sessionId>"+E(t?this.refreshToken:this.accessToken)+"</sessionId>","</SessionHeader>","</se:Header>","<se:Body>",'<logout xmlns="urn:partner.soap.sforce.com"/>',"</se:Body>","</se:Envelope>"].join("");return this._transport.httpRequest({method:"POST",url:[this.instanceUrl,"services/Soap/u",this.version].join("/"),body:t,headers:{"Content-Type":"text/xml",SOAPAction:'""'}}).then(function(t){if(n.debug("SOAP statusCode = "+t.statusCode+", response = "+t.body),400<=t.statusCode){var e=t.body.match(/<faultstring>([^<]+)<\/faultstring>/),e=e&&e[1];throw new Error(e||t.body)}r.accessToken=null,r.userInfo=null,r.refreshToken=null,r.instanceUrl=null,r.cache.clear()}).thenCall(e)},_.prototype.recent=function(t,e,r){var n;return u.isString(t)||(r=e,e=t,t=void 0),u.isNumber(e)||(r=e,e=void 0),t?(n=[this._baseUrl(),"sobjects",t].join("/"),this.request(n).then(function(t){return e?t.recentItems.slice(0,e):t.recentItems}).thenCall(r)):(n=this._baseUrl()+"/recent",e&&(n+="?limit="+e),this.request(n).thenCall(r))},_.prototype.updated=function(t,e,r,n){t=[this._baseUrl(),"sobjects",t,"updated"].join("/");return"string"==typeof e&&(e=new Date(e)),e instanceof Date&&(e=b(e)),e&&(t+="?start="+encodeURIComponent(e)),"string"==typeof r&&(r=new Date(r)),r instanceof Date&&(r=b(r)),r&&(t+="&end="+encodeURIComponent(r)),this.request(t).thenCall(n)},_.prototype.deleted=function(t,e,r,n){t=[this._baseUrl(),"sobjects",t,"deleted"].join("/");return"string"==typeof e&&(e=new Date(e)),e instanceof Date&&(e=b(e)),e&&(t+="?start="+encodeURIComponent(e)),"string"==typeof r&&(r=new Date(r)),r instanceof Date&&(r=b(r)),r&&(t+="&end="+encodeURIComponent(r)),this.request(t).thenCall(n)},_.prototype.tabs=function(t){var e=[this._baseUrl(),"tabs"].join("/");return this.request(e).thenCall(t)},_.prototype.limits=function(t){var e=[this._baseUrl(),"limits"].join("/");return this.request(e).thenCall(t)},_.prototype.theme=function(t){var e=[this._baseUrl(),"theme"].join("/");return this.request(e).thenCall(t)},_.prototype.quickActions=function(t){return this.request("/quickActions").thenCall(t)},_.prototype.quickAction=function(t){return new a(this,"/quickActions/"+t)}}).call(this,T("buffer").Buffer)},{"./cache":8,"./core":10,"./http-api":13,"./logger":14,"./oauth2":15,"./process":16,"./promise":17,"./query":18,"./quick-action":19,"./sobject":24,"./transport":26,buffer:30,events:37,inherits:39,"lodash/core":43}],10:[function(t,e,r){"use strict";var n=t("events").EventEmitter,n=e.exports=new n;n.VERSION=t("./VERSION"),n.Connection=t("./connection"),n.OAuth2=t("./oauth2"),n.Date=n.SfDate=t("./date"),n.RecordStream=t("./record-stream"),n.Promise=t("./promise"),n.require=t("./require")},{"./VERSION":2,"./connection":9,"./date":12,"./oauth2":15,"./promise":17,"./record-stream":20,"./require":22,events:37}],11:[function(t,e,r){"use strict";var n=t("lodash/core"),i=t("csv-parse/lib/es5"),o=t("csv-parse/lib/es5/sync"),s=t("csv-stringify"),a=t("csv-stringify/lib/sync");e.exports={parseCSV:function(t,e){return e=n.extend({},e,{columns:!0}),o(t,e)},toCSV:function(t,e){return e=n.extend({},e,{header:!0}),a(t,e)},parseCSVStream:function(t){return t=n.extend({},t,{columns:!0}),i(t)},serializeCSVStream:function(t){return t=n.extend({},t,{header:!0}),s(t)}}},{"csv-parse/lib/es5":33,"csv-parse/lib/es5/sync":34,"csv-stringify":35,"csv-stringify/lib/sync":36,"lodash/core":43}],12:[function(t,e,r){"use strict";var s=t("lodash/core"),a=e.exports=function(t){this._literal=t};function u(t){return(t<10?"0":"")+t}a.prototype.toString=a.prototype.toJSON=function(){return this._literal},a.toDateLiteral=function(t){s.isNumber(t)?t=new Date(t):s.isString(t)&&(t=a.parseDate(t));var e=t.getFullYear(),r=t.getMonth()+1,t=t.getDate(),t=[e,u(r),u(t)].join("-");return new a(t)},a.toDateTimeLiteral=function(t){s.isNumber(t)?t=new Date(t):s.isString(t)&&(t=a.parseDate(t));var e=t.getUTCFullYear(),r=t.getUTCMonth()+1,n=t.getUTCDate(),i=t.getUTCHours(),o=t.getUTCMinutes(),t=t.getUTCSeconds(),t=[e,u(r),u(n)].join("-")+"T"+[u(i),u(o),u(t)].join(":")+"Z";return new a(t)},a.parseDate=function(t){var e=new Date,r=t.match(/^([\d]{4})-?([\d]{2})-?([\d]{2})(T([\d]{2}):?([\d]{2}):?([\d]{2})(.([\d]{3}))?(Z|([\+\-])([\d]{2}):?([\d]{2})))?$/);if(r){var n,e=new Date(0);return r[4]?(e.setUTCFullYear(parseInt(r[1],10)),e.setUTCDate(parseInt(r[3],10)),e.setUTCMonth(parseInt(r[2],10)-1),e.setUTCHours(parseInt(r[5],10)),e.setUTCMinutes(parseInt(r[6],10)),e.setUTCSeconds(parseInt(r[7],10)),e.setUTCMilliseconds(parseInt(r[9]||"0",10)),r[10]&&"Z"!==r[10]&&(n=60*parseInt(r[12],10)+parseInt(r[13],10),e.setTime(("+"===r[11]?-1:1)*n*60*1e3+e.getTime()))):(e.setFullYear(parseInt(r[1],10)),e.setDate(parseInt(r[3],10)),e.setMonth(parseInt(r[2],10)-1),e.setHours(0),e.setMinutes(0),e.setSeconds(0),e.setMilliseconds(0)),e}throw new Error("Invalid date format is specified : "+t)};var n,i={YESTERDAY:1,TODAY:1,TOMORROW:1,LAST_WEEK:1,THIS_WEEK:1,NEXT_WEEK:1,LAST_MONTH:1,THIS_MONTH:1,NEXT_MONTH:1,LAST_90_DAYS:1,NEXT_90_DAYS:1,LAST_N_DAYS:2,NEXT_N_DAYS:2,NEXT_N_WEEKS:2,LAST_N_WEEKS:2,NEXT_N_MONTHS:2,LAST_N_MONTHS:2,THIS_QUARTER:1,LAST_QUARTER:1,NEXT_QUARTER:1,NEXT_N_QUARTERS:2,LAST_N_QUARTERS:2,THIS_YEAR:1,LAST_YEAR:1,NEXT_YEAR:1,NEXT_N_YEARS:2,LAST_N_YEARS:2,THIS_FISCAL_QUARTER:1,LAST_FISCAL_QUARTER:1,NEXT_FISCAL_QUARTER:1,NEXT_N_FISCAL_QUARTERS:2,LAST_N_FISCAL_QUARTERS:2,THIS_FISCAL_YEAR:1,LAST_FISCAL_YEAR:1,NEXT_FISCAL_YEAR:1,NEXT_N_FISCAL_YEARS:2,LAST_N_FISCAL_YEARS:2};for(n in i){var o=i[n];a[n]=1===o?new a(n):function(e){return function(t){return new a(e+":"+t)}}(n)}},{"lodash/core":43}],13:[function(e,t,r){"use strict";function n(e,t){t=t||{},this._conn=e,this.on("resume",function(t){e.emit("resume",t)}),this._responseType=t.responseType,this._transport=t.transport||e._transport,this._noContentResponse=t.noContentResponse}var i=e("inherits"),o=e("events"),s=e("lodash/core"),l=e("./promise");function a(t){return JSON.parse(t)}function u(t){var r={};if(e("xml2js").parseString(t,{explicitArray:!1},function(t,e){r={error:t,result:e}}),r.error)throw r.error;return r.result}function c(t){return e("./csv").parseCSV(t)}function h(t){return t}i(n,o.EventEmitter),n.prototype.request=function(r,t){function n(t){t?u.reject(t):(a!==e.instanceUrl&&(r.url=r.url.replace(a,e.instanceUrl)),i.request(r).then(function(t){u.resolve(t)},function(t){u.reject(t)}))}var i=this,e=this._conn,o=e._logger,s=this.getRefreshDelegate(),a=e.instanceUrl,u=l.defer();if(s&&s._refreshing)return s.once("resume",n),u.promise.thenCall(t);i.beforeSend(r),i.emit("request",r),o.debug("<request> method="+r.method+", url="+r.url);var c=Date.now();return this._transport.httpRequest(r).then(function(t){var e=Date.now();if(o.debug("elapsed time : "+(e-c)+"msec"),o.debug("<response> status="+t.statusCode+", url="+r.url),i.emit("response",t),i.isSessionExpired(t)&&s)return s.refresh(c,n),u.promise;if(i.isErrorResponse(t))throw i.getError(t);return i.getResponseBody(t)},function(t){var e=Date.now();throw o.debug("elapsed time : "+(e-c)+"msec"),o.error(t),t}).thenCall(t)},n.prototype.getRefreshDelegate=function(){return this._conn._refreshDelegate},n.prototype.beforeSend=function(t){if(t.headers=t.headers||{},this._conn.accessToken&&(t.headers.Authorization="Bearer "+this._conn.accessToken),this._conn.callOptions){var e,r=[];for(e in this._conn.callOptions)r.push(e+"="+this._conn.callOptions[e]);t.headers["Sforce-Call-Options"]=r.join(", ")}},n.prototype.getResponseContentType=function(t){return this._responseType||t.headers&&t.headers["content-type"]},n.prototype.parseResponseBody=function(e){var t=this.getResponseContentType(e),r=/^(text|application)\/xml(;|$)/.test(t)?u:/^application\/json(;|$)/.test(t)?a:/^text\/csv(;|$)/.test(t)?c:h;try{return r(e.body)}catch(t){return e.body}},n.prototype.getResponseBody=function(t){if(204===t.statusCode)return this._noContentResponse;var e,r=this.parseResponseBody(t);if(this.hasErrorInResponseBody(r))throw e=this.getError(t,r);if(300===t.statusCode)throw(e=new Error("Multiple records found")).name="MULTIPLE_CHOICES",e.content=r,e;return r},n.prototype.isSessionExpired=function(t){return 401===t.statusCode},n.prototype.isErrorResponse=function(t){return 400<=t.statusCode},n.prototype.hasErrorInResponseBody=function(t){return!1},n.prototype.parseError=function(t){return s.isArray(t)?t[0]:t},n.prototype.getError=function(t,e){var r;try{r=this.parseError(e||this.parseResponseBody(t))}catch(t){}r=s.isObject(r)&&s.isString(r.message)?r:{errorCode:"ERROR_HTTP_"+t.statusCode,message:t.body};var n,i=new Error(r.message);for(n in i.name=r.errorCode,r)i[n]=r[n];return i};function f(t,e){this._conn=t,this._refreshFn=e,this._refreshing=!1}i(f,o.EventEmitter),f.prototype.refresh=function(t,e){if(this._lastRefreshedAt>t)return e();var n=this,i=this._conn,o=i._logger;return n.once("resume",e),n._refreshing?void 0:(o.debug("<refresh token>"),n._refreshing=!0,n._refreshFn(i,function(t,e,r){t||(o.debug("Connection refresh completed."),i.accessToken=e,i.emit("refresh",e,r)),n._lastRefreshedAt=Date.now(),n._refreshing=!1,n.emit("resume",t)}))},n.SessionRefreshDelegate=f,t.exports=n},{"./csv":11,"./promise":17,events:37,inherits:39,"lodash/core":43,xml2js:78}],14:[function(t,e,r){"use strict";var n,i=e.exports=function(t){"string"==typeof t&&(t=o[t]),t=t||o.INFO,this._logLevel=t},o=i.LogLevels={DEBUG:1,INFO:2,WARN:3,ERROR:4,FATAL:5};for(n in i.prototype.log=function(t,e){this._logLevel<=t&&(t<o.ERROR?console.log(e):console.error(e))},o)i.prototype[n.toLowerCase()]=function(e){return function(t){this.log(e,t)}}(o[n])},{}],15:[function(t,e,r){"use strict";var n=t("querystring"),i=t("lodash/core"),o=t("./transport"),s="https://login.salesforce.com",e=e.exports=function(t){t.authzServiceUrl&&t.tokenServiceUrl?(this.loginUrl=t.authzServiceUrl.split("/").slice(0,3).join("/"),this.authzServiceUrl=t.authzServiceUrl,this.tokenServiceUrl=t.tokenServiceUrl,this.revokeServiceUrl=t.revokeServiceUrl):(this.loginUrl=t.loginUrl||s,this.authzServiceUrl=this.loginUrl+"/services/oauth2/authorize",this.tokenServiceUrl=this.loginUrl+"/services/oauth2/token",this.revokeServiceUrl=this.loginUrl+"/services/oauth2/revoke"),this.clientId=t.clientId,this.clientSecret=t.clientSecret,this.redirectUri=t.redirectUri,t.proxyUrl?this._transport=new o.ProxyTransport(t.proxyUrl):t.httpProxy?this._transport=new o.HttpProxyTransport(t.httpProxy):this._transport=new o};i.extend(e.prototype,{getAuthorizationUrl:function(t){return t=i.extend({response_type:"code",client_id:this.clientId,redirect_uri:this.redirectUri},t||{}),this.authzServiceUrl+(0<=this.authzServiceUrl.indexOf("?")?"&":"?")+n.stringify(t)},refreshToken:function(t,e){t={grant_type:"refresh_token",refresh_token:t,client_id:this.clientId};return this.clientSecret&&(t.client_secret=this.clientSecret),this._postParams(t,e)},requestToken:function(t,e,r){return"function"==typeof e&&(r=e,e={}),e=i.extend({grant_type:"authorization_code",code:t,client_id:this.clientId,redirect_uri:this.redirectUri},e||{}),this.clientSecret&&(e.client_secret=this.clientSecret),this._postParams(e,r)},authenticate:function(t,e,r){return this._postParams({grant_type:"password",username:t,password:e,client_id:this.clientId,client_secret:this.clientSecret,redirect_uri:this.redirectUri},r)},revokeToken:function(t,e){return this._transport.httpRequest({method:"POST",url:this.revokeServiceUrl,body:n.stringify({token:t}),headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(t){if(400<=t.statusCode){var e=n.parse(t.body);e&&e.error||(e={error:"ERROR_HTTP_"+t.statusCode,error_description:t.body});t=new Error(e.error_description);throw t.name=e.error,t}}).thenCall(e)},_postParams:function(t,e){return this._transport.httpRequest({method:"POST",url:this.tokenServiceUrl,body:n.stringify(t),headers:{"content-type":"application/x-www-form-urlencoded"}}).then(function(t){var e;try{e=JSON.parse(t.body)}catch(t){}if(400<=t.statusCode){e=e||{error:"ERROR_HTTP_"+t.statusCode,error_description:t.body};var r=new Error(e.error_description);throw r.name=e.error,r}return e}).thenCall(e)}})},{"./transport":26,"lodash/core":43,querystring:51}],16:[function(t,e,r){"use strict";var o=t("lodash/core"),n=(t("./promise"),t("./connection"),e.exports=function(t){this.rule=new n(t),this.approval=new i(t)},function(t){this._conn=t});n.prototype.list=function(t){return this._conn.request("/process/rules").then(function(t){return t.rules}).thenCall(t)},n.prototype.trigger=function(t,e){return t=o.isArray(t)?t:[t],this._conn.request({method:"POST",url:"/process/rules/",body:JSON.stringify({contextIds:t}),headers:{"content-type":"application/json"}}).thenCall(e)};var i=function(t){this._conn=t};i.prototype.list=function(t){return this._conn.request("/process/approvals").then(function(t){return t.approvals}).thenCall(t)},i.prototype.request=function(t,e){return t=t.map(function(t){return t._request||t}),this._conn.request({method:"POST",url:"/process/approvals",headers:{"content-type":"application/json"},body:JSON.stringify({requests:t})}).thenCall(e)},i.prototype._createRequest=function(t,e,r,n,i){"function"==typeof r&&(i=r,r=n=null),"function"==typeof n&&(i=n,n=null),n=n||{};r={actionType:t,contextId:e,comments:r};return o.extend(r,n),new s(this,r).thenCall(i)},i.prototype.submit=function(t,e,r,n){return this._createRequest("Submit",t,e,r,n)},i.prototype.approve=function(t,e,r,n){return this._createRequest("Approve",t,e,r,n)},i.prototype.reject=function(t,e,r,n){return this._createRequest("Reject",t,e,r,n)};var s=function(t,e){this._process=t,this._request=e};s.prototype.then=function(t,e){this._promise||(this._promise=this._process.request([this]).then(function(t){return t[0]})),this._promise.then(t,e)},s.prototype.thenCall=function(e){return e?this.then(function(t){e(null,t)},function(t){e(t)}):this}},{"./connection":9,"./promise":17,"lodash/core":43}],17:[function(i,o,t){(function(r){"use strict";var t=i("lodash/core"),e=i("promise/lib/es6-extensions");e.prototype.thenCall=function(e){return t.isFunction(e)&&this.then(function(t){r.nextTick(function(){e(null,t)})},function(t){r.nextTick(function(){e(t)})}),this},e.prototype.fail=e.prototype.catch,e.defer=function(){return new n};var n=function(){var r=this;this.promise=new e(function(t,e){r.resolve=t,r.reject=e})};o.exports=e}).call(this,i("_process"))},{_process:46,"lodash/core":43,"promise/lib/es6-extensions":48}],18:[function(s,u,t){(function(r){"use strict";var t=s("inherits"),e=(s("events"),s("readable-stream")),c=s("lodash/core"),l=s("./promise"),n=(s("./date"),s("./soql-builder")),i=s("./record-stream"),o=u.exports=function(t,e,r){o.super_.call(this,{objectMode:!0}),this._conn=t,c.isString(e)?this._soql=e:e.locator&&0<=e.locator.indexOf("/")?this._locator=e.locator.split("/").pop():(this._config=e,this.select(e.fields),e.includes&&this.include(e.includes),e.sort&&this.sort(e.sort)),this._options=c.defaults(r||{},{maxFetch:1e4,autoFetch:!1,scanAll:!1,responseTarget:h.QueryResult}),this._executed=!1,this._finished=!1,this._chaining=!1,this._deferred=l.defer()};t(o,e.Readable),o.prototype.select=function(t){if(this._soql)throw Error("Cannot set select fields for the query which has already built SOQL.");if(t=t||"*",c.isString(t))t=t.split(/\s*,\s*/);else if(c.isObject(t)&&!c.isArray(t)){var e,r=[];for(e in t)t[e]&&r.push(e);t=r}return this._config.fields=t,this},o.prototype.where=function(t){if(this._soql)throw Error("Cannot set where conditions for the query which has already built SOQL.");return this._config.conditions=t,this},o.prototype.limit=function(t){if(this._soql)throw Error("Cannot set limit for the query which has already built SOQL.");return this._config.limit=t,this},o.prototype.skip=o.prototype.offset=function(t){if(this._soql)throw Error("Cannot set skip/offset for the query which has already built SOQL.");return this._config.offset=t,this},o.prototype.sort=o.prototype.orderby=function(t,e){if(this._soql)throw Error("Cannot set sort for the query which has already built SOQL.");return c.isString(t)&&c.isString(e)&&(t=[[t,e]]),this._config.sort=t,this},o.prototype.include=function(t,e,r,n){if(this._soql)throw Error("Cannot include child relationship into the query which has already built SOQL.");if(!c.isObject(t)){n={table:t,conditions:e,fields:r,limit:n&&n.limit,offset:n&&(n.offset||n.skip),sort:n&&n.sort};c.isArray(this._config.includes)||(this._config.includes=[]),this._config.includes.push(n);n=new a(this._conn,this,n);return this._children=this._children||[],this._children.push(n),n}var i,o=t;for(i in o){var s=o[i];this.include(i,s.conditions,s.fields,s)}},o.prototype.maxFetch=function(t){return this._options.maxFetch=t,this},o.prototype.autoFetch=function(t){return this._options.autoFetch=t,this},o.prototype.scanAll=function(t){return this._options.scanAll=t,this};var h=o.ResponseTargets={};["QueryResult","Records","SingleRecord","Count"].forEach(function(t){h[t]=t}),o.prototype.setResponseTarget=function(t){return t in h&&(this._options.responseTarget=t),this},o.prototype.run=o.prototype.exec=o.prototype.execute=function(r,n){var i=this,o=this._conn._logger,s=this._deferred;if(this._executed)return s.reject(new Error("re-executing already executed query")),this;if(this._finished)return s.reject(new Error("executing already closed query")),this;"function"==typeof r&&(n=r,r={}),r={headers:(r=r||{}).headers||i._options.headers,responseTarget:r.responseTarget||i._options.responseTarget,autoFetch:r.autoFetch||i._options.autoFetch,maxFetch:r.maxFetch||i._options.maxFetch,scanAll:r.scanAll||i._options.scanAll};function e(e,t){if(c.isFunction(n))try{t=n(e,t),e=null}catch(t){e=t}e?s.reject(e):s.resolve(t)}return this.once("response",function(t){e(null,t)}),this.once("error",function(t){e(t)}),this.once("fetch",function(){var e,t;r.responseTarget===h.Records&&(i._chaining||n)&&(o.debug("--- collecting all fetched records ---"),e=[],t=function(t){e.push(t)},i.on("record",t),i.once("end",function(){i.removeListener("record",t),i.emit("response",e,i)}))}),this._executed=!0,o.debug(">>> Query start >>>"),this._execute(r).then(function(){o.debug("*** Query finished ***")}).fail(function(t){o.debug("--- Query error ---"),i.emit("error",t)}),this},o.prototype._execute=function(o){var s=this,e=this._conn._logger,a=o.responseTarget,u=o.autoFetch,c=o.maxFetch,r=o.scanAll;return l.resolve(s._locator?s._conn._baseUrl()+"/query/"+s._locator:s.toSOQL().then(function(t){return s.totalFetched=0,e.debug("SOQL = "+t),s._conn._baseUrl()+"/"+(r?"queryAll":"query")+"?q="+encodeURIComponent(t)})).then(function(t){return s._conn.request({method:"GET",url:t,headers:o.headers})}).then(function(t){var e;switch(s.emit("fetch"),s.totalSize=t.totalSize,a){case h.SingleRecord:e=t.records&&0<t.records.length?t.records[0]:null;break;case h.Records:e=t.records;break;case h.Count:e=t.totalSize;break;default:e=t}a!==h.Records&&s.emit("response",e,s);for(var r=t.records&&t.records.length||0,n=0;n<r;n++){if(s.totalFetched>=c){s._finished=!0;break}var i=t.records[n];s.push(i),s.emit("record",i,s.totalFetched++,s)}return t.nextRecordsUrl&&(s._locator=t.nextRecordsUrl.split("/").pop()),s._finished=s._finished||t.done||!u,s._finished?s.push(null):s._execute(o),e})},o.prototype._read=function(t){this._finished||this._executed||this.execute({autoFetch:!0})},o.prototype.on=function(t,e){var r;return"record"===t&&(r=this).on("readable",function(){for(;null!==r.read(););}),o.super_.prototype.on.call(this,t,e)},o.prototype.addListener=o.prototype.on,o.prototype._expandFields=function(){if(this._soql)return l.reject(new Error("Cannot expand fields for the query which has already built SOQL."));var r,t,n=this,s=n._conn._logger,e=this._conn,i=this._config.table,o=this._config.fields||[];return s.debug("_expandFields: table = "+i+", fields = "+o.join(", ")),l.all([l.resolve(n._parent?(r=i,t=n._parent._config.table,s.debug('finding table for relation "'+r+'" in "'+t+'"...'),a(t).then(function(t){var e=r.toUpperCase(),t=c.find(t.childRelationships,function(t){return(t.relationshipName||"").toUpperCase()===e});return t?t.childSObject:l.reject(new Error("No child relationship found: "+r))})):i).then(function(e){return l.all(c.map(o,function(t){return function n(i,t){s.debug('expanding field "'+t+'" in "'+i+'"...');var o=t.split(".");return"*"===o[o.length-1]?a(i).then(function(t){if(s.debug("table "+i+"has been described"),1<o.length){var e=o.shift(),r=c.find(t.fields,function(t){return t.relationshipName&&t.relationshipName.toUpperCase()===e.toUpperCase()});if(r){var r=1===r.referenceTo.length?r.referenceTo[0]:"Name";return n(r,o.join(".")).then(function(t){return c.map(t,function(t){return e+"."+t})})}return[]}return c.map(t.fields,function(t){return t.name})}):l.resolve([t])}(e,t)})).then(function(t){n._config.fields=c.flatten(t)})}),l.all(c.map(n