@mountainpass/waychaser 4.0.38 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +37 -26
  3. package/dist/augment-options.d.ts +29 -0
  4. package/dist/augment-options.js +70 -0
  5. package/dist/augment-options.js.map +1 -0
  6. package/dist/expand-operation.d.ts +5 -0
  7. package/dist/expand-operation.js +78 -0
  8. package/dist/expand-operation.js.map +1 -0
  9. package/dist/handlers/hal/de-curie.d.ts +9 -0
  10. package/dist/handlers/hal/de-curie.js +50 -0
  11. package/dist/handlers/hal/de-curie.js.map +1 -0
  12. package/dist/handlers/hal/hal-handler.d.ts +6 -0
  13. package/dist/handlers/hal/hal-handler.js +91 -0
  14. package/dist/handlers/hal/hal-handler.js.map +1 -0
  15. package/dist/handlers/hal/map-hal-link-to-operation.d.ts +7 -0
  16. package/dist/handlers/hal/map-hal-link-to-operation.js +40 -0
  17. package/dist/handlers/hal/map-hal-link-to-operation.js.map +1 -0
  18. package/dist/handlers/link-header/link-header-handler.d.ts +7 -0
  19. package/dist/handlers/link-header/link-header-handler.js +83 -0
  20. package/dist/handlers/link-header/link-header-handler.js.map +1 -0
  21. package/dist/handlers/location-header/location-header-handler.d.ts +5 -0
  22. package/dist/handlers/location-header/location-header-handler.js +16 -0
  23. package/dist/handlers/location-header/location-header-handler.js.map +1 -0
  24. package/dist/handlers/siren/map-siren-action-to-operation.d.ts +6 -0
  25. package/dist/handlers/siren/map-siren-action-to-operation.js +63 -0
  26. package/dist/handlers/siren/map-siren-action-to-operation.js.map +1 -0
  27. package/dist/handlers/siren/map-siren-link-to-operation.d.ts +13 -0
  28. package/dist/handlers/siren/map-siren-link-to-operation.js +43 -0
  29. package/dist/handlers/siren/map-siren-link-to-operation.js.map +1 -0
  30. package/dist/handlers/siren/siren-action-handler.d.ts +5 -0
  31. package/dist/handlers/siren/siren-action-handler.js +46 -0
  32. package/dist/handlers/siren/siren-action-handler.js.map +1 -0
  33. package/dist/handlers/siren/siren-handler.d.ts +6 -0
  34. package/dist/handlers/siren/siren-handler.js +48 -0
  35. package/dist/handlers/siren/siren-handler.js.map +1 -0
  36. package/dist/handlers/siren/siren-link-handler.d.ts +6 -0
  37. package/dist/handlers/siren/siren-link-handler.js +59 -0
  38. package/dist/handlers/siren/siren-link-handler.js.map +1 -0
  39. package/dist/operation-array.d.ts +12 -0
  40. package/dist/operation-array.js +110 -0
  41. package/dist/operation-array.js.map +1 -0
  42. package/dist/operation.d.ts +24 -0
  43. package/dist/operation.js +304 -0
  44. package/dist/operation.js.map +1 -0
  45. package/dist/util/media-types.d.ts +5 -0
  46. package/dist/util/media-types.js +8 -0
  47. package/dist/util/media-types.js.map +1 -0
  48. package/dist/util/method-can-have-body.d.ts +4 -0
  49. package/dist/util/method-can-have-body.js +11 -0
  50. package/dist/util/method-can-have-body.js.map +1 -0
  51. package/dist/util/parse-accept.d.ts +6 -0
  52. package/dist/util/parse-accept.js +85 -0
  53. package/dist/util/parse-accept.js.map +1 -0
  54. package/dist/util/parse-operations.d.ts +14 -0
  55. package/dist/util/parse-operations.js +94 -0
  56. package/dist/util/parse-operations.js.map +1 -0
  57. package/dist/util/preferred-content-type.d.ts +6 -0
  58. package/dist/util/preferred-content-type.js +23 -0
  59. package/dist/util/preferred-content-type.js.map +1 -0
  60. package/dist/util/uri-template-lite.d.ts +1 -0
  61. package/dist/util/uri-template-lite.js +31 -0
  62. package/dist/util/uri-template-lite.js.map +1 -0
  63. package/dist/waychaser.d.ts +130 -0
  64. package/dist/waychaser.es.js +2331 -0
  65. package/dist/waychaser.es.min.js +15 -0
  66. package/dist/waychaser.js +582 -4527
  67. package/dist/waychaser.js.map +1 -1
  68. package/package.json +36 -63
  69. package/dist/waychaser.cjs +0 -14
  70. package/dist/waychaser.cjs.map +0 -1
  71. package/dist/waychaser.min.js +0 -7
  72. package/dist/waychaser.min.js.map +0 -1
  73. package/dist/waychaser.mjs +0 -14
  74. package/dist/waychaser.mjs.map +0 -1
@@ -0,0 +1,2331 @@
1
+ /*! *****************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+ /* global Reflect, Promise */
16
+
17
+ var extendStatics = function(d, b) {
18
+ extendStatics = Object.setPrototypeOf ||
19
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
21
+ return extendStatics(d, b);
22
+ };
23
+
24
+ function __extends(d, b) {
25
+ if (typeof b !== "function" && b !== null)
26
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
27
+ extendStatics(d, b);
28
+ function __() { this.constructor = d; }
29
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30
+ }
31
+
32
+ var __assign = function() {
33
+ __assign = Object.assign || function __assign(t) {
34
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
35
+ s = arguments[i];
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
37
+ }
38
+ return t;
39
+ };
40
+ return __assign.apply(this, arguments);
41
+ };
42
+
43
+ function __rest(s, e) {
44
+ var t = {};
45
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
46
+ t[p] = s[p];
47
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
48
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
49
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
50
+ t[p[i]] = s[p[i]];
51
+ }
52
+ return t;
53
+ }
54
+
55
+ function __awaiter(thisArg, _arguments, P, generator) {
56
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
57
+ return new (P || (P = Promise))(function (resolve, reject) {
58
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
59
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
60
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
61
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
62
+ });
63
+ }
64
+
65
+ function __generator(thisArg, body) {
66
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
67
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
68
+ function verb(n) { return function (v) { return step([n, v]); }; }
69
+ function step(op) {
70
+ if (f) throw new TypeError("Generator is already executing.");
71
+ while (_) try {
72
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
73
+ if (y = 0, t) op = [op[0] & 2, t.value];
74
+ switch (op[0]) {
75
+ case 0: case 1: t = op; break;
76
+ case 4: _.label++; return { value: op[1], done: false };
77
+ case 5: _.label++; y = op[1]; op = [0]; continue;
78
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
79
+ default:
80
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
81
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
82
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
83
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
84
+ if (t[2]) _.ops.pop();
85
+ _.trys.pop(); continue;
86
+ }
87
+ op = body.call(thisArg, _);
88
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
89
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
90
+ }
91
+ }
92
+
93
+ function __values(o) {
94
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
95
+ if (m) return m.call(o);
96
+ if (o && typeof o.length === "number") return {
97
+ next: function () {
98
+ if (o && i >= o.length) o = void 0;
99
+ return { value: o && o[i++], done: !o };
100
+ }
101
+ };
102
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
103
+ }
104
+
105
+ function __read(o, n) {
106
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
107
+ if (!m) return o;
108
+ var i = m.call(o), r, ar = [], e;
109
+ try {
110
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
111
+ }
112
+ catch (error) { e = { error: error }; }
113
+ finally {
114
+ try {
115
+ if (r && !r.done && (m = i["return"])) m.call(i);
116
+ }
117
+ finally { if (e) throw e.error; }
118
+ }
119
+ return ar;
120
+ }
121
+
122
+ function __spreadArray(to, from, pack) {
123
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
124
+ if (ar || !(i in from)) {
125
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
126
+ ar[i] = from[i];
127
+ }
128
+ }
129
+ return to.concat(ar || Array.prototype.slice.call(from));
130
+ }
131
+
132
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
133
+
134
+ var uriTemplateLite = {};
135
+
136
+ /**
137
+ * @version 20.5.0
138
+ * @author Lauri Rooden <lauri@rooden.ee>
139
+ * @license MIT License
140
+ */
141
+
142
+
143
+
144
+ !function(URI) {
145
+
146
+ /**
147
+ * URI Template
148
+ * @see http://tools.ietf.org/html/rfc6570
149
+ */
150
+
151
+ var RESERVED = /[!'()]/g
152
+ // /[[\]:\/!#$&()*+,;='?@]/g
153
+ , SEPARATORS = {"": ",", "+": ",", "#": ",", "?": "&"}
154
+ , escapeRe = /[$-\/?[-^{|}]/g
155
+ , expandRe = /\{([#&+.\/;?]?)((?:[-\w%.]+(\*|:\d+)?,?)+)\}/g
156
+ , parseRe = RegExp(expandRe.source + "|.[^{]*?", "g");
157
+
158
+ /*** EXPAND ***/
159
+ function encodeNormal(val) {
160
+ return encodeURIComponent(val).replace(RESERVED, escape)
161
+ }
162
+
163
+ function notNull(s) {
164
+ return s != null
165
+ }
166
+
167
+ function mapCleanJoin(arr, mapFn, joinStr) {
168
+ arr = arr.map(mapFn).filter(notNull);
169
+ return arr.length && arr.join(joinStr)
170
+ }
171
+
172
+ function expand(template, data) {
173
+ return template.replace(expandRe, function(_, op, vals) {
174
+ var sep = SEPARATORS[op] || op
175
+ , named = sep == ";" || sep == "&"
176
+ , enc = op && sep == "," ? encodeURI : encodeNormal
177
+ , out = mapCleanJoin(vals.split(","), function(_name) {
178
+ var mod = _name.split(/[*:]/)
179
+ , name = mod[0]
180
+ , val = data[name];
181
+
182
+ if (val == null) return
183
+
184
+ if (typeof val == "object") {
185
+ mod = name != _name;
186
+ if (Array.isArray(val)) {
187
+ val = mapCleanJoin(val, enc, mod ? named ? sep + name + "=" : sep : "," );
188
+ } else {
189
+ val = mapCleanJoin(Object.keys(val), function(key) {
190
+ return enc(key) + (mod ? "=" : ",") + enc(val[key])
191
+ }, mod && (named || sep == "/") ? sep : ",");
192
+ if (mod) named = 0;
193
+ }
194
+ if (!val) return
195
+ } else {
196
+ val = enc(mod[1] ? val.slice(0, mod[1]) : val);
197
+ }
198
+
199
+ return (
200
+ named ?
201
+ name + (val || sep == "&" ? "=" + val : val) :
202
+ val
203
+ )
204
+ }, sep);
205
+
206
+ return out || out === "" ? (op != "+" ? op + out : out) : ""
207
+ }
208
+ )}
209
+
210
+ URI.expand = expand;
211
+ /**/
212
+
213
+ URI.Template = function Template(template) {
214
+ var self = this
215
+ //if (!(self instanceof Template)) return new Template(template)
216
+ /*** PARSE ***/
217
+ , pos = 0
218
+ , lengths = {}
219
+ , fnStr = ""
220
+ , reStr = "^" + template.replace(parseRe, function(_, op, vals) {
221
+ if (!vals) return escapeRegExp(_)
222
+
223
+ var sep = SEPARATORS[op] || op
224
+ , named = sep == ";" || sep == "&"
225
+ , reGroup = vals.split(",").map(function(_name) {
226
+ var mod = _name.split(/[*:]/)
227
+ , name = mod[0]
228
+ , re = (lengths[name] || "(") + ".*?)";
229
+
230
+ pos++;
231
+ //console.log("KEY", arguments)
232
+ if (mod[1]) {
233
+ re = "((?:%..|.){1," + mod[1] + "})";
234
+ lengths[name] = "(\\" + pos;
235
+ }
236
+ //TODO: decodeURIComponent throws an Error on invalid input, add try-catch
237
+ fnStr += "t=($[" + pos + "]||'').split('" + sep + "').map(decodeURIComponent);";
238
+ fnStr += "o[\"" + name + "\"]=t.length>1?t:t[0];";
239
+ return (
240
+ named ?
241
+ escapeRegExp(name) + "(?:=" + re + ")?" :
242
+ sep == "&" ?
243
+ escapeRegExp(name + "=") + re :
244
+ re
245
+ )
246
+ }).join(escapeRegExp(sep));
247
+ return (op != "+" ? escapeRegExp(op) + reGroup : reGroup)
248
+
249
+ }) + "$"
250
+ , re = RegExp(reStr)
251
+ , fn = Function("$", "var t,o={};" + fnStr + "return o");
252
+ self.template = template;
253
+ self.match = function(uri) {
254
+ var match = re.exec(uri);
255
+ return match && fn(match)
256
+ };
257
+
258
+ function escapeRegExp(string) {
259
+ return string.replace(escapeRe, "\\$&")
260
+ }
261
+ /**/
262
+ /*** EXPAND ***/
263
+ self.expand = expand.bind(self, template);
264
+ /**/
265
+ };
266
+
267
+ // `this` is `exports` in NodeJS and `window` in browser.
268
+ }(commonjsGlobal.URI || (commonjsGlobal.URI = {}));
269
+
270
+ /* eslint-disable unicorn/prefer-ternary */
271
+
272
+
273
+ /**
274
+ *
275
+ */
276
+ function getUri() {
277
+ /* istanbul ignore next: it's complicated */
278
+ if (typeof window === 'undefined') {
279
+ // eslint-disable-next-line unicorn/prefer-module
280
+ return uriTemplateLite.URI || global.URI
281
+ } else {
282
+ return window.URI || uriTemplateLite.URI
283
+ }
284
+ }
285
+
286
+ /**
287
+ *
288
+ */
289
+ function getExtendedUri() {
290
+ const base = getUri();
291
+ base.parameters = function (url) {
292
+ const template = new URI.Template(url);
293
+ return template.match(url)
294
+ };
295
+ return base
296
+ }
297
+
298
+
299
+ const URI = getExtendedUri();
300
+
301
+ var has = Object.prototype.hasOwnProperty;
302
+
303
+ /**
304
+ * Stringify an object for use in a query string.
305
+ *
306
+ * @param {Object} obj - The object.
307
+ * @param {string} prefix - When nesting, the parent key.
308
+ * keys in `obj` will be stringified as `prefix[key]`.
309
+ * @returns {string}
310
+ */
311
+
312
+ var qsStringify = function queryStringify (obj, prefix) {
313
+ var pairs = [];
314
+ for (var key in obj) {
315
+ if (!has.call(obj, key)) {
316
+ continue
317
+ }
318
+
319
+ var value = obj[key];
320
+ var enkey = encodeURIComponent(key);
321
+ var pair;
322
+ if (typeof value === 'object') {
323
+ pair = queryStringify(value, prefix ? prefix + '[' + enkey + ']' : enkey);
324
+ } else {
325
+ pair = (prefix ? prefix + '[' + enkey + ']' : enkey) + '=' + encodeURIComponent(value);
326
+ }
327
+ pairs.push(pair);
328
+ }
329
+ return pairs.join('&')
330
+ };
331
+
332
+ /* eslint-env browser */
333
+
334
+ var browser = typeof self == 'object' ? self.FormData : window.FormData;
335
+
336
+ // negotiated (https://www.npmjs.com/package/negotiated) doesn't working in IE 11 due to missing regex polyfill stuff
337
+ /**
338
+ * @param {string} accept
339
+ */
340
+ function parseAccept(accept) {
341
+ var entries = accept.split(',');
342
+ return entries
343
+ .map(function (entry) {
344
+ var e_1, _a;
345
+ var fields = entry.split(';');
346
+ var type = fields.shift();
347
+ var types = type === null || type === void 0 ? void 0 : type.split('/');
348
+ var parsedEntry = {
349
+ type: type,
350
+ parentType: types === null || types === void 0 ? void 0 : types[0],
351
+ subType: types === null || types === void 0 ? void 0 : types[1],
352
+ q: 1
353
+ };
354
+ try {
355
+ for (var fields_1 = __values(fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
356
+ var field = fields_1_1.value;
357
+ var parsedFields = field.split('=');
358
+ if (field[0] === 'q') {
359
+ parsedEntry[parsedFields[0]] = Number.parseFloat(parsedFields[1]);
360
+ }
361
+ }
362
+ }
363
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
364
+ finally {
365
+ try {
366
+ if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
367
+ }
368
+ finally { if (e_1) throw e_1.error; }
369
+ }
370
+ return parsedEntry;
371
+ })
372
+ .sort(function (first, second) {
373
+ // It is expected to return a negative value if first argument is less than second argument, zero if they're
374
+ // equal and a positive value otherwise
375
+ if (first.q > second.q) {
376
+ return -1;
377
+ }
378
+ else if (first.q < second.q) {
379
+ return 1;
380
+ }
381
+ else if (first.parentType === '*' && second.parentType !== '*') {
382
+ return 1;
383
+ }
384
+ else if (first.parentType !== '*' && second.parentType === '*') {
385
+ return -1;
386
+ }
387
+ else if (first.subType === '*' && second.subType !== '*') {
388
+ return 1;
389
+ }
390
+ else if (first.subType !== '*' && second.subType === '*') {
391
+ return -1;
392
+ }
393
+ else {
394
+ return 0;
395
+ }
396
+ })
397
+ .map(function (entry) {
398
+ return {
399
+ type: entry.type || ''
400
+ };
401
+ })
402
+ .filter(function (entry) { return entry.type !== ''; });
403
+ }
404
+
405
+ /**
406
+ * @param accept
407
+ * @param supportedContentTypes
408
+ * @param defaultType
409
+ */
410
+ function preferredContentType (
411
+ accept,
412
+ supportedContentTypes,
413
+ defaultType
414
+ ) {
415
+ if (accept) {
416
+ const acceptable = parseAccept(accept);
417
+
418
+ const acceptableMediaTypes = acceptable.find(row => {
419
+ return supportedContentTypes.includes(row.type)
420
+ });
421
+
422
+ return acceptableMediaTypes.type
423
+ } else {
424
+ return defaultType
425
+ }
426
+ }
427
+
428
+ var flat = flatten;
429
+ flatten.flatten = flatten;
430
+ flatten.unflatten = unflatten;
431
+
432
+ function isBuffer (obj) {
433
+ return obj &&
434
+ obj.constructor &&
435
+ (typeof obj.constructor.isBuffer === 'function') &&
436
+ obj.constructor.isBuffer(obj)
437
+ }
438
+
439
+ function keyIdentity (key) {
440
+ return key
441
+ }
442
+
443
+ function flatten (target, opts) {
444
+ opts = opts || {};
445
+
446
+ const delimiter = opts.delimiter || '.';
447
+ const maxDepth = opts.maxDepth;
448
+ const transformKey = opts.transformKey || keyIdentity;
449
+ const output = {};
450
+
451
+ function step (object, prev, currentDepth) {
452
+ currentDepth = currentDepth || 1;
453
+ Object.keys(object).forEach(function (key) {
454
+ const value = object[key];
455
+ const isarray = opts.safe && Array.isArray(value);
456
+ const type = Object.prototype.toString.call(value);
457
+ const isbuffer = isBuffer(value);
458
+ const isobject = (
459
+ type === '[object Object]' ||
460
+ type === '[object Array]'
461
+ );
462
+
463
+ const newKey = prev
464
+ ? prev + delimiter + transformKey(key)
465
+ : transformKey(key);
466
+
467
+ if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
468
+ (!opts.maxDepth || currentDepth < maxDepth)) {
469
+ return step(value, newKey, currentDepth + 1)
470
+ }
471
+
472
+ output[newKey] = value;
473
+ });
474
+ }
475
+
476
+ step(target);
477
+
478
+ return output
479
+ }
480
+
481
+ function unflatten (target, opts) {
482
+ opts = opts || {};
483
+
484
+ const delimiter = opts.delimiter || '.';
485
+ const overwrite = opts.overwrite || false;
486
+ const transformKey = opts.transformKey || keyIdentity;
487
+ const result = {};
488
+
489
+ const isbuffer = isBuffer(target);
490
+ if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {
491
+ return target
492
+ }
493
+
494
+ // safely ensure that the key is
495
+ // an integer.
496
+ function getkey (key) {
497
+ const parsedKey = Number(key);
498
+
499
+ return (
500
+ isNaN(parsedKey) ||
501
+ key.indexOf('.') !== -1 ||
502
+ opts.object
503
+ ) ? key
504
+ : parsedKey
505
+ }
506
+
507
+ function addKeys (keyPrefix, recipient, target) {
508
+ return Object.keys(target).reduce(function (result, key) {
509
+ result[keyPrefix + delimiter + key] = target[key];
510
+
511
+ return result
512
+ }, recipient)
513
+ }
514
+
515
+ function isEmpty (val) {
516
+ const type = Object.prototype.toString.call(val);
517
+ const isArray = type === '[object Array]';
518
+ const isObject = type === '[object Object]';
519
+
520
+ if (!val) {
521
+ return true
522
+ } else if (isArray) {
523
+ return !val.length
524
+ } else if (isObject) {
525
+ return !Object.keys(val).length
526
+ }
527
+ }
528
+
529
+ target = Object.keys(target).reduce(function (result, key) {
530
+ const type = Object.prototype.toString.call(target[key]);
531
+ const isObject = (type === '[object Object]' || type === '[object Array]');
532
+ if (!isObject || isEmpty(target[key])) {
533
+ result[key] = target[key];
534
+ return result
535
+ } else {
536
+ return addKeys(
537
+ key,
538
+ result,
539
+ flatten(target[key], opts)
540
+ )
541
+ }
542
+ }, {});
543
+
544
+ Object.keys(target).forEach(function (key) {
545
+ const split = key.split(delimiter).map(transformKey);
546
+ let key1 = getkey(split.shift());
547
+ let key2 = getkey(split[0]);
548
+ let recipient = result;
549
+
550
+ while (key2 !== undefined) {
551
+ if (key1 === '__proto__') {
552
+ return
553
+ }
554
+
555
+ const type = Object.prototype.toString.call(recipient[key1]);
556
+ const isobject = (
557
+ type === '[object Object]' ||
558
+ type === '[object Array]'
559
+ );
560
+
561
+ // do not write over falsey, non-undefined values if overwrite is false
562
+ if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {
563
+ return
564
+ }
565
+
566
+ if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {
567
+ recipient[key1] = (
568
+ typeof key2 === 'number' &&
569
+ !opts.object ? [] : {}
570
+ );
571
+ }
572
+
573
+ recipient = recipient[key1];
574
+ if (split.length > 0) {
575
+ key1 = getkey(split.shift());
576
+ key2 = getkey(split[0]);
577
+ }
578
+ }
579
+
580
+ // unflatten again for 'messy objects'
581
+ recipient[key1] = unflatten(target[key], opts);
582
+ });
583
+
584
+ return result
585
+ }
586
+
587
+ var jsonpointer = {};
588
+
589
+ var hasExcape = /~/;
590
+ var escapeMatcher = /~[01]/g;
591
+ function escapeReplacer (m) {
592
+ switch (m) {
593
+ case '~1': return '/'
594
+ case '~0': return '~'
595
+ }
596
+ throw new Error('Invalid tilde escape: ' + m)
597
+ }
598
+
599
+ function untilde (str) {
600
+ if (!hasExcape.test(str)) return str
601
+ return str.replace(escapeMatcher, escapeReplacer)
602
+ }
603
+
604
+ function setter (obj, pointer, value) {
605
+ var part;
606
+ var hasNextPart;
607
+
608
+ for (var p = 1, len = pointer.length; p < len;) {
609
+ if (pointer[p] === 'constructor' || pointer[p] === 'prototype' || pointer[p] === '__proto__') return obj
610
+
611
+ part = untilde(pointer[p++]);
612
+ hasNextPart = len > p;
613
+
614
+ if (typeof obj[part] === 'undefined') {
615
+ // support setting of /-
616
+ if (Array.isArray(obj) && part === '-') {
617
+ part = obj.length;
618
+ }
619
+
620
+ // support nested objects/array when setting values
621
+ if (hasNextPart) {
622
+ if ((pointer[p] !== '' && pointer[p] < Infinity) || pointer[p] === '-') obj[part] = [];
623
+ else obj[part] = {};
624
+ }
625
+ }
626
+
627
+ if (!hasNextPart) break
628
+ obj = obj[part];
629
+ }
630
+
631
+ var oldValue = obj[part];
632
+ if (value === undefined) delete obj[part];
633
+ else obj[part] = value;
634
+ return oldValue
635
+ }
636
+
637
+ function compilePointer (pointer) {
638
+ if (typeof pointer === 'string') {
639
+ pointer = pointer.split('/');
640
+ if (pointer[0] === '') return pointer
641
+ throw new Error('Invalid JSON pointer.')
642
+ } else if (Array.isArray(pointer)) {
643
+ for (const part of pointer) {
644
+ if (typeof part !== 'string' && typeof part !== 'number') {
645
+ throw new Error('Invalid JSON pointer. Must be of type string or number.')
646
+ }
647
+ }
648
+ return pointer
649
+ }
650
+
651
+ throw new Error('Invalid JSON pointer.')
652
+ }
653
+
654
+ function get (obj, pointer) {
655
+ if (typeof obj !== 'object') throw new Error('Invalid input object.')
656
+ pointer = compilePointer(pointer);
657
+ var len = pointer.length;
658
+ if (len === 1) return obj
659
+
660
+ for (var p = 1; p < len;) {
661
+ obj = obj[untilde(pointer[p++])];
662
+ if (len === p) return obj
663
+ if (typeof obj !== 'object') return undefined
664
+ }
665
+ }
666
+
667
+ function set (obj, pointer, value) {
668
+ if (typeof obj !== 'object') throw new Error('Invalid input object.')
669
+ pointer = compilePointer(pointer);
670
+ if (pointer.length === 0) throw new Error('Invalid JSON pointer for set.')
671
+ return setter(obj, pointer, value)
672
+ }
673
+
674
+ function compile (pointer) {
675
+ var compiled = compilePointer(pointer);
676
+ return {
677
+ get: function (object) {
678
+ return get(object, compiled)
679
+ },
680
+ set: function (object, value) {
681
+ return set(object, compiled, value)
682
+ }
683
+ }
684
+ }
685
+
686
+ jsonpointer.get = get;
687
+ jsonpointer.set = set;
688
+ jsonpointer.compile = compile;
689
+
690
+ /**
691
+ * @param method
692
+ */
693
+ function methodCanHaveBody (method) {
694
+ return !['GET', 'DELETE', 'TRACE', 'OPTIONS', 'HEAD'].includes(method)
695
+ }
696
+
697
+ var lib = {};
698
+
699
+ Object.defineProperty(lib, "__esModule", { value: true });
700
+ var ProblemDocument_1 = lib.ProblemDocument = void 0;
701
+ /**
702
+ *
703
+ * This class implements RFC7807 "problem detail", a way to carry machine-
704
+ * readable details of errors in a HTTP response to avoid the need to
705
+ * define new error response formats for HTTP APIs.
706
+ *
707
+ * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7807
708
+ *
709
+ * Consumers MUST use the "type" string as the primary identifier for
710
+ * the problem type; the "title" string is advisory and included only
711
+ * for users who are not aware of the semantics of the URI and do not
712
+ * have the ability to discover them (e.g., offline log analysis).
713
+ * Consumers SHOULD NOT automatically dereference the type URI.
714
+ *
715
+ * The "status" member, if present, is only advisory; it conveys the
716
+ * HTTP status code used for the convenience of the consumer.
717
+ * Generators MUST use the same status code in the actual HTTP response,
718
+ * to assure that generic HTTP software that does not understand this
719
+ * format still behaves correctly. See Section 5 for further caveats
720
+ * regarding its use.
721
+ *
722
+ * Consumers can use the status member to determine what the original
723
+ * status code used by the generator was, in cases where it has been
724
+ * changed (e.g., by an intermediary or cache), and when message bodies
725
+ * persist without HTTP information. Generic HTTP software will still
726
+ * use the HTTP status code.
727
+ *
728
+ * The "detail" member, if present, ought to focus on helping the client
729
+ * correct the problem, rather than giving debugging information.
730
+ *
731
+ * Consumers SHOULD NOT parse the "detail" member for information;
732
+ * extensions are more suitable and less error-prone ways to obtain such
733
+ * information.
734
+ *
735
+ * Note that both {@link BaseProblemDocumentProperties.type type} and {@link BaseProblemDocumentProperties.instance instance} accept relative URIs; this means
736
+ * that they must be resolved relative to the document's base URI, as
737
+ * per {@link https://datatracker.ietf.org/doc/html/rfc3986#section-5 [RFC3986], Section 5}.
738
+ */
739
+ class ProblemDocument {
740
+ /**
741
+ *
742
+ * construct a new ProblemDocument instance
743
+ *
744
+ * @param data properties to assign to the new instance
745
+ */
746
+ constructor(data) {
747
+ Object.assign(this, data);
748
+ }
749
+ }
750
+ ProblemDocument_1 = lib.ProblemDocument = ProblemDocument;
751
+
752
+ var Operation = /** @class */ (function () {
753
+ function Operation(_a) {
754
+ var rel = _a.rel, uri = _a.uri, method = _a.method, parameters = _a.parameters, accept = _a.accept, anchor = _a.anchor, otherProperties = __rest(_a, ["rel", "uri", "method", "parameters", "accept", "anchor"]);
755
+ this.rel = rel;
756
+ this.uri = uri;
757
+ this.method = method;
758
+ this.parameters = parameters || {};
759
+ this.accept = accept;
760
+ this.anchor = anchor;
761
+ Object.assign(this, otherProperties);
762
+ }
763
+ return Operation;
764
+ }());
765
+ var InvocableOperation = /** @class */ (function (_super) {
766
+ __extends(InvocableOperation, _super);
767
+ function InvocableOperation(operation, response, defaultOptions, thisContext) {
768
+ var _this = _super.call(this, operation) || this;
769
+ _this.response = response;
770
+ _this.defaultOptions = defaultOptions;
771
+ if (_this.uri.includes('{this.')) {
772
+ _this.uri = URI.expand(_this.uri, thisContext);
773
+ }
774
+ return _this;
775
+ // const pathParameters = URI.parameters(operation.uri)
776
+ // for (const key in pathParameters) {
777
+ // this.parameters[key] = {}
778
+ // }
779
+ }
780
+ InvocableOperation.prototype.invokeAsFragment = function (parameters, validator) {
781
+ if (this.uri.startsWith('#/')) {
782
+ var anchor = this.expandUrl(parameters).toString();
783
+ var fragmentContent = this.response.fullContent && jsonpointer.get(this.response.fullContent, anchor.slice(1));
784
+ if (validator) {
785
+ var validationResult = validator(fragmentContent);
786
+ if (isValidationSuccess(validationResult)) {
787
+ return new WayChaserResponse({ defaultOptions: this.defaultOptions, baseResponse: this.response.response, content: validationResult.content, fullContent: this.response.fullContent, anchor: anchor, parentOperations: this.response.allOperations, parameters: parameters });
788
+ }
789
+ else {
790
+ throw new WayChaserProblem({
791
+ problem: validationResult.problem,
792
+ response: new WayChaserResponse({ defaultOptions: this.defaultOptions, baseResponse: this.response.response, content: fragmentContent, fullContent: this.response.fullContent, parameters: parameters })
793
+ });
794
+ }
795
+ }
796
+ else {
797
+ return new WayChaserResponse({ defaultOptions: this.defaultOptions, baseResponse: this.response.response, content: fragmentContent, fullContent: this.response.fullContent, anchor: anchor, parentOperations: this.response.allOperations, parameters: parameters });
798
+ }
799
+ }
800
+ };
801
+ InvocableOperation.prototype.invokeAll = function (options) {
802
+ return __awaiter(this, void 0, void 0, function () {
803
+ var result;
804
+ return __generator(this, function (_a) {
805
+ if (this.uri.startsWith('#/') && this.response instanceof WayChaserResponse) {
806
+ result = this.doInvokeAll((options === null || options === void 0 ? void 0 : options.parameters) || {});
807
+ return [2 /*return*/, Promise.all(result)];
808
+ }
809
+ return [2 /*return*/, Promise.all([this.invoke(options)])];
810
+ });
811
+ });
812
+ };
813
+ InvocableOperation.prototype.doInvokeAll = function (parameters, validator) {
814
+ var _this = this;
815
+ var response = this.response;
816
+ // expand the URI with whatever parameters have been passed in
817
+ var template = new URI.Template(this.uri);
818
+ var uriParameters = Object.assign(URI.parameters(this.uri), parameters);
819
+ var currentUri = template.expand(uriParameters).replace(/%7B/g, "{").replace(/%7D/g, "}");
820
+ // get unfilled parameters
821
+ var currentUriParameters = URI.parameters(currentUri);
822
+ var keys = Object.keys(currentUriParameters);
823
+ if (keys.length !== 0) {
824
+ var field = currentUriParameters[keys[0]];
825
+ var parentUri = currentUri.slice(1, currentUri.indexOf(field) - 1);
826
+ var parent_1 = parentUri === '' ? response.content : jsonpointer.get(response.content, parentUri);
827
+ if (parent_1) {
828
+ var indices = Array.isArray(parent_1) ? __spreadArray([], __read(Array.from({ length: parent_1.length }).keys()), false) : Object.keys(parent_1);
829
+ return indices.flatMap(function (index) {
830
+ var _a;
831
+ var extendedParameters = Object.assign({}, parameters, (_a = {}, _a[keys[0]] = index, _a));
832
+ return _this.doInvokeAll(extendedParameters, validator);
833
+ });
834
+ }
835
+ else {
836
+ throw new WayChaserProblem({
837
+ response: this.response,
838
+ problem: new ProblemDocument_1({
839
+ type: "https://waychaser.io/fragment-uri-error",
840
+ title: "The fragment URI does not match the content structure",
841
+ uri: parentUri, content: response.content,
842
+ parameters: parameters
843
+ }),
844
+ });
845
+ }
846
+ }
847
+ return [this.invokeAsFragment(parameters, validator)];
848
+ };
849
+ InvocableOperation.prototype.invoke = function (options) {
850
+ return __awaiter(this, void 0, void 0, function () {
851
+ var fragment, parameterSpecs, parameters, invokeUrl, body, parameterSpecs_1, parameterSpecs_1_1, key, _a, _b, key, encodedContent, headers, requestOptions, contentType, name_1;
852
+ var e_1, _c, e_2, _d;
853
+ return __generator(this, function (_e) {
854
+ fragment = this.invokeAsFragment(options === null || options === void 0 ? void 0 : options.parameters);
855
+ if (fragment) {
856
+ return [2 /*return*/, fragment];
857
+ }
858
+ parameterSpecs = this.parameters || {};
859
+ parameters = Object.assign({}, this.defaultOptions.parameters, options === null || options === void 0 ? void 0 : options.parameters);
860
+ invokeUrl = this.url(parameters);
861
+ body = {};
862
+ /* istanbul ignore if reason: TODO */
863
+ if (Array.isArray(parameterSpecs)) {
864
+ try {
865
+ for (parameterSpecs_1 = __values(parameterSpecs), parameterSpecs_1_1 = parameterSpecs_1.next(); !parameterSpecs_1_1.done; parameterSpecs_1_1 = parameterSpecs_1.next()) {
866
+ key = parameterSpecs_1_1.value;
867
+ body[key] = parameters === null || parameters === void 0 ? void 0 : parameters[key];
868
+ }
869
+ }
870
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
871
+ finally {
872
+ try {
873
+ if (parameterSpecs_1_1 && !parameterSpecs_1_1.done && (_c = parameterSpecs_1.return)) _c.call(parameterSpecs_1);
874
+ }
875
+ finally { if (e_1) throw e_1.error; }
876
+ }
877
+ }
878
+ else {
879
+ try {
880
+ for (_a = __values(Object.keys(parameterSpecs)), _b = _a.next(); !_b.done; _b = _a.next()) {
881
+ key = _b.value;
882
+ body[key] = parameters === null || parameters === void 0 ? void 0 : parameters[key];
883
+ }
884
+ }
885
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
886
+ finally {
887
+ try {
888
+ if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
889
+ }
890
+ finally { if (e_2) throw e_2.error; }
891
+ }
892
+ }
893
+ headers = {};
894
+ requestOptions = Object.assign({}, options);
895
+ requestOptions.method = this.method;
896
+ if (Object.keys(this.parameters).length !== 0 && methodCanHaveBody(this.method || 'GET')) {
897
+ contentType = preferredContentType(this.accept, [
898
+ 'application/x-www-form-urlencoded',
899
+ 'application/json',
900
+ 'multipart/form-data'
901
+ ], 'application/x-www-form-urlencoded');
902
+ switch (contentType) {
903
+ case 'application/x-www-form-urlencoded':
904
+ encodedContent = qsStringify(body);
905
+ break;
906
+ case 'application/json':
907
+ encodedContent = JSON.stringify(body);
908
+ break;
909
+ case 'multipart/form-data':
910
+ encodedContent = new browser();
911
+ for (name_1 in body) {
912
+ encodedContent.append(name_1, body[name_1]);
913
+ }
914
+ break;
915
+ }
916
+ if (contentType !== 'multipart/form-data') {
917
+ headers = {
918
+ 'content-type': contentType
919
+ };
920
+ }
921
+ // else fetch adds the right content-type header for us
922
+ // with the boundaries
923
+ requestOptions.body = encodedContent;
924
+ requestOptions.headers = Object.assign(headers, options === null || options === void 0 ? void 0 : options.headers);
925
+ }
926
+ return [2 /*return*/, _waychaser(invokeUrl.toString(), this.defaultOptions, requestOptions)];
927
+ });
928
+ });
929
+ };
930
+ InvocableOperation.prototype.url = function (parameters) {
931
+ var expandedUri = this.expandUrl(parameters);
932
+ var invokeUrl = new URL(expandedUri, this.response.url);
933
+ return invokeUrl;
934
+ };
935
+ InvocableOperation.prototype.expandUrl = function (parameters) {
936
+ return URI.expand(this.uri, flat(parameters || {}));
937
+ };
938
+ return InvocableOperation;
939
+ }(Operation));
940
+
941
+ // const foo: Array<InvocableOperation> = []
942
+ // foo.filter())
943
+ var OperationArray = /** @class */ (function (_super) {
944
+ __extends(OperationArray, _super);
945
+ function OperationArray(items) {
946
+ return _super.apply(this, __spreadArray([], __read((items || [])), false)) || this;
947
+ }
948
+ OperationArray.create = function () {
949
+ return Object.create(OperationArray.prototype);
950
+ };
951
+ OperationArray.prototype.find = function (query, thisArgument) {
952
+ var finder = Array.prototype.find.bind(this);
953
+ if (typeof query === 'string') {
954
+ return finder(objectFinder({ rel: query }), thisArgument);
955
+ }
956
+ else if (typeof query === 'object') {
957
+ return finder(objectFinder(query), thisArgument);
958
+ }
959
+ else {
960
+ return finder(query, thisArgument);
961
+ }
962
+ };
963
+ OperationArray.prototype.filter = function (query, thisArgument) {
964
+ if (typeof query === 'string') {
965
+ return this.filter({ rel: query }, thisArgument);
966
+ }
967
+ else if (typeof query === 'object') {
968
+ return this.filter(objectFinder(query), thisArgument);
969
+ }
970
+ else {
971
+ var filtered = Array.prototype.filter.bind(this)(query);
972
+ Object.setPrototypeOf(filtered, OperationArray.prototype);
973
+ return filtered;
974
+ }
975
+ };
976
+ OperationArray.prototype.invoke = function (relationship, options) {
977
+ var operation = this.find(relationship);
978
+ return operation ? operation.invoke(options) : undefined;
979
+ };
980
+ OperationArray.prototype.invokeAll = function (relationship, options) {
981
+ return Promise.all(this.filter(relationship).map(function (operation) {
982
+ return operation.invokeAll(options);
983
+ })).then(function (arrayOfArrays) {
984
+ var flat = arrayOfArrays.flat();
985
+ return flat;
986
+ });
987
+ };
988
+ return OperationArray;
989
+ }(Array));
990
+ // ideally we'd just subclass Array, and that works most of the time, BUT sometimes in firefox, instead of it
991
+ // giving us an ObjectArray, we get a plain old Array, without our invoke method or customised find method.
992
+ // FU JavaScript, FU.
993
+ /**
994
+ * @param query
995
+ */
996
+ function objectFinder(query) {
997
+ return function (o) {
998
+ for (var key in query) {
999
+ if (query[key] !== o[key]) {
1000
+ return false;
1001
+ }
1002
+ }
1003
+ return true;
1004
+ };
1005
+ }
1006
+
1007
+ /**
1008
+ * @param operation
1009
+ */
1010
+ function expandOperation(operation) {
1011
+ var e_1, _a, e_2, _b;
1012
+ var expandedOperations = [];
1013
+ var rangeRegex = /{\[(\d+)..(\d+)]}/;
1014
+ var originalUrl = operation.uri.toString();
1015
+ var matches = originalUrl.match(rangeRegex);
1016
+ if (matches) {
1017
+ for (var index = Number.parseInt(matches[1]); index <= Number.parseInt(matches[2]); ++index) {
1018
+ var newOp = new Operation(Object.assign(operation, {
1019
+ uri: originalUrl.replace(rangeRegex, index.toFixed(0))
1020
+ }));
1021
+ var thisExpandedOperations = expandOperation(newOp);
1022
+ try {
1023
+ for (var thisExpandedOperations_1 = (e_1 = void 0, __values(thisExpandedOperations)), thisExpandedOperations_1_1 = thisExpandedOperations_1.next(); !thisExpandedOperations_1_1.done; thisExpandedOperations_1_1 = thisExpandedOperations_1.next()) {
1024
+ var operation_1 = thisExpandedOperations_1_1.value;
1025
+ expandedOperations.push(operation_1);
1026
+ }
1027
+ }
1028
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1029
+ finally {
1030
+ try {
1031
+ if (thisExpandedOperations_1_1 && !thisExpandedOperations_1_1.done && (_a = thisExpandedOperations_1.return)) _a.call(thisExpandedOperations_1);
1032
+ }
1033
+ finally { if (e_1) throw e_1.error; }
1034
+ }
1035
+ }
1036
+ }
1037
+ else {
1038
+ var originalAnchor = operation.anchor;
1039
+ var anchorMatches = originalAnchor === null || originalAnchor === void 0 ? void 0 : originalAnchor.match(rangeRegex);
1040
+ if (originalAnchor &&
1041
+ anchorMatches) {
1042
+ for (var index = Number.parseInt(anchorMatches[1]); index <= Number.parseInt(anchorMatches[2]); ++index) {
1043
+ var newOp = new Operation(Object.assign(operation, {
1044
+ anchor: originalAnchor.replace(rangeRegex, index.toFixed(0))
1045
+ }));
1046
+ var thisExpandedOperations = expandOperation(newOp);
1047
+ try {
1048
+ for (var thisExpandedOperations_2 = (e_2 = void 0, __values(thisExpandedOperations)), thisExpandedOperations_2_1 = thisExpandedOperations_2.next(); !thisExpandedOperations_2_1.done; thisExpandedOperations_2_1 = thisExpandedOperations_2.next()) {
1049
+ var operation_2 = thisExpandedOperations_2_1.value;
1050
+ expandedOperations.push(operation_2);
1051
+ }
1052
+ }
1053
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1054
+ finally {
1055
+ try {
1056
+ if (thisExpandedOperations_2_1 && !thisExpandedOperations_2_1.done && (_b = thisExpandedOperations_2.return)) _b.call(thisExpandedOperations_2);
1057
+ }
1058
+ finally { if (e_2) throw e_2.error; }
1059
+ }
1060
+ }
1061
+ }
1062
+ else {
1063
+ expandedOperations.push(operation);
1064
+ }
1065
+ }
1066
+ return expandedOperations;
1067
+ }
1068
+
1069
+ /**
1070
+ * @param root0
1071
+ * @param root0.handlers
1072
+ * @param root0.response
1073
+ * @param root0.baseResponse
1074
+ * @param root0.content
1075
+ */
1076
+ function parseOperations(_a) {
1077
+ var e_1, _b, e_2, _c, e_3, _d, e_4, _e;
1078
+ var handlers = _a.handlers, baseResponse = _a.baseResponse, content = _a.content;
1079
+ var operations = [];
1080
+ var stop = false;
1081
+ try {
1082
+ for (var handlers_1 = __values(handlers), handlers_1_1 = handlers_1.next(); !handlers_1_1.done; handlers_1_1 = handlers_1.next()) {
1083
+ var handler = handlers_1_1.value;
1084
+ // TODO only call handers for the current media type
1085
+ var handledOperations = handler.handler(baseResponse, content, function () {
1086
+ stop = true;
1087
+ });
1088
+ if (handledOperations) {
1089
+ try {
1090
+ for (var handledOperations_1 = (e_2 = void 0, __values(handledOperations)), handledOperations_1_1 = handledOperations_1.next(); !handledOperations_1_1.done; handledOperations_1_1 = handledOperations_1.next()) {
1091
+ var operation = handledOperations_1_1.value;
1092
+ operations.push(operation);
1093
+ }
1094
+ }
1095
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1096
+ finally {
1097
+ try {
1098
+ if (handledOperations_1_1 && !handledOperations_1_1.done && (_c = handledOperations_1.return)) _c.call(handledOperations_1);
1099
+ }
1100
+ finally { if (e_2) throw e_2.error; }
1101
+ }
1102
+ }
1103
+ if (stop) {
1104
+ break;
1105
+ }
1106
+ }
1107
+ }
1108
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1109
+ finally {
1110
+ try {
1111
+ if (handlers_1_1 && !handlers_1_1.done && (_b = handlers_1.return)) _b.call(handlers_1);
1112
+ }
1113
+ finally { if (e_1) throw e_1.error; }
1114
+ }
1115
+ var expandedOperations = {};
1116
+ try {
1117
+ for (var operations_1 = __values(operations), operations_1_1 = operations_1.next(); !operations_1_1.done; operations_1_1 = operations_1.next()) {
1118
+ var operation = operations_1_1.value;
1119
+ var expanded = expandOperation(operation);
1120
+ try {
1121
+ for (var expanded_1 = (e_4 = void 0, __values(expanded)), expanded_1_1 = expanded_1.next(); !expanded_1_1.done; expanded_1_1 = expanded_1.next()) {
1122
+ var operation_1 = expanded_1_1.value;
1123
+ var anchor = operation_1.anchor || '';
1124
+ expandedOperations[anchor] || (expandedOperations[anchor] = []);
1125
+ expandedOperations[anchor].push(operation_1);
1126
+ }
1127
+ }
1128
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1129
+ finally {
1130
+ try {
1131
+ if (expanded_1_1 && !expanded_1_1.done && (_e = expanded_1.return)) _e.call(expanded_1);
1132
+ }
1133
+ finally { if (e_4) throw e_4.error; }
1134
+ }
1135
+ }
1136
+ }
1137
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1138
+ finally {
1139
+ try {
1140
+ if (operations_1_1 && !operations_1_1.done && (_d = operations_1.return)) _d.call(operations_1);
1141
+ }
1142
+ finally { if (e_3) throw e_3.error; }
1143
+ }
1144
+ return expandedOperations;
1145
+ }
1146
+
1147
+ const MediaTypes = {
1148
+ HAL: 'application/hal+json',
1149
+ SIREN: 'application/vnd.siren+json'
1150
+ };
1151
+
1152
+ /**
1153
+ * @param relationship
1154
+ * @param curies
1155
+ */
1156
+
1157
+ /**
1158
+ * @param relationship
1159
+ * @param curies
1160
+ */
1161
+ function deCurie (relationship, curies) {
1162
+ // we can either look in the rel for ':' and try to convert if it exists, but then we'll be trying to covert almost
1163
+ // everything because none standard rels typically start with 'http:' or 'https:'.
1164
+ // otherwise we can iterate over all the curies and try to replace. Seems inefficient.
1165
+ // Going with option 1 for now.
1166
+ // ⚠️ NOTE TO SELF: never use 'http' or 'https' as a curie name or hilarity will not ensue 😬
1167
+ // ⚠️ ALSO NOTE TO SELF: never use ':' in a curie name or hilarity will not ensue 😬
1168
+ // I'm going to assume that if there are multiple ':' characters, then we ignore all but the first
1169
+ const splitRelationship = relationship.split(/:(.+)/);
1170
+ if (splitRelationship.length > 1) {
1171
+ const [curieName, curieRemainder] = splitRelationship;
1172
+ const rval = curies[curieName]
1173
+ ? URI.expand(curies[curieName], { rel: curieRemainder })
1174
+ : relationship;
1175
+ return rval
1176
+ } else {
1177
+ return relationship
1178
+ }
1179
+ }
1180
+
1181
+ /**
1182
+ * @param relationship
1183
+ * @param link
1184
+ * @param curies
1185
+ */
1186
+ function mapHalLinkToOperation(relationship, link, curies) {
1187
+ // we don't need to copy `templated` across, because when we invoke an operation, we always
1188
+ // assume it's a template and expand it with the passed parameters
1189
+ const { href, templated, ...otherProperties } = link;
1190
+ return new Operation({ rel: deCurie(relationship, curies), uri: href, ...otherProperties })
1191
+ }
1192
+
1193
+ /**
1194
+ * @param response
1195
+ * @param content
1196
+ */
1197
+ function halHandler(response, content) {
1198
+ var e_1, _a, e_2, _b, e_3, _c;
1199
+ var _d;
1200
+ var operations = [];
1201
+ var contentType = (_d = response.headers.get('content-type')) === null || _d === void 0 ? void 0 : _d.split(';');
1202
+ if ((contentType === null || contentType === void 0 ? void 0 : contentType[0]) === MediaTypes.HAL &&
1203
+ content &&
1204
+ typeof content === 'object' &&
1205
+ '_links' in content) {
1206
+ var body = content;
1207
+ // if there are curies in the Hal Links, we need to load them first, so we can expand them wherever they are used
1208
+ // we also want to convert them to a map, for easy lookup
1209
+ var curies = {};
1210
+ if (body._links.curies) {
1211
+ if (Array.isArray(body._links.curies)) {
1212
+ try {
1213
+ for (var _e = __values(body._links.curies), _f = _e.next(); !_f.done; _f = _e.next()) {
1214
+ var curie = _f.value;
1215
+ curies[curie.name] = curie.href;
1216
+ }
1217
+ }
1218
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1219
+ finally {
1220
+ try {
1221
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
1222
+ }
1223
+ finally { if (e_1) throw e_1.error; }
1224
+ }
1225
+ }
1226
+ else {
1227
+ curies[body._links.curies.name] = body._links.curies.href;
1228
+ }
1229
+ }
1230
+ try {
1231
+ for (var _g = __values(Object.keys(body._links).filter(function (relationship) { return relationship !== 'curies'; })), _h = _g.next(); !_h.done; _h = _g.next()) {
1232
+ var key = _h.value;
1233
+ if (Array.isArray(body._links[key])) {
1234
+ try {
1235
+ for (var _j = (e_3 = void 0, __values(body._links[key])), _k = _j.next(); !_k.done; _k = _j.next()) {
1236
+ var link = _k.value;
1237
+ operations.push(mapHalLinkToOperation(key, link, curies));
1238
+ }
1239
+ }
1240
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1241
+ finally {
1242
+ try {
1243
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
1244
+ }
1245
+ finally { if (e_3) throw e_3.error; }
1246
+ }
1247
+ }
1248
+ else {
1249
+ operations.push(mapHalLinkToOperation(key, body._links[key], curies));
1250
+ }
1251
+ }
1252
+ }
1253
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1254
+ finally {
1255
+ try {
1256
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
1257
+ }
1258
+ finally { if (e_2) throw e_2.error; }
1259
+ }
1260
+ }
1261
+ return operations;
1262
+ }
1263
+
1264
+ var COMPATIBLE_ENCODING_PATTERN = /^utf-?8|ascii|utf-?16-?le|ucs-?2|base-?64|latin-?1$/i;
1265
+ var WS_TRIM_PATTERN = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
1266
+ var WS_CHAR_PATTERN = /\s|\uFEFF|\xA0/;
1267
+ var WS_FOLD_PATTERN = /\r?\n[\x20\x09]+/g;
1268
+ var DELIMITER_PATTERN = /[;,"]/;
1269
+ var WS_DELIMITER_PATTERN = /[;,"]|\s/;
1270
+
1271
+ /**
1272
+ * Token character pattern
1273
+ * @type {RegExp}
1274
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
1275
+ */
1276
+ var TOKEN_PATTERN = /^[!#$%&'*+\-\.^_`|~\da-zA-Z]+$/;
1277
+
1278
+ var STATE = {
1279
+ IDLE: 1 << 0,
1280
+ URI: 1 << 1,
1281
+ ATTR: 1 << 2,
1282
+ };
1283
+
1284
+ function trim( value ) {
1285
+ return value.replace( WS_TRIM_PATTERN, '' )
1286
+ }
1287
+
1288
+ function hasWhitespace( value ) {
1289
+ return WS_CHAR_PATTERN.test( value )
1290
+ }
1291
+
1292
+ function skipWhitespace( value, offset ) {
1293
+ while( hasWhitespace( value[offset] ) ) {
1294
+ offset++;
1295
+ }
1296
+ return offset
1297
+ }
1298
+
1299
+ function needsQuotes( value ) {
1300
+ return WS_DELIMITER_PATTERN.test( value ) ||
1301
+ !TOKEN_PATTERN.test( value )
1302
+ }
1303
+
1304
+ class Link {
1305
+
1306
+ /**
1307
+ * Link
1308
+ * @constructor
1309
+ * @param {String} [value]
1310
+ * @returns {Link}
1311
+ */
1312
+ constructor( value ) {
1313
+
1314
+ /** @type {Array} URI references */
1315
+ this.refs = [];
1316
+
1317
+ if( value ) {
1318
+ this.parse( value );
1319
+ }
1320
+
1321
+ }
1322
+
1323
+ /**
1324
+ * Get refs with given relation type
1325
+ * @param {String} value
1326
+ * @returns {Array<Object>}
1327
+ */
1328
+ rel( value ) {
1329
+
1330
+ var links = [];
1331
+ var type = value.toLowerCase();
1332
+
1333
+ for( var i = 0; i < this.refs.length; i++ ) {
1334
+ if( this.refs[ i ].rel.toLowerCase() === type ) {
1335
+ links.push( this.refs[ i ] );
1336
+ }
1337
+ }
1338
+
1339
+ return links
1340
+
1341
+ }
1342
+
1343
+ /**
1344
+ * Get refs where given attribute has a given value
1345
+ * @param {String} attr
1346
+ * @param {String} value
1347
+ * @returns {Array<Object>}
1348
+ */
1349
+ get( attr, value ) {
1350
+
1351
+ attr = attr.toLowerCase();
1352
+
1353
+ var links = [];
1354
+
1355
+ for( var i = 0; i < this.refs.length; i++ ) {
1356
+ if( this.refs[ i ][ attr ] === value ) {
1357
+ links.push( this.refs[ i ] );
1358
+ }
1359
+ }
1360
+
1361
+ return links
1362
+
1363
+ }
1364
+
1365
+ set( link ) {
1366
+ this.refs.push( link );
1367
+ return this
1368
+ }
1369
+
1370
+ has( attr, value ) {
1371
+
1372
+ attr = attr.toLowerCase();
1373
+
1374
+ for( var i = 0; i < this.refs.length; i++ ) {
1375
+ if( this.refs[ i ][ attr ] === value ) {
1376
+ return true
1377
+ }
1378
+ }
1379
+
1380
+ return false
1381
+
1382
+ }
1383
+
1384
+ parse( value, offset ) {
1385
+
1386
+ offset = offset || 0;
1387
+ value = offset ? value.slice( offset ) : value;
1388
+
1389
+ // Trim & unfold folded lines
1390
+ value = trim( value ).replace( WS_FOLD_PATTERN, '' );
1391
+
1392
+ var state = STATE.IDLE;
1393
+ var length = value.length;
1394
+ var offset = 0;
1395
+ var ref = null;
1396
+
1397
+ while( offset < length ) {
1398
+ if( state === STATE.IDLE ) {
1399
+ if( hasWhitespace( value[offset] ) ) {
1400
+ offset++;
1401
+ continue
1402
+ } else if( value[offset] === '<' ) {
1403
+ if( ref != null ) {
1404
+ ref.rel != null ?
1405
+ this.refs.push( ...Link.expandRelations( ref ) ) :
1406
+ this.refs.push( ref );
1407
+ }
1408
+ var end = value.indexOf( '>', offset );
1409
+ if( end === -1 ) throw new Error( 'Expected end of URI delimiter at offset ' + offset )
1410
+ ref = { uri: value.slice( offset + 1, end ) };
1411
+ // this.refs.push( ref )
1412
+ offset = end;
1413
+ state = STATE.URI;
1414
+ } else {
1415
+ throw new Error( 'Unexpected character "' + value[offset] + '" at offset ' + offset )
1416
+ }
1417
+ offset++;
1418
+ } else if( state === STATE.URI ) {
1419
+ if( hasWhitespace( value[offset] ) ) {
1420
+ offset++;
1421
+ continue
1422
+ } else if( value[offset] === ';' ) {
1423
+ state = STATE.ATTR;
1424
+ offset++;
1425
+ } else if( value[offset] === ',' ) {
1426
+ state = STATE.IDLE;
1427
+ offset++;
1428
+ } else {
1429
+ throw new Error( 'Unexpected character "' + value[offset] + '" at offset ' + offset )
1430
+ }
1431
+ } else if( state === STATE.ATTR ) {
1432
+ if( value[offset] ===';' || hasWhitespace( value[offset] ) ) {
1433
+ offset++;
1434
+ continue
1435
+ }
1436
+ var end = value.indexOf( '=', offset );
1437
+ if( end === -1 ) throw new Error( 'Expected attribute delimiter at offset ' + offset )
1438
+ var attr = trim( value.slice( offset, end ) ).toLowerCase();
1439
+ var attrValue = '';
1440
+ offset = end + 1;
1441
+ offset = skipWhitespace( value, offset );
1442
+ if( value[offset] === '"' ) {
1443
+ offset++;
1444
+ while( offset < length ) {
1445
+ if( value[offset] === '"' ) {
1446
+ offset++; break
1447
+ }
1448
+ if( value[offset] === '\\' ) {
1449
+ offset++;
1450
+ }
1451
+ attrValue += value[offset];
1452
+ offset++;
1453
+ }
1454
+ } else {
1455
+ var end = offset + 1;
1456
+ while( !DELIMITER_PATTERN.test( value[end] ) && end < length ) {
1457
+ end++;
1458
+ }
1459
+ attrValue = value.slice( offset, end );
1460
+ offset = end;
1461
+ }
1462
+ if( ref[ attr ] && Link.isSingleOccurenceAttr( attr ) ) ; else if( attr[ attr.length - 1 ] === '*' ) {
1463
+ ref[ attr ] = Link.parseExtendedValue( attrValue );
1464
+ } else {
1465
+ attrValue = attr === 'type' ?
1466
+ attrValue.toLowerCase() : attrValue;
1467
+ if( ref[ attr ] != null ) {
1468
+ if( Array.isArray( ref[ attr ] ) ) {
1469
+ ref[ attr ].push( attrValue );
1470
+ } else {
1471
+ ref[ attr ] = [ ref[ attr ], attrValue ];
1472
+ }
1473
+ } else {
1474
+ ref[ attr ] = attrValue;
1475
+ }
1476
+ }
1477
+ switch( value[offset] ) {
1478
+ case ',': state = STATE.IDLE; break
1479
+ case ';': state = STATE.ATTR; break
1480
+ }
1481
+ offset++;
1482
+ } else {
1483
+ throw new Error( 'Unknown parser state "' + state + '"' )
1484
+ }
1485
+ }
1486
+
1487
+ if( ref != null ) {
1488
+ ref.rel != null ?
1489
+ this.refs.push( ...Link.expandRelations( ref ) ) :
1490
+ this.refs.push( ref );
1491
+ }
1492
+
1493
+ ref = null;
1494
+
1495
+ return this
1496
+
1497
+ }
1498
+
1499
+ toString() {
1500
+
1501
+ var refs = [];
1502
+ var link = '';
1503
+ var ref = null;
1504
+
1505
+ for( var i = 0; i < this.refs.length; i++ ) {
1506
+ ref = this.refs[i];
1507
+ link = Object.keys( this.refs[i] ).reduce( function( link, attr ) {
1508
+ if( attr === 'uri' ) return link
1509
+ return link + '; ' + Link.formatAttribute( attr, ref[ attr ] )
1510
+ }, '<' + ref.uri + '>' );
1511
+ refs.push( link );
1512
+ }
1513
+
1514
+ return refs.join( ', ' )
1515
+
1516
+ }
1517
+
1518
+ }
1519
+
1520
+ /**
1521
+ * Determines whether an encoding can be
1522
+ * natively handled with a `Buffer`
1523
+ * @param {String} value
1524
+ * @returns {Boolean}
1525
+ */
1526
+ Link.isCompatibleEncoding = function( value ) {
1527
+ return COMPATIBLE_ENCODING_PATTERN.test( value )
1528
+ };
1529
+
1530
+ Link.parse = function( value, offset ) {
1531
+ return new Link().parse( value, offset )
1532
+ };
1533
+
1534
+ Link.isSingleOccurenceAttr = function( attr ) {
1535
+ return attr === 'rel' || attr === 'type' || attr === 'media' ||
1536
+ attr === 'title' || attr === 'title*'
1537
+ };
1538
+
1539
+ Link.isTokenAttr = function( attr ) {
1540
+ return attr === 'rel' || attr === 'type' || attr === 'anchor'
1541
+ };
1542
+
1543
+ Link.escapeQuotes = function( value ) {
1544
+ return value.replace( /"/g, '\\"' )
1545
+ };
1546
+
1547
+ Link.expandRelations = function( ref ) {
1548
+ var rels = ref.rel.split( ' ' );
1549
+ return rels.map( function( rel ) {
1550
+ var value = Object.assign( {}, ref );
1551
+ value.rel = rel;
1552
+ return value
1553
+ })
1554
+ };
1555
+
1556
+ /**
1557
+ * Parses an extended value and attempts to decode it
1558
+ * @internal
1559
+ * @param {String} value
1560
+ * @return {Object}
1561
+ */
1562
+ Link.parseExtendedValue = function( value ) {
1563
+ var parts = /([^']+)?(?:'([^']+)')?(.+)/.exec( value );
1564
+ return {
1565
+ language: parts[2].toLowerCase(),
1566
+ encoding: Link.isCompatibleEncoding( parts[1] ) ?
1567
+ null : parts[1].toLowerCase(),
1568
+ value: Link.isCompatibleEncoding( parts[1] ) ?
1569
+ decodeURIComponent( parts[3] ) : parts[3]
1570
+ }
1571
+ };
1572
+
1573
+ /**
1574
+ * Format a given extended attribute and it's value
1575
+ * @param {String} attr
1576
+ * @param {Object} data
1577
+ * @return {String}
1578
+ */
1579
+ Link.formatExtendedAttribute = function( attr, data ) {
1580
+
1581
+ var encoding = ( data.encoding || 'utf-8' ).toUpperCase();
1582
+ var language = data.language || 'en';
1583
+
1584
+ var encodedValue = '';
1585
+
1586
+ if( Buffer.isBuffer( data.value ) && Link.isCompatibleEncoding( encoding ) ) {
1587
+ encodedValue = data.value.toString( encoding );
1588
+ } else if( Buffer.isBuffer( data.value ) ) {
1589
+ encodedValue = data.value.toString( 'hex' )
1590
+ .replace( /[0-9a-f]{2}/gi, '%$1' );
1591
+ } else {
1592
+ encodedValue = encodeURIComponent( data.value );
1593
+ }
1594
+
1595
+ return attr + '=' + encoding + '\'' +
1596
+ language + '\'' + encodedValue
1597
+
1598
+ };
1599
+
1600
+ /**
1601
+ * Format a given attribute and it's value
1602
+ * @param {String} attr
1603
+ * @param {String|Object} value
1604
+ * @return {String}
1605
+ */
1606
+ Link.formatAttribute = function( attr, value ) {
1607
+
1608
+ if( Array.isArray( value ) ) {
1609
+ return value.map(( item ) => {
1610
+ return Link.formatAttribute( attr, item )
1611
+ }).join( '; ' )
1612
+ }
1613
+
1614
+ if( attr[ attr.length - 1 ] === '*' || typeof value !== 'string' ) {
1615
+ return Link.formatExtendedAttribute( attr, value )
1616
+ }
1617
+
1618
+ if( Link.isTokenAttr( attr ) ) {
1619
+ value = needsQuotes( value ) ?
1620
+ '"' + Link.escapeQuotes( value ) + '"' :
1621
+ Link.escapeQuotes( value );
1622
+ } else if( needsQuotes( value ) ) {
1623
+ value = encodeURIComponent( value );
1624
+ // We don't need to escape <SP> <,> <;> within quotes
1625
+ value = value
1626
+ .replace( /%20/g, ' ' )
1627
+ .replace( /%2C/g, ',' )
1628
+ .replace( /%3B/g, ';' );
1629
+
1630
+ value = '"' + value + '"';
1631
+ }
1632
+
1633
+ return attr + '=' + value
1634
+
1635
+ };
1636
+
1637
+ var link = Link;
1638
+
1639
+ /**
1640
+ * @param response
1641
+ * @param content
1642
+ * @param stopper
1643
+ */
1644
+ function linkHeaderHandler(response, content, stopper) {
1645
+ return __spreadArray(__spreadArray([], __read(parseHeader(response.headers.get('link'))), false), __read(parseHeader(response.headers.get('link-template'))), false);
1646
+ }
1647
+ /**
1648
+ * @param linkHeader
1649
+ */
1650
+ function parseHeader(linkHeader) {
1651
+ if (linkHeader) {
1652
+ var links = link.parse(linkHeader);
1653
+ return links.refs.map(function (reference) {
1654
+ var rel = reference.rel, uri = reference.uri, method = reference.method, accept = reference["accept*"], parameters = reference["params*"], otherProperties = __rest(reference, ["rel", "uri", "method", 'accept*', 'params*']);
1655
+ var parsedParameters = (parameters === null || parameters === void 0 ? void 0 : parameters.value)
1656
+ ? JSON.parse(parameters === null || parameters === void 0 ? void 0 : parameters.value)
1657
+ : undefined;
1658
+ return new Operation(__assign({ rel: rel, uri: uri, method: method, parameters: parsedParameters, accept: accept === null || accept === void 0 ? void 0 : accept.value }, otherProperties));
1659
+ });
1660
+ }
1661
+ else {
1662
+ return [];
1663
+ }
1664
+ }
1665
+
1666
+ /**
1667
+ * @param {object} action the siren action to map
1668
+ * @returns {object} the link objection that the @{param action} maps to
1669
+ */
1670
+ function mapSirenActionToOperation(action) {
1671
+ var e_1, _a;
1672
+ var name = action.name, href = action.href, fields = action.fields, type = action.type, otherProperties = __rest(action, ["name", "href", "fields", "type"]);
1673
+ var bodyParameters = {};
1674
+ if (fields) {
1675
+ try {
1676
+ for (var fields_1 = __values(fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
1677
+ var parameter = fields_1_1.value;
1678
+ bodyParameters[parameter.name] = {};
1679
+ }
1680
+ }
1681
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1682
+ finally {
1683
+ try {
1684
+ if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
1685
+ }
1686
+ finally { if (e_1) throw e_1.error; }
1687
+ }
1688
+ }
1689
+ return __assign({ rel: name, uri: href, accept: type, parameters: fields && bodyParameters }, otherProperties);
1690
+ }
1691
+
1692
+ /**
1693
+ * @param content
1694
+ */
1695
+ function sirenActionHandler(content) {
1696
+ var e_1, _a;
1697
+ var operations = [];
1698
+ if (content &&
1699
+ typeof content === 'object' &&
1700
+ 'actions' in content) {
1701
+ var body = content;
1702
+ if (body.actions) {
1703
+ try {
1704
+ for (var _b = __values(body.actions), _c = _b.next(); !_c.done; _c = _b.next()) {
1705
+ var action = _c.value;
1706
+ var operation = mapSirenActionToOperation(action);
1707
+ operations.push(operation);
1708
+ }
1709
+ }
1710
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1711
+ finally {
1712
+ try {
1713
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1714
+ }
1715
+ finally { if (e_1) throw e_1.error; }
1716
+ }
1717
+ }
1718
+ }
1719
+ return operations;
1720
+ }
1721
+
1722
+ /**
1723
+ * @param relationship
1724
+ * @param link
1725
+ */
1726
+ /**
1727
+ * @param relationship
1728
+ * @param link
1729
+ */
1730
+ function mapSirenLinkToOperation(relationship, link) {
1731
+ // we don't need to copy `rel` across, because we already have that from the {@param relationship}.
1732
+ // Also `rel` in `link` is an array, which is not what we're after.
1733
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1734
+ var href = link.href; link.rel; var otherProperties = __rest(link, ["href", "rel"]);
1735
+ return new Operation(__assign({ rel: relationship, uri: href }, otherProperties));
1736
+ }
1737
+
1738
+ /**
1739
+ * @param response
1740
+ * @param content
1741
+ */
1742
+ function sirenLinkHandler(content) {
1743
+ var e_1, _a, e_2, _b;
1744
+ var operations = [];
1745
+ if (content &&
1746
+ typeof content === 'object' &&
1747
+ 'links' in content) {
1748
+ var body = content;
1749
+ if (body.links) {
1750
+ try {
1751
+ for (var _c = __values(body.links), _d = _c.next(); !_d.done; _d = _c.next()) {
1752
+ var link = _d.value;
1753
+ try {
1754
+ for (var _e = (e_2 = void 0, __values(link.rel)), _f = _e.next(); !_f.done; _f = _e.next()) {
1755
+ var relationship = _f.value;
1756
+ var mappedLink = mapSirenLinkToOperation(relationship, link);
1757
+ operations.push(mappedLink);
1758
+ }
1759
+ }
1760
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1761
+ finally {
1762
+ try {
1763
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1764
+ }
1765
+ finally { if (e_2) throw e_2.error; }
1766
+ }
1767
+ }
1768
+ }
1769
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1770
+ finally {
1771
+ try {
1772
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
1773
+ }
1774
+ finally { if (e_1) throw e_1.error; }
1775
+ }
1776
+ }
1777
+ }
1778
+ return operations;
1779
+ }
1780
+
1781
+ /**
1782
+ * @param response
1783
+ * @param content
1784
+ */
1785
+ function sirenHandler(response, content) {
1786
+ var _a;
1787
+ var contentType = (_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';');
1788
+ if ((contentType === null || contentType === void 0 ? void 0 : contentType[0]) === MediaTypes.SIREN) {
1789
+ return __spreadArray(__spreadArray([], __read((sirenLinkHandler(content))), false), __read((sirenActionHandler(content))), false);
1790
+ }
1791
+ return [];
1792
+ }
1793
+
1794
+ /**
1795
+ * @param response
1796
+ */
1797
+ function locationHeaderHandler(response) {
1798
+ var locationHeader = response === null || response === void 0 ? void 0 : response.headers.get('location');
1799
+ if (locationHeader) {
1800
+ return [new Operation({ rel: 'related', uri: locationHeader })];
1801
+ }
1802
+ return [];
1803
+ }
1804
+
1805
+ /**
1806
+ * @param baseOptions
1807
+ * @param additionalOptions
1808
+ */
1809
+ function augmentOptions(baseOptions, additionalOptions) {
1810
+ var baseHandlers = baseOptions.handlers, baseDefaultHandlers = baseOptions.defaultHandlers, baseHeaders = baseOptions.headers, baseOther = __rest(baseOptions, ["handlers", "defaultHandlers", "headers"]);
1811
+ var _a = additionalOptions || {}, additionalHandlers = _a.handlers, additionalDefaultHandlers = _a.defaultHandlers, additionalHeaders = _a.headers, additionalOther = __rest(_a, ["handlers", "defaultHandlers", "headers"]);
1812
+ // if additional has default, don't use base default
1813
+ // if additional has handlers, don;'t use base handlers
1814
+ // augment({ dh: [XXX] }, { h: [YYY] }) => { h: [], dh: [YYY, XXX] }
1815
+ // augment({ dh: [XXX] }, { h: [YYY], dh: [] }) => { h: [], dh: [YYY] }
1816
+ // augment({ dh: [YYY, XXX] }, { h: [ZZZ] }) => { h: [], dh: [ZZZ, YYY, XXX] }
1817
+ // augment({ dh: [YYY, XXX] }, { h: [ZZZ], dh: [] }) => { h: [], dh: [ZZZ] }
1818
+ var mergedHandlers = sortHandlers(__spreadArray(__spreadArray([], __read((additionalHandlers || baseHandlers || [])), false), __read((additionalDefaultHandlers || baseDefaultHandlers || [])), false));
1819
+ var finalOptions = __assign(__assign(__assign({}, baseOther), additionalOther), { defaultHandlers: mergedHandlers, handlers: [], headers: __assign(__assign({}, baseHeaders), additionalHeaders) });
1820
+ return finalOptions;
1821
+ }
1822
+
1823
+ var _a, _b;
1824
+ /**
1825
+ * @param result
1826
+ */
1827
+ function isValidationSuccess(result) {
1828
+ return result.success;
1829
+ }
1830
+ var WayChaserResponse = /** @class */ (function () {
1831
+ function WayChaserResponse(_a) {
1832
+ var e_1, _b, e_2, _c, e_3, _d;
1833
+ var handlers = _a.handlers, defaultOptions = _a.defaultOptions, baseResponse = _a.baseResponse, content = _a.content, fullContent = _a.fullContent, anchor = _a.anchor, parentOperations = _a.parentOperations, parameters = _a.parameters;
1834
+ this.response = baseResponse;
1835
+ this.anchor = anchor;
1836
+ this.parameters = parameters || {};
1837
+ this.fullContent = fullContent || content;
1838
+ this.content = content;
1839
+ this.operations = OperationArray.create();
1840
+ var thisContext = flat({ this: content });
1841
+ if (parentOperations && anchor && defaultOptions) {
1842
+ this.allOperations = parentOperations;
1843
+ try {
1844
+ for (var _e = __values(this.allOperations[anchor] || []), _f = _e.next(); !_f.done; _f = _e.next()) {
1845
+ var operation = _f.value;
1846
+ this.operations.push(new InvocableOperation(operation, this, defaultOptions, thisContext));
1847
+ }
1848
+ }
1849
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1850
+ finally {
1851
+ try {
1852
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1853
+ }
1854
+ finally { if (e_1) throw e_1.error; }
1855
+ }
1856
+ // not only do we need to go through the operations with a matching anchor
1857
+ // we also need to go though anchors that could match this.anchor
1858
+ for (var key in this.allOperations) {
1859
+ if (key !== '') {
1860
+ // need to see if key could match this.anchor
1861
+ var template = new URI.Template(key);
1862
+ var parameters_1 = template.match(this.anchor);
1863
+ var expandedAnchor = template.expand(parameters_1);
1864
+ if (expandedAnchor === this.anchor) {
1865
+ var expandedOptions = Object.assign({}, defaultOptions, { parameters: Object.assign(parameters_1, defaultOptions.parameters) });
1866
+ try {
1867
+ for (var _g = (e_2 = void 0, __values(this.allOperations[key])), _h = _g.next(); !_h.done; _h = _g.next()) {
1868
+ var operation = _h.value;
1869
+ this.operations.push(new InvocableOperation(operation, this, expandedOptions, thisContext));
1870
+ }
1871
+ }
1872
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1873
+ finally {
1874
+ try {
1875
+ if (_h && !_h.done && (_c = _g.return)) _c.call(_g);
1876
+ }
1877
+ finally { if (e_2) throw e_2.error; }
1878
+ }
1879
+ }
1880
+ }
1881
+ }
1882
+ }
1883
+ else if (baseResponse && handlers && defaultOptions) {
1884
+ this.allOperations = parseOperations({
1885
+ baseResponse: baseResponse,
1886
+ content: content,
1887
+ handlers: handlers
1888
+ });
1889
+ this.operations = OperationArray.create();
1890
+ try {
1891
+ for (var _j = __values(this.allOperations[''] || []), _k = _j.next(); !_k.done; _k = _j.next()) {
1892
+ var operation = _k.value;
1893
+ var op = new InvocableOperation(operation, this, defaultOptions, thisContext);
1894
+ this.operations.push(op);
1895
+ }
1896
+ }
1897
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1898
+ finally {
1899
+ try {
1900
+ if (_k && !_k.done && (_d = _j.return)) _d.call(_j);
1901
+ }
1902
+ finally { if (e_3) throw e_3.error; }
1903
+ }
1904
+ }
1905
+ }
1906
+ /**
1907
+ * @param baseResponse
1908
+ * @param content
1909
+ * @param defaultOptions
1910
+ * @param mergedOptions
1911
+ * @returns
1912
+ * @throws {WayChaserProblem}
1913
+ */
1914
+ WayChaserResponse.create = function (baseResponse, content, defaultOptions, mergedOptions) {
1915
+ if (content instanceof ProblemDocument_1) {
1916
+ throw new WayChaserProblem({
1917
+ response: new WayChaserResponse({ handlers: mergedOptions.defaultHandlers, defaultOptions: defaultOptions, baseResponse: baseResponse, content: content, parameters: mergedOptions.parameters }),
1918
+ problem: content,
1919
+ });
1920
+ }
1921
+ else {
1922
+ if (mergedOptions.validator) {
1923
+ var validationResult = mergedOptions.validator(content);
1924
+ if (isValidationSuccess(validationResult)) {
1925
+ return new WayChaserResponse({ handlers: mergedOptions.defaultHandlers, defaultOptions: defaultOptions, baseResponse: baseResponse, content: validationResult.content, parameters: mergedOptions.parameters });
1926
+ }
1927
+ else {
1928
+ throw new WayChaserProblem({
1929
+ response: new WayChaserResponse({ handlers: mergedOptions.defaultHandlers, defaultOptions: defaultOptions, baseResponse: baseResponse, content: content, parameters: mergedOptions.parameters }),
1930
+ problem: validationResult.problem,
1931
+ });
1932
+ }
1933
+ }
1934
+ else {
1935
+ return new WayChaserResponse({ handlers: mergedOptions.defaultHandlers, defaultOptions: defaultOptions, baseResponse: baseResponse, content: content, parameters: mergedOptions.parameters });
1936
+ }
1937
+ }
1938
+ };
1939
+ Object.defineProperty(WayChaserResponse.prototype, "ops", {
1940
+ get: function () {
1941
+ return this.operations;
1942
+ },
1943
+ enumerable: false,
1944
+ configurable: true
1945
+ });
1946
+ WayChaserResponse.prototype.invoke = function (relationship, options) {
1947
+ return this.operations.invoke(relationship, options);
1948
+ };
1949
+ WayChaserResponse.prototype.invokeAll = function (relationship, options) {
1950
+ return this.operations.invokeAll(relationship, options);
1951
+ };
1952
+ Object.defineProperty(WayChaserResponse.prototype, "body", {
1953
+ get: function () {
1954
+ throw new Error('Not Implemented. Use `.content` instead');
1955
+ },
1956
+ enumerable: false,
1957
+ configurable: true
1958
+ });
1959
+ Object.defineProperty(WayChaserResponse.prototype, "bodyUsed", {
1960
+ get: function () {
1961
+ return true;
1962
+ },
1963
+ enumerable: false,
1964
+ configurable: true
1965
+ });
1966
+ Object.defineProperty(WayChaserResponse.prototype, "headers", {
1967
+ get: function () {
1968
+ var _a;
1969
+ return (_a = this.response) === null || _a === void 0 ? void 0 : _a.headers;
1970
+ },
1971
+ enumerable: false,
1972
+ configurable: true
1973
+ });
1974
+ Object.defineProperty(WayChaserResponse.prototype, "ok", {
1975
+ get: function () {
1976
+ return this.response ? this.response.ok : false;
1977
+ },
1978
+ enumerable: false,
1979
+ configurable: true
1980
+ });
1981
+ Object.defineProperty(WayChaserResponse.prototype, "redirected", {
1982
+ get: function () {
1983
+ return this.response ? this.response.redirected : false;
1984
+ },
1985
+ enumerable: false,
1986
+ configurable: true
1987
+ });
1988
+ Object.defineProperty(WayChaserResponse.prototype, "status", {
1989
+ get: function () {
1990
+ var _a;
1991
+ return (_a = this.response) === null || _a === void 0 ? void 0 : _a.status;
1992
+ },
1993
+ enumerable: false,
1994
+ configurable: true
1995
+ });
1996
+ Object.defineProperty(WayChaserResponse.prototype, "statusText", {
1997
+ get: function () {
1998
+ var _a;
1999
+ return (_a = this.response) === null || _a === void 0 ? void 0 : _a.statusText;
2000
+ },
2001
+ enumerable: false,
2002
+ configurable: true
2003
+ });
2004
+ Object.defineProperty(WayChaserResponse.prototype, "type", {
2005
+ get: function () {
2006
+ var _a;
2007
+ return (_a = this.response) === null || _a === void 0 ? void 0 : _a.type;
2008
+ },
2009
+ enumerable: false,
2010
+ configurable: true
2011
+ });
2012
+ Object.defineProperty(WayChaserResponse.prototype, "url", {
2013
+ get: function () {
2014
+ var _a;
2015
+ return (_a = this.response) === null || _a === void 0 ? void 0 : _a.url;
2016
+ },
2017
+ enumerable: false,
2018
+ configurable: true
2019
+ });
2020
+ WayChaserResponse.prototype.arrayBuffer = function () {
2021
+ throw new Error('Not Implemented. Use `.content` instead');
2022
+ };
2023
+ WayChaserResponse.prototype.blob = function () {
2024
+ throw new Error('Not Implemented. Use `.content` instead');
2025
+ };
2026
+ WayChaserResponse.prototype.clone = function () {
2027
+ throw new Error('Not Implemented');
2028
+ };
2029
+ WayChaserResponse.prototype.formData = function () {
2030
+ throw new Error('Not Implemented. Use `.content` instead');
2031
+ };
2032
+ // async json() {
2033
+ // throw new Error('Not Implemented. Use `.content` instead')
2034
+ // }
2035
+ WayChaserResponse.prototype.text = function () {
2036
+ throw new Error('Not Implemented. Use `.content` instead');
2037
+ };
2038
+ return WayChaserResponse;
2039
+ }());
2040
+ var WayChaserProblem = /** @class */ (function (_super) {
2041
+ __extends(WayChaserProblem, _super);
2042
+ function WayChaserProblem(_a) {
2043
+ var _newTarget = this.constructor;
2044
+ var response = _a.response, problem = _a.problem;
2045
+ var _this =
2046
+ // 'Error' breaks prototype chain here
2047
+ _super.call(this, problem.detail) || this;
2048
+ // restore prototype chain
2049
+ var actualProto = _newTarget.prototype;
2050
+ if (Object.setPrototypeOf) {
2051
+ Object.setPrototypeOf(_this, actualProto);
2052
+ }
2053
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2054
+ else {
2055
+ _this.__proto__ = actualProto;
2056
+ }
2057
+ _this.problem = problem;
2058
+ _this.response = response;
2059
+ return _this;
2060
+ }
2061
+ return WayChaserProblem;
2062
+ }(Error));
2063
+ /**
2064
+ * @param handlers
2065
+ */
2066
+ function sortHandlers(handlers) {
2067
+ return handlers.sort(function (a, b) {
2068
+ // -ve if less
2069
+ // e.g. a.q = 0.3, b.q = 0.4, then a.q - b.q = 0.3 - 0.4 = -0.1
2070
+ return (b.q || 1) - (a.q || 1);
2071
+ });
2072
+ }
2073
+ // pre handlers is sorted
2074
+ /**
2075
+ * @param handlers
2076
+ */
2077
+ function allMediaRanges(handlers) {
2078
+ var e_4, _a, e_5, _b;
2079
+ var rval = [];
2080
+ try {
2081
+ for (var handlers_1 = __values(handlers), handlers_1_1 = handlers_1.next(); !handlers_1_1.done; handlers_1_1 = handlers_1.next()) {
2082
+ var handlerSpec = handlers_1_1.value;
2083
+ try {
2084
+ for (var _c = (e_5 = void 0, __values(handlerSpec.mediaRanges)), _d = _c.next(); !_d.done; _d = _c.next()) {
2085
+ var range = _d.value;
2086
+ if (typeof range === 'object') {
2087
+ if (handlerSpec.q) {
2088
+ rval.push({ type: range.mediaType, q: handlerSpec.q * (range.q || 1) });
2089
+ }
2090
+ else {
2091
+ rval.push({ type: range.mediaType, q: (range.q || 1) });
2092
+ }
2093
+ }
2094
+ else {
2095
+ if (handlerSpec.q) {
2096
+ rval.push({ type: range, q: handlerSpec.q });
2097
+ }
2098
+ else {
2099
+ rval.push({ type: range, q: 1 });
2100
+ }
2101
+ }
2102
+ }
2103
+ }
2104
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
2105
+ finally {
2106
+ try {
2107
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2108
+ }
2109
+ finally { if (e_5) throw e_5.error; }
2110
+ }
2111
+ }
2112
+ }
2113
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
2114
+ finally {
2115
+ try {
2116
+ if (handlers_1_1 && !handlers_1_1.done && (_a = handlers_1.return)) _a.call(handlers_1);
2117
+ }
2118
+ finally { if (e_4) throw e_4.error; }
2119
+ }
2120
+ var sorted = rval.sort(function (a, b) {
2121
+ return a.q - b.q;
2122
+ });
2123
+ var seen = new Set();
2124
+ var filtered = sorted.filter(function (item) {
2125
+ var k = item.type;
2126
+ return seen.has(k) ? false : seen.add(k);
2127
+ });
2128
+ return filtered;
2129
+ }
2130
+ /**
2131
+ * @param uriOrRequest
2132
+ * @param defaultOptions
2133
+ * @param options
2134
+ * @returns WayChaserResponse<Content>
2135
+ * @throws TypeError | AbortError | WayChaserResponseProblem
2136
+ */
2137
+ function _waychaser(uriOrRequest, defaultOptions, options) {
2138
+ var _a;
2139
+ return __awaiter(this, void 0, void 0, function () {
2140
+ var mergedOptions, mergedHandlers, defaultAcceptRanges, defaultAcceptStrings, additionalAcceptHeader, fullAcceptHeader, updateOptions, stop, _b, _c, interceptor, baseResponse, content, response, _d, _e, interceptor, _f, _g, interceptor;
2141
+ var e_6, _h, e_7, _j, e_8, _k;
2142
+ return __generator(this, function (_l) {
2143
+ switch (_l.label) {
2144
+ case 0:
2145
+ mergedOptions = augmentOptions(defaultOptions, options);
2146
+ mergedHandlers = mergedOptions.defaultHandlers;
2147
+ if (!mergedOptions.fetch) {
2148
+ throw new Error('No global fetch and fetch not provided in options');
2149
+ }
2150
+ defaultAcceptRanges = allMediaRanges(mergedHandlers);
2151
+ defaultAcceptStrings = defaultAcceptRanges.map(function (accept) {
2152
+ return accept.q === 1 ? accept.type : "".concat(accept.type, ";q=").concat(accept.q);
2153
+ });
2154
+ additionalAcceptHeader = ((_a = options === null || options === void 0 ? void 0 : options.headers) === null || _a === void 0 ? void 0 : _a['accept'])
2155
+ ? [options.headers['accept']]
2156
+ : [];
2157
+ fullAcceptHeader = __spreadArray(__spreadArray([], __read(additionalAcceptHeader), false), __read(defaultAcceptStrings), false).join(',');
2158
+ updateOptions = __assign(__assign({}, mergedOptions), { headers: __assign(__assign({}, mergedOptions.headers), { accept: fullAcceptHeader }) });
2159
+ stop = false;
2160
+ try {
2161
+ for (_b = __values(updateOptions.preInterceptors || []), _c = _b.next(); !_c.done; _c = _b.next()) {
2162
+ interceptor = _c.value;
2163
+ interceptor(uriOrRequest, updateOptions, function () { return (stop = true); });
2164
+ if (stop) {
2165
+ break;
2166
+ }
2167
+ }
2168
+ }
2169
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
2170
+ finally {
2171
+ try {
2172
+ if (_c && !_c.done && (_h = _b.return)) _h.call(_b);
2173
+ }
2174
+ finally { if (e_6) throw e_6.error; }
2175
+ }
2176
+ return [4 /*yield*/, mergedOptions.fetch(uriOrRequest.toString(), updateOptions)
2177
+ // TODO allow lazy loading of the content
2178
+ ];
2179
+ case 1:
2180
+ baseResponse = _l.sent();
2181
+ return [4 /*yield*/, mergedOptions.contentParser(baseResponse)
2182
+ // content is
2183
+ // 1. unknown,
2184
+ // 2. a post response client side Problem Document,
2185
+ // 3. a server side ProblemDocument, or
2186
+ // 4. undefined
2187
+ ];
2188
+ case 2:
2189
+ content = _l.sent();
2190
+ // content is
2191
+ // 1. unknown,
2192
+ // 2. a post response client side Problem Document,
2193
+ // 3. a server side ProblemDocument, or
2194
+ // 4. undefined
2195
+ try {
2196
+ response = WayChaserResponse.create(baseResponse, content, defaultOptions, mergedOptions);
2197
+ stop = false;
2198
+ try {
2199
+ for (_d = __values(updateOptions.postInterceptors), _e = _d.next(); !_e.done; _e = _d.next()) {
2200
+ interceptor = _e.value;
2201
+ interceptor(response, function () { return (stop = true); });
2202
+ if (stop) {
2203
+ break;
2204
+ }
2205
+ }
2206
+ }
2207
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
2208
+ finally {
2209
+ try {
2210
+ if (_e && !_e.done && (_j = _d.return)) _j.call(_d);
2211
+ }
2212
+ finally { if (e_7) throw e_7.error; }
2213
+ }
2214
+ return [2 /*return*/, response];
2215
+ }
2216
+ catch (error) {
2217
+ stop = false;
2218
+ try {
2219
+ for (_f = __values(updateOptions.postErrorInterceptors), _g = _f.next(); !_g.done; _g = _f.next()) {
2220
+ interceptor = _g.value;
2221
+ interceptor(error, function () { return (stop = true); });
2222
+ if (stop) {
2223
+ break;
2224
+ }
2225
+ }
2226
+ }
2227
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
2228
+ finally {
2229
+ try {
2230
+ if (_g && !_g.done && (_k = _f.return)) _k.call(_f);
2231
+ }
2232
+ finally { if (e_8) throw e_8.error; }
2233
+ }
2234
+ throw error;
2235
+ }
2236
+ return [2 /*return*/];
2237
+ }
2238
+ });
2239
+ });
2240
+ }
2241
+ /**
2242
+ *
2243
+ */
2244
+ function getGlobal() {
2245
+ if (typeof self !== 'undefined') {
2246
+ return self;
2247
+ }
2248
+ if (typeof window !== 'undefined') {
2249
+ return window;
2250
+ }
2251
+ if (typeof global !== 'undefined') {
2252
+ return global;
2253
+ }
2254
+ return;
2255
+ }
2256
+ var wayChaserDefaults = {
2257
+ fetch: typeof window !== 'undefined' ? (_a = window.fetch) === null || _a === void 0 ? void 0 : _a.bind(window) : (_b = getGlobal()) === null || _b === void 0 ? void 0 : _b.fetch,
2258
+ handlers: [],
2259
+ defaultHandlers: sortHandlers([
2260
+ { handler: locationHeaderHandler, mediaRanges: ['*/*'], q: 0.4 },
2261
+ { handler: linkHeaderHandler, mediaRanges: ['*/*'], q: 0.5 },
2262
+ { handler: halHandler, mediaRanges: [MediaTypes.HAL], q: 0.5 },
2263
+ { handler: sirenHandler, mediaRanges: [MediaTypes.SIREN], q: 0.5 }
2264
+ ]),
2265
+ preInterceptors: [],
2266
+ postInterceptors: [],
2267
+ postErrorInterceptors: [],
2268
+ contentParser: function (response) { return __awaiter(void 0, void 0, void 0, function () {
2269
+ var content, contentType, jsonContent;
2270
+ var _a;
2271
+ return __generator(this, function (_b) {
2272
+ switch (_b.label) {
2273
+ case 0:
2274
+ if (!(response.headers.get('content-length') &&
2275
+ response.headers.get('content-length') !== '0')) return [3 /*break*/, 2];
2276
+ return [4 /*yield*/, response.text()];
2277
+ case 1:
2278
+ content = _b.sent();
2279
+ contentType = response.headers.get('content-type');
2280
+ if ((_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')) === null || _a === void 0 ? void 0 : _a[0].endsWith('json')) {
2281
+ try {
2282
+ jsonContent = JSON.parse(content);
2283
+ return [2 /*return*/, contentType === 'application/problem+json' ? Object.assign(new ProblemDocument_1(jsonContent), jsonContent) : jsonContent];
2284
+ }
2285
+ catch (error) {
2286
+ return [2 /*return*/, new ProblemDocument_1({
2287
+ type: "https://waychaser.io/invalid-json",
2288
+ title: "JSON response could not be parsed",
2289
+ detail: "The response document with content type '".concat(contentType, "' could not be parsed as json"),
2290
+ content: content,
2291
+ error: error
2292
+ })];
2293
+ }
2294
+ }
2295
+ return [2 /*return*/, new ProblemDocument_1(__assign({ type: "https://waychaser.io/unsupported-content-type", title: "The response has an unsupported content type", detail: "The response document has a content type of '".concat(contentType, "' which is not supported"), content: content }, (contentType && { contentType: contentType })))];
2296
+ case 2: return [2 /*return*/];
2297
+ }
2298
+ });
2299
+ }); }
2300
+ };
2301
+ /**
2302
+ * @param newDefaults
2303
+ * @param oldDefaults
2304
+ */
2305
+ function _defaults(newDefaults, oldDefaults) {
2306
+ var mergedOptions = augmentOptions(oldDefaults, newDefaults);
2307
+ var defaultedWaychaser = function (uriOrRequest, options) { return _waychaser(uriOrRequest, mergedOptions, options); };
2308
+ defaultedWaychaser.currentDefaults = mergedOptions;
2309
+ defaultedWaychaser.defaults = function (newDefaults) {
2310
+ return _defaults(newDefaults, mergedOptions);
2311
+ };
2312
+ return defaultedWaychaser;
2313
+ }
2314
+ /**
2315
+ * calls fetch on the passed in uriOrRequest and parses the response
2316
+ *
2317
+ * @param uriOrRequest see RequestInit
2318
+ * @param options see WayChaserOptions
2319
+ * @returns WayChaserResponse<Content>
2320
+ * @throws TypeError | AbortError | WayChaserResponseProblem | Error
2321
+ */
2322
+ var waychaser = Object.assign(function (uriOrRequest, options) {
2323
+ return _waychaser(uriOrRequest, wayChaserDefaults, options);
2324
+ }, {
2325
+ currentDefaults: wayChaserDefaults,
2326
+ defaults: function (newDefaults) {
2327
+ return _defaults(newDefaults, wayChaserDefaults);
2328
+ }
2329
+ });
2330
+
2331
+ export { WayChaserProblem, WayChaserResponse, _waychaser, isValidationSuccess, sortHandlers, waychaser };