@prenetics/react-context-provider 23.0.8

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of @prenetics/react-context-provider might be problematic. Click here for more details.

@@ -0,0 +1,3059 @@
1
+ import React, { useState, useCallback, useContext, useRef, useEffect } from 'react';
2
+ import axios from 'axios';
3
+ //import jwt from 'jwt-decode';
4
+ import moment from 'moment';
5
+ import { v4 } from 'uuid';
6
+ import equal from 'fast-deep-equal';
7
+
8
+ function _regeneratorRuntime() {
9
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
10
+
11
+ _regeneratorRuntime = function () {
12
+ return exports;
13
+ };
14
+
15
+ var exports = {},
16
+ Op = Object.prototype,
17
+ hasOwn = Op.hasOwnProperty,
18
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
19
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
20
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
21
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
22
+
23
+ function define(obj, key, value) {
24
+ return Object.defineProperty(obj, key, {
25
+ value: value,
26
+ enumerable: !0,
27
+ configurable: !0,
28
+ writable: !0
29
+ }), obj[key];
30
+ }
31
+
32
+ try {
33
+ define({}, "");
34
+ } catch (err) {
35
+ define = function (obj, key, value) {
36
+ return obj[key] = value;
37
+ };
38
+ }
39
+
40
+ function wrap(innerFn, outerFn, self, tryLocsList) {
41
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
42
+ generator = Object.create(protoGenerator.prototype),
43
+ context = new Context(tryLocsList || []);
44
+ return generator._invoke = function (innerFn, self, context) {
45
+ var state = "suspendedStart";
46
+ return function (method, arg) {
47
+ if ("executing" === state) throw new Error("Generator is already running");
48
+
49
+ if ("completed" === state) {
50
+ if ("throw" === method) throw arg;
51
+ return doneResult();
52
+ }
53
+
54
+ for (context.method = method, context.arg = arg;;) {
55
+ var delegate = context.delegate;
56
+
57
+ if (delegate) {
58
+ var delegateResult = maybeInvokeDelegate(delegate, context);
59
+
60
+ if (delegateResult) {
61
+ if (delegateResult === ContinueSentinel) continue;
62
+ return delegateResult;
63
+ }
64
+ }
65
+
66
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
67
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
68
+ context.dispatchException(context.arg);
69
+ } else "return" === context.method && context.abrupt("return", context.arg);
70
+ state = "executing";
71
+ var record = tryCatch(innerFn, self, context);
72
+
73
+ if ("normal" === record.type) {
74
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
75
+ return {
76
+ value: record.arg,
77
+ done: context.done
78
+ };
79
+ }
80
+
81
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
82
+ }
83
+ };
84
+ }(innerFn, self, context), generator;
85
+ }
86
+
87
+ function tryCatch(fn, obj, arg) {
88
+ try {
89
+ return {
90
+ type: "normal",
91
+ arg: fn.call(obj, arg)
92
+ };
93
+ } catch (err) {
94
+ return {
95
+ type: "throw",
96
+ arg: err
97
+ };
98
+ }
99
+ }
100
+
101
+ exports.wrap = wrap;
102
+ var ContinueSentinel = {};
103
+
104
+ function Generator() {}
105
+
106
+ function GeneratorFunction() {}
107
+
108
+ function GeneratorFunctionPrototype() {}
109
+
110
+ var IteratorPrototype = {};
111
+ define(IteratorPrototype, iteratorSymbol, function () {
112
+ return this;
113
+ });
114
+ var getProto = Object.getPrototypeOf,
115
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
116
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
117
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
118
+
119
+ function defineIteratorMethods(prototype) {
120
+ ["next", "throw", "return"].forEach(function (method) {
121
+ define(prototype, method, function (arg) {
122
+ return this._invoke(method, arg);
123
+ });
124
+ });
125
+ }
126
+
127
+ function AsyncIterator(generator, PromiseImpl) {
128
+ function invoke(method, arg, resolve, reject) {
129
+ var record = tryCatch(generator[method], generator, arg);
130
+
131
+ if ("throw" !== record.type) {
132
+ var result = record.arg,
133
+ value = result.value;
134
+ return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
135
+ invoke("next", value, resolve, reject);
136
+ }, function (err) {
137
+ invoke("throw", err, resolve, reject);
138
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
139
+ result.value = unwrapped, resolve(result);
140
+ }, function (error) {
141
+ return invoke("throw", error, resolve, reject);
142
+ });
143
+ }
144
+
145
+ reject(record.arg);
146
+ }
147
+
148
+ var previousPromise;
149
+
150
+ this._invoke = function (method, arg) {
151
+ function callInvokeWithMethodAndArg() {
152
+ return new PromiseImpl(function (resolve, reject) {
153
+ invoke(method, arg, resolve, reject);
154
+ });
155
+ }
156
+
157
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
158
+ };
159
+ }
160
+
161
+ function maybeInvokeDelegate(delegate, context) {
162
+ var method = delegate.iterator[context.method];
163
+
164
+ if (undefined === method) {
165
+ if (context.delegate = null, "throw" === context.method) {
166
+ if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
167
+ context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
168
+ }
169
+
170
+ return ContinueSentinel;
171
+ }
172
+
173
+ var record = tryCatch(method, delegate.iterator, context.arg);
174
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
175
+ var info = record.arg;
176
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
177
+ }
178
+
179
+ function pushTryEntry(locs) {
180
+ var entry = {
181
+ tryLoc: locs[0]
182
+ };
183
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
184
+ }
185
+
186
+ function resetTryEntry(entry) {
187
+ var record = entry.completion || {};
188
+ record.type = "normal", delete record.arg, entry.completion = record;
189
+ }
190
+
191
+ function Context(tryLocsList) {
192
+ this.tryEntries = [{
193
+ tryLoc: "root"
194
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
195
+ }
196
+
197
+ function values(iterable) {
198
+ if (iterable) {
199
+ var iteratorMethod = iterable[iteratorSymbol];
200
+ if (iteratorMethod) return iteratorMethod.call(iterable);
201
+ if ("function" == typeof iterable.next) return iterable;
202
+
203
+ if (!isNaN(iterable.length)) {
204
+ var i = -1,
205
+ next = function next() {
206
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
207
+
208
+ return next.value = undefined, next.done = !0, next;
209
+ };
210
+
211
+ return next.next = next;
212
+ }
213
+ }
214
+
215
+ return {
216
+ next: doneResult
217
+ };
218
+ }
219
+
220
+ function doneResult() {
221
+ return {
222
+ value: undefined,
223
+ done: !0
224
+ };
225
+ }
226
+
227
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
228
+ var ctor = "function" == typeof genFun && genFun.constructor;
229
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
230
+ }, exports.mark = function (genFun) {
231
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
232
+ }, exports.awrap = function (arg) {
233
+ return {
234
+ __await: arg
235
+ };
236
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
237
+ return this;
238
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
239
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
240
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
241
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
242
+ return result.done ? result.value : iter.next();
243
+ });
244
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
245
+ return this;
246
+ }), define(Gp, "toString", function () {
247
+ return "[object Generator]";
248
+ }), exports.keys = function (object) {
249
+ var keys = [];
250
+
251
+ for (var key in object) keys.push(key);
252
+
253
+ return keys.reverse(), function next() {
254
+ for (; keys.length;) {
255
+ var key = keys.pop();
256
+ if (key in object) return next.value = key, next.done = !1, next;
257
+ }
258
+
259
+ return next.done = !0, next;
260
+ };
261
+ }, exports.values = values, Context.prototype = {
262
+ constructor: Context,
263
+ reset: function (skipTempReset) {
264
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
265
+ },
266
+ stop: function () {
267
+ this.done = !0;
268
+ var rootRecord = this.tryEntries[0].completion;
269
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
270
+ return this.rval;
271
+ },
272
+ dispatchException: function (exception) {
273
+ if (this.done) throw exception;
274
+ var context = this;
275
+
276
+ function handle(loc, caught) {
277
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
278
+ }
279
+
280
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
281
+ var entry = this.tryEntries[i],
282
+ record = entry.completion;
283
+ if ("root" === entry.tryLoc) return handle("end");
284
+
285
+ if (entry.tryLoc <= this.prev) {
286
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
287
+ hasFinally = hasOwn.call(entry, "finallyLoc");
288
+
289
+ if (hasCatch && hasFinally) {
290
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
291
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
292
+ } else if (hasCatch) {
293
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
294
+ } else {
295
+ if (!hasFinally) throw new Error("try statement without catch or finally");
296
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
297
+ }
298
+ }
299
+ }
300
+ },
301
+ abrupt: function (type, arg) {
302
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
303
+ var entry = this.tryEntries[i];
304
+
305
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
306
+ var finallyEntry = entry;
307
+ break;
308
+ }
309
+ }
310
+
311
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
312
+ var record = finallyEntry ? finallyEntry.completion : {};
313
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
314
+ },
315
+ complete: function (record, afterLoc) {
316
+ if ("throw" === record.type) throw record.arg;
317
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
318
+ },
319
+ finish: function (finallyLoc) {
320
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
321
+ var entry = this.tryEntries[i];
322
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
323
+ }
324
+ },
325
+ catch: function (tryLoc) {
326
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
327
+ var entry = this.tryEntries[i];
328
+
329
+ if (entry.tryLoc === tryLoc) {
330
+ var record = entry.completion;
331
+
332
+ if ("throw" === record.type) {
333
+ var thrown = record.arg;
334
+ resetTryEntry(entry);
335
+ }
336
+
337
+ return thrown;
338
+ }
339
+ }
340
+
341
+ throw new Error("illegal catch attempt");
342
+ },
343
+ delegateYield: function (iterable, resultName, nextLoc) {
344
+ return this.delegate = {
345
+ iterator: values(iterable),
346
+ resultName: resultName,
347
+ nextLoc: nextLoc
348
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
349
+ }
350
+ }, exports;
351
+ }
352
+
353
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
354
+ try {
355
+ var info = gen[key](arg);
356
+ var value = info.value;
357
+ } catch (error) {
358
+ reject(error);
359
+ return;
360
+ }
361
+
362
+ if (info.done) {
363
+ resolve(value);
364
+ } else {
365
+ Promise.resolve(value).then(_next, _throw);
366
+ }
367
+ }
368
+
369
+ function _asyncToGenerator(fn) {
370
+ return function () {
371
+ var self = this,
372
+ args = arguments;
373
+ return new Promise(function (resolve, reject) {
374
+ var gen = fn.apply(self, args);
375
+
376
+ function _next(value) {
377
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
378
+ }
379
+
380
+ function _throw(err) {
381
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
382
+ }
383
+
384
+ _next(undefined);
385
+ });
386
+ };
387
+ }
388
+
389
+ function _extends() {
390
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
391
+ for (var i = 1; i < arguments.length; i++) {
392
+ var source = arguments[i];
393
+
394
+ for (var key in source) {
395
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
396
+ target[key] = source[key];
397
+ }
398
+ }
399
+ }
400
+
401
+ return target;
402
+ };
403
+ return _extends.apply(this, arguments);
404
+ }
405
+
406
+ function _inheritsLoose(subClass, superClass) {
407
+ subClass.prototype = Object.create(superClass.prototype);
408
+ subClass.prototype.constructor = subClass;
409
+
410
+ _setPrototypeOf(subClass, superClass);
411
+ }
412
+
413
+ function _getPrototypeOf(o) {
414
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
415
+ return o.__proto__ || Object.getPrototypeOf(o);
416
+ };
417
+ return _getPrototypeOf(o);
418
+ }
419
+
420
+ function _setPrototypeOf(o, p) {
421
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
422
+ o.__proto__ = p;
423
+ return o;
424
+ };
425
+ return _setPrototypeOf(o, p);
426
+ }
427
+
428
+ function _isNativeReflectConstruct() {
429
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
430
+ if (Reflect.construct.sham) return false;
431
+ if (typeof Proxy === "function") return true;
432
+
433
+ try {
434
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
435
+ return true;
436
+ } catch (e) {
437
+ return false;
438
+ }
439
+ }
440
+
441
+ function _construct(Parent, args, Class) {
442
+ if (_isNativeReflectConstruct()) {
443
+ _construct = Reflect.construct.bind();
444
+ } else {
445
+ _construct = function _construct(Parent, args, Class) {
446
+ var a = [null];
447
+ a.push.apply(a, args);
448
+ var Constructor = Function.bind.apply(Parent, a);
449
+ var instance = new Constructor();
450
+ if (Class) _setPrototypeOf(instance, Class.prototype);
451
+ return instance;
452
+ };
453
+ }
454
+
455
+ return _construct.apply(null, arguments);
456
+ }
457
+
458
+ function _isNativeFunction(fn) {
459
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
460
+ }
461
+
462
+ function _wrapNativeSuper(Class) {
463
+ var _cache = typeof Map === "function" ? new Map() : undefined;
464
+
465
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
466
+ if (Class === null || !_isNativeFunction(Class)) return Class;
467
+
468
+ if (typeof Class !== "function") {
469
+ throw new TypeError("Super expression must either be null or a function");
470
+ }
471
+
472
+ if (typeof _cache !== "undefined") {
473
+ if (_cache.has(Class)) return _cache.get(Class);
474
+
475
+ _cache.set(Class, Wrapper);
476
+ }
477
+
478
+ function Wrapper() {
479
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
480
+ }
481
+
482
+ Wrapper.prototype = Object.create(Class.prototype, {
483
+ constructor: {
484
+ value: Wrapper,
485
+ enumerable: false,
486
+ writable: true,
487
+ configurable: true
488
+ }
489
+ });
490
+ return _setPrototypeOf(Wrapper, Class);
491
+ };
492
+
493
+ return _wrapNativeSuper(Class);
494
+ }
495
+
496
+ function _assertThisInitialized(self) {
497
+ if (self === void 0) {
498
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
499
+ }
500
+
501
+ return self;
502
+ }
503
+
504
+ /* istanbul ignore next */
505
+
506
+ var AuthContext = /*#__PURE__*/React.createContext({
507
+ token: undefined,
508
+ requestOtp: function requestOtp() {
509
+ return Promise.resolve('');
510
+ },
511
+ verifyOtp: function verifyOtp() {
512
+ return Promise.resolve('');
513
+ },
514
+ register: function register() {
515
+ return Promise.resolve('');
516
+ },
517
+ login: function login() {
518
+ return Promise.resolve('');
519
+ },
520
+ logout: function logout() {
521
+ return Promise.resolve();
522
+ },
523
+ updatePassword: function updatePassword() {
524
+ return Promise.resolve();
525
+ }
526
+ });
527
+
528
+ var AuthHeader = function AuthHeader(token) {
529
+ return {
530
+ Authorization: "Bearer " + token
531
+ };
532
+ }; // axios.defaults.baseURL = getEnvironment.baseUrl;
533
+
534
+ var replaceUriParams = function replaceUriParams(obj, url) {
535
+ var updatedUrl = url;
536
+ Object.entries(obj).forEach(function (_ref) {
537
+ var key = _ref[0],
538
+ value = _ref[1];
539
+ updatedUrl = updatedUrl.replace(":" + key, value.toString());
540
+ });
541
+ return updatedUrl;
542
+ };
543
+
544
+ var request = function request(config, errorHandler, uriParams) {
545
+ if (uriParams === void 0) {
546
+ uriParams = {};
547
+ }
548
+
549
+ var url = config.url;
550
+ if (url) url = replaceUriParams(uriParams, url);
551
+
552
+ var options = _extends({}, config, {
553
+ url: url
554
+ });
555
+
556
+ return axios(options)["catch"](function (error) {
557
+ return errorHandler(error, config);
558
+ });
559
+ };
560
+
561
+ var baseURL$2 = undefined;
562
+ var application$2 = '/authentication';
563
+ var postOtpRequest = function postOtpRequest(context, handler) {
564
+ return request({
565
+ baseURL: baseURL$2,
566
+ url: application$2 + '/v1.0/otp',
567
+ method: 'POST',
568
+ data: {
569
+ username: context.username,
570
+ type: context.type,
571
+ lang: context.lang
572
+ },
573
+ params: context.verify ? {
574
+ verify: context.verify
575
+ } : undefined
576
+ }, handler).then(function () {
577
+ return context.username;
578
+ });
579
+ };
580
+ var postOtpVerification = function postOtpVerification(context, handler) {
581
+ return request({
582
+ baseURL: baseURL$2,
583
+ url: application$2 + '/v1.0/token/otp',
584
+ method: 'POST',
585
+ data: context
586
+ }, handler).then(function (response) {
587
+ return response == null ? void 0 : response.data.token;
588
+ });
589
+ };
590
+ var postCreateToken = function postCreateToken(context, handler) {
591
+ return request({
592
+ baseURL: baseURL$2,
593
+ url: application$2 + '/v1.0/token/user',
594
+ method: 'POST',
595
+ data: context
596
+ }, handler).then(function (response) {
597
+ return response == null ? void 0 : response.data.token;
598
+ });
599
+ };
600
+ var putUpdateUser = function putUpdateUser(context, token, handler) {
601
+ return request({
602
+ baseURL: baseURL$2,
603
+ url: application$2 + '/v1.0/user/:userid',
604
+ method: 'PUT',
605
+ data: context.info,
606
+ headers: AuthHeader(token)
607
+ }, handler, {
608
+ userid: context.userid
609
+ });
610
+ };
611
+
612
+ // import { Identity } from '../../type/Customer';
613
+ var baseURL$1 = undefined;
614
+ var application$1 = 'customer';
615
+ var postCreateAccount = function postCreateAccount(context, token, handler) {
616
+ return request({
617
+ baseURL: baseURL$1,
618
+ url: application$1 + '/v1.0/customer',
619
+ method: 'POST',
620
+ data: {
621
+ customer: {
622
+ name: {
623
+ nickName: context.nickname
624
+ }
625
+ },
626
+ userName: context.username,
627
+ loginType: 'email',
628
+ password: context.password,
629
+ locale: context.locale,
630
+ location: context.location
631
+ },
632
+ headers: AuthHeader(token)
633
+ }, handler).then(function (response) {
634
+ return {
635
+ customerId: response == null ? void 0 : response.data.customerId,
636
+ profileId: response == null ? void 0 : response.data.profileId,
637
+ emailIdentity: response == null ? void 0 : response.data.emailIdentity
638
+ };
639
+ });
640
+ };
641
+
642
+ var capture = function capture(e, cb) {
643
+ if (cb) cb(e);
644
+ };
645
+
646
+ var Role;
647
+
648
+ (function (Role) {
649
+ Role["CustomerUser"] = "customer_user";
650
+ Role["OtpVerified"] = "otp_verified";
651
+ })(Role || (Role = {}));
652
+
653
+ var LoginType;
654
+
655
+ (function (LoginType) {
656
+ LoginType["Basic"] = "basic";
657
+ LoginType["Mobile"] = "mobile";
658
+ LoginType["WeChat"] = "wechat";
659
+ LoginType["Email"] = "email";
660
+ })(LoginType || (LoginType = {}));
661
+
662
+ var capturing = function capturing(e) {
663
+ if (e instanceof Error) {
664
+ console.warn("Invalid jwt: " + e.message);
665
+ } else {
666
+ console.warn("Invalid jwt: " + e);
667
+ }
668
+ };
669
+
670
+ var getUserId = function getUserId(input) {
671
+ try {
672
+ var decoded = jwt(input);
673
+ var token = decoded;
674
+ return token.uid;
675
+ } catch (error) {
676
+ capture(error, capturing);
677
+ return;
678
+ }
679
+ };
680
+ var getRoles = function getRoles(input) {
681
+ try {
682
+ var decoded = jwt(input);
683
+ var token = decoded;
684
+ return token.roles;
685
+ } catch (error) {
686
+ capture(error, capturing);
687
+ return;
688
+ }
689
+ };
690
+ var isActive = function isActive(input) {
691
+ try {
692
+ var decoded = jwt(input);
693
+ if (decoded.exp === undefined) return undefined;
694
+ var now = moment(); // https://www.rfc-editor.org/rfc/rfc7519#section-2
695
+ // jwt exp is defined as the number of seconds (not milliseconds) since Epoch
696
+
697
+ var exp = moment(decoded.exp * 1000);
698
+ if (!moment(exp).isAfter(now)) return false;
699
+ return true;
700
+ } catch (error) {
701
+ capture(error);
702
+ return;
703
+ }
704
+ };
705
+
706
+ var AuthorizationErrorReason;
707
+
708
+ (function (AuthorizationErrorReason) {
709
+ AuthorizationErrorReason["Expired"] = "ERR_EXPIRED";
710
+ AuthorizationErrorReason["Unauthroized"] = "ERR_UNAUTHORIZED";
711
+ })(AuthorizationErrorReason || (AuthorizationErrorReason = {}));
712
+
713
+ var AuthorizationError = /*#__PURE__*/function (_Error) {
714
+ _inheritsLoose(AuthorizationError, _Error);
715
+
716
+ function AuthorizationError(m, r) {
717
+ var _this;
718
+
719
+ if (r === void 0) {
720
+ r = AuthorizationErrorReason.Expired;
721
+ }
722
+
723
+ _this = _Error.call(this, m) || this;
724
+ _this.reason = void 0;
725
+ _this.name = 'AuthorizationError';
726
+ _this.reason = r; // Set the prototype explicitly.
727
+
728
+ Object.setPrototypeOf(_assertThisInitialized(_this), AuthorizationError.prototype);
729
+ return _this;
730
+ }
731
+
732
+ return AuthorizationError;
733
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
734
+
735
+ var UnexpectedError = /*#__PURE__*/function (_Error) {
736
+ _inheritsLoose(UnexpectedError, _Error);
737
+
738
+ function UnexpectedError(m) {
739
+ var _this;
740
+
741
+ _this = _Error.call(this, m) || this;
742
+ _this.name = 'UnexpectedError'; // Set the prototype explicitly.
743
+
744
+ Object.setPrototypeOf(_assertThisInitialized(_this), UnexpectedError.prototype);
745
+ return _this;
746
+ }
747
+
748
+ return UnexpectedError;
749
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
750
+
751
+ var ApiErrorHandler = function ApiErrorHandler(error) {
752
+ if (error instanceof Error) {
753
+ console.log('[ApiErrorHandler] ' + error.name + ': ' + error.message);
754
+ } else {
755
+ console.log('[ApiErrorHandler] Unknown Error: ' + error);
756
+ }
757
+
758
+ if (axios.isAxiosError(error)) {
759
+ var _error$response;
760
+
761
+ if (((_error$response = error.response) == null ? void 0 : _error$response.status) === 401) {
762
+ var _error$config, _error$config$headers;
763
+
764
+ if ((_error$config = error.config) != null && (_error$config$headers = _error$config.headers) != null && _error$config$headers.Authorization && typeof error.config.headers.Authorization === 'string' && error.config.headers.Authorization.startsWith('Bearer ')) {
765
+ var token = error.config.headers.Authorization.substring(7); // Remove `Bearer `
766
+
767
+ var active = isActive(token);
768
+
769
+ if (active !== undefined && !active) {
770
+ throw new AuthorizationError('Session Expired', AuthorizationErrorReason.Expired);
771
+ }
772
+ }
773
+ }
774
+
775
+ throw error;
776
+ }
777
+
778
+ throw new UnexpectedError('Unexpected API Error');
779
+ };
780
+
781
+ var AuthenticationErrorReason;
782
+
783
+ (function (AuthenticationErrorReason) {
784
+ AuthenticationErrorReason["TooMany"] = "ERR_AUTH_TOO_MANY";
785
+ AuthenticationErrorReason["NotExists"] = "ERR_AUTH_NOT_EXISTS";
786
+ AuthenticationErrorReason["AlreadyExists"] = "ERR_AUTH_ALREADY_EXISTS";
787
+ AuthenticationErrorReason["General"] = "ERR_AUTH_GENERAL";
788
+ AuthenticationErrorReason["InvalidCredential"] = "ERR_AUTH_INVALID_CRED";
789
+ })(AuthenticationErrorReason || (AuthenticationErrorReason = {}));
790
+
791
+ var AuthenticationError = /*#__PURE__*/function (_Error) {
792
+ _inheritsLoose(AuthenticationError, _Error);
793
+
794
+ function AuthenticationError(r, m) {
795
+ var _this;
796
+
797
+ if (r === void 0) {
798
+ r = AuthenticationErrorReason.General;
799
+ }
800
+
801
+ _this = _Error.call(this, m || r) || this;
802
+ _this.reason = void 0;
803
+ _this.name = 'AuthenticationError';
804
+ _this.reason = r; // Set the prototype explicitly.
805
+
806
+ Object.setPrototypeOf(_assertThisInitialized(_this), AuthenticationError.prototype);
807
+ return _this;
808
+ }
809
+
810
+ return AuthenticationError;
811
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
812
+
813
+ var AuthProvider = function AuthProvider(_ref) {
814
+ var children = _ref.children,
815
+ defaults = _ref.defaults,
816
+ _ref$locale = _ref.locale,
817
+ locale = _ref$locale === void 0 ? 'en-HK' : _ref$locale;
818
+
819
+ var _useState = useState(defaults == null ? void 0 : defaults.token),
820
+ authToken = _useState[0],
821
+ setAuthToken = _useState[1];
822
+
823
+ var requestOtp = useCallback( /*#__PURE__*/function () {
824
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(email, verify) {
825
+ var _e$response, status, _e$response2, _e$response3, hasErrorMessage, errMsg;
826
+
827
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
828
+ while (1) {
829
+ switch (_context.prev = _context.next) {
830
+ case 0:
831
+ _context.prev = 0;
832
+ console.log("Requesting OTP for " + email + "; Verify: " + verify);
833
+ _context.next = 4;
834
+ return postOtpRequest({
835
+ username: email,
836
+ type: 'email',
837
+ lang: locale,
838
+ verify: verify
839
+ }, ApiErrorHandler);
840
+
841
+ case 4:
842
+ return _context.abrupt("return", _context.sent);
843
+
844
+ case 7:
845
+ _context.prev = 7;
846
+ _context.t0 = _context["catch"](0);
847
+
848
+ if (!axios.isAxiosError(_context.t0)) {
849
+ _context.next = 20;
850
+ break;
851
+ }
852
+
853
+ status = (_e$response = _context.t0.response) == null ? void 0 : _e$response.status;
854
+
855
+ if (!(status === 429)) {
856
+ _context.next = 15;
857
+ break;
858
+ }
859
+
860
+ throw new AuthenticationError(AuthenticationErrorReason.TooMany);
861
+
862
+ case 15:
863
+ if (!(status === 400)) {
864
+ _context.next = 20;
865
+ break;
866
+ }
867
+
868
+ hasErrorMessage = function hasErrorMessage(data) {
869
+ if (data && typeof data === 'object') {
870
+ if ('error_message' in data) {
871
+ return true;
872
+ }
873
+ }
874
+
875
+ return false;
876
+ };
877
+
878
+ errMsg = hasErrorMessage((_e$response2 = _context.t0.response) == null ? void 0 : _e$response2.data) && ((_e$response3 = _context.t0.response) == null ? void 0 : _e$response3.data.error_message);
879
+
880
+ if (!(errMsg && errMsg.match(/^.+does not exist$/))) {
881
+ _context.next = 20;
882
+ break;
883
+ }
884
+
885
+ throw new AuthenticationError(AuthenticationErrorReason.NotExists, errMsg);
886
+
887
+ case 20:
888
+ throw new AuthenticationError(AuthenticationErrorReason.General);
889
+
890
+ case 21:
891
+ case "end":
892
+ return _context.stop();
893
+ }
894
+ }
895
+ }, _callee, null, [[0, 7]]);
896
+ }));
897
+
898
+ return function (_x, _x2) {
899
+ return _ref2.apply(this, arguments);
900
+ };
901
+ }(), [locale]);
902
+
903
+ var verifyOtp = /*#__PURE__*/function () {
904
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(email, otp) {
905
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
906
+ while (1) {
907
+ switch (_context2.prev = _context2.next) {
908
+ case 0:
909
+ console.log("Verifying OTP for " + email);
910
+ _context2.next = 3;
911
+ return postOtpVerification({
912
+ username: email,
913
+ password: otp,
914
+ type: 'email'
915
+ }, ApiErrorHandler);
916
+
917
+ case 3:
918
+ return _context2.abrupt("return", _context2.sent);
919
+
920
+ case 4:
921
+ case "end":
922
+ return _context2.stop();
923
+ }
924
+ }
925
+ }, _callee2);
926
+ }));
927
+
928
+ return function verifyOtp(_x3, _x4) {
929
+ return _ref3.apply(this, arguments);
930
+ };
931
+ }();
932
+
933
+ var register = useCallback( /*#__PURE__*/function () {
934
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(email, password, token, location) {
935
+ var roles, result;
936
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
937
+ while (1) {
938
+ switch (_context3.prev = _context3.next) {
939
+ case 0:
940
+ console.log("Creating user for " + email + "; Location: " + location);
941
+ roles = getRoles(token);
942
+
943
+ if (!(token && roles)) {
944
+ _context3.next = 7;
945
+ break;
946
+ }
947
+
948
+ if (!roles.some(function (role) {
949
+ return role === Role.CustomerUser;
950
+ })) {
951
+ _context3.next = 5;
952
+ break;
953
+ }
954
+
955
+ throw new AuthenticationError(AuthenticationErrorReason.AlreadyExists);
956
+
957
+ case 5:
958
+ _context3.next = 8;
959
+ break;
960
+
961
+ case 7:
962
+ throw new Error('Cannot create account: Invalid OTP token');
963
+
964
+ case 8:
965
+ _context3.next = 10;
966
+ return postCreateAccount({
967
+ username: email,
968
+ password: password,
969
+ nickname: email,
970
+ locale: locale,
971
+ location: location
972
+ }, token, ApiErrorHandler);
973
+
974
+ case 10:
975
+ result = _context3.sent;
976
+ setAuthToken(result.emailIdentity);
977
+ return _context3.abrupt("return", result.emailIdentity);
978
+
979
+ case 13:
980
+ case "end":
981
+ return _context3.stop();
982
+ }
983
+ }
984
+ }, _callee3);
985
+ }));
986
+
987
+ return function (_x5, _x6, _x7, _x8) {
988
+ return _ref4.apply(this, arguments);
989
+ };
990
+ }(), [locale]);
991
+ var login = useCallback( /*#__PURE__*/function () {
992
+ var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(username, password) {
993
+ var token, _error$response, _error$response2;
994
+
995
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
996
+ while (1) {
997
+ switch (_context4.prev = _context4.next) {
998
+ case 0:
999
+ console.log("Login as " + username);
1000
+ _context4.prev = 1;
1001
+ _context4.next = 4;
1002
+ return postCreateToken({
1003
+ username: username,
1004
+ password: password,
1005
+ locale: 'en-HK'
1006
+ }, ApiErrorHandler);
1007
+
1008
+ case 4:
1009
+ token = _context4.sent;
1010
+ setAuthToken(token);
1011
+ return _context4.abrupt("return", token);
1012
+
1013
+ case 9:
1014
+ _context4.prev = 9;
1015
+ _context4.t0 = _context4["catch"](1);
1016
+
1017
+ if (!axios.isAxiosError(_context4.t0)) {
1018
+ _context4.next = 18;
1019
+ break;
1020
+ }
1021
+
1022
+ if (!(((_error$response = _context4.t0.response) == null ? void 0 : _error$response.status) === 401)) {
1023
+ _context4.next = 16;
1024
+ break;
1025
+ }
1026
+
1027
+ throw new AuthenticationError(AuthenticationErrorReason.InvalidCredential);
1028
+
1029
+ case 16:
1030
+ if (!(((_error$response2 = _context4.t0.response) == null ? void 0 : _error$response2.status) === 429)) {
1031
+ _context4.next = 18;
1032
+ break;
1033
+ }
1034
+
1035
+ throw new AuthenticationError(AuthenticationErrorReason.TooMany);
1036
+
1037
+ case 18:
1038
+ throw _context4.t0;
1039
+
1040
+ case 19:
1041
+ case "end":
1042
+ return _context4.stop();
1043
+ }
1044
+ }
1045
+ }, _callee4, null, [[1, 9]]);
1046
+ }));
1047
+
1048
+ return function (_x9, _x10) {
1049
+ return _ref5.apply(this, arguments);
1050
+ };
1051
+ }(), []);
1052
+ var logout = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
1053
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1054
+ while (1) {
1055
+ switch (_context5.prev = _context5.next) {
1056
+ case 0:
1057
+ console.log('Logout');
1058
+ setAuthToken(undefined);
1059
+
1060
+ case 2:
1061
+ case "end":
1062
+ return _context5.stop();
1063
+ }
1064
+ }
1065
+ }, _callee5);
1066
+ })), []);
1067
+ var updatePassword = useCallback( /*#__PURE__*/function () {
1068
+ var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(password, jwt) {
1069
+ var uid;
1070
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1071
+ while (1) {
1072
+ switch (_context6.prev = _context6.next) {
1073
+ case 0:
1074
+ console.log('Updating password');
1075
+ uid = getUserId(jwt);
1076
+
1077
+ if (uid) {
1078
+ _context6.next = 4;
1079
+ break;
1080
+ }
1081
+
1082
+ throw new Error('Missing user ID');
1083
+
1084
+ case 4:
1085
+ _context6.prev = 4;
1086
+ _context6.next = 7;
1087
+ return putUpdateUser({
1088
+ userid: uid,
1089
+ info: {
1090
+ password: password
1091
+ }
1092
+ }, jwt, ApiErrorHandler);
1093
+
1094
+ case 7:
1095
+ _context6.next = 12;
1096
+ break;
1097
+
1098
+ case 9:
1099
+ _context6.prev = 9;
1100
+ _context6.t0 = _context6["catch"](4);
1101
+ throw _context6.t0;
1102
+
1103
+ case 12:
1104
+ case "end":
1105
+ return _context6.stop();
1106
+ }
1107
+ }
1108
+ }, _callee6, null, [[4, 9]]);
1109
+ }));
1110
+
1111
+ return function (_x11, _x12) {
1112
+ return _ref7.apply(this, arguments);
1113
+ };
1114
+ }(), []);
1115
+ var authContext = React.useMemo(function () {
1116
+ return {
1117
+ token: authToken,
1118
+ requestOtp: requestOtp,
1119
+ verifyOtp: verifyOtp,
1120
+ register: register,
1121
+ login: login,
1122
+ logout: logout,
1123
+ updatePassword: updatePassword
1124
+ };
1125
+ }, [authToken, login, logout, register, requestOtp, updatePassword]);
1126
+ return React.createElement(AuthContext.Provider, {
1127
+ value: authContext
1128
+ }, children);
1129
+ };
1130
+ var useAuth = function useAuth() {
1131
+ return useContext(AuthContext);
1132
+ };
1133
+
1134
+ /* istanbul ignore next */
1135
+
1136
+ var ProfileContext = /*#__PURE__*/React.createContext({
1137
+ isProfileReady: false,
1138
+ userProfiles: undefined,
1139
+ rootProfile: undefined,
1140
+ currentProfile: undefined,
1141
+ setCurrentProfile: function setCurrentProfile() {
1142
+ return undefined;
1143
+ },
1144
+ createProfile: /*#__PURE__*/function () {
1145
+ var _createProfile = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1146
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1147
+ while (1) {
1148
+ switch (_context.prev = _context.next) {
1149
+ case 0:
1150
+ return _context.abrupt("return", {
1151
+ profileId: '',
1152
+ owner: '',
1153
+ root: false,
1154
+ name: {}
1155
+ });
1156
+
1157
+ case 1:
1158
+ case "end":
1159
+ return _context.stop();
1160
+ }
1161
+ }
1162
+ }, _callee);
1163
+ }));
1164
+
1165
+ function createProfile() {
1166
+ return _createProfile.apply(this, arguments);
1167
+ }
1168
+
1169
+ return createProfile;
1170
+ }(),
1171
+ updateProfile: /*#__PURE__*/function () {
1172
+ var _updateProfile = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1173
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1174
+ while (1) {
1175
+ switch (_context2.prev = _context2.next) {
1176
+ case 0:
1177
+ return _context2.abrupt("return");
1178
+
1179
+ case 1:
1180
+ case "end":
1181
+ return _context2.stop();
1182
+ }
1183
+ }
1184
+ }, _callee2);
1185
+ }));
1186
+
1187
+ function updateProfile() {
1188
+ return _updateProfile.apply(this, arguments);
1189
+ }
1190
+
1191
+ return updateProfile;
1192
+ }(),
1193
+ deleteProfile: /*#__PURE__*/function () {
1194
+ var _deleteProfile = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1195
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1196
+ while (1) {
1197
+ switch (_context3.prev = _context3.next) {
1198
+ case 0:
1199
+ return _context3.abrupt("return");
1200
+
1201
+ case 1:
1202
+ case "end":
1203
+ return _context3.stop();
1204
+ }
1205
+ }
1206
+ }, _callee3);
1207
+ }));
1208
+
1209
+ function deleteProfile() {
1210
+ return _deleteProfile.apply(this, arguments);
1211
+ }
1212
+
1213
+ return deleteProfile;
1214
+ }(),
1215
+ createTag: /*#__PURE__*/function () {
1216
+ var _createTag = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
1217
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1218
+ while (1) {
1219
+ switch (_context4.prev = _context4.next) {
1220
+ case 0:
1221
+ return _context4.abrupt("return");
1222
+
1223
+ case 1:
1224
+ case "end":
1225
+ return _context4.stop();
1226
+ }
1227
+ }
1228
+ }, _callee4);
1229
+ }));
1230
+
1231
+ function createTag() {
1232
+ return _createTag.apply(this, arguments);
1233
+ }
1234
+
1235
+ return createTag;
1236
+ }(),
1237
+ updateTag: /*#__PURE__*/function () {
1238
+ var _updateTag = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
1239
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1240
+ while (1) {
1241
+ switch (_context5.prev = _context5.next) {
1242
+ case 0:
1243
+ return _context5.abrupt("return");
1244
+
1245
+ case 1:
1246
+ case "end":
1247
+ return _context5.stop();
1248
+ }
1249
+ }
1250
+ }, _callee5);
1251
+ }));
1252
+
1253
+ function updateTag() {
1254
+ return _updateTag.apply(this, arguments);
1255
+ }
1256
+
1257
+ return updateTag;
1258
+ }(),
1259
+ deleteTag: /*#__PURE__*/function () {
1260
+ var _deleteTag = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
1261
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1262
+ while (1) {
1263
+ switch (_context6.prev = _context6.next) {
1264
+ case 0:
1265
+ return _context6.abrupt("return");
1266
+
1267
+ case 1:
1268
+ case "end":
1269
+ return _context6.stop();
1270
+ }
1271
+ }
1272
+ }, _callee6);
1273
+ }));
1274
+
1275
+ function deleteTag() {
1276
+ return _deleteTag.apply(this, arguments);
1277
+ }
1278
+
1279
+ return deleteTag;
1280
+ }(),
1281
+ createIdentity: /*#__PURE__*/function () {
1282
+ var _createIdentity = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
1283
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1284
+ while (1) {
1285
+ switch (_context7.prev = _context7.next) {
1286
+ case 0:
1287
+ return _context7.abrupt("return");
1288
+
1289
+ case 1:
1290
+ case "end":
1291
+ return _context7.stop();
1292
+ }
1293
+ }
1294
+ }, _callee7);
1295
+ }));
1296
+
1297
+ function createIdentity() {
1298
+ return _createIdentity.apply(this, arguments);
1299
+ }
1300
+
1301
+ return createIdentity;
1302
+ }(),
1303
+ updateIdentity: /*#__PURE__*/function () {
1304
+ var _updateIdentity = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
1305
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1306
+ while (1) {
1307
+ switch (_context8.prev = _context8.next) {
1308
+ case 0:
1309
+ return _context8.abrupt("return");
1310
+
1311
+ case 1:
1312
+ case "end":
1313
+ return _context8.stop();
1314
+ }
1315
+ }
1316
+ }, _callee8);
1317
+ }));
1318
+
1319
+ function updateIdentity() {
1320
+ return _updateIdentity.apply(this, arguments);
1321
+ }
1322
+
1323
+ return updateIdentity;
1324
+ }(),
1325
+ deleteIdentity: /*#__PURE__*/function () {
1326
+ var _deleteIdentity = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
1327
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1328
+ while (1) {
1329
+ switch (_context9.prev = _context9.next) {
1330
+ case 0:
1331
+ return _context9.abrupt("return");
1332
+
1333
+ case 1:
1334
+ case "end":
1335
+ return _context9.stop();
1336
+ }
1337
+ }
1338
+ }, _callee9);
1339
+ }));
1340
+
1341
+ function deleteIdentity() {
1342
+ return _deleteIdentity.apply(this, arguments);
1343
+ }
1344
+
1345
+ return deleteIdentity;
1346
+ }(),
1347
+ createAddress: /*#__PURE__*/function () {
1348
+ var _createAddress = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
1349
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1350
+ while (1) {
1351
+ switch (_context10.prev = _context10.next) {
1352
+ case 0:
1353
+ return _context10.abrupt("return");
1354
+
1355
+ case 1:
1356
+ case "end":
1357
+ return _context10.stop();
1358
+ }
1359
+ }
1360
+ }, _callee10);
1361
+ }));
1362
+
1363
+ function createAddress() {
1364
+ return _createAddress.apply(this, arguments);
1365
+ }
1366
+
1367
+ return createAddress;
1368
+ }(),
1369
+ updateQuestionnaire: /*#__PURE__*/function () {
1370
+ var _updateQuestionnaire = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
1371
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1372
+ while (1) {
1373
+ switch (_context11.prev = _context11.next) {
1374
+ case 0:
1375
+ return _context11.abrupt("return");
1376
+
1377
+ case 1:
1378
+ case "end":
1379
+ return _context11.stop();
1380
+ }
1381
+ }
1382
+ }, _callee11);
1383
+ }));
1384
+
1385
+ function updateQuestionnaire() {
1386
+ return _updateQuestionnaire.apply(this, arguments);
1387
+ }
1388
+
1389
+ return updateQuestionnaire;
1390
+ }(),
1391
+ createAvatar: /*#__PURE__*/function () {
1392
+ var _createAvatar = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1393
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1394
+ while (1) {
1395
+ switch (_context12.prev = _context12.next) {
1396
+ case 0:
1397
+ return _context12.abrupt("return");
1398
+
1399
+ case 1:
1400
+ case "end":
1401
+ return _context12.stop();
1402
+ }
1403
+ }
1404
+ }, _callee12);
1405
+ }));
1406
+
1407
+ function createAvatar() {
1408
+ return _createAvatar.apply(this, arguments);
1409
+ }
1410
+
1411
+ return createAvatar;
1412
+ }()
1413
+ });
1414
+
1415
+ var PARTNER = 'circle';
1416
+
1417
+ var hasKeys = function hasKeys(obj, keys) {
1418
+ return typeof obj === 'object' && keys.every(function (k) {
1419
+ return k in obj;
1420
+ });
1421
+ };
1422
+ function validateString(string) {
1423
+ if (typeof string === 'string') {
1424
+ return string;
1425
+ } else {
1426
+ throw new Error("Validation for string failed " + string);
1427
+ }
1428
+ }
1429
+ function validateNumber(number) {
1430
+ if (typeof number === 'number') {
1431
+ return number;
1432
+ } else {
1433
+ throw new Error('Validation for number failed');
1434
+ }
1435
+ }
1436
+ function validateBoolean(_boolean) {
1437
+ if (typeof _boolean === 'boolean') {
1438
+ return _boolean;
1439
+ } else {
1440
+ throw new Error('Validation for boolean failed');
1441
+ }
1442
+ }
1443
+ function validateOptionalString(string) {
1444
+ if (typeof string === 'string') {
1445
+ return string;
1446
+ } else {
1447
+ return undefined;
1448
+ }
1449
+ }
1450
+ function validateEnum(value, accepted) {
1451
+ if (typeof value === 'string' && accepted.includes(value)) {
1452
+ return value;
1453
+ } else {
1454
+ throw new Error("Validation for enum(" + value + ") failed");
1455
+ }
1456
+ }
1457
+ function validateArray(value, validationFunction) {
1458
+ if (Array.isArray(value)) {
1459
+ return value.map(validationFunction);
1460
+ } else {
1461
+ throw new Error('Validation for array failed');
1462
+ }
1463
+ } // export function parseUnixTimestampToMoment(value: unknown) {
1464
+ // if (typeof value !== 'number') {
1465
+ // throw new Error('Validation for unix timestamp failed');
1466
+ // }
1467
+ // const date = moment(value * 1000);
1468
+ // if (date.isValid()) {
1469
+ // return date;
1470
+ // } else {
1471
+ // throw new Error('Validation for unix timestamp failed');
1472
+ // }
1473
+ // }
1474
+ // export function validateAndTransformDateTimeString(value: string) {
1475
+ // const date = moment(value);
1476
+ // if (date.isValid()) {
1477
+ // return date.format('LLL');
1478
+ // } else {
1479
+ // throw new Error('Validation for unix timestamp failed');
1480
+ // }
1481
+ // }
1482
+ // export function validateMoment(value: unknown) {
1483
+ // const date = moment(validateString(value));
1484
+ // if (date.isValid()) {
1485
+ // return date;
1486
+ // } else {
1487
+ // throw new Error('Validation for string data failed');
1488
+ // }
1489
+ // }
1490
+
1491
+ var Ethnicity;
1492
+
1493
+ (function (Ethnicity) {
1494
+ Ethnicity["eastAsian"] = "eastasian";
1495
+ Ethnicity["southAsian"] = "southasian";
1496
+ Ethnicity["middleEastern"] = "middleeastern";
1497
+ Ethnicity["pacificIslander"] = "pacificislander";
1498
+ Ethnicity["nativeAmerican"] = "nativeamerican";
1499
+ Ethnicity["african"] = "african";
1500
+ Ethnicity["caucasian"] = "caucasian";
1501
+ Ethnicity["southEastAsian"] = "southeastasian";
1502
+ Ethnicity["hispanic"] = "hispanic";
1503
+ Ethnicity["eastAsianSouthEastAsian"] = "eastasiansoutheastasian";
1504
+ Ethnicity["other"] = "other";
1505
+ })(Ethnicity || (Ethnicity = {}));
1506
+
1507
+ var Ethnicities = /*#__PURE__*/Object.values(Ethnicity);
1508
+ var Gender;
1509
+
1510
+ (function (Gender) {
1511
+ Gender["male"] = "male";
1512
+ Gender["female"] = "female";
1513
+ })(Gender || (Gender = {}));
1514
+
1515
+ var IdentityType;
1516
+
1517
+ (function (IdentityType) {
1518
+ IdentityType["hkid"] = "hkid";
1519
+ IdentityType["hkidpassport"] = "hkidpassport";
1520
+ IdentityType["hkreturnhomepermit"] = "hkreturnhomepermit";
1521
+ IdentityType["passport"] = "passport";
1522
+ IdentityType["traveldocument"] = "traveldocument";
1523
+ IdentityType["externaluserid"] = "externaluserid";
1524
+ IdentityType["participantid"] = "participantid";
1525
+ IdentityType["castawayclubid"] = "castawayclubid";
1526
+ IdentityType["nhsnumber"] = "nhsnumber";
1527
+ IdentityType["microchipid"] = "microchipid";
1528
+ })(IdentityType || (IdentityType = {}));
1529
+
1530
+ var parseProfiles = function parseProfiles(profiles) {
1531
+ try {
1532
+ return profiles ? validateArray(profiles, parseProfile) : [];
1533
+ } catch (error) {
1534
+ console.log(error.stack);
1535
+ throw new Error("Failed to parse profiles: " + error);
1536
+ }
1537
+ };
1538
+ var parseProfile = function parseProfile(profile) {
1539
+ var expectedKeys = ['profileId', 'owner', 'name'];
1540
+
1541
+ if (!hasKeys(profile, expectedKeys)) {
1542
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1543
+ }
1544
+
1545
+ var profileId = profile.profileId,
1546
+ owner = profile.owner,
1547
+ name = profile.name;
1548
+ var validIdentityTypes = Object.values(IdentityType);
1549
+ return {
1550
+ profileId: validateString(profileId),
1551
+ owner: validateString(owner),
1552
+ root: hasKeys(profile, ['root']) && profile.root ? validateBoolean(profile.root) : false,
1553
+ name: parseProfileName(name),
1554
+ email: hasKeys(profile, ['email']) ? validateArray(profile.email, parseProfileEmail) : undefined,
1555
+ health: hasKeys(profile, ['health']) && isHealth(profile.health) ? parseProfileHealth(profile.health) : undefined,
1556
+ tag: hasKeys(profile, ['tag']) ? validateArray(profile.tag, parseProfileTag) : undefined,
1557
+ preference: hasKeys(profile, ['preference']) && isPreference(profile.preference) ? parseProfilePreference(profile.preference) : undefined,
1558
+ identity: hasKeys(profile, ['identity']) && Array.isArray(profile.identity) ? validateArray(profile.identity.filter(function (identity) {
1559
+ return typeof identity === 'object' && validIdentityTypes.includes(identity.identityType);
1560
+ }), parseProfileIdentity) : undefined,
1561
+ address: hasKeys(profile, ['address']) ? profile.address : undefined,
1562
+ phone: hasKeys(profile, ['phone']) ? profile.phone : undefined,
1563
+ species: hasKeys(profile, ['species']) ? profile.species : undefined,
1564
+ avatar: hasKeys(profile, ['avatar']) && isAvatar(profile.avatar) ? parseProfileAvatar(profile.avatar) : undefined
1565
+ };
1566
+ };
1567
+ var parseCreateProfile = function parseCreateProfile(profile) {
1568
+ var expectedKeys = ['profileId', 'owner', 'name'];
1569
+
1570
+ if (!hasKeys(profile, expectedKeys)) {
1571
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1572
+ }
1573
+
1574
+ var profileId = profile.profileId,
1575
+ owner = profile.owner,
1576
+ name = profile.name;
1577
+ return {
1578
+ profileId: validateString(profileId),
1579
+ owner: validateString(owner),
1580
+ root: hasKeys(profile, ['root']) && profile.root ? validateBoolean(profile.root) : false,
1581
+ name: parseProfileName(name)
1582
+ };
1583
+ };
1584
+
1585
+ var parseProfileName = function parseProfileName(profileName) {
1586
+ var expectedKeys = ['nameId'];
1587
+
1588
+ if (!hasKeys(profileName, expectedKeys)) {
1589
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1590
+ }
1591
+
1592
+ var nameId = profileName.nameId;
1593
+ return {
1594
+ nameId: validateString(nameId),
1595
+ lastName: hasKeys(profileName, ['lastName']) ? validateOptionalString(profileName.lastName) : undefined,
1596
+ firstName: hasKeys(profileName, ['firstName']) ? validateOptionalString(profileName.firstName) : undefined
1597
+ };
1598
+ };
1599
+
1600
+ var parseProfileHealth = function parseProfileHealth(profileHealth) {
1601
+ var expectedKeys = ['healthId', 'dob', 'gender', 'ethnicity', 'weight', 'weightUnit', 'height', 'heightUnit', 'questionnaire'];
1602
+
1603
+ if (!hasKeys(profileHealth, expectedKeys)) {
1604
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1605
+ }
1606
+
1607
+ var healthId = profileHealth.healthId,
1608
+ dob = profileHealth.dob,
1609
+ gender = profileHealth.gender,
1610
+ ethnicity = profileHealth.ethnicity,
1611
+ weight = profileHealth.weight,
1612
+ weightUnit = profileHealth.weightUnit,
1613
+ height = profileHealth.height,
1614
+ heightUnit = profileHealth.heightUnit,
1615
+ questionnaire = profileHealth.questionnaire;
1616
+ return {
1617
+ healthId: validateString(healthId),
1618
+ dob: validateString(dob),
1619
+ gender: validateEnum(gender, Object.values(Gender)),
1620
+ ethnicity: Object.values(Ethnicity).includes(ethnicity) ? ethnicity : undefined,
1621
+ weight: weight ? {
1622
+ value: Number(validateString(weight)),
1623
+ unit: validateString(weightUnit)
1624
+ } : undefined,
1625
+ height: height ? {
1626
+ value: validateNumber(height),
1627
+ unit: validateString(heightUnit)
1628
+ } : undefined,
1629
+ questionnaire: questionnaire
1630
+ };
1631
+ };
1632
+
1633
+ var isHealth = function isHealth(health) {
1634
+ if (typeof health !== 'object' || !health) {
1635
+ return false;
1636
+ }
1637
+
1638
+ return Object.keys(health).includes('healthId');
1639
+ };
1640
+
1641
+ var isAvatar = function isAvatar(avatar) {
1642
+ if (typeof avatar !== 'object' || !avatar) {
1643
+ return false;
1644
+ }
1645
+
1646
+ return Object.keys(avatar).includes('avatarId');
1647
+ };
1648
+
1649
+ var isPreference = function isPreference(preference) {
1650
+ if (typeof preference !== 'object' || !preference) {
1651
+ return false;
1652
+ }
1653
+
1654
+ return Object.keys(preference).includes('preferenceId');
1655
+ };
1656
+
1657
+ var parseProfilePreference = function parseProfilePreference(profilePreference) {
1658
+ var expectedKeys = ['preferenceId', 'language'];
1659
+
1660
+ if (!hasKeys(profilePreference, expectedKeys)) {
1661
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1662
+ }
1663
+
1664
+ var preferenceId = profilePreference.preferenceId,
1665
+ language = profilePreference.language;
1666
+ var location = hasKeys(profilePreference, ['location']) && profilePreference.location ? validateString(profilePreference.location) : undefined;
1667
+ return {
1668
+ preferenceId: validateString(preferenceId),
1669
+ language: validateString(language),
1670
+ location: location
1671
+ };
1672
+ };
1673
+
1674
+ var parseProfileEmail = function parseProfileEmail(profileEmail) {
1675
+ var expectedKeys = ['emailId', 'datetime', 'primary', 'name', 'email'];
1676
+
1677
+ if (!hasKeys(profileEmail, expectedKeys)) {
1678
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1679
+ }
1680
+
1681
+ var emailId = profileEmail.emailId,
1682
+ datetime = profileEmail.datetime,
1683
+ primary = profileEmail.primary,
1684
+ name = profileEmail.name,
1685
+ email = profileEmail.email;
1686
+ return {
1687
+ emailId: validateString(emailId),
1688
+ datetime: validateString(datetime),
1689
+ primary: validateBoolean(primary),
1690
+ name: validateString(name),
1691
+ email: validateString(email)
1692
+ };
1693
+ };
1694
+
1695
+ var parseDeleteProfile = function parseDeleteProfile(deleteProfile) {
1696
+ var expectedKeys = ['profileId', 'active'];
1697
+
1698
+ if (!hasKeys(deleteProfile, expectedKeys)) {
1699
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1700
+ }
1701
+
1702
+ var profileId = deleteProfile.profileId,
1703
+ active = deleteProfile.active;
1704
+ return {
1705
+ profileId: validateString(profileId),
1706
+ active: validateBoolean(active)
1707
+ };
1708
+ };
1709
+
1710
+ function parseProfileTag(profileTag) {
1711
+ var expectedKeys = ['tagId', 'tag', 'active', 'modified'];
1712
+
1713
+ if (!hasKeys(profileTag, expectedKeys)) {
1714
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1715
+ }
1716
+
1717
+ var tagId = profileTag.tagId,
1718
+ tag = profileTag.tag,
1719
+ active = profileTag.active,
1720
+ modified = profileTag.modified;
1721
+ return {
1722
+ tagId: validateString(tagId),
1723
+ tag: validateString(tag),
1724
+ active: validateBoolean(active),
1725
+ modified: validateString(modified)
1726
+ };
1727
+ }
1728
+
1729
+ function parseProfileIdentity(profileIdentity) {
1730
+ var expectedKeys = ['identityId', 'identityType', 'identityValue'];
1731
+
1732
+ if (!hasKeys(profileIdentity, expectedKeys)) {
1733
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1734
+ }
1735
+
1736
+ var identityId = profileIdentity.identityId,
1737
+ identityType = profileIdentity.identityType,
1738
+ identityValue = profileIdentity.identityValue;
1739
+ return {
1740
+ identityId: validateString(identityId),
1741
+ identityType: validateEnum(identityType, Object.values(IdentityType)),
1742
+ identityValue: validateString(identityValue)
1743
+ };
1744
+ }
1745
+
1746
+ function parseProfileAvatar(profileAvatar) {
1747
+ var expectedKeys = ['url', 'avatarId', 'status'];
1748
+
1749
+ if (!hasKeys(profileAvatar, expectedKeys)) {
1750
+ throw new Error("Missing keys " + expectedKeys.join(', '));
1751
+ }
1752
+
1753
+ var url = profileAvatar.url,
1754
+ avatarId = profileAvatar.avatarId,
1755
+ status = profileAvatar.status;
1756
+ return {
1757
+ url: validateString(url),
1758
+ avatarId: validateString(avatarId),
1759
+ status: validateString(status)
1760
+ };
1761
+ }
1762
+
1763
+ var baseURL = undefined;
1764
+ var application = 'profile'; // Get Profiles
1765
+
1766
+ var getProfiles = function getProfiles(token, species, handler) {
1767
+ if (species === void 0) {
1768
+ species = 'all';
1769
+ }
1770
+
1771
+ return request({
1772
+ baseURL: baseURL,
1773
+ url: application + '/v1.0/profile',
1774
+ method: 'GET',
1775
+ headers: AuthHeader(token),
1776
+ params: {
1777
+ species: species
1778
+ }
1779
+ }, handler).then(function (response) {
1780
+ return parseProfiles(response == null ? void 0 : response.data);
1781
+ })["catch"](function (e) {
1782
+ console.warn("Invalid profile: " + e);
1783
+ throw e;
1784
+ });
1785
+ };
1786
+ var postCreateProfile = function postCreateProfile(context, token, handler) {
1787
+ var _context$health, _context$health$weigh, _context$health2, _context$health2$weig;
1788
+
1789
+ return request({
1790
+ baseURL: baseURL,
1791
+ url: application + '/v1.0/profile',
1792
+ params: {
1793
+ health: !!context.health,
1794
+ email: !!context.email,
1795
+ preference: true,
1796
+ identity: !!context.identities && context.identities.length > 0,
1797
+ species: !!context.species
1798
+ },
1799
+ method: 'POST',
1800
+ data: {
1801
+ profile: {
1802
+ name: {
1803
+ firstName: context.firstName,
1804
+ lastName: context.lastName
1805
+ },
1806
+ email: {
1807
+ name: v4(),
1808
+ primary: true,
1809
+ detail: {
1810
+ email: context.email
1811
+ }
1812
+ },
1813
+ health: _extends({}, context.health, {
1814
+ weight: {
1815
+ value: (_context$health = context.health) == null ? void 0 : (_context$health$weigh = _context$health.weight) == null ? void 0 : _context$health$weigh.value.toFixed(1),
1816
+ unit: (_context$health2 = context.health) == null ? void 0 : (_context$health2$weig = _context$health2.weight) == null ? void 0 : _context$health2$weig.unit
1817
+ }
1818
+ }),
1819
+ preference: {
1820
+ language: context.locale
1821
+ },
1822
+ identities: context.identities,
1823
+ species: context.species || undefined
1824
+ }
1825
+ },
1826
+ headers: AuthHeader(token)
1827
+ }, handler).then(function (response) {
1828
+ return parseCreateProfile(response == null ? void 0 : response.data);
1829
+ });
1830
+ };
1831
+ var putUpdateProfilePreference = /*#__PURE__*/function () {
1832
+ var _ref = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(context, token, handler) {
1833
+ var response;
1834
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1835
+ while (1) {
1836
+ switch (_context.prev = _context.next) {
1837
+ case 0:
1838
+ _context.next = 2;
1839
+ return request({
1840
+ baseURL: baseURL,
1841
+ url: application + '/v1.0/profile/:profileid/preference',
1842
+ method: 'PUT',
1843
+ data: {
1844
+ preference: {
1845
+ language: context.language,
1846
+ location: context.location
1847
+ }
1848
+ },
1849
+ headers: AuthHeader(token)
1850
+ }, handler, {
1851
+ profileid: context.profileId
1852
+ });
1853
+
1854
+ case 2:
1855
+ response = _context.sent;
1856
+ return _context.abrupt("return", response);
1857
+
1858
+ case 4:
1859
+ case "end":
1860
+ return _context.stop();
1861
+ }
1862
+ }
1863
+ }, _callee);
1864
+ }));
1865
+
1866
+ return function putUpdateProfilePreference(_x, _x2, _x3) {
1867
+ return _ref.apply(this, arguments);
1868
+ };
1869
+ }();
1870
+ var putUpdateProfileName = /*#__PURE__*/function () {
1871
+ var _ref2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(context, token, handler) {
1872
+ var response;
1873
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1874
+ while (1) {
1875
+ switch (_context2.prev = _context2.next) {
1876
+ case 0:
1877
+ _context2.next = 2;
1878
+ return request({
1879
+ baseURL: baseURL,
1880
+ url: application + '/v1.0/profile/:profileid/name',
1881
+ method: 'PUT',
1882
+ data: {
1883
+ name: {
1884
+ firstName: context.firstName,
1885
+ lastName: context.lastName
1886
+ }
1887
+ },
1888
+ headers: AuthHeader(token)
1889
+ }, handler, {
1890
+ profileid: context.profileId
1891
+ });
1892
+
1893
+ case 2:
1894
+ response = _context2.sent;
1895
+ return _context2.abrupt("return", response);
1896
+
1897
+ case 4:
1898
+ case "end":
1899
+ return _context2.stop();
1900
+ }
1901
+ }
1902
+ }, _callee2);
1903
+ }));
1904
+
1905
+ return function putUpdateProfileName(_x4, _x5, _x6) {
1906
+ return _ref2.apply(this, arguments);
1907
+ };
1908
+ }();
1909
+ var putUpdateProfileHealth = /*#__PURE__*/function () {
1910
+ var _ref3 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(context, token, handler) {
1911
+ var _context$weight, _context$weight2;
1912
+
1913
+ var response;
1914
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1915
+ while (1) {
1916
+ switch (_context3.prev = _context3.next) {
1917
+ case 0:
1918
+ _context3.next = 2;
1919
+ return request({
1920
+ baseURL: baseURL,
1921
+ url: application + '/v1.0/profile/:profileid/health',
1922
+ method: 'PUT',
1923
+ data: {
1924
+ health: {
1925
+ weight: context.weight ? {
1926
+ unit: (_context$weight = context.weight) == null ? void 0 : _context$weight.unit,
1927
+ value: (_context$weight2 = context.weight) == null ? void 0 : _context$weight2.value.toFixed(1)
1928
+ } : undefined,
1929
+ height: context.height,
1930
+ gender: context.gender,
1931
+ dob: context.dob,
1932
+ ethnicity: context.ethnicity
1933
+ }
1934
+ },
1935
+ headers: AuthHeader(token)
1936
+ }, handler, {
1937
+ profileid: context.profileId
1938
+ });
1939
+
1940
+ case 2:
1941
+ response = _context3.sent;
1942
+ return _context3.abrupt("return", response);
1943
+
1944
+ case 4:
1945
+ case "end":
1946
+ return _context3.stop();
1947
+ }
1948
+ }
1949
+ }, _callee3);
1950
+ }));
1951
+
1952
+ return function putUpdateProfileHealth(_x7, _x8, _x9) {
1953
+ return _ref3.apply(this, arguments);
1954
+ };
1955
+ }();
1956
+ var postCreateProfileAddress = /*#__PURE__*/function () {
1957
+ var _ref4 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(context, token, handler) {
1958
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1959
+ while (1) {
1960
+ switch (_context4.prev = _context4.next) {
1961
+ case 0:
1962
+ _context4.next = 2;
1963
+ return request({
1964
+ baseURL: baseURL,
1965
+ url: application + '/v1.0/profile/:profileid/address',
1966
+ method: 'POST',
1967
+ data: {
1968
+ address: {
1969
+ name: v4(),
1970
+ primary: true,
1971
+ detail: context.address
1972
+ }
1973
+ },
1974
+ headers: AuthHeader(token)
1975
+ }, handler, {
1976
+ profileid: context.profileId
1977
+ });
1978
+
1979
+ case 2:
1980
+ return _context4.abrupt("return", _context4.sent);
1981
+
1982
+ case 3:
1983
+ case "end":
1984
+ return _context4.stop();
1985
+ }
1986
+ }
1987
+ }, _callee4);
1988
+ }));
1989
+
1990
+ return function postCreateProfileAddress(_x10, _x11, _x12) {
1991
+ return _ref4.apply(this, arguments);
1992
+ };
1993
+ }(); // FIXME: We should support the rest of field and move the all update profile call to use this one.
1994
+ // Currently we are only doing phone update.
1995
+
1996
+ var patchUpdateProfile = /*#__PURE__*/function () {
1997
+ var _ref5 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(context, token, handler) {
1998
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1999
+ while (1) {
2000
+ switch (_context5.prev = _context5.next) {
2001
+ case 0:
2002
+ _context5.next = 2;
2003
+ return request({
2004
+ baseURL: baseURL,
2005
+ url: application + '/v1.0/profile/:profileid',
2006
+ method: 'PATCH',
2007
+ data: {
2008
+ profile: {
2009
+ phone: {
2010
+ name: v4(),
2011
+ primary: true,
2012
+ detail: context.phone
2013
+ },
2014
+ species: context.species
2015
+ }
2016
+ },
2017
+ params: {
2018
+ phone: !!context.phone,
2019
+ species: !!context.species
2020
+ },
2021
+ headers: AuthHeader(token)
2022
+ }, handler, {
2023
+ profileid: context.profileId
2024
+ });
2025
+
2026
+ case 2:
2027
+ return _context5.abrupt("return", _context5.sent);
2028
+
2029
+ case 3:
2030
+ case "end":
2031
+ return _context5.stop();
2032
+ }
2033
+ }
2034
+ }, _callee5);
2035
+ }));
2036
+
2037
+ return function patchUpdateProfile(_x13, _x14, _x15) {
2038
+ return _ref5.apply(this, arguments);
2039
+ };
2040
+ }();
2041
+ var deleteRemoveProfile = /*#__PURE__*/function () {
2042
+ var _ref6 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(context, token, handler) {
2043
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
2044
+ while (1) {
2045
+ switch (_context6.prev = _context6.next) {
2046
+ case 0:
2047
+ return _context6.abrupt("return", request({
2048
+ baseURL: baseURL,
2049
+ url: application + '/v1.0/profile/:profileid',
2050
+ method: 'DELETE',
2051
+ headers: AuthHeader(token)
2052
+ }, handler, {
2053
+ profileid: context.profileId
2054
+ }).then(function (response) {
2055
+ return parseDeleteProfile(response == null ? void 0 : response.data);
2056
+ }));
2057
+
2058
+ case 1:
2059
+ case "end":
2060
+ return _context6.stop();
2061
+ }
2062
+ }
2063
+ }, _callee6);
2064
+ }));
2065
+
2066
+ return function deleteRemoveProfile(_x16, _x17, _x18) {
2067
+ return _ref6.apply(this, arguments);
2068
+ };
2069
+ }();
2070
+ var postCreateTag = function postCreateTag(context, token, handler) {
2071
+ return request({
2072
+ baseURL: baseURL,
2073
+ url: application + '/v1.0/profile/:profileid/tag',
2074
+ method: 'POST',
2075
+ data: {
2076
+ tag: {
2077
+ tag: context.tag
2078
+ }
2079
+ },
2080
+ headers: AuthHeader(token)
2081
+ }, handler, {
2082
+ profileid: context.profileId
2083
+ });
2084
+ };
2085
+ var putUpdateTag = function putUpdateTag(context, token, handler) {
2086
+ return request({
2087
+ baseURL: baseURL,
2088
+ url: application + '/v1.0/profile/:profileid/tag',
2089
+ method: 'PUT',
2090
+ data: {
2091
+ tag: {
2092
+ tag: context.tag
2093
+ }
2094
+ },
2095
+ headers: AuthHeader(token)
2096
+ }, handler, {
2097
+ profileid: context.profileId
2098
+ });
2099
+ };
2100
+ var deleteTag = function deleteTag(context, token, handler) {
2101
+ return request({
2102
+ baseURL: baseURL,
2103
+ url: application + '/v1.0/profile/:profileid/tag/:tagId',
2104
+ method: 'DELETE',
2105
+ data: {},
2106
+ headers: AuthHeader(token)
2107
+ }, handler, {
2108
+ profileid: context.profileId,
2109
+ tagId: context.tagId
2110
+ });
2111
+ };
2112
+ var postProfileIdentity = function postProfileIdentity(context, token, handler) {
2113
+ return request({
2114
+ baseURL: baseURL,
2115
+ url: application + '/v1.0/profile/:profileid/identity',
2116
+ method: 'POST',
2117
+ data: {
2118
+ identity: {
2119
+ identityType: context.identityType,
2120
+ identityValue: context.identityValue
2121
+ }
2122
+ },
2123
+ headers: AuthHeader(token)
2124
+ }, handler, {
2125
+ profileid: context.profileId
2126
+ });
2127
+ };
2128
+ var putUpdateProfileIdentity = function putUpdateProfileIdentity(context, token, handler) {
2129
+ return request({
2130
+ baseURL: baseURL,
2131
+ url: application + '/v1.0/profile/:profileid/identity/:identityId',
2132
+ method: 'PATCH',
2133
+ data: {
2134
+ identityType: context.identityType,
2135
+ identityValue: context.identityValue
2136
+ },
2137
+ headers: AuthHeader(token)
2138
+ }, handler, {
2139
+ profileid: context.profileId,
2140
+ identityId: context.identityId
2141
+ });
2142
+ };
2143
+ var deleteProfileIdentity = function deleteProfileIdentity(context, token, handler) {
2144
+ return request({
2145
+ baseURL: baseURL,
2146
+ url: application + '/v1.0/profile/:profileid/identity/:identityId',
2147
+ method: 'DELETE',
2148
+ headers: AuthHeader(token)
2149
+ }, handler, {
2150
+ profileid: context.profileId,
2151
+ identityId: context.identityId
2152
+ });
2153
+ };
2154
+ var putUpdateQuestionnaire = function putUpdateQuestionnaire(context, token, handler) {
2155
+ var _answers;
2156
+
2157
+ return request({
2158
+ baseURL: baseURL,
2159
+ url: application + '/v1.0/health/:healthid/questionnaire',
2160
+ method: 'PUT',
2161
+ data: {
2162
+ answers: (_answers = {}, _answers[PARTNER] = context.answers, _answers)
2163
+ },
2164
+ headers: _extends({}, AuthHeader(token), {
2165
+ 'x-owner': context.owner
2166
+ })
2167
+ }, handler, {
2168
+ healthid: context.healthId
2169
+ });
2170
+ };
2171
+ var postProfileAvatar = /*#__PURE__*/function () {
2172
+ var _ref7 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(context, token, handler) {
2173
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
2174
+ while (1) {
2175
+ switch (_context7.prev = _context7.next) {
2176
+ case 0:
2177
+ _context7.next = 2;
2178
+ return request({
2179
+ baseURL: baseURL,
2180
+ url: application + '/v1.0/profile/:profileid/avatar',
2181
+ method: 'POST',
2182
+ data: context.formData,
2183
+ headers: _extends({}, AuthHeader(token), {
2184
+ 'content-type': 'multipart/form-data'
2185
+ })
2186
+ }, handler, {
2187
+ profileid: context.profileId
2188
+ });
2189
+
2190
+ case 2:
2191
+ return _context7.abrupt("return", _context7.sent);
2192
+
2193
+ case 3:
2194
+ case "end":
2195
+ return _context7.stop();
2196
+ }
2197
+ }
2198
+ }, _callee7);
2199
+ }));
2200
+
2201
+ return function postProfileAvatar(_x19, _x20, _x21) {
2202
+ return _ref7.apply(this, arguments);
2203
+ };
2204
+ }();
2205
+
2206
+ var getProfileDateTime = function getProfileDateTime(profile) {
2207
+ var _profile$email;
2208
+
2209
+ var profileEmail = (_profile$email = profile.email) == null ? void 0 : _profile$email.find(function (email) {
2210
+ return email.datetime;
2211
+ });
2212
+ if (!profileEmail) return;
2213
+ var date = moment(validateString(profileEmail.datetime));
2214
+
2215
+ if (date.isValid()) {
2216
+ return date;
2217
+ }
2218
+ };
2219
+
2220
+ var getRootProfile = function getRootProfile(profiles) {
2221
+ return profiles.find(function (item) {
2222
+ return item.root;
2223
+ });
2224
+ };
2225
+ var getUserProfile = function getUserProfile(profiles) {
2226
+ return profiles.filter(function (profile) {
2227
+ return !profile.root;
2228
+ }).sort(function (a, b) {
2229
+ var aDate = getProfileDateTime(a);
2230
+ var bDate = getProfileDateTime(b);
2231
+
2232
+ if (!aDate || !bDate) {
2233
+ return 1;
2234
+ }
2235
+
2236
+ return bDate.diff(aDate);
2237
+ });
2238
+ };
2239
+
2240
+ var usePrevious = function usePrevious(value) {
2241
+ var ref = useRef();
2242
+ useEffect(function () {
2243
+ ref.current = value;
2244
+ });
2245
+ return ref.current;
2246
+ };
2247
+
2248
+ var ProfileProvider = function ProfileProvider(_ref) {
2249
+ var children = _ref.children,
2250
+ _ref$locale = _ref.locale,
2251
+ locale = _ref$locale === void 0 ? 'en-HK' : _ref$locale,
2252
+ defaults = _ref.defaults,
2253
+ capturing = _ref.capturing;
2254
+
2255
+ // Provider
2256
+ var _useAuth = useAuth(),
2257
+ token = _useAuth.token; // State
2258
+
2259
+
2260
+ var _useState = useState(false),
2261
+ isReady = _useState[0],
2262
+ setReady = _useState[1];
2263
+
2264
+ var _useState2 = useState(),
2265
+ profiles = _useState2[0],
2266
+ setProfiles = _useState2[1];
2267
+
2268
+ var _useState3 = useState(),
2269
+ userProfiles = _useState3[0],
2270
+ setUserProfiles = _useState3[1];
2271
+
2272
+ var _useState4 = useState(),
2273
+ rootProfile = _useState4[0],
2274
+ setRootProfile = _useState4[1];
2275
+
2276
+ var _useState5 = useState(),
2277
+ currentProfile = _useState5[0],
2278
+ _setCurrentProfile = _useState5[1];
2279
+
2280
+ var prevRootProfile = usePrevious(rootProfile);
2281
+ var prevCurrentProfile = usePrevious(currentProfile);
2282
+ var refreshProfiles = useCallback( /*#__PURE__*/function () {
2283
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(token) {
2284
+ var profiles;
2285
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2286
+ while (1) {
2287
+ switch (_context.prev = _context.next) {
2288
+ case 0:
2289
+ if (token) {
2290
+ _context.next = 2;
2291
+ break;
2292
+ }
2293
+
2294
+ return _context.abrupt("return");
2295
+
2296
+ case 2:
2297
+ _context.next = 4;
2298
+ return getProfiles(token, 'all', ApiErrorHandler);
2299
+
2300
+ case 4:
2301
+ profiles = _context.sent;
2302
+ setProfiles(profiles);
2303
+ setUserProfiles(getUserProfile(profiles));
2304
+ setRootProfile(getRootProfile(profiles));
2305
+
2306
+ case 8:
2307
+ case "end":
2308
+ return _context.stop();
2309
+ }
2310
+ }
2311
+ }, _callee);
2312
+ }));
2313
+
2314
+ return function (_x) {
2315
+ return _ref2.apply(this, arguments);
2316
+ };
2317
+ }(), []);
2318
+ var createProfile = useCallback( /*#__PURE__*/function () {
2319
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(context) {
2320
+ var newProfie;
2321
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2322
+ while (1) {
2323
+ switch (_context2.prev = _context2.next) {
2324
+ case 0:
2325
+ _context2.prev = 0;
2326
+
2327
+ if (token) {
2328
+ _context2.next = 3;
2329
+ break;
2330
+ }
2331
+
2332
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2333
+
2334
+ case 3:
2335
+ console.log("Creating profile " + context.firstName + " " + context.lastName);
2336
+ _context2.next = 6;
2337
+ return postCreateProfile(context, token, ApiErrorHandler);
2338
+
2339
+ case 6:
2340
+ newProfie = _context2.sent;
2341
+ _context2.next = 9;
2342
+ return refreshProfiles(token);
2343
+
2344
+ case 9:
2345
+ console.log('Set default profile to new profile:', newProfie.profileId);
2346
+
2347
+ _setCurrentProfile(newProfie);
2348
+
2349
+ return _context2.abrupt("return", newProfie);
2350
+
2351
+ case 14:
2352
+ _context2.prev = 14;
2353
+ _context2.t0 = _context2["catch"](0);
2354
+ throw _context2.t0;
2355
+
2356
+ case 17:
2357
+ case "end":
2358
+ return _context2.stop();
2359
+ }
2360
+ }
2361
+ }, _callee2, null, [[0, 14]]);
2362
+ }));
2363
+
2364
+ return function (_x2) {
2365
+ return _ref3.apply(this, arguments);
2366
+ };
2367
+ }(), [refreshProfiles, token]);
2368
+ var updateProfile = useCallback( /*#__PURE__*/function () {
2369
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(profileId, category, refresh) {
2370
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
2371
+ while (1) {
2372
+ switch (_context3.prev = _context3.next) {
2373
+ case 0:
2374
+ if (refresh === void 0) {
2375
+ refresh = true;
2376
+ }
2377
+
2378
+ _context3.prev = 1;
2379
+
2380
+ if (token) {
2381
+ _context3.next = 4;
2382
+ break;
2383
+ }
2384
+
2385
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2386
+
2387
+ case 4:
2388
+ _context3.t0 = category.preference;
2389
+
2390
+ if (!_context3.t0) {
2391
+ _context3.next = 8;
2392
+ break;
2393
+ }
2394
+
2395
+ _context3.next = 8;
2396
+ return putUpdateProfilePreference({
2397
+ profileId: profileId,
2398
+ language: category.preference.language,
2399
+ location: category.preference.location || undefined
2400
+ }, token, ApiErrorHandler);
2401
+
2402
+ case 8:
2403
+ _context3.t1 = category.name;
2404
+
2405
+ if (!_context3.t1) {
2406
+ _context3.next = 12;
2407
+ break;
2408
+ }
2409
+
2410
+ _context3.next = 12;
2411
+ return putUpdateProfileName({
2412
+ profileId: profileId,
2413
+ firstName: category.name.firstName,
2414
+ lastName: category.name.lastName
2415
+ }, token, ApiErrorHandler);
2416
+
2417
+ case 12:
2418
+ _context3.t2 = category.health && category.health.dob && category.health.ethnicity;
2419
+
2420
+ if (!_context3.t2) {
2421
+ _context3.next = 16;
2422
+ break;
2423
+ }
2424
+
2425
+ _context3.next = 16;
2426
+ return putUpdateProfileHealth({
2427
+ profileId: profileId,
2428
+ gender: category.health.gender,
2429
+ dob: category.health.dob,
2430
+ ethnicity: category.health.ethnicity,
2431
+ height: category.health.height ? {
2432
+ value: category.health.height.value,
2433
+ unit: category.health.height.unit
2434
+ } : undefined,
2435
+ weight: category.health.weight ? {
2436
+ value: category.health.weight.value,
2437
+ unit: category.health.weight.unit
2438
+ } : undefined
2439
+ }, token, ApiErrorHandler);
2440
+
2441
+ case 16:
2442
+ _context3.t3 = category.phone || category.species;
2443
+
2444
+ if (!_context3.t3) {
2445
+ _context3.next = 20;
2446
+ break;
2447
+ }
2448
+
2449
+ _context3.next = 20;
2450
+ return patchUpdateProfile({
2451
+ profileId: profileId,
2452
+ phone: category.phone,
2453
+ species: category.species
2454
+ }, token, ApiErrorHandler);
2455
+
2456
+ case 20:
2457
+ if (!refresh) {
2458
+ _context3.next = 24;
2459
+ break;
2460
+ }
2461
+
2462
+ console.log('Refresh after profile update');
2463
+ _context3.next = 24;
2464
+ return refreshProfiles(token);
2465
+
2466
+ case 24:
2467
+ _context3.next = 29;
2468
+ break;
2469
+
2470
+ case 26:
2471
+ _context3.prev = 26;
2472
+ _context3.t4 = _context3["catch"](1);
2473
+ throw _context3.t4;
2474
+
2475
+ case 29:
2476
+ case "end":
2477
+ return _context3.stop();
2478
+ }
2479
+ }
2480
+ }, _callee3, null, [[1, 26]]);
2481
+ }));
2482
+
2483
+ return function (_x3, _x4, _x5) {
2484
+ return _ref4.apply(this, arguments);
2485
+ };
2486
+ }(), [refreshProfiles, token]);
2487
+ var deleteProfile = useCallback( /*#__PURE__*/function () {
2488
+ var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(profileId) {
2489
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
2490
+ while (1) {
2491
+ switch (_context4.prev = _context4.next) {
2492
+ case 0:
2493
+ _context4.prev = 0;
2494
+
2495
+ if (token) {
2496
+ _context4.next = 3;
2497
+ break;
2498
+ }
2499
+
2500
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2501
+
2502
+ case 3:
2503
+ _context4.next = 5;
2504
+ return deleteRemoveProfile({
2505
+ profileId: profileId
2506
+ }, token, ApiErrorHandler);
2507
+
2508
+ case 5:
2509
+ _context4.next = 7;
2510
+ return refreshProfiles(token);
2511
+
2512
+ case 7:
2513
+ _context4.next = 12;
2514
+ break;
2515
+
2516
+ case 9:
2517
+ _context4.prev = 9;
2518
+ _context4.t0 = _context4["catch"](0);
2519
+ throw _context4.t0;
2520
+
2521
+ case 12:
2522
+ case "end":
2523
+ return _context4.stop();
2524
+ }
2525
+ }
2526
+ }, _callee4, null, [[0, 9]]);
2527
+ }));
2528
+
2529
+ return function (_x6) {
2530
+ return _ref5.apply(this, arguments);
2531
+ };
2532
+ }(), [refreshProfiles, token]);
2533
+ var createTag = useCallback( /*#__PURE__*/function () {
2534
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(profileId, tag) {
2535
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2536
+ while (1) {
2537
+ switch (_context5.prev = _context5.next) {
2538
+ case 0:
2539
+ if (token) {
2540
+ _context5.next = 2;
2541
+ break;
2542
+ }
2543
+
2544
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2545
+
2546
+ case 2:
2547
+ _context5.next = 4;
2548
+ return postCreateTag({
2549
+ profileId: profileId,
2550
+ tag: tag
2551
+ }, token, ApiErrorHandler);
2552
+
2553
+ case 4:
2554
+ _context5.next = 6;
2555
+ return refreshProfiles(token);
2556
+
2557
+ case 6:
2558
+ case "end":
2559
+ return _context5.stop();
2560
+ }
2561
+ }
2562
+ }, _callee5);
2563
+ }));
2564
+
2565
+ return function (_x7, _x8) {
2566
+ return _ref6.apply(this, arguments);
2567
+ };
2568
+ }(), [refreshProfiles, token]);
2569
+ var updateTag = useCallback( /*#__PURE__*/function () {
2570
+ var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(profileId, tag) {
2571
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
2572
+ while (1) {
2573
+ switch (_context6.prev = _context6.next) {
2574
+ case 0:
2575
+ if (token) {
2576
+ _context6.next = 2;
2577
+ break;
2578
+ }
2579
+
2580
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2581
+
2582
+ case 2:
2583
+ _context6.next = 4;
2584
+ return putUpdateTag({
2585
+ profileId: profileId,
2586
+ tag: tag
2587
+ }, token, ApiErrorHandler);
2588
+
2589
+ case 4:
2590
+ _context6.next = 6;
2591
+ return refreshProfiles(token);
2592
+
2593
+ case 6:
2594
+ case "end":
2595
+ return _context6.stop();
2596
+ }
2597
+ }
2598
+ }, _callee6);
2599
+ }));
2600
+
2601
+ return function (_x9, _x10) {
2602
+ return _ref7.apply(this, arguments);
2603
+ };
2604
+ }(), [refreshProfiles, token]);
2605
+ var deleteTag$1 = useCallback( /*#__PURE__*/function () {
2606
+ var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(profileId, tagId) {
2607
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
2608
+ while (1) {
2609
+ switch (_context7.prev = _context7.next) {
2610
+ case 0:
2611
+ if (token) {
2612
+ _context7.next = 2;
2613
+ break;
2614
+ }
2615
+
2616
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2617
+
2618
+ case 2:
2619
+ _context7.next = 4;
2620
+ return deleteTag({
2621
+ profileId: profileId,
2622
+ tagId: tagId
2623
+ }, token, ApiErrorHandler);
2624
+
2625
+ case 4:
2626
+ _context7.next = 6;
2627
+ return refreshProfiles(token);
2628
+
2629
+ case 6:
2630
+ case "end":
2631
+ return _context7.stop();
2632
+ }
2633
+ }
2634
+ }, _callee7);
2635
+ }));
2636
+
2637
+ return function (_x11, _x12) {
2638
+ return _ref8.apply(this, arguments);
2639
+ };
2640
+ }(), [refreshProfiles, token]);
2641
+ var createIdentity = useCallback( /*#__PURE__*/function () {
2642
+ var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(profileId, identity) {
2643
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
2644
+ while (1) {
2645
+ switch (_context8.prev = _context8.next) {
2646
+ case 0:
2647
+ if (token) {
2648
+ _context8.next = 2;
2649
+ break;
2650
+ }
2651
+
2652
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2653
+
2654
+ case 2:
2655
+ _context8.next = 4;
2656
+ return postProfileIdentity(_extends({
2657
+ profileId: profileId
2658
+ }, identity), token, ApiErrorHandler);
2659
+
2660
+ case 4:
2661
+ _context8.next = 6;
2662
+ return refreshProfiles(token);
2663
+
2664
+ case 6:
2665
+ case "end":
2666
+ return _context8.stop();
2667
+ }
2668
+ }
2669
+ }, _callee8);
2670
+ }));
2671
+
2672
+ return function (_x13, _x14) {
2673
+ return _ref9.apply(this, arguments);
2674
+ };
2675
+ }(), [refreshProfiles, token]);
2676
+ var updateIdentity = useCallback( /*#__PURE__*/function () {
2677
+ var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(profileId, profileIdentity) {
2678
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
2679
+ while (1) {
2680
+ switch (_context9.prev = _context9.next) {
2681
+ case 0:
2682
+ if (token) {
2683
+ _context9.next = 2;
2684
+ break;
2685
+ }
2686
+
2687
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2688
+
2689
+ case 2:
2690
+ _context9.next = 4;
2691
+ return putUpdateProfileIdentity(_extends({
2692
+ profileId: profileId
2693
+ }, profileIdentity), token, ApiErrorHandler);
2694
+
2695
+ case 4:
2696
+ _context9.next = 6;
2697
+ return refreshProfiles(token);
2698
+
2699
+ case 6:
2700
+ case "end":
2701
+ return _context9.stop();
2702
+ }
2703
+ }
2704
+ }, _callee9);
2705
+ }));
2706
+
2707
+ return function (_x15, _x16) {
2708
+ return _ref10.apply(this, arguments);
2709
+ };
2710
+ }(), [refreshProfiles, token]);
2711
+ var deleteIdentity = useCallback( /*#__PURE__*/function () {
2712
+ var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(profileId, identityId) {
2713
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
2714
+ while (1) {
2715
+ switch (_context10.prev = _context10.next) {
2716
+ case 0:
2717
+ if (token) {
2718
+ _context10.next = 2;
2719
+ break;
2720
+ }
2721
+
2722
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2723
+
2724
+ case 2:
2725
+ _context10.next = 4;
2726
+ return deleteProfileIdentity({
2727
+ profileId: profileId,
2728
+ identityId: identityId
2729
+ }, token, ApiErrorHandler);
2730
+
2731
+ case 4:
2732
+ _context10.next = 6;
2733
+ return refreshProfiles(token);
2734
+
2735
+ case 6:
2736
+ case "end":
2737
+ return _context10.stop();
2738
+ }
2739
+ }
2740
+ }, _callee10);
2741
+ }));
2742
+
2743
+ return function (_x17, _x18) {
2744
+ return _ref11.apply(this, arguments);
2745
+ };
2746
+ }(), [refreshProfiles, token]);
2747
+ var createAddress = useCallback( /*#__PURE__*/function () {
2748
+ var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(profileId, address) {
2749
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
2750
+ while (1) {
2751
+ switch (_context11.prev = _context11.next) {
2752
+ case 0:
2753
+ if (token) {
2754
+ _context11.next = 2;
2755
+ break;
2756
+ }
2757
+
2758
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2759
+
2760
+ case 2:
2761
+ _context11.next = 4;
2762
+ return postCreateProfileAddress({
2763
+ profileId: profileId,
2764
+ address: address
2765
+ }, token, ApiErrorHandler);
2766
+
2767
+ case 4:
2768
+ _context11.next = 6;
2769
+ return refreshProfiles(token);
2770
+
2771
+ case 6:
2772
+ case "end":
2773
+ return _context11.stop();
2774
+ }
2775
+ }
2776
+ }, _callee11);
2777
+ }));
2778
+
2779
+ return function (_x19, _x20) {
2780
+ return _ref12.apply(this, arguments);
2781
+ };
2782
+ }(), [refreshProfiles, token]);
2783
+ var updateQuestionnaire = useCallback( /*#__PURE__*/function () {
2784
+ var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(profile, questionnaire) {
2785
+ var _profile$health;
2786
+
2787
+ var healthId;
2788
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
2789
+ while (1) {
2790
+ switch (_context12.prev = _context12.next) {
2791
+ case 0:
2792
+ if (token) {
2793
+ _context12.next = 2;
2794
+ break;
2795
+ }
2796
+
2797
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2798
+
2799
+ case 2:
2800
+ healthId = profile == null ? void 0 : (_profile$health = profile.health) == null ? void 0 : _profile$health.healthId;
2801
+
2802
+ if (healthId) {
2803
+ _context12.next = 5;
2804
+ break;
2805
+ }
2806
+
2807
+ throw new Error("Missing health record in profile " + profile.profileId);
2808
+
2809
+ case 5:
2810
+ _context12.next = 7;
2811
+ return putUpdateQuestionnaire({
2812
+ healthId: healthId,
2813
+ owner: profile.owner,
2814
+ answers: questionnaire
2815
+ }, token, ApiErrorHandler);
2816
+
2817
+ case 7:
2818
+ _context12.next = 9;
2819
+ return refreshProfiles(token);
2820
+
2821
+ case 9:
2822
+ case "end":
2823
+ return _context12.stop();
2824
+ }
2825
+ }
2826
+ }, _callee12);
2827
+ }));
2828
+
2829
+ return function (_x21, _x22) {
2830
+ return _ref13.apply(this, arguments);
2831
+ };
2832
+ }(), [refreshProfiles, token]);
2833
+ var createAvatar = useCallback( /*#__PURE__*/function () {
2834
+ var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(profileId, formData) {
2835
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
2836
+ while (1) {
2837
+ switch (_context13.prev = _context13.next) {
2838
+ case 0:
2839
+ if (token) {
2840
+ _context13.next = 2;
2841
+ break;
2842
+ }
2843
+
2844
+ throw new AuthorizationError('Unauthorized', AuthorizationErrorReason.Unauthroized);
2845
+
2846
+ case 2:
2847
+ _context13.next = 4;
2848
+ return postProfileAvatar({
2849
+ profileId: profileId,
2850
+ formData: formData
2851
+ }, token, ApiErrorHandler);
2852
+
2853
+ case 4:
2854
+ _context13.next = 6;
2855
+ return refreshProfiles(token);
2856
+
2857
+ case 6:
2858
+ case "end":
2859
+ return _context13.stop();
2860
+ }
2861
+ }
2862
+ }, _callee13);
2863
+ }));
2864
+
2865
+ return function (_x23, _x24) {
2866
+ return _ref14.apply(this, arguments);
2867
+ };
2868
+ }(), [refreshProfiles, token]); // Init Profile Provider
2869
+
2870
+ useEffect(function () {
2871
+ if (token) {
2872
+ refreshProfiles(token)["catch"](function (e) {
2873
+ return capture(e, capturing);
2874
+ })["finally"]( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
2875
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
2876
+ while (1) {
2877
+ switch (_context14.prev = _context14.next) {
2878
+ case 0:
2879
+ setReady(true);
2880
+
2881
+ case 1:
2882
+ case "end":
2883
+ return _context14.stop();
2884
+ }
2885
+ }
2886
+ }, _callee14);
2887
+ })));
2888
+ } else {
2889
+ setReady(true);
2890
+ }
2891
+ }, [capturing, refreshProfiles, token]); // Init/Update Current Profile
2892
+
2893
+ useEffect(function () {
2894
+ var setDefaultProfile = function setDefaultProfile(profiles, defaultProfileId) {
2895
+ _setCurrentProfile(function (current) {
2896
+ var latestCurrent = profiles.find(function (p) {
2897
+ return p.profileId === (current == null ? void 0 : current.profileId);
2898
+ });
2899
+
2900
+ if (current && latestCurrent && !equal(current, latestCurrent)) {
2901
+ return _extends({}, latestCurrent);
2902
+ }
2903
+
2904
+ if (!current) {
2905
+ if (defaultProfileId) {
2906
+ // if defaults profile is cached/set by called use it
2907
+ var found = profiles.find(function (p) {
2908
+ return p.profileId === defaultProfileId;
2909
+ }); // use the latest one if caller preferred profile does not exist
2910
+
2911
+ var target = found || profiles[0];
2912
+ console.log('Set default profile:', target.profileId);
2913
+ return _extends({}, target);
2914
+ } else {
2915
+ // otherwise go for whatever is latest
2916
+ console.log('Set defeault profile to latest:', profiles[0].profileId);
2917
+ return _extends({}, profiles[0]);
2918
+ }
2919
+ }
2920
+
2921
+ return current;
2922
+ });
2923
+ };
2924
+
2925
+ var mounted = true;
2926
+
2927
+ if (profiles) {
2928
+ var _userProfiles = getUserProfile(profiles);
2929
+
2930
+ if (_userProfiles.length === 0) {
2931
+ console.log('Reset default profile');
2932
+ if (mounted) _setCurrentProfile(undefined);
2933
+ } else {
2934
+ if (defaults != null && defaults.pid) {
2935
+ var _rootProfile = getRootProfile(profiles);
2936
+
2937
+ defaults.pid(_rootProfile == null ? void 0 : _rootProfile.profileId).then(function (defaultProfileId) {
2938
+ if (mounted) setDefaultProfile(_userProfiles, defaultProfileId);
2939
+ });
2940
+ } else {
2941
+ if (mounted) setDefaultProfile(_userProfiles);
2942
+ }
2943
+ }
2944
+ }
2945
+
2946
+ return function () {
2947
+ mounted = false;
2948
+ };
2949
+ }, [defaults, profiles]); // Update locale for root profile whenever switch/login to an account
2950
+
2951
+ useEffect(function () {
2952
+ if (rootProfile && (prevRootProfile == null ? void 0 : prevRootProfile.profileId) !== rootProfile.profileId) {
2953
+ var _rootProfile$preferen;
2954
+
2955
+ if (((_rootProfile$preferen = rootProfile.preference) == null ? void 0 : _rootProfile$preferen.language) !== locale) {
2956
+ console.log("Update account language to " + locale); // Don't really care if it fails
2957
+
2958
+ updateProfile(rootProfile.profileId, {
2959
+ preference: {
2960
+ language: locale
2961
+ }
2962
+ })["catch"](function (error) {
2963
+ return capture(error, capturing);
2964
+ });
2965
+ }
2966
+ }
2967
+ }, [capturing, locale, prevRootProfile == null ? void 0 : prevRootProfile.profileId, rootProfile, updateProfile]); // Update locale for user profile whenever switching/creating a new profile
2968
+
2969
+ useEffect(function () {
2970
+ if (currentProfile && (prevCurrentProfile == null ? void 0 : prevCurrentProfile.profileId) !== currentProfile.profileId) {
2971
+ var _currentProfile$prefe;
2972
+
2973
+ if (((_currentProfile$prefe = currentProfile.preference) == null ? void 0 : _currentProfile$prefe.language) !== locale) {
2974
+ console.log("Update profile language to " + locale); // Don't really care if it fails
2975
+
2976
+ updateProfile(currentProfile.profileId, {
2977
+ preference: {
2978
+ language: locale
2979
+ }
2980
+ }, false)["catch"](function (error) {
2981
+ return capture(error, capturing);
2982
+ });
2983
+ }
2984
+ }
2985
+ }, [locale, prevCurrentProfile, currentProfile, updateProfile, capturing]); // Clean up (Basically logout)
2986
+
2987
+ useEffect(function () {
2988
+ if (!token) {
2989
+ console.log('ProfileProvider cleanup');
2990
+ setProfiles(undefined);
2991
+ setRootProfile(undefined);
2992
+ setUserProfiles(undefined);
2993
+
2994
+ _setCurrentProfile(undefined);
2995
+ }
2996
+ }, [token]);
2997
+ var profileContext = React.useMemo(function () {
2998
+ return {
2999
+ isProfileReady: isReady,
3000
+ userProfiles: userProfiles,
3001
+ rootProfile: rootProfile,
3002
+ currentProfile: currentProfile,
3003
+ setCurrentProfile: function () {
3004
+ var _setCurrentProfile2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(profile) {
3005
+ var target;
3006
+ return _regeneratorRuntime().wrap(function _callee15$(_context15) {
3007
+ while (1) {
3008
+ switch (_context15.prev = _context15.next) {
3009
+ case 0:
3010
+ if (rootProfile && profile && userProfiles) {
3011
+ target = userProfiles.find(function (p) {
3012
+ return p.profileId === profile.profileId;
3013
+ });
3014
+
3015
+ if (target) {
3016
+ console.log('Set curent profile:', target.profileId);
3017
+
3018
+ _setCurrentProfile(target);
3019
+ }
3020
+ }
3021
+
3022
+ case 1:
3023
+ case "end":
3024
+ return _context15.stop();
3025
+ }
3026
+ }
3027
+ }, _callee15);
3028
+ }));
3029
+
3030
+ function setCurrentProfile(_x25) {
3031
+ return _setCurrentProfile2.apply(this, arguments);
3032
+ }
3033
+
3034
+ return setCurrentProfile;
3035
+ }(),
3036
+ createProfile: createProfile,
3037
+ updateProfile: updateProfile,
3038
+ deleteProfile: deleteProfile,
3039
+ createTag: createTag,
3040
+ updateTag: updateTag,
3041
+ deleteTag: deleteTag$1,
3042
+ createIdentity: createIdentity,
3043
+ updateIdentity: updateIdentity,
3044
+ deleteIdentity: deleteIdentity,
3045
+ createAddress: createAddress,
3046
+ updateQuestionnaire: updateQuestionnaire,
3047
+ createAvatar: createAvatar
3048
+ };
3049
+ }, [isReady, userProfiles, rootProfile, currentProfile, createProfile, updateProfile, deleteProfile, createTag, updateTag, deleteTag$1, createIdentity, updateIdentity, deleteIdentity, createAddress, updateQuestionnaire, createAvatar]);
3050
+ return React.createElement(ProfileContext.Provider, {
3051
+ value: profileContext
3052
+ }, children);
3053
+ };
3054
+ var useProfile = function useProfile() {
3055
+ return useContext(ProfileContext);
3056
+ };
3057
+
3058
+ export { AuthProvider, AuthenticationError, AuthenticationErrorReason, AuthorizationError, AuthorizationErrorReason, Ethnicities, Ethnicity, Gender, IdentityType, ProfileProvider, UnexpectedError, useAuth, useProfile };
3059
+ //# sourceMappingURL=react-context-provider.esm.js.map