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