particle-api-js 10.0.0 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/EventStream-e2e-browser.html +0 -1
  3. package/EventStream-e2e-node.js +2 -3
  4. package/README.md +2 -2
  5. package/dist/particle.min.js +1 -434
  6. package/dist/particle.min.js.map +1 -1
  7. package/docs/api.md +4916 -266
  8. package/karma.conf.js +18 -6
  9. package/package.json +18 -22
  10. package/src/Agent.js +407 -0
  11. package/src/Client.js +170 -0
  12. package/src/Defaults.js +7 -0
  13. package/src/EventStream.js +263 -0
  14. package/src/Library.js +33 -0
  15. package/src/Particle.js +2644 -0
  16. package/test/Agent.integration.js +2 -3
  17. package/test/Agent.spec.js +2 -2
  18. package/test/Client.spec.js +7 -7
  19. package/test/Defaults.spec.js +2 -2
  20. package/test/EventStream.spec.js +6 -4
  21. package/test/FakeAgent.js +2 -2
  22. package/test/Library.spec.js +2 -2
  23. package/test/Particle.integration.js +2 -3
  24. package/test/Particle.spec.js +54 -54
  25. package/test/fixtures/index.js +4 -18
  26. package/test/support/FixtureHttpServer.js +5 -3
  27. package/test/test-setup.js +5 -5
  28. package/tsconfig.json +14 -0
  29. package/webpack.config.js +45 -0
  30. package/.babelrc +0 -4
  31. package/lib/Agent.js +0 -615
  32. package/lib/Agent.js.map +0 -1
  33. package/lib/Client.js +0 -312
  34. package/lib/Client.js.map +0 -1
  35. package/lib/Defaults.js +0 -14
  36. package/lib/Defaults.js.map +0 -1
  37. package/lib/EventStream.js +0 -335
  38. package/lib/EventStream.js.map +0 -1
  39. package/lib/Library.js +0 -67
  40. package/lib/Library.js.map +0 -1
  41. package/lib/Particle.js +0 -3831
  42. package/lib/Particle.js.map +0 -1
  43. package/test/Client.integration.js +0 -69
  44. package/test/fixtures/tarball.tar.gz +0 -0
  45. package/test/fixtures/test-library-publish-0.0.1.tar.gz +0 -0
  46. package/test/fixtures/test-library-publish-0.0.2.tar.gz +0 -0
package/lib/Agent.js DELETED
@@ -1,615 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
-
7
- var _keys = require('babel-runtime/core-js/object/keys');
8
-
9
- var _keys2 = _interopRequireDefault(_keys);
10
-
11
- var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');
12
-
13
- var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
14
-
15
- var _entries = require('babel-runtime/core-js/object/entries');
16
-
17
- var _entries2 = _interopRequireDefault(_entries);
18
-
19
- var _getIterator2 = require('babel-runtime/core-js/get-iterator');
20
-
21
- var _getIterator3 = _interopRequireDefault(_getIterator2);
22
-
23
- var _stringify = require('babel-runtime/core-js/json/stringify');
24
-
25
- var _stringify2 = _interopRequireDefault(_stringify);
26
-
27
- var _assign = require('babel-runtime/core-js/object/assign');
28
-
29
- var _assign2 = _interopRequireDefault(_assign);
30
-
31
- var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
32
-
33
- var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
34
-
35
- var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
36
-
37
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
38
-
39
- var _createClass2 = require('babel-runtime/helpers/createClass');
40
-
41
- var _createClass3 = _interopRequireDefault(_createClass2);
42
-
43
- var _nodeFetch = require('node-fetch');
44
-
45
- var _nodeFetch2 = _interopRequireDefault(_nodeFetch);
46
-
47
- var _formData = require('form-data');
48
-
49
- var _formData2 = _interopRequireDefault(_formData);
50
-
51
- var _qs = require('qs');
52
-
53
- var _qs2 = _interopRequireDefault(_qs);
54
-
55
- var _fs = require('../fs');
56
-
57
- var _fs2 = _interopRequireDefault(_fs);
58
-
59
- var _package = require('../package.json');
60
-
61
- var _package2 = _interopRequireDefault(_package);
62
-
63
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
64
-
65
- /**
66
- * The object returned for a basic request
67
- * @typedef {object} JSONResponse
68
- * @property {number} statusCode The HTTP response status
69
- * @property {object} body The endpoint's response parsed as a JSON
70
- */
71
-
72
- /**
73
- * The possible response from an API request
74
- * @typedef {JSONResponse|Buffer|arrayBuffer} RequestResponse The type is based on
75
- * the request config and whether is on browser or node
76
- */
77
-
78
- /**
79
- * The error object generated in case of a failed request
80
- * @typedef {object} RequestError
81
- * @property {number} statusCode The HTTP response status
82
- * @property {string} errorDescription Details on what caused the failed request
83
- * @property {string} shortErrorDescription Summarized version of the fail reason
84
- * @property {object} body The response object from the request
85
- * @property {object} error The error object from the request
86
- */
87
-
88
- var Agent = function () {
89
- function Agent(baseUrl) {
90
- (0, _classCallCheck3.default)(this, Agent);
91
-
92
- this.setBaseUrl(baseUrl);
93
- }
94
-
95
- (0, _createClass3.default)(Agent, [{
96
- key: 'setBaseUrl',
97
- value: function setBaseUrl(baseUrl) {
98
- this.baseUrl = baseUrl;
99
- }
100
-
101
- /**
102
- * Make a GET request
103
- * @param {string} uri The URI to request
104
- * @param {string} [auth] Authorization token to use
105
- * @param {object} [headers] Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
106
- * @param {object} [query] Key/Value pairs of query params
107
- * @param {object} [context] The invocation context, describing the tool and project
108
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
109
- */
110
-
111
- }, {
112
- key: 'get',
113
- value: function get(_ref) {
114
- var uri = _ref.uri,
115
- auth = _ref.auth,
116
- headers = _ref.headers,
117
- query = _ref.query,
118
- context = _ref.context;
119
-
120
- return this.request({ uri: uri, method: 'get', auth: auth, headers: headers, query: query, context: context });
121
- }
122
-
123
- /**
124
- * Make a HEAD request
125
- * @param {string} uri The URI to request
126
- * @param {string} [auth] Authorization token to use
127
- * @param {object} [headers] Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
128
- * @param {object} [query] Key/Value pairs of query params
129
- * @param {object} [context] The invocation context, describing the tool and project
130
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
131
- */
132
-
133
- }, {
134
- key: 'head',
135
- value: function head(_ref2) {
136
- var uri = _ref2.uri,
137
- auth = _ref2.auth,
138
- headers = _ref2.headers,
139
- query = _ref2.query,
140
- context = _ref2.context;
141
-
142
- return this.request({ uri: uri, method: 'head', auth: auth, headers: headers, query: query, context: context });
143
- }
144
-
145
- /**
146
- * Make a POST request
147
- * @param {string} uri The URI to request
148
- * @param {string} [auth] Authorization token to use
149
- * @param {object} [headers] Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
150
- * @param {object} [data] Payload to send in the request body in JSON format
151
- * @param {object} [context] The invocation context, describing the tool and project
152
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
153
- */
154
-
155
- }, {
156
- key: 'post',
157
- value: function post(_ref3) {
158
- var uri = _ref3.uri,
159
- headers = _ref3.headers,
160
- data = _ref3.data,
161
- auth = _ref3.auth,
162
- context = _ref3.context;
163
-
164
- return this.request({ uri: uri, method: 'post', auth: auth, headers: headers, data: data, context: context });
165
- }
166
-
167
- /**
168
- * Make a PUT request
169
- * @param {string} uri The URI to request
170
- * @param {string} [auth] Authorization token to use
171
- * @param {object} [headers] Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
172
- * @param {object} [data] Payload to send in the request body in JSON format
173
- * @param {object} [context] The invocation context, describing the tool and project
174
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
175
- */
176
-
177
- }, {
178
- key: 'put',
179
- value: function put(_ref4) {
180
- var uri = _ref4.uri,
181
- auth = _ref4.auth,
182
- headers = _ref4.headers,
183
- data = _ref4.data,
184
- context = _ref4.context;
185
-
186
- return this.request({ uri: uri, method: 'put', auth: auth, headers: headers, data: data, context: context });
187
- }
188
-
189
- /**
190
- * Make a DELETE request
191
- * @param {string} uri The URI to request
192
- * @param {string} [auth] Authorization token to use
193
- * @param {object} [headers] Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
194
- * @param {object} [data] Payload to send in the request body in JSON format
195
- * @param {object} [context] The invocation context, describing the tool and project
196
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
197
- */
198
-
199
- }, {
200
- key: 'delete',
201
- value: function _delete(_ref5) {
202
- var uri = _ref5.uri,
203
- auth = _ref5.auth,
204
- headers = _ref5.headers,
205
- data = _ref5.data,
206
- context = _ref5.context;
207
-
208
- return this.request({ uri: uri, method: 'delete', auth: auth, headers: headers, data: data, context: context });
209
- }
210
-
211
- /**
212
- *
213
- * @param {Object} config An obj with all the possible request configurations
214
- * @param {String} config.uri The URI to request
215
- * @param {String} config.method The method used to request the URI, should be in uppercase.
216
- * @param {Object} config.headers Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.
217
- * @param {Object} config.data Arbitrary data to send as the body.
218
- * @param {Object} config.auth Authorization
219
- * @param {String} config.query Query parameters
220
- * @param {Object} config.form Form fields
221
- * @param {Object} config.files array of file names and file content
222
- * @param {Object} config.context the invocation context, describing the tool and project.
223
- * @param {boolean} config.isBuffer Indicate if the response should be treated as Buffer instead of JSON
224
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
225
- */
226
-
227
- }, {
228
- key: 'request',
229
- value: function request(_ref6) {
230
- var uri = _ref6.uri,
231
- method = _ref6.method,
232
- _ref6$headers = _ref6.headers,
233
- headers = _ref6$headers === undefined ? undefined : _ref6$headers,
234
- _ref6$data = _ref6.data,
235
- data = _ref6$data === undefined ? undefined : _ref6$data,
236
- auth = _ref6.auth,
237
- _ref6$query = _ref6.query,
238
- query = _ref6$query === undefined ? undefined : _ref6$query,
239
- _ref6$form = _ref6.form,
240
- form = _ref6$form === undefined ? undefined : _ref6$form,
241
- _ref6$files = _ref6.files,
242
- files = _ref6$files === undefined ? undefined : _ref6$files,
243
- _ref6$context = _ref6.context,
244
- context = _ref6$context === undefined ? undefined : _ref6$context,
245
- _ref6$isBuffer = _ref6.isBuffer,
246
- isBuffer = _ref6$isBuffer === undefined ? false : _ref6$isBuffer;
247
-
248
- var requestFiles = this._sanitizeFiles(files);
249
- var requestParams = this._buildRequest({ uri: uri, method: method, headers: headers, data: data, auth: auth, query: query, form: form, context: context, files: requestFiles });
250
- return this._promiseResponse(requestParams, isBuffer);
251
- }
252
-
253
- /**
254
- * Promises to send the request and retreive the response.
255
- * @param {[string, object]} requestParams First argument is the URI to request, the second one are the options.
256
- * @param {boolean} isBuffer Indicate if the response body should be returned as a Buffer (Node) / ArrayBuffer (browser) instead of JSON
257
- * @param {Fetch} [makerequest] The fetch function to use. Override for testing.
258
- * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object
259
- * @private
260
- */
261
-
262
- }, {
263
- key: '_promiseResponse',
264
- value: function _promiseResponse(requestParams, isBuffer) {
265
- var _this = this;
266
-
267
- var makerequest = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _nodeFetch2.default;
268
-
269
- var status = void 0;
270
- return makerequest.apply(undefined, (0, _toConsumableArray3.default)(requestParams)).then(function (resp) {
271
- status = resp.status;
272
- if (!resp.ok) {
273
- return resp.text().then(function (err) {
274
- var objError = JSON.parse(err);
275
- // particle-commnds/src/cmd/api expects response.text. to be a string
276
- var response = (0, _assign2.default)(resp, { text: err });
277
- throw (0, _assign2.default)(objError, { response: response });
278
- });
279
- }
280
- if (status === 204) {
281
- // Can't do resp.json() since there is no body to parse
282
- return '';
283
- }
284
- if (isBuffer) {
285
- return resp.blob();
286
- }
287
- return resp.json();
288
- }).then(function (body) {
289
- if (isBuffer) {
290
- return body.arrayBuffer().then(function (arrayBuffer) {
291
- if (!_this.isForBrowser()) {
292
- return Buffer.from(arrayBuffer);
293
- }
294
- return arrayBuffer;
295
- });
296
- }
297
- return {
298
- body: body,
299
- statusCode: status
300
- };
301
- }).catch(function (error) {
302
- var errorType = status ? 'HTTP error ' + status : 'Network error';
303
- var errorDescription = errorType + ' from ' + requestParams[0];
304
- var shortErrorDescription = void 0;
305
- if (error.error_description) {
306
- // Fetch responded with ok false
307
- errorDescription = errorDescription + ' - ' + error.error_description;
308
- shortErrorDescription = error.error_description;
309
- }
310
- var reason = new Error(errorDescription);
311
- (0, _assign2.default)(reason, {
312
- statusCode: status,
313
- errorDescription: errorDescription,
314
- shortErrorDescription: shortErrorDescription,
315
- error: error,
316
- body: error
317
- });
318
- throw reason;
319
- });
320
- }
321
- }, {
322
- key: '_buildRequest',
323
- value: function _buildRequest(_ref7) {
324
- var uri = _ref7.uri,
325
- method = _ref7.method,
326
- headers = _ref7.headers,
327
- data = _ref7.data,
328
- auth = _ref7.auth,
329
- query = _ref7.query,
330
- form = _ref7.form,
331
- files = _ref7.files,
332
- context = _ref7.context;
333
-
334
- var actualUri = uri;
335
- if (this.baseUrl && uri[0] === '/') {
336
- actualUri = '' + this.baseUrl + uri;
337
- }
338
- if (query) {
339
- var queryParams = _qs2.default.stringify(query);
340
- var hasParams = actualUri.includes('?');
341
- actualUri = '' + actualUri + (hasParams ? '&' : '?') + queryParams;
342
- }
343
-
344
- var userAgentHeader = { 'User-Agent': _package2.default.name + '/' + _package2.default.version + ' (' + _package2.default.repository.url + ')' };
345
- var body = void 0;
346
- var contentTypeHeader = void 0;
347
- if (files) {
348
- contentTypeHeader = {}; // Needed to allow fetch create its own
349
- body = this._getFromData(files, form);
350
- } else if (form) {
351
- contentTypeHeader = { 'Content-Type': 'application/x-www-form-urlencoded' };
352
- body = _qs2.default.stringify(form);
353
- } else if (data) {
354
- contentTypeHeader = { 'Content-Type': 'application/json' };
355
- body = (0, _stringify2.default)(data);
356
- }
357
- var finalHeaders = (0, _assign2.default)({}, userAgentHeader, contentTypeHeader, this._getAuthorizationHeader(auth), this._getContextHeaders(context), headers);
358
-
359
- return [actualUri, { method: method, body: body, headers: finalHeaders }];
360
- }
361
- }, {
362
- key: 'isForBrowser',
363
- value: function isForBrowser() {
364
- return typeof window !== 'undefined';
365
- }
366
- }, {
367
- key: '_getFromData',
368
- value: function _getFromData(files, form) {
369
- var formData = new _formData2.default();
370
- var _iteratorNormalCompletion = true;
371
- var _didIteratorError = false;
372
- var _iteratorError = undefined;
373
-
374
- try {
375
- for (var _iterator = (0, _getIterator3.default)((0, _entries2.default)(files)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
376
- var _step$value = (0, _slicedToArray3.default)(_step.value, 2),
377
- name = _step$value[0],
378
- file = _step$value[1];
379
-
380
- var path = file.path;
381
- var fileData = file.data;
382
- if (!this.isForBrowser()) {
383
- var nodeFormData = this._getNodeFormData(file);
384
- path = nodeFormData.path;
385
- fileData = nodeFormData.file;
386
- }
387
- formData.append(name, fileData, path);
388
- }
389
- } catch (err) {
390
- _didIteratorError = true;
391
- _iteratorError = err;
392
- } finally {
393
- try {
394
- if (!_iteratorNormalCompletion && _iterator.return) {
395
- _iterator.return();
396
- }
397
- } finally {
398
- if (_didIteratorError) {
399
- throw _iteratorError;
400
- }
401
- }
402
- }
403
-
404
- if (form) {
405
- var _iteratorNormalCompletion2 = true;
406
- var _didIteratorError2 = false;
407
- var _iteratorError2 = undefined;
408
-
409
- try {
410
- for (var _iterator2 = (0, _getIterator3.default)((0, _entries2.default)(form)), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
411
- var _step2$value = (0, _slicedToArray3.default)(_step2.value, 2),
412
- name = _step2$value[0],
413
- value = _step2$value[1];
414
-
415
- formData.append(name, value);
416
- }
417
- } catch (err) {
418
- _didIteratorError2 = true;
419
- _iteratorError2 = err;
420
- } finally {
421
- try {
422
- if (!_iteratorNormalCompletion2 && _iterator2.return) {
423
- _iterator2.return();
424
- }
425
- } finally {
426
- if (_didIteratorError2) {
427
- throw _iteratorError2;
428
- }
429
- }
430
- }
431
- }
432
- return formData;
433
- }
434
- }, {
435
- key: '_getNodeFormData',
436
- value: function _getNodeFormData(file) {
437
- var fileData = file.data;
438
- if (typeof file.data === 'string') {
439
- fileData = _fs2.default.createReadStream(file.data);
440
- }
441
- return {
442
- file: fileData,
443
- path: { filepath: file.path // Different API for nodejs
444
- } };
445
- }
446
- }, {
447
- key: '_getContextHeaders',
448
- value: function _getContextHeaders() {
449
- var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
450
-
451
- return (0, _assign2.default)({}, this._getToolContext(context.tool), this._getProjectContext(context.project));
452
- }
453
- }, {
454
- key: '_getToolContext',
455
- value: function _getToolContext() {
456
- var tool = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
457
-
458
- var value = '';
459
- if (tool.name) {
460
- value += this._toolIdent(tool);
461
- if (tool.components) {
462
- var _iteratorNormalCompletion3 = true;
463
- var _didIteratorError3 = false;
464
- var _iteratorError3 = undefined;
465
-
466
- try {
467
- for (var _iterator3 = (0, _getIterator3.default)(tool.components), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
468
- var component = _step3.value;
469
-
470
- value += ', ' + this._toolIdent(component);
471
- }
472
- } catch (err) {
473
- _didIteratorError3 = true;
474
- _iteratorError3 = err;
475
- } finally {
476
- try {
477
- if (!_iteratorNormalCompletion3 && _iterator3.return) {
478
- _iterator3.return();
479
- }
480
- } finally {
481
- if (_didIteratorError3) {
482
- throw _iteratorError3;
483
- }
484
- }
485
- }
486
- }
487
- }
488
- if (value) {
489
- return { 'X-Particle-Tool': value };
490
- }
491
- return {};
492
- }
493
- }, {
494
- key: '_toolIdent',
495
- value: function _toolIdent(tool) {
496
- return this._nameAtVersion(tool.name, tool.version);
497
- }
498
- }, {
499
- key: '_nameAtVersion',
500
- value: function _nameAtVersion(name, version) {
501
- var value = '';
502
- if (name) {
503
- value += name;
504
- if (version) {
505
- value += '@' + version;
506
- }
507
- }
508
- return value;
509
- }
510
- }, {
511
- key: '_getProjectContext',
512
- value: function _getProjectContext() {
513
- var project = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
514
-
515
- var value = this._buildSemicolonSeparatedProperties(project, 'name');
516
- if (value) {
517
- return { 'X-Particle-Project': value };
518
- }
519
- return {};
520
- }
521
-
522
- /**
523
- * Creates a string like primaryPropertyValue; name=value; name1=value
524
- * from the properties of an object.
525
- * @param {object} obj The object to create the string from
526
- * @param {string} primaryProperty The name of the primary property which is the default value and must be defined.
527
- * @private
528
- * @return {string} The formatted string representing the object properties and the default property.
529
- */
530
-
531
- }, {
532
- key: '_buildSemicolonSeparatedProperties',
533
- value: function _buildSemicolonSeparatedProperties(obj, primaryProperty) {
534
- var value = '';
535
- if (obj[primaryProperty]) {
536
- value += obj[primaryProperty];
537
- for (var prop in obj) {
538
- if (prop !== primaryProperty && obj.hasOwnProperty(prop)) {
539
- value += '; ' + prop + '=' + obj[prop];
540
- }
541
- }
542
- }
543
- return value;
544
- }
545
-
546
- /**
547
- * Adds an authorization header.
548
- * @param {string} auth The authorization bearer token.
549
- * @returns {object} The original request.
550
- */
551
-
552
- }, {
553
- key: '_getAuthorizationHeader',
554
- value: function _getAuthorizationHeader(auth) {
555
- if (!auth) {
556
- return {};
557
- }
558
- if (typeof auth === 'string') {
559
- return { Authorization: 'Bearer ' + auth };
560
- }
561
- var encoded = void 0;
562
- if (this.isForBrowser()) {
563
- encoded = btoa(auth.username + ':' + auth.password);
564
- } else {
565
- encoded = Buffer.from(auth.username + ':' + auth.password).toString('base64');
566
- }
567
- return { Authorization: 'Basic ' + encoded };
568
- }
569
-
570
- /**
571
- *
572
- * @param {Object} files converts the file names to file, file1, file2.
573
- * @returns {object} the renamed files.
574
- */
575
-
576
- }, {
577
- key: '_sanitizeFiles',
578
- value: function _sanitizeFiles(files) {
579
- var requestFiles = void 0;
580
- if (files) {
581
- requestFiles = {};
582
- (0, _keys2.default)(files).forEach(function (k, i) {
583
- var name = i ? 'file' + (i + 1) : 'file';
584
- requestFiles[name] = {
585
- data: files[k],
586
- path: k
587
- };
588
- });
589
- }
590
- return requestFiles;
591
- }
592
- }]);
593
- return Agent;
594
- }(); /*
595
- ******************************************************************************
596
- Copyright (c) 2016 Particle Industries, Inc. All rights reserved.
597
-
598
- This program is free software; you can redistribute it and/or
599
- modify it under the terms of the GNU Lesser General Public
600
- License as published by the Free Software Foundation, either
601
- version 3 of the License, or (at your option) any later version.
602
-
603
- This program is distributed in the hope that it will be useful,
604
- but WITHOUT ANY WARRANTY; without even the implied warranty of
605
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
606
- Lesser General Public License for more details.
607
-
608
- You should have received a copy of the GNU Lesser General Public
609
- License along with this program; if not, see <http://www.gnu.org/licenses/>.
610
- ******************************************************************************
611
- */
612
-
613
- exports.default = Agent;
614
- module.exports = exports['default'];
615
- //# sourceMappingURL=Agent.js.map
package/lib/Agent.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/Agent.js"],"names":["Agent","baseUrl","setBaseUrl","uri","auth","headers","query","context","request","method","data","undefined","form","files","isBuffer","requestFiles","_sanitizeFiles","requestParams","_buildRequest","_promiseResponse","makerequest","status","then","resp","ok","text","err","objError","JSON","parse","response","blob","json","body","arrayBuffer","isForBrowser","Buffer","from","statusCode","catch","error","errorType","errorDescription","shortErrorDescription","error_description","reason","Error","actualUri","queryParams","stringify","hasParams","includes","userAgentHeader","name","version","repository","url","contentTypeHeader","_getFromData","finalHeaders","_getAuthorizationHeader","_getContextHeaders","window","formData","file","path","fileData","nodeFormData","_getNodeFormData","append","value","createReadStream","filepath","_getToolContext","tool","_getProjectContext","project","_toolIdent","components","component","_nameAtVersion","_buildSemicolonSeparatedProperties","obj","primaryProperty","prop","hasOwnProperty","Authorization","encoded","btoa","username","password","toString","forEach","k","i"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;;;AAEA;;;;;;;AAOA;;;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AAED;;;;;;;;0CAKwBlE,I,EAAK;AAC5B,OAAI,CAACA,IAAL,EAAW;AACV,WAAO,EAAP;AACA;AACD,OAAI,OAAOA,IAAP,KAAgB,QAApB,EAA8B;AAC7B,WAAO,EAAEkF,2BAAyBlF,IAA3B,EAAP;AACA;AACD,OAAImF,gBAAJ;AACA,OAAI,KAAKpD,YAAL,EAAJ,EAAyB;AACxBoD,cAAUC,KAAQpF,KAAKqF,QAAb,SAAyBrF,KAAKsF,QAA9B,CAAV;AACA,IAFD,MAEO;AACNH,cAAUnD,OAAOC,IAAP,CAAejC,KAAKqF,QAApB,SAAgCrF,KAAKsF,QAArC,EACRC,QADQ,CACC,QADD,CAAV;AAEA;AACD,UAAO,EAAEL,0BAAwBC,OAA1B,EAAP;AACA;;AAED;;;;;;;;iCAKe1E,K,EAAM;AACpB,OAAIE,qBAAJ;AACA,OAAIF,KAAJ,EAAU;AACTE,mBAAe,EAAf;AACA,wBAAYF,KAAZ,EAAmB+E,OAAnB,CAA2B,UAACC,CAAD,EAAIC,CAAJ,EAAU;AACpC,SAAMzC,OAAOyC,cAAWA,IAAI,CAAf,IAAqB,MAAlC;AACA/E,kBAAasC,IAAb,IAAqB;AACpB3C,YAAMG,MAAMgF,CAAN,CADc;AAEpB5B,YAAM4B;AAFc,MAArB;AAIA,KAND;AAOA;AACD,UAAO9E,YAAP;AACA;;;KAxYF;;;;;;;;;;;;;;;;;;;kBAgDqBf,K","file":"Agent.js","sourcesContent":["/*\n ******************************************************************************\n Copyright (c) 2016 Particle Industries, Inc. All rights reserved.\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, either\n version 3 of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this program; if not, see <http://www.gnu.org/licenses/>.\n ******************************************************************************\n */\n\nimport fetch from 'node-fetch';\nimport FormData from 'form-data';\nimport qs from 'qs';\nimport fs from '../fs';\nimport packageJson from '../package.json';\n\n/**\n * The object returned for a basic request\n * @typedef {object} JSONResponse\n * @property {number} statusCode\tThe HTTP response status\n * @property {object} body\t\tThe endpoint's response parsed as a JSON\n */\n\n/**\n * The possible response from an API request\n * @typedef {JSONResponse|Buffer|arrayBuffer} RequestResponse\tThe type is based on\n * the request config and whether is on browser or node\n */\n\n/**\n * The error object generated in case of a failed request\n * @typedef {object} RequestError\n * @property {number} statusCode\tThe HTTP response status\n * @property {string} errorDescription\tDetails on what caused the failed request\n * @property {string} shortErrorDescription\tSummarized version of the fail reason\n * @property {object} body\t\tThe response object from the request\n * @property {object} error\t\tThe error object from the request\n */\n\nexport default class Agent {\n\tconstructor(baseUrl){\n\t\tthis.setBaseUrl(baseUrl);\n\t}\n\n\tsetBaseUrl(baseUrl) {\n\t\tthis.baseUrl = baseUrl;\n\t}\n\n\t/**\n\t * Make a GET request\n\t * @param {string} uri\t\tThe URI to request\n\t * @param {string} [auth]\tAuthorization token to use\n\t * @param {object} [headers]\tKey/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {object} [query] Key/Value pairs of query params\n\t * @param {object} [context]\tThe invocation context, describing the tool and project\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\tget({ uri, auth, headers, query, context }) {\n\t\treturn this.request({ uri, method: 'get', auth, headers, query, context });\n\t}\n\n\t/**\n\t * Make a HEAD request\n\t * @param {string} uri\t\tThe URI to request\n\t * @param {string} [auth]\tAuthorization token to use\n\t * @param {object} [headers]\tKey/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {object} [query] Key/Value pairs of query params\n\t * @param {object} [context]\tThe invocation context, describing the tool and project\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\thead({ uri, auth, headers, query, context }) {\n\t\treturn this.request({ uri, method: 'head', auth, headers, query, context });\n\t}\n\n\t/**\n\t * Make a POST request\n\t * @param {string} uri\t\tThe URI to request\n\t * @param {string} [auth]\tAuthorization token to use\n\t * @param {object} [headers]\tKey/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {object} [data] Payload to send in the request body in JSON format\n\t * @param {object} [context]\tThe invocation context, describing the tool and project\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\tpost({ uri, headers, data, auth, context }) {\n\t\treturn this.request({ uri, method: 'post', auth, headers, data, context });\n\t}\n\n\t/**\n\t * Make a PUT request\n\t * @param {string} uri\t\tThe URI to request\n\t * @param {string} [auth]\tAuthorization token to use\n\t * @param {object} [headers]\tKey/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {object} [data] Payload to send in the request body in JSON format\n\t * @param {object} [context]\tThe invocation context, describing the tool and project\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\tput({ uri, auth, headers, data, context }) {\n\t\treturn this.request({ uri, method: 'put', auth, headers, data, context });\n\t}\n\n\t/**\n\t * Make a DELETE request\n\t * @param {string} uri\t\tThe URI to request\n\t * @param {string} [auth]\tAuthorization token to use\n\t * @param {object} [headers]\tKey/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {object} [data] Payload to send in the request body in JSON format\n\t * @param {object} [context]\tThe invocation context, describing the tool and project\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\tdelete({ uri, auth, headers, data, context }) {\n\t\treturn this.request({ uri, method: 'delete', auth, headers, data, context });\n\t}\n\n\t/**\n\t *\n\t * @param {Object} config\t\tAn obj with all the possible request configurations\n\t * @param {String} config.uri\t\tThe URI to request\n\t * @param {String} config.method The method used to request the URI, should be in uppercase.\n\t * @param {Object} config.headers Key/Value pairs like `{ 'X-FOO': 'foo', X-BAR: 'bar' }` to send as headers.\n\t * @param {Object} config.data Arbitrary data to send as the body.\n\t * @param {Object} config.auth Authorization\n\t * @param {String} config.query Query parameters\n\t * @param {Object} config.form Form fields\n\t * @param {Object} config.files array of file names and file content\n\t * @param {Object} config.context the invocation context, describing the tool and project.\n\t * @param {boolean} config.isBuffer\tIndicate if the response should be treated as Buffer instead of JSON\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t */\n\trequest({\n\t\turi,\n\t\tmethod,\n\t\theaders = undefined,\n\t\tdata = undefined,\n\t\tauth,\n\t\tquery = undefined,\n\t\tform = undefined,\n\t\tfiles = undefined,\n\t\tcontext = undefined,\n\t\tisBuffer = false\n\t}){\n\t\tconst requestFiles = this._sanitizeFiles(files);\n\t\tconst requestParams = this._buildRequest({ uri, method, headers, data, auth, query, form, context, files: requestFiles });\n\t\treturn this._promiseResponse(requestParams, isBuffer);\n\t}\n\n\t/**\n\t * Promises to send the request and retreive the response.\n\t * @param {[string, object]} requestParams\tFirst argument is the URI to request, the second one are the options.\n\t * @param {boolean} isBuffer Indicate if the response body should be returned as a Buffer (Node) / ArrayBuffer (browser) instead of JSON\n\t * @param {Fetch} [makerequest] The fetch function to use. Override for testing.\n\t * @returns {Promise<RequestResponse, RequestError>} A promise that resolves with either the requested data or an error object\n\t * @private\n\t */\n\t_promiseResponse(requestParams, isBuffer, makerequest = fetch) {\n\t\tlet status;\n\t\treturn makerequest(...requestParams)\n\t\t\t.then((resp) => {\n\t\t\t\tstatus = resp.status;\n\t\t\t\tif (!resp.ok) {\n\t\t\t\t\treturn resp.text().then((err) => {\n\t\t\t\t\t\tconst objError = JSON.parse(err);\n\t\t\t\t\t\t// particle-commnds/src/cmd/api expects response.text. to be a string\n\t\t\t\t\t\tconst response = Object.assign(resp, { text: err });\n\t\t\t\t\t\tthrow Object.assign(objError, { response });\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (status === 204) { // Can't do resp.json() since there is no body to parse\n\t\t\t\t\treturn '';\n\t\t\t\t}\n\t\t\t\tif (isBuffer) {\n\t\t\t\t\treturn resp.blob();\n\t\t\t\t}\n\t\t\t\treturn resp.json();\n\t\t\t}).then((body) => {\n\t\t\t\tif (isBuffer) {\n\t\t\t\t\treturn body.arrayBuffer().then((arrayBuffer) => {\n\t\t\t\t\t\tif (!this.isForBrowser()) {\n\t\t\t\t\t\t\treturn Buffer.from(arrayBuffer);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn arrayBuffer;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tbody,\n\t\t\t\t\tstatusCode: status\n\t\t\t\t};\n\t\t\t}).catch((error) => {\n\t\t\t\tconst errorType = status ? `HTTP error ${status}` : 'Network error';\n\t\t\t\tlet errorDescription = `${errorType} from ${requestParams[0]}`;\n\t\t\t\tlet shortErrorDescription;\n\t\t\t\tif (error.error_description) { // Fetch responded with ok false\n\t\t\t\t\terrorDescription = `${errorDescription} - ${error.error_description}`;\n\t\t\t\t\tshortErrorDescription = error.error_description;\n\t\t\t\t}\n\t\t\t\tconst reason = new Error(errorDescription);\n\t\t\t\tObject.assign(reason, {\n\t\t\t\t\tstatusCode: status,\n\t\t\t\t\terrorDescription,\n\t\t\t\t\tshortErrorDescription,\n\t\t\t\t\terror,\n\t\t\t\t\tbody: error\n\t\t\t\t});\n\t\t\t\tthrow reason;\n\t\t\t});\n\t}\n\n\t_buildRequest({ uri, method, headers, data, auth, query, form, files, context }){\n\t\tlet actualUri = uri;\n\t\tif (this.baseUrl && uri[0] === '/') {\n\t\t\tactualUri = `${this.baseUrl}${uri}`;\n\t\t}\n\t\tif (query) {\n\t\t\tconst queryParams = qs.stringify(query);\n\t\t\tconst hasParams = actualUri.includes('?');\n\t\t\tactualUri = `${actualUri}${hasParams ? '&' : '?'}${queryParams}`;\n\t\t}\n\n\t\tconst userAgentHeader = { 'User-Agent': `${packageJson.name}/${packageJson.version} (${packageJson.repository.url})` };\n\t\tlet body;\n\t\tlet contentTypeHeader;\n\t\tif (files){\n\t\t\tcontentTypeHeader = {}; // Needed to allow fetch create its own\n\t\t\tbody = this._getFromData(files, form);\n\t\t} else if (form){\n\t\t\tcontentTypeHeader = { 'Content-Type': 'application/x-www-form-urlencoded' };\n\t\t\tbody = qs.stringify(form);\n\t\t} else if (data){\n\t\t\tcontentTypeHeader = { 'Content-Type': 'application/json' };\n\t\t\tbody = JSON.stringify(data);\n\t\t}\n\t\tconst finalHeaders = Object.assign({},\n\t\t\tuserAgentHeader,\n\t\t\tcontentTypeHeader,\n\t\t\tthis._getAuthorizationHeader(auth),\n\t\t\tthis._getContextHeaders(context),\n\t\t\theaders\n\t\t);\n\n\t\treturn [actualUri, { method, body, headers: finalHeaders }];\n\t}\n\n\tisForBrowser() {\n\t\treturn typeof window !== 'undefined';\n\t}\n\n\t_getFromData(files, form) {\n\t\tconst formData = new FormData();\n\t\tfor (let [name, file] of Object.entries(files)){\n\t\t\tlet path = file.path;\n\t\t\tlet fileData = file.data;\n\t\t\tif (!this.isForBrowser()) {\n\t\t\t\tconst nodeFormData = this._getNodeFormData(file);\n\t\t\t\tpath = nodeFormData.path;\n\t\t\t\tfileData = nodeFormData.file;\n\t\t\t}\n\t\t\tformData.append(name, fileData, path);\n\t\t}\n\t\tif (form){\n\t\t\tfor (let [name, value] of Object.entries(form)){\n\t\t\t\tformData.append(name, value);\n\t\t\t}\n\t\t}\n\t\treturn formData;\n\t}\n\n\t_getNodeFormData(file) {\n\t\tlet fileData = file.data;\n\t\tif (typeof file.data === 'string') {\n\t\t\tfileData = fs.createReadStream(file.data);\n\t\t}\n\t\treturn {\n\t\t\tfile: fileData,\n\t\t\tpath: { filepath: file.path } // Different API for nodejs\n\t\t};\n\t}\n\n\t_getContextHeaders(context = {}) {\n\t\treturn Object.assign({},\n\t\t\tthis._getToolContext(context.tool),\n\t\t\tthis._getProjectContext(context.project)\n\t\t);\n\t}\n\n\t_getToolContext(tool = {}){\n\t\tlet value = '';\n\t\tif (tool.name){\n\t\t\tvalue += this._toolIdent(tool);\n\t\t\tif (tool.components){\n\t\t\t\tfor (let component of tool.components){\n\t\t\t\t\tvalue += ', '+this._toolIdent(component);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (value){\n\t\t\treturn { 'X-Particle-Tool': value };\n\t\t}\n\t\treturn {};\n\t}\n\n\t_toolIdent(tool){\n\t\treturn this._nameAtVersion(tool.name, tool.version);\n\t}\n\n\t_nameAtVersion(name, version){\n\t\tlet value = '';\n\t\tif (name){\n\t\t\tvalue += name;\n\t\t\tif (version){\n\t\t\t\tvalue += '@'+version;\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n\n\t_getProjectContext(project = {}){\n\t\tlet value = this._buildSemicolonSeparatedProperties(project, 'name');\n\t\tif (value){\n\t\t\treturn { 'X-Particle-Project': value };\n\t\t}\n\t\treturn {};\n\t}\n\n\t/**\n\t * Creates a string like primaryPropertyValue; name=value; name1=value\n\t * from the properties of an object.\n\t * @param {object} obj The object to create the string from\n\t * @param {string} primaryProperty The name of the primary property which is the default value and must be defined.\n\t * @private\n\t * @return {string} The formatted string representing the object properties and the default property.\n\t */\n\t_buildSemicolonSeparatedProperties(obj, primaryProperty){\n\t\tlet value = '';\n\t\tif (obj[primaryProperty]){\n\t\t\tvalue += obj[primaryProperty];\n\t\t\tfor (let prop in obj){\n\t\t\t\tif (prop!==primaryProperty && obj.hasOwnProperty(prop)){\n\t\t\t\t\tvalue += '; '+prop+'='+obj[prop];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Adds an authorization header.\n\t * @param {string} auth The authorization bearer token.\n\t * @returns {object} The original request.\n\t */\n\t_getAuthorizationHeader(auth){\n\t\tif (!auth) {\n\t\t\treturn {};\n\t\t}\n\t\tif (typeof auth === 'string') {\n\t\t\treturn { Authorization: `Bearer ${auth}` };\n\t\t}\n\t\tlet encoded;\n\t\tif (this.isForBrowser()) {\n\t\t\tencoded = btoa(`${auth.username}:${auth.password}`);\n\t\t} else {\n\t\t\tencoded = Buffer.from(`${auth.username}:${auth.password}`)\n\t\t\t\t.toString('base64');\n\t\t}\n\t\treturn { Authorization: `Basic ${encoded}` };\n\t}\n\n\t/**\n\t *\n\t * @param {Object} files converts the file names to file, file1, file2.\n\t * @returns {object} the renamed files.\n\t */\n\t_sanitizeFiles(files){\n\t\tlet requestFiles;\n\t\tif (files){\n\t\t\trequestFiles = {};\n\t\t\tObject.keys(files).forEach((k, i) => {\n\t\t\t\tconst name = i ? `file${i + 1}` : 'file';\n\t\t\t\trequestFiles[name] = {\n\t\t\t\t\tdata: files[k],\n\t\t\t\t\tpath: k\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t\treturn requestFiles;\n\t}\n}\n\n"]}