stratumn-agent-client
Advanced tools
Comparing version 0.7.0 to 1.5.0
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | ||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | ||
(factory((global.StratumnSDK = global.StratumnSDK || {}))); | ||
(factory((global.AgentClient = global.AgentClient || {}))); | ||
}(this, (function (exports) { 'use strict'; | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
function deprecated(oldFunc, newFunc) { | ||
if (!newFunc) { | ||
console.warn("WARNING: " + oldFunc + " is deprecated."); | ||
} else { | ||
console.warn("WARNING: " + oldFunc + " is deprecated. Please use " + newFunc + " instead."); | ||
} | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
/** | ||
* Makes a query string. | ||
* @param {object} obj - an object of keys | ||
* @returns {string} a query string | ||
*/ | ||
function makeQueryString(obj) { | ||
var parts = Object.keys(obj).reduce(function (curr, key) { | ||
var val = Array.isArray(obj[key]) ? obj[key].join('+') : obj[key]; | ||
curr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); | ||
return curr; | ||
}, []); | ||
if (parts.length) { | ||
return '?' + parts.join('&'); | ||
} | ||
return ''; | ||
} | ||
function interopDefault(ex) { | ||
@@ -612,4 +655,5 @@ return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; | ||
request({ method: method, url: url, body: args }, function (err, res) { | ||
var error = err || res.body && res.body.meta && res.body.meta.errorMessage; | ||
if (error) { | ||
if (err) { | ||
var error = err && err.body && err.body.meta && err.body.meta.errorMessage ? new Error(err.body.meta.errorMessage) : err; | ||
error.status = err.status; | ||
reject(error); | ||
@@ -639,7 +683,12 @@ } else { | ||
var config = { | ||
baseUrl: 'https://stratumn.rocks', | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
function findSegments(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
}); | ||
} | ||
/* | ||
@@ -653,5 +702,21 @@ Copyright (C) 2017 Stratumn SAS | ||
function linkify(app, obj) { | ||
Object.keys(app.agentInfo.functions).filter(function (key) { | ||
return ['init', 'catchAll'].indexOf(key) < 0; | ||
function getBranches(agent, prevLinkHash) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
deprecated('Agent#getBranches(agent, prevLinkHash, tags = [])', 'Agent#findSegments(agent, filter)'); | ||
return findSegments(agent, { prevLinkHash: prevLinkHash, tags: tags }); | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
function segmentify(agent, obj) { | ||
Object.keys(agent.agentInfo.actions).filter(function (key) { | ||
return ['init'].indexOf(key) < 0; | ||
}).forEach(function (key) { | ||
@@ -664,7 +729,4 @@ /*eslint-disable*/ | ||
var url = config.applicationUrl.replace('%s', app.name) + '/links/' + obj.meta.linkHash + '/' + key; | ||
/*eslint-enable*/ | ||
return post(url, args).then(function (res) { | ||
return linkify(app, res.body); | ||
return post(agent.url + '/segments/' + obj.meta.linkHash + '/' + key, args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -678,3 +740,3 @@ }; | ||
if (obj.link.meta.prevLinkHash) { | ||
return app.getLink(obj.link.meta.prevLinkHash); | ||
return agent.getSegment(obj.link.meta.prevLinkHash); | ||
} | ||
@@ -685,12 +747,22 @@ | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.getBranches = function (tags) { | ||
obj.load = function () { | ||
/*eslint-enable*/ | ||
return app.getBranches(obj.meta.linkHash, tags); | ||
deprecated('segment#load()'); | ||
return Promise.resolve(segmentify(agent, { | ||
link: JSON.parse(JSON.stringify(obj.link)), | ||
meta: JSON.parse(JSON.stringify(obj.meta)) | ||
})); | ||
}; | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.load = function () { | ||
obj.getBranches = function () { | ||
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
/*eslint-enable*/ | ||
return app.getLink(obj.meta.linkHash); | ||
return getBranches.apply(undefined, [agent, obj.meta.linkHash].concat(args)); | ||
}; | ||
@@ -709,5 +781,3 @@ | ||
function createMap(app) { | ||
var url = config.applicationUrl.replace('%s', app.name) + '/maps'; | ||
function createMap(agent) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
@@ -717,4 +787,4 @@ args[_key - 1] = arguments[_key]; | ||
return post(url, args).then(function (res) { | ||
return linkify(app, res.body); | ||
return post(agent.url + '/segments', args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -731,7 +801,5 @@ } | ||
function getLink(app, linkHash) { | ||
var url = config.applicationUrl.replace('%s', app.name) + '/links/' + linkHash; | ||
return get(url).then(function (res) { | ||
return linkify(app, res.body); | ||
function getSegment(agent, linkHash) { | ||
return get(agent.url + '/segments/' + linkHash).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -748,18 +816,22 @@ } | ||
function getMap(app, mapId) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
function getMapIds(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var query = ''; | ||
return get(agent.url + '/maps' + makeQueryString(opts)).then(function (res) { | ||
return res.body; | ||
}); | ||
} | ||
if (tags && tags.length) { | ||
query = '?tags=' + tags.join('&tags='); | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
var url = config.applicationUrl.replace('%s', app.name) + '/maps/' + mapId + query; | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
return get(url).then(function (res) { | ||
return res.body.map(function (link) { | ||
return linkify(app, link); | ||
}); | ||
}); | ||
function getLink(agent, hash) { | ||
deprecated('Agent#getLink(agent, hash)', 'Agent#getSegment(agent, hash)'); | ||
return getSegment(agent, hash); | ||
} | ||
@@ -775,6 +847,8 @@ | ||
function getMapIds(agent) { | ||
return get(agent.url + '/maps').then(function (res) { | ||
return res.body; | ||
}); | ||
function getMap(agent, mapId) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
deprecated('getMap(agent, mapId, tags = [])', 'findSegments(agent, filter)'); | ||
return findSegments(agent, { mapId: mapId, tags: tags }); | ||
} | ||
@@ -790,17 +864,34 @@ | ||
function getBranches(app, linkHash) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
// Deprecated. | ||
function getAgent(url) { | ||
return get(url).then(function (res) { | ||
var agent = res.body; | ||
var query = ''; | ||
agent.url = url; | ||
agent.createMap = createMap.bind(null, agent); | ||
agent.getSegment = getSegment.bind(null, agent); | ||
agent.findSegments = findSegments.bind(null, agent); | ||
agent.getMapIds = getMapIds.bind(null, agent); | ||
if (tags && tags.length) { | ||
query = '?tags=' + tags.join('&tags='); | ||
} | ||
// Deprecated. | ||
agent.getBranches = getBranches.bind(null, agent); | ||
agent.getLink = getLink.bind(null, agent); | ||
agent.getMap = getMap.bind(null, agent); | ||
var url = config.applicationUrl.replace('%s', app.name) + '/branches/' + linkHash + query; | ||
return agent; | ||
}); | ||
} | ||
return get(url).then(function (res) { | ||
return res.body.map(function (link) { | ||
return linkify(app, link); | ||
}); | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
function fromSegment(obj) { | ||
return getAgent(obj.meta.agentUrl || obj.meta.applicationLocation).then(function (agent) { | ||
var segment = segmentify(agent, obj); | ||
return { agent: agent, segment: segment }; | ||
}); | ||
@@ -817,17 +908,19 @@ } | ||
function getApplication(appName, appLocation) { | ||
var url = appLocation || config.applicationUrl.replace('%s', appName); | ||
// Deprecated. | ||
var config = { | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
return get(url).then(function (res) { | ||
var app = res.body; | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
app.url = url; | ||
app.createMap = createMap.bind(null, app); | ||
app.getLink = getLink.bind(null, app); | ||
app.getMap = getMap.bind(null, app); | ||
app.getBranches = getBranches.bind(null, app); | ||
app.getMapIds = getMapIds.bind(null, app); | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
return app; | ||
}); | ||
function getApplication(name, url) { | ||
deprecated('getApplication(name, url)', 'getAgent(url)'); | ||
return getAgent(url || config.applicationUrl.replace('%s', name)); | ||
} | ||
@@ -843,12 +936,13 @@ | ||
function loadLink(segment) { | ||
return getApplication(segment.meta.application, segment.meta.applicationLocation).then(function (app) { | ||
var url = segment.meta.linkLocation; | ||
function loadLink(obj) { | ||
deprecated('loadLink(obj)', 'fromSegment(obj)'); | ||
return get(url).then(function (res) { | ||
return linkify(app, res.body); | ||
return fromSegment(obj).then(function (_ref) { | ||
var segment = _ref.segment; | ||
return segment; | ||
}); | ||
}); | ||
} | ||
exports.getAgent = getAgent; | ||
exports.fromSegment = fromSegment; | ||
exports.getApplication = getApplication; | ||
@@ -855,0 +949,0 @@ exports.loadLink = loadLink; |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.StratumnSDK=e.StratumnSDK||{})}(this,function(e){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function r(e,t){return t={exports:{}},e(t,t.exports),t.exports}function n(e,t,r){return new Promise(function(n,o){te({method:e,url:t,body:r},function(e,t){var r=e||t.body&&t.body.meta&&t.body.meta.errorMessage;r?o(r):n(t)})})}function o(e){return n("GET",e)}function s(e,t){return n("POST",e,t)}function a(e,t){return Object.keys(e.agentInfo.functions).filter(function(e){return["init","catchAll"].indexOf(e)<0}).forEach(function(r){t[r]=function(){for(var n=arguments.length,o=Array(n),u=0;u<n;u++)o[u]=arguments[u];var i=re.applicationUrl.replace("%s",e.name)+"/links/"+t.meta.linkHash+"/"+r;return s(i,o).then(function(t){return a(e,t.body)})}}),t.getPrev=function(){return t.link.meta.prevLinkHash?e.getLink(t.link.meta.prevLinkHash):Promise.resolve(null)},t.getBranches=function(r){return e.getBranches(t.meta.linkHash,r)},t.load=function(){return e.getLink(t.meta.linkHash)},t}function u(e){for(var t=re.applicationUrl.replace("%s",e.name)+"/maps",r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return s(t,n).then(function(t){return a(e,t.body)})}function i(e,t){var r=re.applicationUrl.replace("%s",e.name)+"/links/"+t;return o(r).then(function(t){return a(e,t.body)})}function c(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n="";r&&r.length&&(n="?tags="+r.join("&tags="));var s=re.applicationUrl.replace("%s",e.name)+"/maps/"+t+n;return o(s).then(function(t){return t.body.map(function(t){return a(e,t)})})}function f(e){return o(e.url+"/maps").then(function(e){return e.body})}function p(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n="";r&&r.length&&(n="?tags="+r.join("&tags="));var s=re.applicationUrl.replace("%s",e.name)+"/branches/"+t+n;return o(s).then(function(t){return t.body.map(function(t){return a(e,t)})})}function l(e,t){var r=t||re.applicationUrl.replace("%s",e);return o(r).then(function(e){var t=e.body;return t.url=r,t.createMap=u.bind(null,t),t.getLink=i.bind(null,t),t.getMap=c.bind(null,t),t.getBranches=p.bind(null,t),t.getMapIds=f.bind(null,t),t})}function h(e){return l(e.meta.application,e.meta.applicationLocation).then(function(t){var r=e.meta.linkLocation;return o(r).then(function(e){return a(t,e.body)})})}var d=r(function(e){e.exports={processRequest:function(e){var t=e.header("Content-Type"),r=t&&t.indexOf("application/json")!==-1;(null==t||r)&&e.body&&(t||e.header("Content-Type","application/json"),e.body=JSON.stringify(e.body))}}}),y=t(d),b=d.processRequest,m=Object.freeze({default:y,processRequest:b}),v=r(function(e){e.exports={processRequest:function(e){var t=e.header("Accept");null==t&&e.header("Accept","application/json")},processResponse:function(e){if(e.contentType&&/^.*\/(?:.*\+)?json(;|$)/i.test(e.contentType)){var t="string"==typeof e.body?e.body:e.text;t&&(e.body=JSON.parse(t))}}}}),g=t(v),R=v.processRequest,x=v.processResponse,O=Object.freeze({default:g,processRequest:R,processResponse:x}),q=r(function(e){var r=t(m),n=t(O);e.exports={processRequest:function(e){r.processRequest.call(this,e),n.processRequest.call(this,e)},processResponse:function(e){n.processResponse.call(this,e)}}}),k=t(q),j=r(function(e){e.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}}),T=t(j),w=j.processRequest,H=Object.freeze({default:T,processRequest:w}),z=r(function(e){e.exports=window.XMLHttpRequest}),A=t(z),E=Object.freeze({default:A}),L=r(function(e){e.exports=function(e){return function(){var t=Array.prototype.slice.call(arguments,0),r=function(){return e.apply(null,t)};setTimeout(r,0)}}}),U=t(L),P=Object.freeze({default:U}),S=r(function(e){function t(e){var t="string"==typeof e?{url:e}:e||{};this.method=t.method?t.method.toUpperCase():"GET",this.url=t.url,this.headers=t.headers||{},this.body=t.body,this.timeout=t.timeout||0,this.errorOn404=null==t.errorOn404||t.errorOn404,this.onload=t.onload,this.onerror=t.onerror}t.prototype.abort=function(){if(!this.aborted)return this.aborted=!0,this.xhr.abort(),this},t.prototype.header=function(e,t){var r;for(r in this.headers)if(this.headers.hasOwnProperty(r)&&e.toLowerCase()===r.toLowerCase()){if(1===arguments.length)return this.headers[r];delete this.headers[r];break}if(null!=t)return this.headers[e]=t,t},e.exports=t}),C=t(S),M=Object.freeze({default:C}),I=r(function(e){function t(){for(var e={},t=0;t<arguments.length;t++){var r=arguments[t];for(var n in r)r.hasOwnProperty(n)&&(e[n]=r[n])}return e}e.exports=t}),X=t(I),B=Object.freeze({default:X}),D=r(function(e){var r=t(B);e.exports=function(e){var t=e.xhr,n={request:e,xhr:t};try{var o,s,a,u={};if(t.getAllResponseHeaders)for(o=t.getAllResponseHeaders().split("\n"),s=0;s<o.length;s++)(a=o[s].match(/\s*([^\s]+):\s+([^\s]+)/))&&(u[a[1]]=a[2]);n=r(n,{status:t.status,contentType:t.contentType||t.getResponseHeader&&t.getResponseHeader("Content-Type"),headers:u,text:t.responseText,body:t.response||t.responseText})}catch(e){}return n}}),G=t(D),J=Object.freeze({default:G}),K=r(function(e){function r(e){this.request=e.request,this.xhr=e.xhr,this.headers=e.headers||{},this.status=e.status||0,this.text=e.text,this.body=e.body,this.contentType=e.contentType,this.isHttpError=e.status>=400}var n=t(M),o=t(J);r.prototype.header=n.prototype.header,r.fromRequest=function(e){return new r(o(e))},e.exports=r}),N=t(K),_=Object.freeze({default:N}),$=r(function(e){function r(e,t){var r=new Error(e);r.name="RequestError",this.name=r.name,this.message=r.message,r.stack&&(this.stack=r.stack),this.toString=function(){return this.message};for(var n in t)t.hasOwnProperty(n)&&(this[n]=t[n])}var n=t(_),o=t(J),s=t(B);r.prototype=s(Error.prototype),r.prototype.constructor=r,r.create=function(e,t,s){var a=new r(e,s);return n.call(a,o(t)),a},e.exports=r}),F=t($),Q=Object.freeze({default:F}),V=r(function(e){e.exports=function(e){var t,r=!1;return function(){return r||(r=!0,t=e.apply(this,arguments)),t}}}),W=t(V),Y=Object.freeze({default:W}),Z=r(function(e){function r(e,t){function s(r,s){var i,h,d,y,b,m;for(r=new f(p(e,r)),o=0;o<t.length;o++)h=t[o],h.processRequest&&h.processRequest(r);for(o=0;o<t.length;o++)if(h=t[o],h.createXHR){i=h.createXHR(r);break}i=i||new a,r.xhr=i,d=l(u(function(e){clearTimeout(b),i.onload=i.onerror=i.onabort=i.onreadystatechange=i.ontimeout=i.onprogress=null;var a=n(r,e),u=a||c.fromRequest(r);for(o=0;o<t.length;o++)h=t[o],h.processResponse&&h.processResponse(u);a&&r.onerror&&r.onerror(a),!a&&r.onload&&r.onload(u),s&&s(a,a?void 0:u)})),m="onload"in i&&"onerror"in i,i.onload=function(){d()},i.onerror=d,i.onabort=function(){d()},i.onreadystatechange=function(){if(4===i.readyState){if(r.aborted)return d();if(!m){var e;try{e=i.status}catch(e){}var t=0===e?new Error("Internal XHR Error"):null;return d(t)}}},i.ontimeout=function(){},i.onprogress=function(){},i.open(r.method,r.url),r.timeout&&(b=setTimeout(function(){r.timedOut=!0,d();try{i.abort()}catch(e){}},r.timeout));for(y in r.headers)r.headers.hasOwnProperty(y)&&i.setRequestHeader(y,r.headers[y]);return i.send(r.body),r}e=e||{},t=t||[];var h,d=["get","post","put","head","patch","delete"],y=function(e){return function(t,r){return t=new f(t),t.method=e,s(t,r)}};for(o=0;o<d.length;o++)h=d[o],s[h]=y(h);return s.plugins=function(){return t},s.defaults=function(n){return n?r(p(e,n),t):e},s.use=function(){var n=Array.prototype.slice.call(arguments,0);return r(e,t.concat(n))},s.bare=function(){return r()},s.Request=f,s.Response=c,s.RequestError=i,s}function n(e,t){if(e.aborted)return h("Request aborted",e,{name:"Abort"});if(e.timedOut)return h("Request timeout",e,{name:"Timeout"});var r,n=e.xhr,o=Math.floor(n.status/100);switch(o){case 0:case 2:if(!t)return;return h(t.message,e);case 4:if(404===n.status&&!e.errorOn404)return;r="Client";break;case 5:r="Server";break;default:r="HTTP"}var s=r+" Error: The server returned a status of "+n.status+' for the request "'+e.method.toUpperCase()+" "+e.url+'"';return h(s,e)}var o,s=t(H),a=t(E),u=t(P),i=t(Q),c=t(_),f=t(M),p=t(B),l=t(Y),h=i.create;e.exports=r({},[s])}),ee=t(Z),te=ee.use(k),re={baseUrl:"https://stratumn.rocks",applicationUrl:"https://%s.stratumn.rocks"};e.getApplication=l,e.loadLink=h,e.config=re,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.AgentClient=e.AgentClient||{})}(this,function(e){"use strict";function t(e,t){t?console.warn("WARNING: "+e+" is deprecated. Please use "+t+" instead."):console.warn("WARNING: "+e+" is deprecated.")}function n(e){var t=Object.keys(e).reduce(function(t,n){var r=Array.isArray(e[n])?e[n].join("+"):e[n];return t.push(encodeURIComponent(n)+"="+encodeURIComponent(r)),t},[]);return t.length?"?"+t.join("&"):""}function r(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function o(e,t){return t={exports:{}},e(t,t.exports),t.exports}function s(e,t,n){return new Promise(function(r,o){ae({method:e,url:t,body:n},function(e,t){if(e){var n=e&&e.body&&e.body.meta&&e.body.meta.errorMessage?new Error(e.body.meta.errorMessage):e;n.status=e.status,o(n)}else r(t)})})}function u(e){return s("GET",e)}function a(e,t){return s("POST",e,t)}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return u(e.url+"/segments"+n(t)).then(function(t){return t.body.map(function(t){return f(e,t)})})}function c(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t("Agent#getBranches(agent, prevLinkHash, tags = [])","Agent#findSegments(agent, filter)"),i(e,{prevLinkHash:n,tags:r})}function f(e,n){return Object.keys(e.agentInfo.actions).filter(function(e){return["init"].indexOf(e)<0}).forEach(function(t){n[t]=function(){for(var r=arguments.length,o=Array(r),s=0;s<r;s++)o[s]=arguments[s];return a(e.url+"/segments/"+n.meta.linkHash+"/"+t,o).then(function(t){return f(e,t.body)})}}),n.getPrev=function(){return n.link.meta.prevLinkHash?e.getSegment(n.link.meta.prevLinkHash):Promise.resolve(null)},n.load=function(){return t("segment#load()"),Promise.resolve(f(e,{link:JSON.parse(JSON.stringify(n.link)),meta:JSON.parse(JSON.stringify(n.meta))}))},n.getBranches=function(){for(var t=arguments.length,r=Array(t),o=0;o<t;o++)r[o]=arguments[o];return c.apply(void 0,[e,n.meta.linkHash].concat(r))},n}function p(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return a(e.url+"/segments",n).then(function(t){return f(e,t.body)})}function l(e,t){return u(e.url+"/segments/"+t).then(function(t){return f(e,t.body)})}function d(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return u(e.url+"/maps"+n(t)).then(function(e){return e.body})}function h(e,n){return t("Agent#getLink(agent, hash)","Agent#getSegment(agent, hash)"),l(e,n)}function g(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t("getMap(agent, mapId, tags = [])","findSegments(agent, filter)"),i(e,{mapId:n,tags:r})}function m(e){return u(e).then(function(t){var n=t.body;return n.url=e,n.createMap=p.bind(null,n),n.getSegment=l.bind(null,n),n.findSegments=i.bind(null,n),n.getMapIds=d.bind(null,n),n.getBranches=c.bind(null,n),n.getLink=h.bind(null,n),n.getMap=g.bind(null,n),n})}function y(e){return m(e.meta.agentUrl||e.meta.applicationLocation).then(function(t){var n=f(t,e);return{agent:t,segment:n}})}function b(e,n){return t("getApplication(name, url)","getAgent(url)"),m(n||ie.applicationUrl.replace("%s",e))}function v(e){return t("loadLink(obj)","fromSegment(obj)"),y(e).then(function(e){var t=e.segment;return t})}var R=o(function(e){e.exports={processRequest:function(e){var t=e.header("Content-Type"),n=t&&t.indexOf("application/json")!==-1;(null==t||n)&&e.body&&(t||e.header("Content-Type","application/json"),e.body=JSON.stringify(e.body))}}}),x=r(R),O=R.processRequest,q=Object.freeze({default:x,processRequest:O}),j=o(function(e){e.exports={processRequest:function(e){var t=e.header("Accept");null==t&&e.header("Accept","application/json")},processResponse:function(e){if(e.contentType&&/^.*\/(?:.*\+)?json(;|$)/i.test(e.contentType)){var t="string"==typeof e.body?e.body:e.text;t&&(e.body=JSON.parse(t))}}}}),k=r(j),A=j.processRequest,T=j.processResponse,w=Object.freeze({default:k,processRequest:A,processResponse:T}),S=o(function(e){var t=r(q),n=r(w);e.exports={processRequest:function(e){t.processRequest.call(this,e),n.processRequest.call(this,e)},processResponse:function(e){n.processResponse.call(this,e)}}}),H=r(S),C=o(function(e){e.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}}),E=r(C),L=C.processRequest,P=Object.freeze({default:E,processRequest:L}),z=o(function(e){e.exports=window.XMLHttpRequest}),I=r(z),N=Object.freeze({default:I}),M=o(function(e){e.exports=function(e){return function(){var t=Array.prototype.slice.call(arguments,0),n=function(){return e.apply(null,t)};setTimeout(n,0)}}}),U=r(M),J=Object.freeze({default:U}),G=o(function(e){function t(e){var t="string"==typeof e?{url:e}:e||{};this.method=t.method?t.method.toUpperCase():"GET",this.url=t.url,this.headers=t.headers||{},this.body=t.body,this.timeout=t.timeout||0,this.errorOn404=null==t.errorOn404||t.errorOn404,this.onload=t.onload,this.onerror=t.onerror}t.prototype.abort=function(){if(!this.aborted)return this.aborted=!0,this.xhr.abort(),this},t.prototype.header=function(e,t){var n;for(n in this.headers)if(this.headers.hasOwnProperty(n)&&e.toLowerCase()===n.toLowerCase()){if(1===arguments.length)return this.headers[n];delete this.headers[n];break}if(null!=t)return this.headers[e]=t,t},e.exports=t}),X=r(G),B=Object.freeze({default:X}),W=o(function(e){function t(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r])}return e}e.exports=t}),_=r(W),$=Object.freeze({default:_}),D=o(function(e){var t=r($);e.exports=function(e){var n=e.xhr,r={request:e,xhr:n};try{var o,s,u,a={};if(n.getAllResponseHeaders)for(o=n.getAllResponseHeaders().split("\n"),s=0;s<o.length;s++)(u=o[s].match(/\s*([^\s]+):\s+([^\s]+)/))&&(a[u[1]]=u[2]);r=t(r,{status:n.status,contentType:n.contentType||n.getResponseHeader&&n.getResponseHeader("Content-Type"),headers:a,text:n.responseText,body:n.response||n.responseText})}catch(e){}return r}}),F=r(D),K=Object.freeze({default:F}),Q=o(function(e){function t(e){this.request=e.request,this.xhr=e.xhr,this.headers=e.headers||{},this.status=e.status||0,this.text=e.text,this.body=e.body,this.contentType=e.contentType,this.isHttpError=e.status>=400}var n=r(B),o=r(K);t.prototype.header=n.prototype.header,t.fromRequest=function(e){return new t(o(e))},e.exports=t}),V=r(Q),Y=Object.freeze({default:V}),Z=o(function(e){function t(e,t){var n=new Error(e);n.name="RequestError",this.name=n.name,this.message=n.message,n.stack&&(this.stack=n.stack),this.toString=function(){return this.message};for(var r in t)t.hasOwnProperty(r)&&(this[r]=t[r])}var n=r(Y),o=r(K),s=r($);t.prototype=s(Error.prototype),t.prototype.constructor=t,t.create=function(e,r,s){var u=new t(e,s);return n.call(u,o(r)),u},e.exports=t}),ee=r(Z),te=Object.freeze({default:ee}),ne=o(function(e){e.exports=function(e){var t,n=!1;return function(){return n||(n=!0,t=e.apply(this,arguments)),t}}}),re=r(ne),oe=Object.freeze({default:re}),se=o(function(e){function t(e,r){function s(t,s){var i,d,h,g,m,y;for(t=new f(p(e,t)),o=0;o<r.length;o++)d=r[o],d.processRequest&&d.processRequest(t);for(o=0;o<r.length;o++)if(d=r[o],d.createXHR){i=d.createXHR(t);break}i=i||new u,t.xhr=i,h=l(a(function(e){clearTimeout(m),i.onload=i.onerror=i.onabort=i.onreadystatechange=i.ontimeout=i.onprogress=null;var u=n(t,e),a=u||c.fromRequest(t);for(o=0;o<r.length;o++)d=r[o],d.processResponse&&d.processResponse(a);u&&t.onerror&&t.onerror(u),!u&&t.onload&&t.onload(a),s&&s(u,u?void 0:a)})),y="onload"in i&&"onerror"in i,i.onload=function(){h()},i.onerror=h,i.onabort=function(){h()},i.onreadystatechange=function(){if(4===i.readyState){if(t.aborted)return h();if(!y){var e;try{e=i.status}catch(e){}var n=0===e?new Error("Internal XHR Error"):null;return h(n)}}},i.ontimeout=function(){},i.onprogress=function(){},i.open(t.method,t.url),t.timeout&&(m=setTimeout(function(){t.timedOut=!0,h();try{i.abort()}catch(e){}},t.timeout));for(g in t.headers)t.headers.hasOwnProperty(g)&&i.setRequestHeader(g,t.headers[g]);return i.send(t.body),t}e=e||{},r=r||[];var d,h=["get","post","put","head","patch","delete"],g=function(e){return function(t,n){return t=new f(t),t.method=e,s(t,n)}};for(o=0;o<h.length;o++)d=h[o],s[d]=g(d);return s.plugins=function(){return r},s.defaults=function(n){return n?t(p(e,n),r):e},s.use=function(){var n=Array.prototype.slice.call(arguments,0);return t(e,r.concat(n))},s.bare=function(){return t()},s.Request=f,s.Response=c,s.RequestError=i,s}function n(e,t){if(e.aborted)return d("Request aborted",e,{name:"Abort"});if(e.timedOut)return d("Request timeout",e,{name:"Timeout"});var n,r=e.xhr,o=Math.floor(r.status/100);switch(o){case 0:case 2:if(!t)return;return d(t.message,e);case 4:if(404===r.status&&!e.errorOn404)return;n="Client";break;case 5:n="Server";break;default:n="HTTP"}var s=n+" Error: The server returned a status of "+r.status+' for the request "'+e.method.toUpperCase()+" "+e.url+'"';return d(s,e)}var o,s=r(P),u=r(N),a=r(J),i=r(te),c=r(Y),f=r(B),p=r($),l=r(oe),d=i.create;e.exports=t({},[s])}),ue=r(se),ae=ue.use(H),ie={applicationUrl:"https://%s.stratumn.rocks"};e.getAgent=m,e.fromSegment=y,e.getApplication=b,e.loadLink=v,e.config=ie,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
//# sourceMappingURL=stratumn-agent-client.min.js.map |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('httpplease/plugins/json'), require('httpplease')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'httpplease/plugins/json', 'httpplease'], factory) : | ||
(factory((global.StratumnSDK = global.StratumnSDK || {}),global.json,global.httpplease)); | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('httpplease/plugins/json'), require('httpplease')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'httpplease/plugins/json', 'httpplease'], factory) : | ||
(factory((global.AgentClient = global.AgentClient || {}),global.json,global.httpplease)); | ||
}(this, (function (exports,json,httpplease) { 'use strict'; | ||
@@ -18,2 +18,45 @@ | ||
function deprecated(oldFunc, newFunc) { | ||
if (!newFunc) { | ||
console.warn("WARNING: " + oldFunc + " is deprecated."); | ||
} else { | ||
console.warn("WARNING: " + oldFunc + " is deprecated. Please use " + newFunc + " instead."); | ||
} | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
/** | ||
* Makes a query string. | ||
* @param {object} obj - an object of keys | ||
* @returns {string} a query string | ||
*/ | ||
function makeQueryString(obj) { | ||
var parts = Object.keys(obj).reduce(function (curr, key) { | ||
var val = Array.isArray(obj[key]) ? obj[key].join('+') : obj[key]; | ||
curr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); | ||
return curr; | ||
}, []); | ||
if (parts.length) { | ||
return '?' + parts.join('&'); | ||
} | ||
return ''; | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
var request = httpplease.use(json); | ||
@@ -24,4 +67,5 @@ | ||
request({ method: method, url: url, body: args }, function (err, res) { | ||
var error = err || res.body && res.body.meta && res.body.meta.errorMessage; | ||
if (error) { | ||
if (err) { | ||
var error = err && err.body && err.body.meta && err.body.meta.errorMessage ? new Error(err.body.meta.errorMessage) : err; | ||
error.status = err.status; | ||
reject(error); | ||
@@ -51,7 +95,12 @@ } else { | ||
var config = { | ||
baseUrl: 'https://stratumn.rocks', | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
function findSegments(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
}); | ||
} | ||
/* | ||
@@ -65,5 +114,21 @@ Copyright (C) 2017 Stratumn SAS | ||
function linkify(app, obj) { | ||
Object.keys(app.agentInfo.functions).filter(function (key) { | ||
return ['init', 'catchAll'].indexOf(key) < 0; | ||
function getBranches(agent, prevLinkHash) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
deprecated('Agent#getBranches(agent, prevLinkHash, tags = [])', 'Agent#findSegments(agent, filter)'); | ||
return findSegments(agent, { prevLinkHash: prevLinkHash, tags: tags }); | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
function segmentify(agent, obj) { | ||
Object.keys(agent.agentInfo.actions).filter(function (key) { | ||
return ['init'].indexOf(key) < 0; | ||
}).forEach(function (key) { | ||
@@ -76,7 +141,4 @@ /*eslint-disable*/ | ||
var url = config.applicationUrl.replace('%s', app.name) + '/links/' + obj.meta.linkHash + '/' + key; | ||
/*eslint-enable*/ | ||
return post(url, args).then(function (res) { | ||
return linkify(app, res.body); | ||
return post(agent.url + '/segments/' + obj.meta.linkHash + '/' + key, args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -90,3 +152,3 @@ }; | ||
if (obj.link.meta.prevLinkHash) { | ||
return app.getLink(obj.link.meta.prevLinkHash); | ||
return agent.getSegment(obj.link.meta.prevLinkHash); | ||
} | ||
@@ -97,12 +159,22 @@ | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.getBranches = function (tags) { | ||
obj.load = function () { | ||
/*eslint-enable*/ | ||
return app.getBranches(obj.meta.linkHash, tags); | ||
deprecated('segment#load()'); | ||
return Promise.resolve(segmentify(agent, { | ||
link: JSON.parse(JSON.stringify(obj.link)), | ||
meta: JSON.parse(JSON.stringify(obj.meta)) | ||
})); | ||
}; | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.load = function () { | ||
obj.getBranches = function () { | ||
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
/*eslint-enable*/ | ||
return app.getLink(obj.meta.linkHash); | ||
return getBranches.apply(undefined, [agent, obj.meta.linkHash].concat(args)); | ||
}; | ||
@@ -121,5 +193,3 @@ | ||
function createMap(app) { | ||
var url = config.applicationUrl.replace('%s', app.name) + '/maps'; | ||
function createMap(agent) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
@@ -129,4 +199,4 @@ args[_key - 1] = arguments[_key]; | ||
return post(url, args).then(function (res) { | ||
return linkify(app, res.body); | ||
return post(agent.url + '/segments', args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -143,7 +213,5 @@ } | ||
function getLink(app, linkHash) { | ||
var url = config.applicationUrl.replace('%s', app.name) + '/links/' + linkHash; | ||
return get(url).then(function (res) { | ||
return linkify(app, res.body); | ||
function getSegment(agent, linkHash) { | ||
return get(agent.url + '/segments/' + linkHash).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
@@ -160,18 +228,22 @@ } | ||
function getMap(app, mapId) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
function getMapIds(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var query = ''; | ||
return get(agent.url + '/maps' + makeQueryString(opts)).then(function (res) { | ||
return res.body; | ||
}); | ||
} | ||
if (tags && tags.length) { | ||
query = '?tags=' + tags.join('&tags='); | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
var url = config.applicationUrl.replace('%s', app.name) + '/maps/' + mapId + query; | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
return get(url).then(function (res) { | ||
return res.body.map(function (link) { | ||
return linkify(app, link); | ||
}); | ||
}); | ||
function getLink(agent, hash) { | ||
deprecated('Agent#getLink(agent, hash)', 'Agent#getSegment(agent, hash)'); | ||
return getSegment(agent, hash); | ||
} | ||
@@ -187,6 +259,8 @@ | ||
function getMapIds(agent) { | ||
return get(agent.url + '/maps').then(function (res) { | ||
return res.body; | ||
}); | ||
function getMap(agent, mapId) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
deprecated('getMap(agent, mapId, tags = [])', 'findSegments(agent, filter)'); | ||
return findSegments(agent, { mapId: mapId, tags: tags }); | ||
} | ||
@@ -202,17 +276,34 @@ | ||
function getBranches(app, linkHash) { | ||
var tags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; | ||
// Deprecated. | ||
function getAgent(url) { | ||
return get(url).then(function (res) { | ||
var agent = res.body; | ||
var query = ''; | ||
agent.url = url; | ||
agent.createMap = createMap.bind(null, agent); | ||
agent.getSegment = getSegment.bind(null, agent); | ||
agent.findSegments = findSegments.bind(null, agent); | ||
agent.getMapIds = getMapIds.bind(null, agent); | ||
if (tags && tags.length) { | ||
query = '?tags=' + tags.join('&tags='); | ||
} | ||
// Deprecated. | ||
agent.getBranches = getBranches.bind(null, agent); | ||
agent.getLink = getLink.bind(null, agent); | ||
agent.getMap = getMap.bind(null, agent); | ||
var url = config.applicationUrl.replace('%s', app.name) + '/branches/' + linkHash + query; | ||
return agent; | ||
}); | ||
} | ||
return get(url).then(function (res) { | ||
return res.body.map(function (link) { | ||
return linkify(app, link); | ||
}); | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
function fromSegment(obj) { | ||
return getAgent(obj.meta.agentUrl || obj.meta.applicationLocation).then(function (agent) { | ||
var segment = segmentify(agent, obj); | ||
return { agent: agent, segment: segment }; | ||
}); | ||
@@ -229,17 +320,19 @@ } | ||
function getApplication(appName, appLocation) { | ||
var url = appLocation || config.applicationUrl.replace('%s', appName); | ||
// Deprecated. | ||
var config = { | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
return get(url).then(function (res) { | ||
var app = res.body; | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
app.url = url; | ||
app.createMap = createMap.bind(null, app); | ||
app.getLink = getLink.bind(null, app); | ||
app.getMap = getMap.bind(null, app); | ||
app.getBranches = getBranches.bind(null, app); | ||
app.getMapIds = getMapIds.bind(null, app); | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
return app; | ||
}); | ||
function getApplication(name, url) { | ||
deprecated('getApplication(name, url)', 'getAgent(url)'); | ||
return getAgent(url || config.applicationUrl.replace('%s', name)); | ||
} | ||
@@ -255,12 +348,13 @@ | ||
function loadLink(segment) { | ||
return getApplication(segment.meta.application, segment.meta.applicationLocation).then(function (app) { | ||
var url = segment.meta.linkLocation; | ||
function loadLink(obj) { | ||
deprecated('loadLink(obj)', 'fromSegment(obj)'); | ||
return get(url).then(function (res) { | ||
return linkify(app, res.body); | ||
return fromSegment(obj).then(function (_ref) { | ||
var segment = _ref.segment; | ||
return segment; | ||
}); | ||
}); | ||
} | ||
exports.getAgent = getAgent; | ||
exports.fromSegment = fromSegment; | ||
exports.getApplication = getApplication; | ||
@@ -267,0 +361,0 @@ exports.loadLink = loadLink; |
{ | ||
"name": "stratumn-agent-client", | ||
"version": "0.7.0", | ||
"version": "1.5.0", | ||
"description": "Stratumn Indigo agent client library", | ||
@@ -36,5 +36,5 @@ "main": "lib/stratumn-agent-client.js", | ||
"bugs": { | ||
"url": "https://github.com/stratumn/stratumn-agent-client-js/issues" | ||
"url": "https://github.com/stratumn/agent-client-js/issues" | ||
}, | ||
"homepage": "https://github.com/stratumn/stratumn-agent-client-js", | ||
"homepage": "https://github.com/stratumn/agent-client-js", | ||
"devDependencies": { | ||
@@ -61,3 +61,4 @@ "babel-cli": "^6.5.1", | ||
"rollup-pluginutils": "^1.5.1", | ||
"should": "^8.2.2" | ||
"should": "^8.2.2", | ||
"stratumn-agent": "^0.12.3" | ||
}, | ||
@@ -64,0 +65,0 @@ "dependencies": { |
221
README.md
@@ -1,6 +0,6 @@ | ||
# Stratumn SDK for Javascript | ||
# Stratumn SDK for Javascript [ALPHA - incompatible with production] | ||
[![npm version](https://badge.fury.io/js/stratumn-agent-client.svg)](https://badge.fury.io/js/stratumn-agent-client) | ||
[![Bower version](https://badge.fury.io/bo/stratumn-agent-client.svg)](https://badge.fury.io/bo/stratumn-agent-client) | ||
[![build status](https://travis-ci.org/stratumn/stratumn-agent-client-js.svg?branch=master)](https://travis-ci.org/stratumn/stratumn-agent-client-js.svg?branch=master) | ||
[![Build Status](https://travis-ci.org/stratumn/agent-client-js.svg?branch=alpha)](https://travis-ci.org/stratumn/agent-client-js) | ||
[![codecov](https://codecov.io/gh/stratumn/agent-client-js/branch/alpha/graph/badge.svg)](https://codecov.io/gh/stratumn/agent-client-js/branch/alpha) | ||
[![Build Status](https://david-dm.org/stratumn/agent-client-js.svg?branch=alpha)](https://david-dm.org/stratumn/agent-client-js) | ||
@@ -18,12 +18,18 @@ ## Installation | ||
If you want a specific version, include `https://libs.stratumn.com/stratumn-agent-client-{version}.min.js` instead (for instance `https://libs.stratumn.com/stratumn-agent-client-0.4.1.min.js`). | ||
If you want a specific version, include `https://libs.stratumn.com/stratumn-agent-client-{version}.min.js` instead (for instance `https://libs.stratumn.com/stratumn-agent-client-1.0.2.min.js`). | ||
### Bower | ||
``` | ||
$ bower install stratumn-agent-client | ||
``` | ||
### Node.js | ||
``` | ||
$ npm install stratumn-agent-client | ||
$ npm install stratumn-agent-client@alpha | ||
``` | ||
```javascript | ||
var StratumnSDK = require('stratumn-agent-client'); | ||
var AgentClient = require('stratumn-agent-client'); | ||
``` | ||
@@ -34,15 +40,15 @@ | ||
```javascript | ||
StratumnSDK.getApplication('quickstart') | ||
.then(function(app) { | ||
console.log(app); | ||
AgentClient.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
console.log(agent); | ||
// Create a new map, you can pass arguments to init | ||
return app.createMap('My message map'); | ||
return agent.createMap('My conversation'); | ||
}) | ||
.then(function(res) { | ||
// You can call a transition function like a regular function | ||
return res.addMessage('Hello, World'); | ||
.then(function(segment) { | ||
// You can call an action like a regular function | ||
return segment.addMessage('Hello, World'); | ||
}) | ||
.then(function(res) { | ||
console.log(res.link); | ||
console.log(res.meta); | ||
.then(function(segment) { | ||
console.log(segment.link); | ||
console.log(segment.meta); | ||
}) | ||
@@ -56,11 +62,11 @@ .catch(function(err) { | ||
### StratumnSDK#getApplication(appName) | ||
### AgentClient#getAgent(url) | ||
Returns a promise that resolves with an application. | ||
Returns a promise that resolves with an agent client. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
console.log(app.id); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
console.log(agent); | ||
}) | ||
@@ -72,14 +78,12 @@ .catch(function(err) { | ||
### Application#createMap(...args) | ||
### AgentClient#fromSegment(rawSegment) | ||
Returns a promise that resolves with a new map. | ||
Returns a promise that resolves with the agent and segment from a given raw object. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.createMap('A new map'); | ||
}) | ||
AgentClient | ||
.fromSegment(someRawSegment) | ||
.then(function(res) { | ||
console.log(res); | ||
console.log(res.agent); | ||
console.log(res.segment); | ||
}) | ||
@@ -91,14 +95,14 @@ .catch(function(err) { | ||
### Application#getLink(hash) | ||
### Agent#createMap(...args) | ||
Returns a promise that resolves with an existing link. | ||
Returns a promise that resolves with a the first segment of a map. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getLink('aee5427'); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.createMap('A new map'); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
.then(function(segment) { | ||
console.log(segment); | ||
}) | ||
@@ -110,15 +114,14 @@ .catch(function(err) { | ||
### Application#getMap(mapId, tags) | ||
### Agent#getSegment(linkHash) | ||
Returns a promise that resolves with the meta data of the links in a map, | ||
optionally filters by tags. | ||
Returns a promise that resolves with an existing segment. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getMap('56ef33', ['tag1', 'tag2']); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.getSegment('aee5427'); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
.then(function(segment) { | ||
console.log(segment); | ||
}) | ||
@@ -130,33 +133,22 @@ .catch(function(err) { | ||
### Application#getBranches(linkHash, tags) | ||
### Agent#findSegments(opts) | ||
Returns a promise that resolves with the meta data of the links whose previous hashes | ||
are the given hash, optionally filters by tags. | ||
Returns a promise that resolves with existing segments. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getBranches('abcdef', ['tag1', 'tag2']); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
}) | ||
.catch(function(err) { | ||
// Handle errors | ||
}); | ||
``` | ||
Available options are: | ||
### Application#getMapIds() | ||
- `offset`: offset of first returned segments | ||
- `limit`: limit number of returned segments | ||
- `mapId`: return segments with specified map ID | ||
- `prevLinkHash`: return segments with specified previous link hash | ||
- `tags`: return segments that contains all the tags (array) | ||
Returns a promise that resolves with all the map ids in this application. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getMapIds(); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.findSegments({ tags: ['tag1', 'tag2'], offset: 20, limit: 10 }); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
.then(function(segments) { | ||
console.log(segments); | ||
}) | ||
@@ -168,40 +160,20 @@ .catch(function(err) { | ||
### Link#getPrev() | ||
### Agent#getMapIds(opts) | ||
Returns a promise that resolves with the previous link of a link. | ||
Returns a promise that resolves with existing map IDs. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getLink('aee5427'); | ||
}) | ||
.then(function(res) { | ||
return res.getPrev(); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
}) | ||
.catch(function(err) { | ||
// Handle errors | ||
}); | ||
``` | ||
Available options are: | ||
### Link#load() | ||
- `offset`: offset of first returned map ID | ||
- `limit`: limit number of returned map ID | ||
Returns a promise that resolves with the full link. | ||
Can be useful when you only have the meta data of links. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getBranches('aee5427'); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.findSegments({ offset: 20, limit: 10 }); | ||
}) | ||
.then(function(res) { | ||
return Promise.all(res.map(function(link) { return link.load(); })); | ||
.then(function(mapIDs) { | ||
console.log(mapIDs); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
}) | ||
.catch(function(err) { | ||
@@ -212,18 +184,17 @@ // Handle errors | ||
### Link#getBranches(tags) | ||
### Segment#getPrev() | ||
Returns a promise that resolves with the meta data of the links whose previous hashes | ||
are the hash of the link, optionally filters by tags. | ||
Returns a promise that resolves with the previous segment. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getLink('aee5427'); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.getSegment('aee5427'); | ||
}) | ||
.then(function(res) { | ||
return res.getBranches(['tag1']); | ||
.then(function(segment) { | ||
return segment.getPrev(); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
.then(function(segment) { | ||
console.log(segment); | ||
}) | ||
@@ -235,17 +206,17 @@ .catch(function(err) { | ||
### Link#:transitionFunction(...args) | ||
### Segment#:actionName(...args) | ||
Executes a transition function and returns a promise that resolves with a new link. | ||
Executes an action and returns a promise that resolves with a new segment. | ||
```javascript | ||
StratumnSDK | ||
.getApplication('quickstart') | ||
.then(function(app) { | ||
return app.getLink('aee5427'); | ||
AgentClient | ||
.getAgent('http://localhost:3000') | ||
.then(function(agent) { | ||
return agent.getSegment('aee5427'); | ||
}) | ||
.then(function(res) { | ||
return res.addMessage('Hello, World!'); | ||
.then(function(segment) { | ||
return segment.addMessage('Hello, World!'); | ||
}) | ||
.then(function(res) { | ||
console.log(res); | ||
.then(function(segment) { | ||
console.log(segment); | ||
}) | ||
@@ -252,0 +223,0 @@ .catch(function(err) { |
@@ -12,3 +12,3 @@ import babel from 'rollup-plugin-babel'; | ||
entry: 'src/index.js', | ||
moduleName: 'StratumnSDK' | ||
moduleName: 'AgentClient' | ||
}; |
@@ -9,7 +9,5 @@ /* | ||
const config = { | ||
baseUrl: 'https://stratumn.rocks', | ||
// Deprecated. | ||
export default { | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
export default config; |
@@ -9,11 +9,8 @@ /* | ||
import segmentify from './segmentify'; | ||
import { post } from './request'; | ||
import config from './config'; | ||
import linkify from './linkify'; | ||
export default function createMap(app, ...args) { | ||
const url = `${config.applicationUrl.replace('%s', app.name)}/maps`; | ||
return post(url, args) | ||
.then(res => linkify(app, res.body)); | ||
export default function createMap(agent, ...args) { | ||
return post(`${agent.url}/segments`, args) | ||
.then(res => segmentify(agent, res.body)); | ||
} |
@@ -9,26 +9,10 @@ /* | ||
import { get } from './request'; | ||
import getAgent from './getAgent'; | ||
import deprecated from './deprecated'; | ||
import config from './config'; | ||
import createMap from './createMap'; | ||
import getLink from './getLink'; | ||
import getMap from './getMap'; | ||
import getMapIds from './getMapIds'; | ||
import getBranches from './getBranches'; | ||
export default function getApplication(appName, appLocation) { | ||
const url = appLocation || config.applicationUrl.replace('%s', appName); | ||
export default function getApplication(name, url) { | ||
deprecated('getApplication(name, url)', 'getAgent(url)'); | ||
return get(url) | ||
.then(res => { | ||
const app = res.body; | ||
app.url = url; | ||
app.createMap = createMap.bind(null, app); | ||
app.getLink = getLink.bind(null, app); | ||
app.getMap = getMap.bind(null, app); | ||
app.getBranches = getBranches.bind(null, app); | ||
app.getMapIds = getMapIds.bind(null, app); | ||
return app; | ||
}); | ||
return getAgent(url || config.applicationUrl.replace('%s', name)); | ||
} |
@@ -9,17 +9,12 @@ /* | ||
import { get } from './request'; | ||
import config from './config'; | ||
import linkify from './linkify'; | ||
import findSegments from './findSegments'; | ||
import deprecated from './deprecated'; | ||
export default function getBranches(app, linkHash, tags = []) { | ||
let query = ''; | ||
export default function getBranches(agent, prevLinkHash, tags = []) { | ||
deprecated( | ||
'Agent#getBranches(agent, prevLinkHash, tags = [])', | ||
'Agent#findSegments(agent, filter)' | ||
); | ||
if (tags && tags.length) { | ||
query = `?tags=${tags.join('&tags=')}`; | ||
} | ||
const url = `${config.applicationUrl.replace('%s', app.name)}/branches/${linkHash}${query}`; | ||
return get(url) | ||
.then(res => res.body.map((link) => linkify(app, link))); | ||
return findSegments(agent, { prevLinkHash, tags }); | ||
} |
@@ -9,11 +9,9 @@ /* | ||
import { get } from './request'; | ||
import config from './config'; | ||
import linkify from './linkify'; | ||
import getSegment from './getSegment'; | ||
import deprecated from './deprecated'; | ||
export default function getLink(app, linkHash) { | ||
const url = `${config.applicationUrl.replace('%s', app.name)}/links/${linkHash}`; | ||
export default function getLink(agent, hash) { | ||
deprecated('Agent#getLink(agent, hash)', 'Agent#getSegment(agent, hash)'); | ||
return get(url) | ||
.then(res => linkify(app, res.body)); | ||
return getSegment(agent, hash); | ||
} |
@@ -9,17 +9,9 @@ /* | ||
import { get } from './request'; | ||
import config from './config'; | ||
import linkify from './linkify'; | ||
import findSegments from './findSegments'; | ||
import deprecated from './deprecated'; | ||
export default function getMap(app, mapId, tags = []) { | ||
let query = ''; | ||
export default function getMap(agent, mapId, tags = []) { | ||
deprecated('getMap(agent, mapId, tags = [])', 'findSegments(agent, filter)'); | ||
if (tags && tags.length) { | ||
query = `?tags=${tags.join('&tags=')}`; | ||
} | ||
const url = `${config.applicationUrl.replace('%s', app.name)}/maps/${mapId}${query}`; | ||
return get(url) | ||
.then(res => res.body.map((link) => linkify(app, link))); | ||
return findSegments(agent, { mapId, tags }); | ||
} |
@@ -9,7 +9,8 @@ /* | ||
import makeQueryString from './makeQueryString'; | ||
import { get } from './request'; | ||
export default function getMapIds(agent) { | ||
return get(`${agent.url}/maps`) | ||
export default function getMapIds(agent, opts = {}) { | ||
return get(`${agent.url}/maps${makeQueryString(opts)}`) | ||
.then(res => res.body); | ||
} |
@@ -9,4 +9,8 @@ /* | ||
export { default as getAgent } from './getAgent'; | ||
export { default as fromSegment } from './fromSegment'; | ||
// Deprecated. | ||
export { default as getApplication } from './getApplication'; | ||
export { default as loadLink } from './loadLink'; | ||
export { default as config } from './config'; |
@@ -9,13 +9,10 @@ /* | ||
import { get } from './request'; | ||
import linkify from './linkify'; | ||
import getApplication from './getApplication'; | ||
import fromSegment from './fromSegment'; | ||
import deprecated from './deprecated'; | ||
export default function loadLink(segment) { | ||
return getApplication(segment.meta.application, segment.meta.applicationLocation) | ||
.then(app => { | ||
const url = segment.meta.linkLocation; | ||
export default function loadLink(obj) { | ||
deprecated('loadLink(obj)', 'fromSegment(obj)'); | ||
return get(url).then(res => linkify(app, res.body)); | ||
}); | ||
return fromSegment(obj) | ||
.then(({ segment }) => segment); | ||
} |
@@ -17,4 +17,7 @@ /* | ||
request({ method, url, body: args }, (err, res) => { | ||
const error = err || (res.body && res.body.meta && res.body.meta.errorMessage); | ||
if (error) { | ||
if (err) { | ||
const error = (err && err.body && err.body.meta && err.body.meta.errorMessage) | ||
? new Error(err.body.meta.errorMessage) | ||
: err; | ||
error.status = err.status; | ||
reject(error); | ||
@@ -21,0 +24,0 @@ } else { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
203105
41
1682
1
22
3
268