@flarehr/apollo-super-selection 5.54.16008 → 5.55.16332

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 (75) hide show
  1. package/dist/lib/apollo-super-selection/apollo-super-selection.css +1 -1
  2. package/dist/lib/apollo-super-selection/apollo-super-selection.esm.js +1 -1
  3. package/dist/lib/apollo-super-selection/apollo-super-selection.js +1 -1
  4. package/dist/lib/apollo-super-selection/p-1596c9a2.system.entry.js +69 -0
  5. package/dist/lib/apollo-super-selection/{p-ef3afa00.system.entry.js → p-22939048.system.entry.js} +1 -1
  6. package/dist/lib/apollo-super-selection/p-2590548f.system.js +1 -0
  7. package/dist/lib/apollo-super-selection/{p-02f24922.system.entry.js → p-2b42304a.system.entry.js} +1 -1
  8. package/dist/lib/apollo-super-selection/{p-9c855634.entry.js → p-33eca162.entry.js} +1 -1
  9. package/dist/lib/apollo-super-selection/p-4e871154.entry.js +1 -0
  10. package/dist/lib/apollo-super-selection/{p-6ac8791e.system.entry.js → p-53b231f0.system.entry.js} +1 -1
  11. package/dist/lib/apollo-super-selection/{p-b89b68db.entry.js → p-5c73c587.entry.js} +1 -1
  12. package/dist/lib/apollo-super-selection/p-645755ee.system.entry.js +1 -0
  13. package/dist/lib/apollo-super-selection/{p-fcb4050d.entry.js → p-69bbf1dd.entry.js} +1 -1
  14. package/dist/lib/apollo-super-selection/p-6b03f1b2.entry.js +1 -0
  15. package/dist/lib/apollo-super-selection/{p-44bec843.system.js → p-71ca4cf8.system.js} +1 -1
  16. package/dist/lib/apollo-super-selection/p-8f3cc4bf.entry.js +14 -0
  17. package/dist/lib/apollo-super-selection/p-97188c78.system.js +1 -0
  18. package/dist/lib/apollo-super-selection/p-99266549.js +1 -0
  19. package/dist/lib/apollo-super-selection/{p-23cfdd82.entry.js → p-9d2a7c0e.entry.js} +1 -1
  20. package/dist/lib/apollo-super-selection/p-bd6e6a8f.system.js +1 -0
  21. package/dist/lib/apollo-super-selection/p-c775c0e4.system.entry.js +1 -0
  22. package/dist/lib/apollo-super-selection/{p-51c6dd08.js → p-db0bded8.js} +1 -1
  23. package/dist/lib/apollo-super-selection/{p-f29066b9.system.entry.js → p-e957b393.system.entry.js} +1 -1
  24. package/dist/lib/apollo-super-selection/{p-7a89efaf.js → p-fdadb647.js} +1 -1
  25. package/dist/lib/cjs/apollo-super-selection.cjs.js +1 -1
  26. package/dist/lib/cjs/custom-fund-choice.api-713823d3.js +3043 -0
  27. package/dist/lib/cjs/loader.cjs.js +1 -1
  28. package/dist/lib/cjs/{sss-button_33.cjs.entry.js → sss-button_31.cjs.entry.js} +395 -3566
  29. package/dist/lib/cjs/sss-super-byof-host.cjs.entry.js +94 -0
  30. package/dist/lib/collection/apollo-super-selection.css +1 -1
  31. package/dist/lib/collection/collection-manifest.json +1 -4
  32. package/dist/lib/collection/components/super-byof/super-byof-types.js +1 -0
  33. package/dist/lib/collection/components/super-byof/super-byof.form.js +1 -0
  34. package/dist/lib/collection/components/super-byof/super-byof.js +120 -0
  35. package/dist/lib/collection/components/super-selection-app/services/super-selection-app.routes.js +1 -1
  36. package/dist/lib/esm/{active-router-5e40c0f8.js → active-router-d18b36fb.js} +1 -1
  37. package/dist/lib/esm/apollo-super-selection.js +2 -2
  38. package/dist/lib/esm/context-consumer.entry.js +1 -1
  39. package/dist/lib/esm/custom-fund-choice.api-45fa478c.js +3022 -0
  40. package/dist/lib/esm/{index-189b2180.js → index-107d7c24.js} +1 -1
  41. package/dist/lib/esm/loader.js +2 -2
  42. package/dist/lib/esm/{sss-button_33.entry.js → sss-button_31.entry.js} +142 -3311
  43. package/dist/lib/esm/sss-super-byof-host.entry.js +90 -0
  44. package/dist/lib/esm/stencil-async-content.entry.js +1 -1
  45. package/dist/lib/esm/stencil-route-title.entry.js +2 -2
  46. package/dist/lib/esm/stencil-router-prompt.entry.js +2 -2
  47. package/dist/lib/esm/stencil-router-redirect.entry.js +2 -2
  48. package/dist/lib/esm-es5/{active-router-5e40c0f8.js → active-router-d18b36fb.js} +1 -1
  49. package/dist/lib/esm-es5/apollo-super-selection.js +1 -1
  50. package/dist/lib/esm-es5/context-consumer.entry.js +1 -1
  51. package/dist/lib/esm-es5/custom-fund-choice.api-45fa478c.js +1 -0
  52. package/dist/lib/esm-es5/{index-189b2180.js → index-107d7c24.js} +1 -1
  53. package/dist/lib/esm-es5/loader.js +1 -1
  54. package/dist/lib/esm-es5/sss-button_31.entry.js +69 -0
  55. package/dist/lib/esm-es5/sss-super-byof-host.entry.js +1 -0
  56. package/dist/lib/esm-es5/stencil-async-content.entry.js +1 -1
  57. package/dist/lib/esm-es5/stencil-route-title.entry.js +1 -1
  58. package/dist/lib/esm-es5/stencil-router-prompt.entry.js +1 -1
  59. package/dist/lib/esm-es5/stencil-router-redirect.entry.js +1 -1
  60. package/dist/lib/types/components/super-byof/super-byof-types.d.ts +26 -0
  61. package/dist/lib/types/components/super-byof/super-byof.d.ts +18 -0
  62. package/dist/lib/types/components/super-byof/super-byof.form.d.ts +6 -0
  63. package/dist/lib/types/components.d.ts +15 -34
  64. package/package.json +2 -1
  65. package/dist/lib/apollo-super-selection/p-071b8545.entry.js +0 -1
  66. package/dist/lib/apollo-super-selection/p-2298df79.system.entry.js +0 -69
  67. package/dist/lib/apollo-super-selection/p-51aefdb1.system.entry.js +0 -1
  68. package/dist/lib/apollo-super-selection/p-80178f87.system.js +0 -1
  69. package/dist/lib/apollo-super-selection/p-bdcfc026.system.js +0 -1
  70. package/dist/lib/apollo-super-selection/p-d7dbf362.entry.js +0 -14
  71. package/dist/lib/collection/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund-inputs.js +0 -143
  72. package/dist/lib/collection/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund.js +0 -123
  73. package/dist/lib/esm-es5/sss-button_33.entry.js +0 -69
  74. package/dist/lib/types/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund-inputs.d.ts +0 -16
  75. package/dist/lib/types/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund.d.ts +0 -13
@@ -0,0 +1,3022 @@
1
+ import { e as getRenderingRef, f as forceUpdate, h } from './index-107d7c24.js';
2
+ import { A as ActiveRouter } from './active-router-d18b36fb.js';
3
+
4
+ // -------------------------------------------------------------------------------------
5
+ // guards
6
+ // -------------------------------------------------------------------------------------
7
+ /**
8
+ * Returns `true` if the option is an instance of `Some`, `false` otherwise.
9
+ *
10
+ * @example
11
+ * import { some, none, isSome } from 'fp-ts/Option'
12
+ *
13
+ * assert.strictEqual(isSome(some(1)), true)
14
+ * assert.strictEqual(isSome(none), false)
15
+ *
16
+ * @category guards
17
+ * @since 2.0.0
18
+ */
19
+ var isSome = function (fa) { return fa._tag === 'Some'; };
20
+ /**
21
+ * Returns `true` if the option is `None`, `false` otherwise.
22
+ *
23
+ * @example
24
+ * import { some, none, isNone } from 'fp-ts/Option'
25
+ *
26
+ * assert.strictEqual(isNone(some(1)), false)
27
+ * assert.strictEqual(isNone(none), true)
28
+ *
29
+ * @category guards
30
+ * @since 2.0.0
31
+ */
32
+ var isNone = function (fa) { return fa._tag === 'None'; };
33
+ // -------------------------------------------------------------------------------------
34
+ // constructors
35
+ // -------------------------------------------------------------------------------------
36
+ /**
37
+ * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value.
38
+ *
39
+ * @category constructors
40
+ * @since 2.0.0
41
+ */
42
+ var none = { _tag: 'None' };
43
+ /**
44
+ * Constructs a `Some`. Represents an optional value that exists.
45
+ *
46
+ * @category constructors
47
+ * @since 2.0.0
48
+ */
49
+ var some = function (a) { return ({ _tag: 'Some', value: a }); };
50
+ /**
51
+ * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
52
+ * returns the value wrapped in a `Some`.
53
+ *
54
+ * @example
55
+ * import { none, some, fromNullable } from 'fp-ts/Option'
56
+ *
57
+ * assert.deepStrictEqual(fromNullable(undefined), none)
58
+ * assert.deepStrictEqual(fromNullable(null), none)
59
+ * assert.deepStrictEqual(fromNullable(1), some(1))
60
+ *
61
+ * @category constructors
62
+ * @since 2.0.0
63
+ */
64
+ function fromNullable(a) {
65
+ return a == null ? none : some(a);
66
+ }
67
+ /**
68
+ * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`.
69
+ *
70
+ * @example
71
+ * import { some, none, toUndefined } from 'fp-ts/Option'
72
+ * import { pipe } from 'fp-ts/function'
73
+ *
74
+ * assert.strictEqual(
75
+ * pipe(
76
+ * some(1),
77
+ * toUndefined
78
+ * ),
79
+ * 1
80
+ * )
81
+ * assert.strictEqual(
82
+ * pipe(
83
+ * none,
84
+ * toUndefined
85
+ * ),
86
+ * undefined
87
+ * )
88
+ *
89
+ * @category destructors
90
+ * @since 2.0.0
91
+ */
92
+ function toUndefined(ma) {
93
+ return isNone(ma) ? undefined : ma.value;
94
+ }
95
+
96
+ function injectHistory(Component) {
97
+ ActiveRouter.injectProps(Component, ['history', 'location']);
98
+ }
99
+
100
+ function appReady() {
101
+ postMessage({
102
+ type: 'appReady'
103
+ });
104
+ }
105
+ function postMessage(message, origin) {
106
+ if (origin === undefined)
107
+ origin = '*';
108
+ message.sender = 'flare';
109
+ window.parent.postMessage(message, origin);
110
+ }
111
+ function resize(height, width) {
112
+ postMessage({
113
+ type: 'contentResized',
114
+ height,
115
+ width
116
+ });
117
+ }
118
+ function navigation(url) {
119
+ postMessage({
120
+ type: 'pageNavigated',
121
+ url
122
+ });
123
+ }
124
+ function complete() {
125
+ postMessage({ type: 'complete' });
126
+ }
127
+ function submitSuccess() {
128
+ postMessage({
129
+ type: 'submitSuccess'
130
+ });
131
+ }
132
+ const iframe = { appReady, resize, navigation, complete, submitSuccess };
133
+
134
+ const appendToMap = (map, propName, value) => {
135
+ const items = map.get(propName);
136
+ if (!items) {
137
+ map.set(propName, [value]);
138
+ }
139
+ else if (!items.includes(value)) {
140
+ items.push(value);
141
+ }
142
+ };
143
+ const debounce = (fn, ms) => {
144
+ let timeoutId;
145
+ return (...args) => {
146
+ if (timeoutId) {
147
+ clearTimeout(timeoutId);
148
+ }
149
+ timeoutId = setTimeout(() => {
150
+ timeoutId = 0;
151
+ fn(...args);
152
+ }, ms);
153
+ };
154
+ };
155
+
156
+ /**
157
+ * Check if a possible element isConnected.
158
+ * The property might not be there, so we check for it.
159
+ *
160
+ * We want it to return true if isConnected is not a property,
161
+ * otherwise we would remove these elements and would not update.
162
+ *
163
+ * Better leak in Edge than to be useless.
164
+ */
165
+ const isConnected = (maybeElement) => !('isConnected' in maybeElement) || maybeElement.isConnected;
166
+ const cleanupElements = debounce((map) => {
167
+ for (let key of map.keys()) {
168
+ map.set(key, map.get(key).filter(isConnected));
169
+ }
170
+ }, 2000);
171
+ const stencilSubscription = ({ on }) => {
172
+ const elmsToUpdate = new Map();
173
+ if (typeof getRenderingRef === 'function') {
174
+ // If we are not in a stencil project, we do nothing.
175
+ // This function is not really exported by @stencil/core.
176
+ on('dispose', () => {
177
+ elmsToUpdate.clear();
178
+ });
179
+ on('get', (propName) => {
180
+ const elm = getRenderingRef();
181
+ if (elm) {
182
+ appendToMap(elmsToUpdate, propName, elm);
183
+ }
184
+ });
185
+ on('set', (propName) => {
186
+ const elements = elmsToUpdate.get(propName);
187
+ if (elements) {
188
+ elmsToUpdate.set(propName, elements.filter(forceUpdate));
189
+ }
190
+ cleanupElements(elmsToUpdate);
191
+ });
192
+ on('reset', () => {
193
+ elmsToUpdate.forEach((elms) => elms.forEach(forceUpdate));
194
+ cleanupElements(elmsToUpdate);
195
+ });
196
+ }
197
+ };
198
+
199
+ const createObservableMap = (defaultState, shouldUpdate = (a, b) => a !== b) => {
200
+ let states = new Map(Object.entries(defaultState !== null && defaultState !== void 0 ? defaultState : {}));
201
+ const handlers = {
202
+ dispose: [],
203
+ get: [],
204
+ set: [],
205
+ reset: [],
206
+ };
207
+ const reset = () => {
208
+ states = new Map(Object.entries(defaultState !== null && defaultState !== void 0 ? defaultState : {}));
209
+ handlers.reset.forEach((cb) => cb());
210
+ };
211
+ const dispose = () => {
212
+ // Call first dispose as resetting the state would
213
+ // cause less updates ;)
214
+ handlers.dispose.forEach((cb) => cb());
215
+ reset();
216
+ };
217
+ const get = (propName) => {
218
+ handlers.get.forEach((cb) => cb(propName));
219
+ return states.get(propName);
220
+ };
221
+ const set = (propName, value) => {
222
+ const oldValue = states.get(propName);
223
+ if (shouldUpdate(value, oldValue, propName)) {
224
+ states.set(propName, value);
225
+ handlers.set.forEach((cb) => cb(propName, value, oldValue));
226
+ }
227
+ };
228
+ const state = (typeof Proxy === 'undefined'
229
+ ? {}
230
+ : new Proxy(defaultState, {
231
+ get(_, propName) {
232
+ return get(propName);
233
+ },
234
+ ownKeys(_) {
235
+ return Array.from(states.keys());
236
+ },
237
+ getOwnPropertyDescriptor() {
238
+ return {
239
+ enumerable: true,
240
+ configurable: true,
241
+ };
242
+ },
243
+ has(_, propName) {
244
+ return states.has(propName);
245
+ },
246
+ set(_, propName, value) {
247
+ set(propName, value);
248
+ return true;
249
+ },
250
+ }));
251
+ const on = (eventName, callback) => {
252
+ handlers[eventName].push(callback);
253
+ return () => {
254
+ removeFromArray(handlers[eventName], callback);
255
+ };
256
+ };
257
+ const onChange = (propName, cb) => {
258
+ const unSet = on('set', (key, newValue) => {
259
+ if (key === propName) {
260
+ cb(newValue);
261
+ }
262
+ });
263
+ const unReset = on('reset', () => cb(defaultState[propName]));
264
+ return () => {
265
+ unSet();
266
+ unReset();
267
+ };
268
+ };
269
+ const use = (...subscriptions) => subscriptions.forEach((subscription) => {
270
+ if (subscription.set) {
271
+ on('set', subscription.set);
272
+ }
273
+ if (subscription.get) {
274
+ on('get', subscription.get);
275
+ }
276
+ if (subscription.reset) {
277
+ on('reset', subscription.reset);
278
+ }
279
+ });
280
+ return {
281
+ state,
282
+ get,
283
+ set,
284
+ on,
285
+ onChange,
286
+ use,
287
+ dispose,
288
+ reset,
289
+ };
290
+ };
291
+ const removeFromArray = (array, item) => {
292
+ const index = array.indexOf(item);
293
+ if (index >= 0) {
294
+ array[index] = array[array.length - 1];
295
+ array.length--;
296
+ }
297
+ };
298
+
299
+ const createStore = (defaultState, shouldUpdate) => {
300
+ const map = createObservableMap(defaultState, shouldUpdate);
301
+ stencilSubscription(map);
302
+ return map;
303
+ };
304
+
305
+ const initial = {
306
+ handleSubmitFn: async function () {
307
+ return;
308
+ },
309
+ fundName: '',
310
+ fundDetails: { type: 'null' },
311
+ promotedFundId: undefined
312
+ };
313
+ const { state } = createStore(initial);
314
+
315
+ var SuperSelectionAppRoutes;
316
+ (function (SuperSelectionAppRoutes) {
317
+ SuperSelectionAppRoutes["ExistingChoicePage"] = "/existing";
318
+ SuperSelectionAppRoutes["SuperCampaign"] = "/super-campaign";
319
+ SuperSelectionAppRoutes["ChoicePage"] = "/";
320
+ SuperSelectionAppRoutes["MyOwnFund"] = "/super-choice/my-own-fund/";
321
+ SuperSelectionAppRoutes["MyOwnFundEngagementStep"] = "/super-choice/my-own-fund-engagement/";
322
+ SuperSelectionAppRoutes["Prefill"] = "/super-choice/prefill/";
323
+ SuperSelectionAppRoutes["PrefillInvalidMyOwnFundPage"] = "/super-choice/sss-prefill-invalid-my-own-fund/";
324
+ SuperSelectionAppRoutes["PrefillMyOwnFundPage"] = "/super-choice/prefill-my-own-fund/";
325
+ SuperSelectionAppRoutes["PrefillSMSFPage"] = "/super-choice/prefill-smsf/";
326
+ SuperSelectionAppRoutes["PrefillInvalidSMSFPage"] = "/super-choice/prefill-invalid-smsf/";
327
+ SuperSelectionAppRoutes["SelfManagedFund"] = "/super-choice/smsf/";
328
+ SuperSelectionAppRoutes["DefaultFund"] = "/super-choice/default/";
329
+ SuperSelectionAppRoutes["FeaturedFunds"] = "/super-choice/featured-funds/";
330
+ SuperSelectionAppRoutes["StandardChoice"] = "/standard-choice/";
331
+ SuperSelectionAppRoutes["Success"] = "/success/";
332
+ })(SuperSelectionAppRoutes || (SuperSelectionAppRoutes = {}));
333
+ const superSelectionAppStencilRoutes = [
334
+ h("stencil-route", { url: SuperSelectionAppRoutes.ExistingChoicePage, component: "sss-existing-choice-page" }),
335
+ h("stencil-route", { url: SuperSelectionAppRoutes.SuperCampaign, component: "sss-super-campaign-host" }),
336
+ h("stencil-route", { exact: true, url: SuperSelectionAppRoutes.ChoicePage, component: "sss-choice-router" }),
337
+ h("stencil-route", { url: SuperSelectionAppRoutes.MyOwnFund, component: "sss-super-byof-host" }),
338
+ h("stencil-route", { url: SuperSelectionAppRoutes.MyOwnFundEngagementStep, component: "sss-my-own-fund-engagement-step-host" }),
339
+ h("stencil-route", { url: SuperSelectionAppRoutes.PrefillInvalidMyOwnFundPage, component: "sss-prefill-invalid-my-own-fund" }),
340
+ h("stencil-route", { url: SuperSelectionAppRoutes.Prefill, component: "sss-prefill" }),
341
+ h("stencil-route", { url: SuperSelectionAppRoutes.PrefillMyOwnFundPage, component: "sss-prefill-my-own-fund" }),
342
+ h("stencil-route", { url: SuperSelectionAppRoutes.PrefillSMSFPage, component: "sss-prefill-smsf" }),
343
+ h("stencil-route", { url: SuperSelectionAppRoutes.PrefillInvalidSMSFPage, component: "sss-prefill-invalid-smsf" }),
344
+ h("stencil-route", { url: SuperSelectionAppRoutes.SelfManagedFund, component: "sss-super-smsf-host" }),
345
+ h("stencil-route", { url: SuperSelectionAppRoutes.DefaultFund, component: "sss-default-fund" }),
346
+ h("stencil-route", { url: SuperSelectionAppRoutes.FeaturedFunds, component: "sss-super-campaign-featured-funds" }),
347
+ h("stencil-route", { url: SuperSelectionAppRoutes.StandardChoice, component: "sss-standard-choice-form" }),
348
+ h("stencil-route", { url: SuperSelectionAppRoutes.Success, component: "sss-success" })
349
+ ];
350
+
351
+ function createCommonjsModule(fn, basedir, module) {
352
+ return module = {
353
+ path: basedir,
354
+ exports: {},
355
+ require: function (path, base) {
356
+ return commonjsRequire();
357
+ }
358
+ }, fn(module, module.exports), module.exports;
359
+ }
360
+
361
+ function commonjsRequire () {
362
+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
363
+ }
364
+
365
+ var _function = createCommonjsModule(function (module, exports) {
366
+ /**
367
+ * @since 2.0.0
368
+ */
369
+ Object.defineProperty(exports, "__esModule", { value: true });
370
+ exports.bindTo_ = exports.bind_ = exports.hole = exports.pipe = exports.untupled = exports.tupled = exports.absurd = exports.decrement = exports.increment = exports.tuple = exports.flow = exports.flip = exports.constVoid = exports.constUndefined = exports.constNull = exports.constFalse = exports.constTrue = exports.constant = exports.not = exports.unsafeCoerce = exports.identity = void 0;
371
+ /**
372
+ * @since 2.0.0
373
+ */
374
+ function identity(a) {
375
+ return a;
376
+ }
377
+ exports.identity = identity;
378
+ /**
379
+ * @since 2.0.0
380
+ */
381
+ exports.unsafeCoerce = identity;
382
+ /**
383
+ * @since 2.0.0
384
+ */
385
+ function not(predicate) {
386
+ return function (a) { return !predicate(a); };
387
+ }
388
+ exports.not = not;
389
+ /**
390
+ * @since 2.0.0
391
+ */
392
+ function constant(a) {
393
+ return function () { return a; };
394
+ }
395
+ exports.constant = constant;
396
+ /**
397
+ * A thunk that returns always `true`.
398
+ *
399
+ * @since 2.0.0
400
+ */
401
+ exports.constTrue =
402
+ /*#__PURE__*/
403
+ constant(true);
404
+ /**
405
+ * A thunk that returns always `false`.
406
+ *
407
+ * @since 2.0.0
408
+ */
409
+ exports.constFalse =
410
+ /*#__PURE__*/
411
+ constant(false);
412
+ /**
413
+ * A thunk that returns always `null`.
414
+ *
415
+ * @since 2.0.0
416
+ */
417
+ exports.constNull =
418
+ /*#__PURE__*/
419
+ constant(null);
420
+ /**
421
+ * A thunk that returns always `undefined`.
422
+ *
423
+ * @since 2.0.0
424
+ */
425
+ exports.constUndefined =
426
+ /*#__PURE__*/
427
+ constant(undefined);
428
+ /**
429
+ * A thunk that returns always `void`.
430
+ *
431
+ * @since 2.0.0
432
+ */
433
+ exports.constVoid = exports.constUndefined;
434
+ // TODO: remove in v3
435
+ /**
436
+ * Flips the order of the arguments of a function of two arguments.
437
+ *
438
+ * @since 2.0.0
439
+ */
440
+ function flip(f) {
441
+ return function (b, a) { return f(a, b); };
442
+ }
443
+ exports.flip = flip;
444
+ function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
445
+ switch (arguments.length) {
446
+ case 1:
447
+ return ab;
448
+ case 2:
449
+ return function () {
450
+ return bc(ab.apply(this, arguments));
451
+ };
452
+ case 3:
453
+ return function () {
454
+ return cd(bc(ab.apply(this, arguments)));
455
+ };
456
+ case 4:
457
+ return function () {
458
+ return de(cd(bc(ab.apply(this, arguments))));
459
+ };
460
+ case 5:
461
+ return function () {
462
+ return ef(de(cd(bc(ab.apply(this, arguments)))));
463
+ };
464
+ case 6:
465
+ return function () {
466
+ return fg(ef(de(cd(bc(ab.apply(this, arguments))))));
467
+ };
468
+ case 7:
469
+ return function () {
470
+ return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))));
471
+ };
472
+ case 8:
473
+ return function () {
474
+ return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))));
475
+ };
476
+ case 9:
477
+ return function () {
478
+ return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))));
479
+ };
480
+ }
481
+ return;
482
+ }
483
+ exports.flow = flow;
484
+ /**
485
+ * @since 2.0.0
486
+ */
487
+ function tuple() {
488
+ var t = [];
489
+ for (var _i = 0; _i < arguments.length; _i++) {
490
+ t[_i] = arguments[_i];
491
+ }
492
+ return t;
493
+ }
494
+ exports.tuple = tuple;
495
+ /**
496
+ * @since 2.0.0
497
+ */
498
+ function increment(n) {
499
+ return n + 1;
500
+ }
501
+ exports.increment = increment;
502
+ /**
503
+ * @since 2.0.0
504
+ */
505
+ function decrement(n) {
506
+ return n - 1;
507
+ }
508
+ exports.decrement = decrement;
509
+ /**
510
+ * @since 2.0.0
511
+ */
512
+ function absurd(_) {
513
+ throw new Error('Called `absurd` function which should be uncallable');
514
+ }
515
+ exports.absurd = absurd;
516
+ /**
517
+ * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument.
518
+ *
519
+ * @example
520
+ * import { tupled } from 'fp-ts/function'
521
+ *
522
+ * const add = tupled((x: number, y: number): number => x + y)
523
+ *
524
+ * assert.strictEqual(add([1, 2]), 3)
525
+ *
526
+ * @since 2.4.0
527
+ */
528
+ function tupled(f) {
529
+ return function (a) { return f.apply(void 0, a); };
530
+ }
531
+ exports.tupled = tupled;
532
+ /**
533
+ * Inverse function of `tupled`
534
+ *
535
+ * @since 2.4.0
536
+ */
537
+ function untupled(f) {
538
+ return function () {
539
+ var a = [];
540
+ for (var _i = 0; _i < arguments.length; _i++) {
541
+ a[_i] = arguments[_i];
542
+ }
543
+ return f(a);
544
+ };
545
+ }
546
+ exports.untupled = untupled;
547
+ function pipe(a, ab, bc, cd, de, ef, fg, gh, hi, ij, jk, kl, lm, mn, no, op, pq, qr, rs, st) {
548
+ switch (arguments.length) {
549
+ case 1:
550
+ return a;
551
+ case 2:
552
+ return ab(a);
553
+ case 3:
554
+ return bc(ab(a));
555
+ case 4:
556
+ return cd(bc(ab(a)));
557
+ case 5:
558
+ return de(cd(bc(ab(a))));
559
+ case 6:
560
+ return ef(de(cd(bc(ab(a)))));
561
+ case 7:
562
+ return fg(ef(de(cd(bc(ab(a))))));
563
+ case 8:
564
+ return gh(fg(ef(de(cd(bc(ab(a)))))));
565
+ case 9:
566
+ return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
567
+ case 10:
568
+ return ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))));
569
+ case 11:
570
+ return jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))));
571
+ case 12:
572
+ return kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))));
573
+ case 13:
574
+ return lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))));
575
+ case 14:
576
+ return mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))));
577
+ case 15:
578
+ return no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))));
579
+ case 16:
580
+ return op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))));
581
+ case 17:
582
+ return pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))))));
583
+ case 18:
584
+ return qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))))));
585
+ case 19:
586
+ return rs(qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))))))));
587
+ case 20:
588
+ return st(rs(qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))))))));
589
+ }
590
+ return;
591
+ }
592
+ exports.pipe = pipe;
593
+ /**
594
+ * Type hole simulation
595
+ *
596
+ * @since 2.7.0
597
+ */
598
+ exports.hole = absurd;
599
+ /**
600
+ * @internal
601
+ */
602
+ var bind_ = function (a, name, b) {
603
+ var _a;
604
+ return Object.assign({}, a, (_a = {}, _a[name] = b, _a));
605
+ };
606
+ exports.bind_ = bind_;
607
+ /**
608
+ * @internal
609
+ */
610
+ var bindTo_ = function (name) { return function (b) {
611
+ var _a;
612
+ return (_a = {}, _a[name] = b, _a);
613
+ }; };
614
+ exports.bindTo_ = bindTo_;
615
+ });
616
+
617
+ var Option = createCommonjsModule(function (module, exports) {
618
+ Object.defineProperty(exports, "__esModule", { value: true });
619
+ exports.getApplySemigroup = exports.getOrd = exports.getEq = exports.getShow = exports.URI = exports.wilt = exports.wither = exports.sequence = exports.traverse = exports.partitionMap = exports.partition = exports.filterMap = exports.filter = exports.separate = exports.compact = exports.reduceRight = exports.foldMap = exports.reduce = exports.duplicate = exports.extend = exports.throwError = exports.zero = exports.alt = exports.altW = exports.flatten = exports.chainFirst = exports.chain = exports.of = exports.apSecond = exports.apFirst = exports.ap = exports.map = exports.chainNullableK = exports.mapNullable = exports.fromNullableK = exports.getOrElse = exports.getOrElseW = exports.toUndefined = exports.toNullable = exports.fold = exports.fromEither = exports.getRight = exports.getLeft = exports.tryCatch = exports.fromPredicate = exports.fromNullable = exports.some = exports.none = exports.isNone = exports.isSome = void 0;
620
+ exports.sequenceArray = exports.traverseArray = exports.traverseArrayWithIndex = exports.apS = exports.bind = exports.bindTo = exports.Do = exports.getRefinement = exports.exists = exports.elem = exports.option = exports.MonadThrow = exports.Witherable = exports.Traversable = exports.Filterable = exports.Compactable = exports.Extend = exports.Alternative = exports.Alt = exports.Foldable = exports.Monad = exports.Applicative = exports.Functor = exports.getMonoid = exports.getLastMonoid = exports.getFirstMonoid = exports.getApplyMonoid = void 0;
621
+
622
+ // -------------------------------------------------------------------------------------
623
+ // guards
624
+ // -------------------------------------------------------------------------------------
625
+ /**
626
+ * Returns `true` if the option is an instance of `Some`, `false` otherwise.
627
+ *
628
+ * @example
629
+ * import { some, none, isSome } from 'fp-ts/Option'
630
+ *
631
+ * assert.strictEqual(isSome(some(1)), true)
632
+ * assert.strictEqual(isSome(none), false)
633
+ *
634
+ * @category guards
635
+ * @since 2.0.0
636
+ */
637
+ var isSome = function (fa) { return fa._tag === 'Some'; };
638
+ exports.isSome = isSome;
639
+ /**
640
+ * Returns `true` if the option is `None`, `false` otherwise.
641
+ *
642
+ * @example
643
+ * import { some, none, isNone } from 'fp-ts/Option'
644
+ *
645
+ * assert.strictEqual(isNone(some(1)), false)
646
+ * assert.strictEqual(isNone(none), true)
647
+ *
648
+ * @category guards
649
+ * @since 2.0.0
650
+ */
651
+ var isNone = function (fa) { return fa._tag === 'None'; };
652
+ exports.isNone = isNone;
653
+ // -------------------------------------------------------------------------------------
654
+ // constructors
655
+ // -------------------------------------------------------------------------------------
656
+ /**
657
+ * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value.
658
+ *
659
+ * @category constructors
660
+ * @since 2.0.0
661
+ */
662
+ exports.none = { _tag: 'None' };
663
+ /**
664
+ * Constructs a `Some`. Represents an optional value that exists.
665
+ *
666
+ * @category constructors
667
+ * @since 2.0.0
668
+ */
669
+ var some = function (a) { return ({ _tag: 'Some', value: a }); };
670
+ exports.some = some;
671
+ /**
672
+ * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
673
+ * returns the value wrapped in a `Some`.
674
+ *
675
+ * @example
676
+ * import { none, some, fromNullable } from 'fp-ts/Option'
677
+ *
678
+ * assert.deepStrictEqual(fromNullable(undefined), none)
679
+ * assert.deepStrictEqual(fromNullable(null), none)
680
+ * assert.deepStrictEqual(fromNullable(1), some(1))
681
+ *
682
+ * @category constructors
683
+ * @since 2.0.0
684
+ */
685
+ function fromNullable(a) {
686
+ return a == null ? exports.none : exports.some(a);
687
+ }
688
+ exports.fromNullable = fromNullable;
689
+ function fromPredicate(predicate) {
690
+ return function (a) { return (predicate(a) ? exports.some(a) : exports.none); };
691
+ }
692
+ exports.fromPredicate = fromPredicate;
693
+ /**
694
+ * Transforms an exception into an `Option`. If `f` throws, returns `None`, otherwise returns the output wrapped in a
695
+ * `Some`.
696
+ *
697
+ * @example
698
+ * import { none, some, tryCatch } from 'fp-ts/Option'
699
+ *
700
+ * assert.deepStrictEqual(
701
+ * tryCatch(() => {
702
+ * throw new Error()
703
+ * }),
704
+ * none
705
+ * )
706
+ * assert.deepStrictEqual(tryCatch(() => 1), some(1))
707
+ *
708
+ * @category constructors
709
+ * @since 2.0.0
710
+ */
711
+ function tryCatch(f) {
712
+ try {
713
+ return exports.some(f());
714
+ }
715
+ catch (e) {
716
+ return exports.none;
717
+ }
718
+ }
719
+ exports.tryCatch = tryCatch;
720
+ /**
721
+ * Returns the `Left` value of an `Either` if possible.
722
+ *
723
+ * @example
724
+ * import { getLeft, none, some } from 'fp-ts/Option'
725
+ * import { right, left } from 'fp-ts/Either'
726
+ *
727
+ * assert.deepStrictEqual(getLeft(right(1)), none)
728
+ * assert.deepStrictEqual(getLeft(left('a')), some('a'))
729
+ *
730
+ * @category constructors
731
+ * @since 2.0.0
732
+ */
733
+ function getLeft(ma) {
734
+ return ma._tag === 'Right' ? exports.none : exports.some(ma.left);
735
+ }
736
+ exports.getLeft = getLeft;
737
+ /**
738
+ * Returns the `Right` value of an `Either` if possible.
739
+ *
740
+ * @example
741
+ * import { getRight, none, some } from 'fp-ts/Option'
742
+ * import { right, left } from 'fp-ts/Either'
743
+ *
744
+ * assert.deepStrictEqual(getRight(right(1)), some(1))
745
+ * assert.deepStrictEqual(getRight(left('a')), none)
746
+ *
747
+ * @category constructors
748
+ * @since 2.0.0
749
+ */
750
+ function getRight(ma) {
751
+ return ma._tag === 'Left' ? exports.none : exports.some(ma.right);
752
+ }
753
+ exports.getRight = getRight;
754
+ /**
755
+ * Transforms an `Either` to an `Option` discarding the error.
756
+ *
757
+ * Alias of [getRight](#getRight)
758
+ *
759
+ * Derivable from `MonadThrow`.
760
+ *
761
+ * @category constructors
762
+ * @since 2.0.0
763
+ */
764
+ exports.fromEither = getRight;
765
+ // -------------------------------------------------------------------------------------
766
+ // destructors
767
+ // -------------------------------------------------------------------------------------
768
+ /**
769
+ * Takes a (lazy) default value, a function, and an `Option` value, if the `Option` value is `None` the default value is
770
+ * returned, otherwise the function is applied to the value inside the `Some` and the result is returned.
771
+ *
772
+ * @example
773
+ * import { some, none, fold } from 'fp-ts/Option'
774
+ * import { pipe } from 'fp-ts/function'
775
+ *
776
+ * assert.strictEqual(
777
+ * pipe(
778
+ * some(1),
779
+ * fold(() => 'a none', a => `a some containing ${a}`)
780
+ * ),
781
+ * 'a some containing 1'
782
+ * )
783
+ *
784
+ * assert.strictEqual(
785
+ * pipe(
786
+ * none,
787
+ * fold(() => 'a none', a => `a some containing ${a}`)
788
+ * ),
789
+ * 'a none'
790
+ * )
791
+ *
792
+ * @category destructors
793
+ * @since 2.0.0
794
+ */
795
+ function fold(onNone, onSome) {
796
+ return function (ma) { return (exports.isNone(ma) ? onNone() : onSome(ma.value)); };
797
+ }
798
+ exports.fold = fold;
799
+ /**
800
+ * Extracts the value out of the structure, if it exists. Otherwise returns `null`.
801
+ *
802
+ * @example
803
+ * import { some, none, toNullable } from 'fp-ts/Option'
804
+ * import { pipe } from 'fp-ts/function'
805
+ *
806
+ * assert.strictEqual(
807
+ * pipe(
808
+ * some(1),
809
+ * toNullable
810
+ * ),
811
+ * 1
812
+ * )
813
+ * assert.strictEqual(
814
+ * pipe(
815
+ * none,
816
+ * toNullable
817
+ * ),
818
+ * null
819
+ * )
820
+ *
821
+ * @category destructors
822
+ * @since 2.0.0
823
+ */
824
+ function toNullable(ma) {
825
+ return exports.isNone(ma) ? null : ma.value;
826
+ }
827
+ exports.toNullable = toNullable;
828
+ /**
829
+ * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`.
830
+ *
831
+ * @example
832
+ * import { some, none, toUndefined } from 'fp-ts/Option'
833
+ * import { pipe } from 'fp-ts/function'
834
+ *
835
+ * assert.strictEqual(
836
+ * pipe(
837
+ * some(1),
838
+ * toUndefined
839
+ * ),
840
+ * 1
841
+ * )
842
+ * assert.strictEqual(
843
+ * pipe(
844
+ * none,
845
+ * toUndefined
846
+ * ),
847
+ * undefined
848
+ * )
849
+ *
850
+ * @category destructors
851
+ * @since 2.0.0
852
+ */
853
+ function toUndefined(ma) {
854
+ return exports.isNone(ma) ? undefined : ma.value;
855
+ }
856
+ exports.toUndefined = toUndefined;
857
+ /**
858
+ * Less strict version of [`getOrElse`](#getOrElse).
859
+ *
860
+ * @category destructors
861
+ * @since 2.6.0
862
+ */
863
+ var getOrElseW = function (onNone) { return function (ma) { return (exports.isNone(ma) ? onNone() : ma.value); }; };
864
+ exports.getOrElseW = getOrElseW;
865
+ /**
866
+ * Extracts the value out of the structure, if it exists. Otherwise returns the given default value
867
+ *
868
+ * @example
869
+ * import { some, none, getOrElse } from 'fp-ts/Option'
870
+ * import { pipe } from 'fp-ts/function'
871
+ *
872
+ * assert.strictEqual(
873
+ * pipe(
874
+ * some(1),
875
+ * getOrElse(() => 0)
876
+ * ),
877
+ * 1
878
+ * )
879
+ * assert.strictEqual(
880
+ * pipe(
881
+ * none,
882
+ * getOrElse(() => 0)
883
+ * ),
884
+ * 0
885
+ * )
886
+ *
887
+ * @category destructors
888
+ * @since 2.0.0
889
+ */
890
+ exports.getOrElse = exports.getOrElseW;
891
+ // -------------------------------------------------------------------------------------
892
+ // combinators
893
+ // -------------------------------------------------------------------------------------
894
+ /**
895
+ * Returns a *smart constructor* from a function that returns a nullable value.
896
+ *
897
+ * @example
898
+ * import { fromNullableK, none, some } from 'fp-ts/Option'
899
+ *
900
+ * const f = (s: string): number | undefined => {
901
+ * const n = parseFloat(s)
902
+ * return isNaN(n) ? undefined : n
903
+ * }
904
+ *
905
+ * const g = fromNullableK(f)
906
+ *
907
+ * assert.deepStrictEqual(g('1'), some(1))
908
+ * assert.deepStrictEqual(g('a'), none)
909
+ *
910
+ * @category combinators
911
+ * @since 2.9.0
912
+ */
913
+ function fromNullableK(f) {
914
+ return function () {
915
+ var a = [];
916
+ for (var _i = 0; _i < arguments.length; _i++) {
917
+ a[_i] = arguments[_i];
918
+ }
919
+ return fromNullable(f.apply(void 0, a));
920
+ };
921
+ }
922
+ exports.fromNullableK = fromNullableK;
923
+ /**
924
+ * @category combinators
925
+ * @since 2.0.0
926
+ * @deprecated
927
+ */
928
+ exports.mapNullable = chainNullableK;
929
+ /**
930
+ * This is `chain` + `fromNullable`, useful when working with optional values.
931
+ *
932
+ * @example
933
+ * import { some, none, fromNullable, chainNullableK } from 'fp-ts/Option'
934
+ * import { pipe } from 'fp-ts/function'
935
+ *
936
+ * interface Employee {
937
+ * company?: {
938
+ * address?: {
939
+ * street?: {
940
+ * name?: string
941
+ * }
942
+ * }
943
+ * }
944
+ * }
945
+ *
946
+ * const employee1: Employee = { company: { address: { street: { name: 'high street' } } } }
947
+ *
948
+ * assert.deepStrictEqual(
949
+ * pipe(
950
+ * fromNullable(employee1.company),
951
+ * chainNullableK(company => company.address),
952
+ * chainNullableK(address => address.street),
953
+ * chainNullableK(street => street.name)
954
+ * ),
955
+ * some('high street')
956
+ * )
957
+ *
958
+ * const employee2: Employee = { company: { address: { street: {} } } }
959
+ *
960
+ * assert.deepStrictEqual(
961
+ * pipe(
962
+ * fromNullable(employee2.company),
963
+ * chainNullableK(company => company.address),
964
+ * chainNullableK(address => address.street),
965
+ * chainNullableK(street => street.name)
966
+ * ),
967
+ * none
968
+ * )
969
+ *
970
+ * @category combinators
971
+ * @since 2.9.0
972
+ */
973
+ function chainNullableK(f) {
974
+ return function (ma) { return (exports.isNone(ma) ? exports.none : fromNullable(f(ma.value))); };
975
+ }
976
+ exports.chainNullableK = chainNullableK;
977
+ // -------------------------------------------------------------------------------------
978
+ // non-pipeables
979
+ // -------------------------------------------------------------------------------------
980
+ var map_ = function (fa, f) { return _function.pipe(fa, exports.map(f)); };
981
+ var ap_ = function (fab, fa) { return _function.pipe(fab, exports.ap(fa)); };
982
+ var chain_ = function (ma, f) { return _function.pipe(ma, exports.chain(f)); };
983
+ var reduce_ = function (fa, b, f) { return _function.pipe(fa, exports.reduce(b, f)); };
984
+ var foldMap_ = function (M) {
985
+ var foldMapM = exports.foldMap(M);
986
+ return function (fa, f) { return _function.pipe(fa, foldMapM(f)); };
987
+ };
988
+ var reduceRight_ = function (fa, b, f) { return _function.pipe(fa, exports.reduceRight(b, f)); };
989
+ var traverse_ = function (F) {
990
+ var traverseF = exports.traverse(F);
991
+ return function (ta, f) { return _function.pipe(ta, traverseF(f)); };
992
+ };
993
+ /* istanbul ignore next */
994
+ var alt_ = function (fa, that) { return _function.pipe(fa, exports.alt(that)); };
995
+ var filter_ = function (fa, predicate) {
996
+ return _function.pipe(fa, exports.filter(predicate));
997
+ };
998
+ /* istanbul ignore next */
999
+ var filterMap_ = function (fa, f) { return _function.pipe(fa, exports.filterMap(f)); };
1000
+ /* istanbul ignore next */
1001
+ var extend_ = function (wa, f) { return _function.pipe(wa, exports.extend(f)); };
1002
+ /* istanbul ignore next */
1003
+ var partition_ = function (fa, predicate) { return _function.pipe(fa, exports.partition(predicate)); };
1004
+ /* istanbul ignore next */
1005
+ var partitionMap_ = function (fa, f) { return _function.pipe(fa, exports.partitionMap(f)); };
1006
+ /* istanbul ignore next */
1007
+ var wither_ = function (F) {
1008
+ var witherF = exports.wither(F);
1009
+ return function (fa, f) { return _function.pipe(fa, witherF(f)); };
1010
+ };
1011
+ /* istanbul ignore next */
1012
+ var wilt_ = function (F) {
1013
+ var wiltF = exports.wilt(F);
1014
+ return function (fa, f) { return _function.pipe(fa, wiltF(f)); };
1015
+ };
1016
+ // -------------------------------------------------------------------------------------
1017
+ // pipeables
1018
+ // -------------------------------------------------------------------------------------
1019
+ /**
1020
+ * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
1021
+ * use the type constructor `F` to represent some computational context.
1022
+ *
1023
+ * @category Functor
1024
+ * @since 2.0.0
1025
+ */
1026
+ var map = function (f) { return function (fa) {
1027
+ return exports.isNone(fa) ? exports.none : exports.some(f(fa.value));
1028
+ }; };
1029
+ exports.map = map;
1030
+ /**
1031
+ * Apply a function to an argument under a type constructor.
1032
+ *
1033
+ * @category Apply
1034
+ * @since 2.0.0
1035
+ */
1036
+ var ap = function (fa) { return function (fab) {
1037
+ return exports.isNone(fab) ? exports.none : exports.isNone(fa) ? exports.none : exports.some(fab.value(fa.value));
1038
+ }; };
1039
+ exports.ap = ap;
1040
+ /**
1041
+ * Combine two effectful actions, keeping only the result of the first.
1042
+ *
1043
+ * Derivable from `Apply`.
1044
+ *
1045
+ * @category combinators
1046
+ * @since 2.0.0
1047
+ */
1048
+ var apFirst = function (fb) {
1049
+ return _function.flow(exports.map(function (a) { return function () { return a; }; }), exports.ap(fb));
1050
+ };
1051
+ exports.apFirst = apFirst;
1052
+ /**
1053
+ * Combine two effectful actions, keeping only the result of the second.
1054
+ *
1055
+ * Derivable from `Apply`.
1056
+ *
1057
+ * @category combinators
1058
+ * @since 2.0.0
1059
+ */
1060
+ var apSecond = function (fb) {
1061
+ return _function.flow(exports.map(function () { return function (b) { return b; }; }), exports.ap(fb));
1062
+ };
1063
+ exports.apSecond = apSecond;
1064
+ /**
1065
+ * Wrap a value into the type constructor.
1066
+ *
1067
+ * @category Applicative
1068
+ * @since 2.7.0
1069
+ */
1070
+ exports.of = exports.some;
1071
+ /**
1072
+ * Composes computations in sequence, using the return value of one computation to determine the next computation.
1073
+ *
1074
+ * @category Monad
1075
+ * @since 2.0.0
1076
+ */
1077
+ var chain = function (f) { return function (ma) {
1078
+ return exports.isNone(ma) ? exports.none : f(ma.value);
1079
+ }; };
1080
+ exports.chain = chain;
1081
+ /**
1082
+ * Composes computations in sequence, using the return value of one computation to determine the next computation and
1083
+ * keeping only the result of the first.
1084
+ *
1085
+ * Derivable from `Monad`.
1086
+ *
1087
+ * @category combinators
1088
+ * @since 2.0.0
1089
+ */
1090
+ var chainFirst = function (f) {
1091
+ return exports.chain(function (a) {
1092
+ return _function.pipe(f(a), exports.map(function () { return a; }));
1093
+ });
1094
+ };
1095
+ exports.chainFirst = chainFirst;
1096
+ /**
1097
+ * Derivable from `Monad`.
1098
+ *
1099
+ * @category combinators
1100
+ * @since 2.0.0
1101
+ */
1102
+ exports.flatten =
1103
+ /*#__PURE__*/
1104
+ exports.chain(_function.identity);
1105
+ /**
1106
+ * Less strict version of [`alt`](#alt).
1107
+ *
1108
+ * @category Alt
1109
+ * @since 2.9.0
1110
+ */
1111
+ var altW = function (that) { return function (fa) {
1112
+ return exports.isNone(fa) ? that() : fa;
1113
+ }; };
1114
+ exports.altW = altW;
1115
+ /**
1116
+ * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to
1117
+ * types of kind `* -> *`.
1118
+ *
1119
+ * In case of `Option` returns the left-most non-`None` value.
1120
+ *
1121
+ * @example
1122
+ * import * as O from 'fp-ts/Option'
1123
+ * import { pipe } from 'fp-ts/function'
1124
+ *
1125
+ * assert.deepStrictEqual(
1126
+ * pipe(
1127
+ * O.some('a'),
1128
+ * O.alt(() => O.some('b'))
1129
+ * ),
1130
+ * O.some('a')
1131
+ * )
1132
+ * assert.deepStrictEqual(
1133
+ * pipe(
1134
+ * O.none,
1135
+ * O.alt(() => O.some('b'))
1136
+ * ),
1137
+ * O.some('b')
1138
+ * )
1139
+ *
1140
+ * @category Alt
1141
+ * @since 2.0.0
1142
+ */
1143
+ exports.alt = exports.altW;
1144
+ /**
1145
+ * @category Alternative
1146
+ * @since 2.7.0
1147
+ */
1148
+ var zero = function () { return exports.none; };
1149
+ exports.zero = zero;
1150
+ /**
1151
+ * @category MonadThrow
1152
+ * @since 2.7.0
1153
+ */
1154
+ var throwError = function () { return exports.none; };
1155
+ exports.throwError = throwError;
1156
+ /**
1157
+ * @category Extend
1158
+ * @since 2.0.0
1159
+ */
1160
+ var extend = function (f) { return function (wa) {
1161
+ return exports.isNone(wa) ? exports.none : exports.some(f(wa));
1162
+ }; };
1163
+ exports.extend = extend;
1164
+ /**
1165
+ * Derivable from `Extend`.
1166
+ *
1167
+ * @category combinators
1168
+ * @since 2.0.0
1169
+ */
1170
+ exports.duplicate =
1171
+ /*#__PURE__*/
1172
+ exports.extend(_function.identity);
1173
+ /**
1174
+ * @category Foldable
1175
+ * @since 2.0.0
1176
+ */
1177
+ var reduce = function (b, f) { return function (fa) {
1178
+ return exports.isNone(fa) ? b : f(b, fa.value);
1179
+ }; };
1180
+ exports.reduce = reduce;
1181
+ /**
1182
+ * @category Foldable
1183
+ * @since 2.0.0
1184
+ */
1185
+ var foldMap = function (M) { return function (f) { return function (fa) {
1186
+ return exports.isNone(fa) ? M.empty : f(fa.value);
1187
+ }; }; };
1188
+ exports.foldMap = foldMap;
1189
+ /**
1190
+ * @category Foldable
1191
+ * @since 2.0.0
1192
+ */
1193
+ var reduceRight = function (b, f) { return function (fa) {
1194
+ return exports.isNone(fa) ? b : f(fa.value, b);
1195
+ }; };
1196
+ exports.reduceRight = reduceRight;
1197
+ /**
1198
+ * @category Compactable
1199
+ * @since 2.0.0
1200
+ */
1201
+ exports.compact = exports.flatten;
1202
+ var defaultSeparate = { left: exports.none, right: exports.none };
1203
+ /**
1204
+ * @category Compactable
1205
+ * @since 2.0.0
1206
+ */
1207
+ var separate = function (ma) {
1208
+ var o = _function.pipe(ma, exports.map(function (e) { return ({
1209
+ left: getLeft(e),
1210
+ right: getRight(e)
1211
+ }); }));
1212
+ return exports.isNone(o) ? defaultSeparate : o.value;
1213
+ };
1214
+ exports.separate = separate;
1215
+ /**
1216
+ * @category Filterable
1217
+ * @since 2.0.0
1218
+ */
1219
+ var filter = function (predicate) { return function (fa) { return (exports.isNone(fa) ? exports.none : predicate(fa.value) ? fa : exports.none); }; };
1220
+ exports.filter = filter;
1221
+ /**
1222
+ * @category Filterable
1223
+ * @since 2.0.0
1224
+ */
1225
+ var filterMap = function (f) { return function (fa) {
1226
+ return exports.isNone(fa) ? exports.none : f(fa.value);
1227
+ }; };
1228
+ exports.filterMap = filterMap;
1229
+ /**
1230
+ * @category Filterable
1231
+ * @since 2.0.0
1232
+ */
1233
+ var partition = function (predicate) { return function (fa) {
1234
+ return {
1235
+ left: filter_(fa, function (a) { return !predicate(a); }),
1236
+ right: filter_(fa, predicate)
1237
+ };
1238
+ }; };
1239
+ exports.partition = partition;
1240
+ /**
1241
+ * @category Filterable
1242
+ * @since 2.0.0
1243
+ */
1244
+ var partitionMap = function (f) { return _function.flow(exports.map(f), exports.separate); };
1245
+ exports.partitionMap = partitionMap;
1246
+ /**
1247
+ * @category Traversable
1248
+ * @since 2.6.3
1249
+ */
1250
+ var traverse = function (F) { return function (f) { return function (ta) { return (exports.isNone(ta) ? F.of(exports.none) : F.map(f(ta.value), exports.some)); }; }; };
1251
+ exports.traverse = traverse;
1252
+ /**
1253
+ * @category Traversable
1254
+ * @since 2.6.3
1255
+ */
1256
+ var sequence = function (F) { return function (ta) { return (exports.isNone(ta) ? F.of(exports.none) : F.map(ta.value, exports.some)); }; };
1257
+ exports.sequence = sequence;
1258
+ /**
1259
+ * @category Witherable
1260
+ * @since 2.6.5
1261
+ */
1262
+ var wither = function (F) { return function (f) { return function (fa) { return (exports.isNone(fa) ? F.of(exports.none) : f(fa.value)); }; }; };
1263
+ exports.wither = wither;
1264
+ /**
1265
+ * @category Witherable
1266
+ * @since 2.6.5
1267
+ */
1268
+ var wilt = function (F) { return function (f) { return function (fa) {
1269
+ return exports.isNone(fa)
1270
+ ? F.of({
1271
+ left: exports.none,
1272
+ right: exports.none
1273
+ })
1274
+ : F.map(f(fa.value), function (e) { return ({
1275
+ left: getLeft(e),
1276
+ right: getRight(e)
1277
+ }); });
1278
+ }; }; };
1279
+ exports.wilt = wilt;
1280
+ // -------------------------------------------------------------------------------------
1281
+ // instances
1282
+ // -------------------------------------------------------------------------------------
1283
+ /**
1284
+ * @category instances
1285
+ * @since 2.0.0
1286
+ */
1287
+ exports.URI = 'Option';
1288
+ /**
1289
+ * @category instances
1290
+ * @since 2.0.0
1291
+ */
1292
+ function getShow(S) {
1293
+ return {
1294
+ show: function (ma) { return (exports.isNone(ma) ? 'none' : "some(" + S.show(ma.value) + ")"); }
1295
+ };
1296
+ }
1297
+ exports.getShow = getShow;
1298
+ /**
1299
+ * @example
1300
+ * import { none, some, getEq } from 'fp-ts/Option'
1301
+ * import { eqNumber } from 'fp-ts/Eq'
1302
+ *
1303
+ * const E = getEq(eqNumber)
1304
+ * assert.strictEqual(E.equals(none, none), true)
1305
+ * assert.strictEqual(E.equals(none, some(1)), false)
1306
+ * assert.strictEqual(E.equals(some(1), none), false)
1307
+ * assert.strictEqual(E.equals(some(1), some(2)), false)
1308
+ * assert.strictEqual(E.equals(some(1), some(1)), true)
1309
+ *
1310
+ * @category instances
1311
+ * @since 2.0.0
1312
+ */
1313
+ function getEq(E) {
1314
+ return {
1315
+ equals: function (x, y) { return x === y || (exports.isNone(x) ? exports.isNone(y) : exports.isNone(y) ? false : E.equals(x.value, y.value)); }
1316
+ };
1317
+ }
1318
+ exports.getEq = getEq;
1319
+ /**
1320
+ * The `Ord` instance allows `Option` values to be compared with
1321
+ * `compare`, whenever there is an `Ord` instance for
1322
+ * the type the `Option` contains.
1323
+ *
1324
+ * `None` is considered to be less than any `Some` value.
1325
+ *
1326
+ *
1327
+ * @example
1328
+ * import { none, some, getOrd } from 'fp-ts/Option'
1329
+ * import { ordNumber } from 'fp-ts/Ord'
1330
+ *
1331
+ * const O = getOrd(ordNumber)
1332
+ * assert.strictEqual(O.compare(none, none), 0)
1333
+ * assert.strictEqual(O.compare(none, some(1)), -1)
1334
+ * assert.strictEqual(O.compare(some(1), none), 1)
1335
+ * assert.strictEqual(O.compare(some(1), some(2)), -1)
1336
+ * assert.strictEqual(O.compare(some(1), some(1)), 0)
1337
+ *
1338
+ * @category instances
1339
+ * @since 2.0.0
1340
+ */
1341
+ function getOrd(O) {
1342
+ return {
1343
+ equals: getEq(O).equals,
1344
+ compare: function (x, y) { return (x === y ? 0 : exports.isSome(x) ? (exports.isSome(y) ? O.compare(x.value, y.value) : 1) : -1); }
1345
+ };
1346
+ }
1347
+ exports.getOrd = getOrd;
1348
+ /**
1349
+ * `Apply` semigroup
1350
+ *
1351
+ * | x | y | concat(x, y) |
1352
+ * | ------- | ------- | ------------------ |
1353
+ * | none | none | none |
1354
+ * | some(a) | none | none |
1355
+ * | none | some(a) | none |
1356
+ * | some(a) | some(b) | some(concat(a, b)) |
1357
+ *
1358
+ * @example
1359
+ * import { getApplySemigroup, some, none } from 'fp-ts/Option'
1360
+ * import { semigroupSum } from 'fp-ts/Semigroup'
1361
+ *
1362
+ * const S = getApplySemigroup(semigroupSum)
1363
+ * assert.deepStrictEqual(S.concat(none, none), none)
1364
+ * assert.deepStrictEqual(S.concat(some(1), none), none)
1365
+ * assert.deepStrictEqual(S.concat(none, some(1)), none)
1366
+ * assert.deepStrictEqual(S.concat(some(1), some(2)), some(3))
1367
+ *
1368
+ * @category instances
1369
+ * @since 2.0.0
1370
+ */
1371
+ function getApplySemigroup(S) {
1372
+ return {
1373
+ concat: function (x, y) { return (exports.isSome(x) && exports.isSome(y) ? exports.some(S.concat(x.value, y.value)) : exports.none); }
1374
+ };
1375
+ }
1376
+ exports.getApplySemigroup = getApplySemigroup;
1377
+ /**
1378
+ * @category instances
1379
+ * @since 2.0.0
1380
+ */
1381
+ function getApplyMonoid(M) {
1382
+ return {
1383
+ concat: getApplySemigroup(M).concat,
1384
+ empty: exports.some(M.empty)
1385
+ };
1386
+ }
1387
+ exports.getApplyMonoid = getApplyMonoid;
1388
+ /**
1389
+ * Monoid returning the left-most non-`None` value
1390
+ *
1391
+ * | x | y | concat(x, y) |
1392
+ * | ------- | ------- | ------------ |
1393
+ * | none | none | none |
1394
+ * | some(a) | none | some(a) |
1395
+ * | none | some(a) | some(a) |
1396
+ * | some(a) | some(b) | some(a) |
1397
+ *
1398
+ * @example
1399
+ * import { getFirstMonoid, some, none } from 'fp-ts/Option'
1400
+ *
1401
+ * const M = getFirstMonoid<number>()
1402
+ * assert.deepStrictEqual(M.concat(none, none), none)
1403
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1404
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1405
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(1))
1406
+ *
1407
+ * @category instances
1408
+ * @since 2.0.0
1409
+ */
1410
+ function getFirstMonoid() {
1411
+ return {
1412
+ concat: function (x, y) { return (exports.isNone(x) ? y : x); },
1413
+ empty: exports.none
1414
+ };
1415
+ }
1416
+ exports.getFirstMonoid = getFirstMonoid;
1417
+ /**
1418
+ * Monoid returning the right-most non-`None` value
1419
+ *
1420
+ * | x | y | concat(x, y) |
1421
+ * | ------- | ------- | ------------ |
1422
+ * | none | none | none |
1423
+ * | some(a) | none | some(a) |
1424
+ * | none | some(a) | some(a) |
1425
+ * | some(a) | some(b) | some(b) |
1426
+ *
1427
+ * @example
1428
+ * import { getLastMonoid, some, none } from 'fp-ts/Option'
1429
+ *
1430
+ * const M = getLastMonoid<number>()
1431
+ * assert.deepStrictEqual(M.concat(none, none), none)
1432
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1433
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1434
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(2))
1435
+ *
1436
+ * @category instances
1437
+ * @since 2.0.0
1438
+ */
1439
+ function getLastMonoid() {
1440
+ return {
1441
+ concat: function (x, y) { return (exports.isNone(y) ? x : y); },
1442
+ empty: exports.none
1443
+ };
1444
+ }
1445
+ exports.getLastMonoid = getLastMonoid;
1446
+ /**
1447
+ * Monoid returning the left-most non-`None` value. If both operands are `Some`s then the inner values are
1448
+ * concatenated using the provided `Semigroup`
1449
+ *
1450
+ * | x | y | concat(x, y) |
1451
+ * | ------- | ------- | ------------------ |
1452
+ * | none | none | none |
1453
+ * | some(a) | none | some(a) |
1454
+ * | none | some(a) | some(a) |
1455
+ * | some(a) | some(b) | some(concat(a, b)) |
1456
+ *
1457
+ * @example
1458
+ * import { getMonoid, some, none } from 'fp-ts/Option'
1459
+ * import { semigroupSum } from 'fp-ts/Semigroup'
1460
+ *
1461
+ * const M = getMonoid(semigroupSum)
1462
+ * assert.deepStrictEqual(M.concat(none, none), none)
1463
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1464
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1465
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(3))
1466
+ *
1467
+ * @category instances
1468
+ * @since 2.0.0
1469
+ */
1470
+ function getMonoid(S) {
1471
+ return {
1472
+ concat: function (x, y) { return (exports.isNone(x) ? y : exports.isNone(y) ? x : exports.some(S.concat(x.value, y.value))); },
1473
+ empty: exports.none
1474
+ };
1475
+ }
1476
+ exports.getMonoid = getMonoid;
1477
+ /**
1478
+ * @category instances
1479
+ * @since 2.7.0
1480
+ */
1481
+ exports.Functor = {
1482
+ URI: exports.URI,
1483
+ map: map_
1484
+ };
1485
+ /**
1486
+ * @category instances
1487
+ * @since 2.7.0
1488
+ */
1489
+ exports.Applicative = {
1490
+ URI: exports.URI,
1491
+ map: map_,
1492
+ ap: ap_,
1493
+ of: exports.of
1494
+ };
1495
+ /**
1496
+ * @category instances
1497
+ * @since 2.7.0
1498
+ */
1499
+ exports.Monad = {
1500
+ URI: exports.URI,
1501
+ map: map_,
1502
+ ap: ap_,
1503
+ of: exports.of,
1504
+ chain: chain_
1505
+ };
1506
+ /**
1507
+ * @category instances
1508
+ * @since 2.7.0
1509
+ */
1510
+ exports.Foldable = {
1511
+ URI: exports.URI,
1512
+ reduce: reduce_,
1513
+ foldMap: foldMap_,
1514
+ reduceRight: reduceRight_
1515
+ };
1516
+ /**
1517
+ * @category instances
1518
+ * @since 2.7.0
1519
+ */
1520
+ exports.Alt = {
1521
+ URI: exports.URI,
1522
+ map: map_,
1523
+ alt: alt_
1524
+ };
1525
+ /**
1526
+ * @category instances
1527
+ * @since 2.7.0
1528
+ */
1529
+ exports.Alternative = {
1530
+ URI: exports.URI,
1531
+ map: map_,
1532
+ ap: ap_,
1533
+ of: exports.of,
1534
+ alt: alt_,
1535
+ zero: exports.zero
1536
+ };
1537
+ /**
1538
+ * @category instances
1539
+ * @since 2.7.0
1540
+ */
1541
+ exports.Extend = {
1542
+ URI: exports.URI,
1543
+ map: map_,
1544
+ extend: extend_
1545
+ };
1546
+ /**
1547
+ * @category instances
1548
+ * @since 2.7.0
1549
+ */
1550
+ exports.Compactable = {
1551
+ URI: exports.URI,
1552
+ compact: exports.compact,
1553
+ separate: exports.separate
1554
+ };
1555
+ /**
1556
+ * @category instances
1557
+ * @since 2.7.0
1558
+ */
1559
+ exports.Filterable = {
1560
+ URI: exports.URI,
1561
+ map: map_,
1562
+ compact: exports.compact,
1563
+ separate: exports.separate,
1564
+ filter: filter_,
1565
+ filterMap: filterMap_,
1566
+ partition: partition_,
1567
+ partitionMap: partitionMap_
1568
+ };
1569
+ /**
1570
+ * @category instances
1571
+ * @since 2.7.0
1572
+ */
1573
+ exports.Traversable = {
1574
+ URI: exports.URI,
1575
+ map: map_,
1576
+ reduce: reduce_,
1577
+ foldMap: foldMap_,
1578
+ reduceRight: reduceRight_,
1579
+ traverse: traverse_,
1580
+ sequence: exports.sequence
1581
+ };
1582
+ /**
1583
+ * @category instances
1584
+ * @since 2.7.0
1585
+ */
1586
+ exports.Witherable = {
1587
+ URI: exports.URI,
1588
+ map: map_,
1589
+ reduce: reduce_,
1590
+ foldMap: foldMap_,
1591
+ reduceRight: reduceRight_,
1592
+ traverse: traverse_,
1593
+ sequence: exports.sequence,
1594
+ compact: exports.compact,
1595
+ separate: exports.separate,
1596
+ filter: filter_,
1597
+ filterMap: filterMap_,
1598
+ partition: partition_,
1599
+ partitionMap: partitionMap_,
1600
+ wither: wither_,
1601
+ wilt: wilt_
1602
+ };
1603
+ /**
1604
+ * @category instances
1605
+ * @since 2.7.0
1606
+ */
1607
+ exports.MonadThrow = {
1608
+ URI: exports.URI,
1609
+ map: map_,
1610
+ ap: ap_,
1611
+ of: exports.of,
1612
+ chain: chain_,
1613
+ throwError: exports.throwError
1614
+ };
1615
+ // TODO: remove in v3
1616
+ /**
1617
+ * @category instances
1618
+ * @since 2.0.0
1619
+ */
1620
+ exports.option = {
1621
+ URI: exports.URI,
1622
+ map: map_,
1623
+ of: exports.of,
1624
+ ap: ap_,
1625
+ chain: chain_,
1626
+ reduce: reduce_,
1627
+ foldMap: foldMap_,
1628
+ reduceRight: reduceRight_,
1629
+ traverse: traverse_,
1630
+ sequence: exports.sequence,
1631
+ zero: exports.zero,
1632
+ alt: alt_,
1633
+ extend: extend_,
1634
+ compact: exports.compact,
1635
+ separate: exports.separate,
1636
+ filter: filter_,
1637
+ filterMap: filterMap_,
1638
+ partition: partition_,
1639
+ partitionMap: partitionMap_,
1640
+ wither: wither_,
1641
+ wilt: wilt_,
1642
+ throwError: exports.throwError
1643
+ };
1644
+ // -------------------------------------------------------------------------------------
1645
+ // utils
1646
+ // -------------------------------------------------------------------------------------
1647
+ /**
1648
+ * Returns `true` if `ma` contains `a`
1649
+ *
1650
+ * @example
1651
+ * import { some, none, elem } from 'fp-ts/Option'
1652
+ * import { eqNumber } from 'fp-ts/Eq'
1653
+ *
1654
+ * assert.strictEqual(elem(eqNumber)(1, some(1)), true)
1655
+ * assert.strictEqual(elem(eqNumber)(2, some(1)), false)
1656
+ * assert.strictEqual(elem(eqNumber)(1, none), false)
1657
+ *
1658
+ * @since 2.0.0
1659
+ */
1660
+ function elem(E) {
1661
+ return function (a, ma) { return (exports.isNone(ma) ? false : E.equals(a, ma.value)); };
1662
+ }
1663
+ exports.elem = elem;
1664
+ /**
1665
+ * Returns `true` if the predicate is satisfied by the wrapped value
1666
+ *
1667
+ * @example
1668
+ * import { some, none, exists } from 'fp-ts/Option'
1669
+ * import { pipe } from 'fp-ts/function'
1670
+ *
1671
+ * assert.strictEqual(
1672
+ * pipe(
1673
+ * some(1),
1674
+ * exists(n => n > 0)
1675
+ * ),
1676
+ * true
1677
+ * )
1678
+ * assert.strictEqual(
1679
+ * pipe(
1680
+ * some(1),
1681
+ * exists(n => n > 1)
1682
+ * ),
1683
+ * false
1684
+ * )
1685
+ * assert.strictEqual(
1686
+ * pipe(
1687
+ * none,
1688
+ * exists(n => n > 0)
1689
+ * ),
1690
+ * false
1691
+ * )
1692
+ *
1693
+ * @since 2.0.0
1694
+ */
1695
+ function exists(predicate) {
1696
+ return function (ma) { return (exports.isNone(ma) ? false : predicate(ma.value)); };
1697
+ }
1698
+ exports.exists = exists;
1699
+ /**
1700
+ * Returns a `Refinement` (i.e. a custom type guard) from a `Option` returning function.
1701
+ * This function ensures that a custom type guard definition is type-safe.
1702
+ *
1703
+ * ```ts
1704
+ * import { some, none, getRefinement } from 'fp-ts/Option'
1705
+ *
1706
+ * type A = { type: 'A' }
1707
+ * type B = { type: 'B' }
1708
+ * type C = A | B
1709
+ *
1710
+ * const isA = (c: C): c is A => c.type === 'B' // <= typo but typescript doesn't complain
1711
+ * const isA = getRefinement<C, A>(c => (c.type === 'B' ? some(c) : none)) // static error: Type '"B"' is not assignable to type '"A"'
1712
+ * ```
1713
+ *
1714
+ * @since 2.0.0
1715
+ */
1716
+ function getRefinement(getOption) {
1717
+ return function (a) { return exports.isSome(getOption(a)); };
1718
+ }
1719
+ exports.getRefinement = getRefinement;
1720
+ // -------------------------------------------------------------------------------------
1721
+ // do notation
1722
+ // -------------------------------------------------------------------------------------
1723
+ /**
1724
+ * @since 2.9.0
1725
+ */
1726
+ exports.Do =
1727
+ /*#__PURE__*/
1728
+ exports.of({});
1729
+ /**
1730
+ * @since 2.8.0
1731
+ */
1732
+ var bindTo = function (name) { return exports.map(_function.bindTo_(name)); };
1733
+ exports.bindTo = bindTo;
1734
+ /**
1735
+ * @since 2.8.0
1736
+ */
1737
+ var bind = function (name, f) {
1738
+ return exports.chain(function (a) {
1739
+ return _function.pipe(f(a), exports.map(function (b) { return _function.bind_(a, name, b); }));
1740
+ });
1741
+ };
1742
+ exports.bind = bind;
1743
+ // -------------------------------------------------------------------------------------
1744
+ // pipeable sequence S
1745
+ // -------------------------------------------------------------------------------------
1746
+ /**
1747
+ * @since 2.8.0
1748
+ */
1749
+ var apS = function (name, fb) {
1750
+ return _function.flow(exports.map(function (a) { return function (b) { return _function.bind_(a, name, b); }; }), exports.ap(fb));
1751
+ };
1752
+ exports.apS = apS;
1753
+ // -------------------------------------------------------------------------------------
1754
+ // array utils
1755
+ // -------------------------------------------------------------------------------------
1756
+ /**
1757
+ *
1758
+ * @since 2.9.0
1759
+ */
1760
+ var traverseArrayWithIndex = function (f) { return function (arr) {
1761
+ // tslint:disable-next-line: readonly-array
1762
+ var result = [];
1763
+ for (var i = 0; i < arr.length; i++) {
1764
+ var b = f(i, arr[i]);
1765
+ if (exports.isNone(b)) {
1766
+ return exports.none;
1767
+ }
1768
+ result.push(b.value);
1769
+ }
1770
+ return exports.some(result);
1771
+ }; };
1772
+ exports.traverseArrayWithIndex = traverseArrayWithIndex;
1773
+ /**
1774
+ * Runs an action for every element in array and accumulates the results in option
1775
+ *
1776
+ * this function have the same behavior of `A.sequence(O.option)` but it's optimized and perform better
1777
+ *
1778
+ * @example
1779
+ *
1780
+ * import * as A from 'fp-ts/Array'
1781
+ * import { traverseArray, some, fromPredicate, none } from 'fp-ts/Option'
1782
+ * import { pipe } from 'fp-ts/function'
1783
+ *
1784
+ * const arr = A.range(0, 10)
1785
+ * assert.deepStrictEqual(pipe(arr, traverseArray(some)), some(arr))
1786
+ * assert.deepStrictEqual(pipe(arr, traverseArray(fromPredicate((x) => x > 5))), none)
1787
+ *
1788
+ * @since 2.9.0
1789
+ */
1790
+ var traverseArray = function (f) { return exports.traverseArrayWithIndex(function (_, a) { return f(a); }); };
1791
+ exports.traverseArray = traverseArray;
1792
+ /**
1793
+ * get an array of option and convert it to option of array
1794
+ *
1795
+ * this function have the same behavior of `A.sequence(O.option)` but it's optimized and perform better
1796
+ *
1797
+ * @example
1798
+ *
1799
+ * import * as A from 'fp-ts/Array'
1800
+ * import { sequenceArray, some, none, fromPredicate } from 'fp-ts/Option'
1801
+ * import { pipe } from 'fp-ts/function'
1802
+ *
1803
+ * const arr = A.range(0, 10)
1804
+ * assert.deepStrictEqual(pipe(arr, A.map(some), sequenceArray), some(arr))
1805
+ * assert.deepStrictEqual(pipe(arr, A.map(fromPredicate(x => x > 8)), sequenceArray), none)
1806
+ *
1807
+ * @since 2.9.0
1808
+ */
1809
+ exports.sequenceArray =
1810
+ /*#__PURE__*/
1811
+ exports.traverseArray(_function.identity);
1812
+ });
1813
+
1814
+ function e(e){this.message=e;}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw "Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e;}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";
1815
+
1816
+ var __assign = (undefined && undefined.__assign) || function () {
1817
+ __assign = Object.assign || function(t) {
1818
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1819
+ s = arguments[i];
1820
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1821
+ t[p] = s[p];
1822
+ }
1823
+ return t;
1824
+ };
1825
+ return __assign.apply(this, arguments);
1826
+ };
1827
+ var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {
1828
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1829
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
1830
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1831
+ r[k] = a[j];
1832
+ return r;
1833
+ };
1834
+ var mix = function (one, two, mergeArrays) {
1835
+ if (mergeArrays === void 0) { mergeArrays = false; }
1836
+ if (!one || !two || typeof one !== "object" || typeof two !== "object")
1837
+ return one;
1838
+ var clone = __assign({}, one);
1839
+ for (var prop in two) {
1840
+ if (two.hasOwnProperty(prop)) {
1841
+ if (two[prop] instanceof Array && one[prop] instanceof Array) {
1842
+ clone[prop] = mergeArrays ? __spreadArrays(one[prop], two[prop]) : two[prop];
1843
+ }
1844
+ else if (typeof two[prop] === "object" && typeof one[prop] === "object") {
1845
+ clone[prop] = mix(one[prop], two[prop], mergeArrays);
1846
+ }
1847
+ else {
1848
+ clone[prop] = two[prop];
1849
+ }
1850
+ }
1851
+ }
1852
+ return clone;
1853
+ };
1854
+
1855
+ var __spreadArrays$1 = (undefined && undefined.__spreadArrays) || function () {
1856
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1857
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
1858
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1859
+ r[k] = a[j];
1860
+ return r;
1861
+ };
1862
+ var config = {
1863
+ // Default options
1864
+ defaults: {},
1865
+ // Error type
1866
+ errorType: null,
1867
+ // Polyfills
1868
+ polyfills: {
1869
+ fetch: null,
1870
+ FormData: null,
1871
+ URLSearchParams: null,
1872
+ performance: null,
1873
+ PerformanceObserver: null,
1874
+ AbortController: null
1875
+ },
1876
+ polyfill: function (p, _a) {
1877
+ var _b = _a === void 0 ? {} : _a, _c = _b.doThrow, doThrow = _c === void 0 ? true : _c, _d = _b.instance, instance = _d === void 0 ? false : _d;
1878
+ var args = [];
1879
+ for (var _i = 2; _i < arguments.length; _i++) {
1880
+ args[_i - 2] = arguments[_i];
1881
+ }
1882
+ var res = this.polyfills[p] ||
1883
+ (typeof self !== "undefined" ? self[p] : null) ||
1884
+ (typeof global !== "undefined" ? global[p] : null);
1885
+ if (doThrow && !res)
1886
+ throw new Error(p + " is not defined");
1887
+ return instance && res ? new (res.bind.apply(res, __spreadArrays$1([void 0], args)))() : res;
1888
+ }
1889
+ };
1890
+
1891
+ var onMatch = function (entries, name, callback, _performance) {
1892
+ if (!entries.getEntriesByName)
1893
+ return false;
1894
+ var matches = entries.getEntriesByName(name);
1895
+ if (matches && matches.length > 0) {
1896
+ callback(matches.reverse()[0]);
1897
+ if (_performance.clearMeasures)
1898
+ _performance.clearMeasures(name);
1899
+ perfs.callbacks.delete(name);
1900
+ if (perfs.callbacks.size < 1) {
1901
+ perfs.observer.disconnect();
1902
+ if (_performance.clearResourceTimings) {
1903
+ _performance.clearResourceTimings();
1904
+ }
1905
+ }
1906
+ return true;
1907
+ }
1908
+ return false;
1909
+ };
1910
+ var lazyObserver = function (_performance, _observer) {
1911
+ if (!perfs.observer && _performance && _observer) {
1912
+ perfs.observer = new _observer(function (entries) {
1913
+ perfs.callbacks.forEach(function (callback, name) {
1914
+ onMatch(entries, name, callback, _performance);
1915
+ });
1916
+ });
1917
+ if (_performance.clearResourceTimings)
1918
+ _performance.clearResourceTimings();
1919
+ }
1920
+ return perfs.observer;
1921
+ };
1922
+ var perfs = {
1923
+ callbacks: new Map(),
1924
+ observer: null,
1925
+ observe: function (name, callback) {
1926
+ if (!name || !callback)
1927
+ return;
1928
+ var _performance = config.polyfill("performance", { doThrow: false });
1929
+ var _observer = config.polyfill("PerformanceObserver", { doThrow: false });
1930
+ if (!lazyObserver(_performance, _observer))
1931
+ return;
1932
+ if (!onMatch(_performance, name, callback, _performance)) {
1933
+ if (perfs.callbacks.size < 1)
1934
+ perfs.observer.observe({ entryTypes: ["resource", "measure"] });
1935
+ perfs.callbacks.set(name, callback);
1936
+ }
1937
+ }
1938
+ };
1939
+
1940
+ var middlewareHelper = function (middlewares) { return function (fetchFunction) {
1941
+ return (middlewares.length === 0 ?
1942
+ fetchFunction :
1943
+ middlewares.length === 1 ?
1944
+ middlewares[0](fetchFunction) :
1945
+ middlewares.reduceRight(function (acc, curr, idx) {
1946
+ return (idx === middlewares.length - 2) ? curr(acc(fetchFunction)) : curr(acc);
1947
+ }));
1948
+ }; };
1949
+
1950
+ var WretchErrorWrapper = /** @class */ (function () {
1951
+ function WretchErrorWrapper(error) {
1952
+ this.error = error;
1953
+ }
1954
+ return WretchErrorWrapper;
1955
+ }());
1956
+ var resolver = function (wretcher) {
1957
+ var url = wretcher._url, _catchers = wretcher._catchers, resolvers = wretcher._resolvers, middlewares = wretcher._middlewares, opts = wretcher._options;
1958
+ var catchers = new Map(_catchers);
1959
+ var finalOptions = mix(config.defaults, opts);
1960
+ var fetchController = config.polyfill("AbortController", { doThrow: false, instance: true });
1961
+ if (!finalOptions["signal"] && fetchController) {
1962
+ finalOptions["signal"] = fetchController.signal;
1963
+ }
1964
+ // Request timeout
1965
+ var timeout = {
1966
+ ref: null,
1967
+ clear: function () {
1968
+ if (timeout.ref) {
1969
+ clearTimeout(timeout.ref);
1970
+ timeout.ref = null;
1971
+ }
1972
+ }
1973
+ };
1974
+ // The generated fetch request
1975
+ var fetchRequest = middlewareHelper(middlewares)(config.polyfill("fetch"))(url, finalOptions);
1976
+ // Throws on an http error
1977
+ var throwingPromise = fetchRequest
1978
+ .catch(function (error) {
1979
+ throw new WretchErrorWrapper(error);
1980
+ })
1981
+ .then(function (response) {
1982
+ timeout.clear();
1983
+ if (!response.ok) {
1984
+ return response[config.errorType || "text"]().then(function (msg) {
1985
+ // Enhances the error object
1986
+ var err = new Error(msg);
1987
+ err[config.errorType || "text"] = msg;
1988
+ err["status"] = response.status;
1989
+ err["response"] = response;
1990
+ throw err;
1991
+ });
1992
+ }
1993
+ return response;
1994
+ });
1995
+ // Wraps the Promise in order to dispatch the error to a matching catcher
1996
+ var catchersWrapper = function (promise) {
1997
+ return promise.catch(function (err) {
1998
+ timeout.clear();
1999
+ var error = err instanceof WretchErrorWrapper ? err.error : err;
2000
+ if (err instanceof WretchErrorWrapper && catchers.has("__fromFetch"))
2001
+ return catchers.get("__fromFetch")(error, wretcher);
2002
+ else if (catchers.has(error.status))
2003
+ return catchers.get(error.status)(error, wretcher);
2004
+ else if (catchers.has(error.name))
2005
+ return catchers.get(error.name)(error, wretcher);
2006
+ else
2007
+ throw error;
2008
+ });
2009
+ };
2010
+ var bodyParser = function (funName) { return function (cb) { return funName ?
2011
+ // If a callback is provided, then callback with the body result otherwise return the parsed body itself.
2012
+ catchersWrapper(throwingPromise.then(function (_) { return _ && _[funName](); }).then(function (_) { return cb ? cb(_) : _; })) :
2013
+ // No body parsing method - return the response
2014
+ catchersWrapper(throwingPromise.then(function (_) { return cb ? cb(_) : _; })); }; };
2015
+ var responseChain = {
2016
+ /**
2017
+ * Retrieves the raw result as a promise.
2018
+ */
2019
+ res: bodyParser(null),
2020
+ /**
2021
+ * Retrieves the result as a parsed JSON object.
2022
+ */
2023
+ json: bodyParser("json"),
2024
+ /**
2025
+ * Retrieves the result as a Blob object.
2026
+ */
2027
+ blob: bodyParser("blob"),
2028
+ /**
2029
+ * Retrieves the result as a FormData object.
2030
+ */
2031
+ formData: bodyParser("formData"),
2032
+ /**
2033
+ * Retrieves the result as an ArrayBuffer object.
2034
+ */
2035
+ arrayBuffer: bodyParser("arrayBuffer"),
2036
+ /**
2037
+ * Retrieves the result as a string.
2038
+ */
2039
+ text: bodyParser("text"),
2040
+ /**
2041
+ * Performs a callback on the API performance timings of the request.
2042
+ *
2043
+ * Warning: Still experimental on browsers and node.js
2044
+ */
2045
+ perfs: function (cb) {
2046
+ fetchRequest.then(function (res) { return perfs.observe(res.url, cb); });
2047
+ return responseChain;
2048
+ },
2049
+ /**
2050
+ * Aborts the request after a fixed time.
2051
+ *
2052
+ * @param time Time in milliseconds
2053
+ * @param controller A custom controller
2054
+ */
2055
+ setTimeout: function (time, controller) {
2056
+ if (controller === void 0) { controller = fetchController; }
2057
+ timeout.clear();
2058
+ timeout.ref = setTimeout(function () { return controller.abort(); }, time);
2059
+ return responseChain;
2060
+ },
2061
+ /**
2062
+ * Returns the automatically generated AbortController alongside the current wretch response as a pair.
2063
+ */
2064
+ controller: function () { return [fetchController, responseChain]; },
2065
+ /**
2066
+ * Catches an http response with a specific error code or name and performs a callback.
2067
+ */
2068
+ error: function (errorId, cb) {
2069
+ catchers.set(errorId, cb);
2070
+ return responseChain;
2071
+ },
2072
+ /**
2073
+ * Catches a bad request (http code 400) and performs a callback.
2074
+ */
2075
+ badRequest: function (cb) { return responseChain.error(400, cb); },
2076
+ /**
2077
+ * Catches an unauthorized request (http code 401) and performs a callback.
2078
+ */
2079
+ unauthorized: function (cb) { return responseChain.error(401, cb); },
2080
+ /**
2081
+ * Catches a forbidden request (http code 403) and performs a callback.
2082
+ */
2083
+ forbidden: function (cb) { return responseChain.error(403, cb); },
2084
+ /**
2085
+ * Catches a "not found" request (http code 404) and performs a callback.
2086
+ */
2087
+ notFound: function (cb) { return responseChain.error(404, cb); },
2088
+ /**
2089
+ * Catches a timeout (http code 408) and performs a callback.
2090
+ */
2091
+ timeout: function (cb) { return responseChain.error(408, cb); },
2092
+ /**
2093
+ * Catches an internal server error (http code 500) and performs a callback.
2094
+ */
2095
+ internalError: function (cb) { return responseChain.error(500, cb); },
2096
+ /**
2097
+ * Catches errors thrown when calling the fetch function and performs a callback.
2098
+ */
2099
+ fetchError: function (cb) { return responseChain.error("__fromFetch", cb); },
2100
+ /**
2101
+ * Catches an AbortError and performs a callback.
2102
+ */
2103
+ onAbort: function (cb) { return responseChain.error("AbortError", cb); }
2104
+ };
2105
+ return resolvers.reduce(function (chain, r) { return r(chain, wretcher); }, responseChain);
2106
+ };
2107
+
2108
+ var __assign$1 = (undefined && undefined.__assign) || function () {
2109
+ __assign$1 = Object.assign || function(t) {
2110
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2111
+ s = arguments[i];
2112
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2113
+ t[p] = s[p];
2114
+ }
2115
+ return t;
2116
+ };
2117
+ return __assign$1.apply(this, arguments);
2118
+ };
2119
+ var __spreadArrays$2 = (undefined && undefined.__spreadArrays) || function () {
2120
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
2121
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
2122
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
2123
+ r[k] = a[j];
2124
+ return r;
2125
+ };
2126
+ var JSON_MIME = "application/json";
2127
+ var CONTENT_TYPE_HEADER = "Content-Type";
2128
+ /**
2129
+ * The Wretcher class used to perform easy fetch requests.
2130
+ *
2131
+ * Immutability : almost every method of this class return a fresh Wretcher object.
2132
+ */
2133
+ var Wretcher = /** @class */ (function () {
2134
+ function Wretcher(_url, _options, _catchers, _resolvers, _middlewares, _deferredChain) {
2135
+ if (_catchers === void 0) { _catchers = new Map(); }
2136
+ if (_resolvers === void 0) { _resolvers = []; }
2137
+ if (_middlewares === void 0) { _middlewares = []; }
2138
+ if (_deferredChain === void 0) { _deferredChain = []; }
2139
+ this._url = _url;
2140
+ this._options = _options;
2141
+ this._catchers = _catchers;
2142
+ this._resolvers = _resolvers;
2143
+ this._middlewares = _middlewares;
2144
+ this._deferredChain = _deferredChain;
2145
+ }
2146
+ Wretcher.factory = function (url, options) {
2147
+ if (url === void 0) { url = ""; }
2148
+ if (options === void 0) { options = {}; }
2149
+ return new Wretcher(url, options);
2150
+ };
2151
+ Wretcher.prototype.selfFactory = function (_a) {
2152
+ var _b = _a === void 0 ? {} : _a, _c = _b.url, url = _c === void 0 ? this._url : _c, _d = _b.options, options = _d === void 0 ? this._options : _d, _e = _b.catchers, catchers = _e === void 0 ? this._catchers : _e, _f = _b.resolvers, resolvers = _f === void 0 ? this._resolvers : _f, _g = _b.middlewares, middlewares = _g === void 0 ? this._middlewares : _g, _h = _b.deferredChain, deferredChain = _h === void 0 ? this._deferredChain : _h;
2153
+ return new Wretcher(url, __assign$1({}, options), new Map(catchers), __spreadArrays$2(resolvers), __spreadArrays$2(middlewares), __spreadArrays$2(deferredChain));
2154
+ };
2155
+ /**
2156
+ * Sets the default fetch options used for every subsequent fetch call.
2157
+ * @param options New default options
2158
+ * @param mixin If true, mixes in instead of replacing the existing options
2159
+ */
2160
+ Wretcher.prototype.defaults = function (options, mixin) {
2161
+ if (mixin === void 0) { mixin = false; }
2162
+ config.defaults = mixin ? mix(config.defaults, options) : options;
2163
+ return this;
2164
+ };
2165
+ /**
2166
+ * Sets the method (text, json ...) used to parse the data contained in the response body in case of an HTTP error.
2167
+ *
2168
+ * Persists for every subsequent requests.
2169
+ *
2170
+ * Default is "text".
2171
+ */
2172
+ Wretcher.prototype.errorType = function (method) {
2173
+ config.errorType = method;
2174
+ return this;
2175
+ };
2176
+ /**
2177
+ * Sets the non-global polyfills which will be used for every subsequent calls.
2178
+ *
2179
+ * Needed for libraries like [fetch-ponyfill](https://github.com/qubyte/fetch-ponyfill).
2180
+ *
2181
+ * @param polyfills An object containing the polyfills.
2182
+ */
2183
+ Wretcher.prototype.polyfills = function (polyfills) {
2184
+ config.polyfills = __assign$1(__assign$1({}, config.polyfills), polyfills);
2185
+ return this;
2186
+ };
2187
+ /**
2188
+ * Returns a new Wretcher object with the argument url appended and the same options.
2189
+ * @param url String url
2190
+ * @param replace Boolean If true, replaces the current url instead of appending
2191
+ */
2192
+ Wretcher.prototype.url = function (url, replace) {
2193
+ if (replace === void 0) { replace = false; }
2194
+ if (replace)
2195
+ return this.selfFactory({ url: url });
2196
+ var split = this._url.split("?");
2197
+ return this.selfFactory({
2198
+ url: split.length > 1 ?
2199
+ split[0] + url + "?" + split[1] :
2200
+ this._url + url
2201
+ });
2202
+ };
2203
+ /**
2204
+ * Returns a new Wretcher object with the same url and new options.
2205
+ * @param options New options
2206
+ * @param mixin If true, mixes in instead of replacing the existing options
2207
+ */
2208
+ Wretcher.prototype.options = function (options, mixin) {
2209
+ if (mixin === void 0) { mixin = true; }
2210
+ return this.selfFactory({ options: mixin ? mix(this._options, options) : options });
2211
+ };
2212
+ /**
2213
+ * Converts a javascript object to query parameters,
2214
+ * then appends this query string to the current url.
2215
+ *
2216
+ * If given a string, use the string as the query verbatim.
2217
+ *
2218
+ * ```
2219
+ * let w = wretch("http://example.com") // url is http://example.com
2220
+ *
2221
+ * // Chain query calls
2222
+ * w = w.query({ a: 1, b : 2 }) // url is now http://example.com?a=1&b=2
2223
+ * w = w.query("foo-bar-baz-woz") // url is now http://example.com?a=1&b=2&foo-bar-baz-woz
2224
+ *
2225
+ * // Pass true as the second argument to replace existing query parameters
2226
+ * w = w.query("c=3&d=4", true) // url is now http://example.com?c=3&d=4
2227
+ * ```
2228
+ *
2229
+ * @param qp An object which will be converted, or a string which will be used verbatim.
2230
+ */
2231
+ Wretcher.prototype.query = function (qp, replace) {
2232
+ if (replace === void 0) { replace = false; }
2233
+ return this.selfFactory({ url: appendQueryParams(this._url, qp, replace) });
2234
+ };
2235
+ /**
2236
+ * Set request headers.
2237
+ * @param headerValues An object containing header keys and values
2238
+ */
2239
+ Wretcher.prototype.headers = function (headerValues) {
2240
+ return this.selfFactory({ options: mix(this._options, { headers: headerValues || {} }) });
2241
+ };
2242
+ /**
2243
+ * Shortcut to set the "Accept" header.
2244
+ * @param headerValue Header value
2245
+ */
2246
+ Wretcher.prototype.accept = function (headerValue) {
2247
+ return this.headers({ Accept: headerValue });
2248
+ };
2249
+ /**
2250
+ * Shortcut to set the "Content-Type" header.
2251
+ * @param headerValue Header value
2252
+ */
2253
+ Wretcher.prototype.content = function (headerValue) {
2254
+ var _a;
2255
+ return this.headers((_a = {}, _a[CONTENT_TYPE_HEADER] = headerValue, _a));
2256
+ };
2257
+ /**
2258
+ * Shortcut to set the "Authorization" header.
2259
+ * @param headerValue Header value
2260
+ */
2261
+ Wretcher.prototype.auth = function (headerValue) {
2262
+ return this.headers({ Authorization: headerValue });
2263
+ };
2264
+ /**
2265
+ * Adds a default catcher which will be called on every subsequent request error when the error code matches.
2266
+ * @param errorId Error code or name
2267
+ * @param catcher: The catcher method
2268
+ */
2269
+ Wretcher.prototype.catcher = function (errorId, catcher) {
2270
+ var newMap = new Map(this._catchers);
2271
+ newMap.set(errorId, catcher);
2272
+ return this.selfFactory({ catchers: newMap });
2273
+ };
2274
+ /**
2275
+ * Associates a custom signal with the request.
2276
+ * @param controller : An AbortController
2277
+ */
2278
+ Wretcher.prototype.signal = function (controller) {
2279
+ return this.selfFactory({ options: __assign$1(__assign$1({}, this._options), { signal: controller.signal }) });
2280
+ };
2281
+ /**
2282
+ * Program a resolver to perform response chain tasks automatically.
2283
+ * @param doResolve : Resolver callback
2284
+ */
2285
+ Wretcher.prototype.resolve = function (doResolve, clear) {
2286
+ if (clear === void 0) { clear = false; }
2287
+ return this.selfFactory({ resolvers: clear ? [doResolve] : __spreadArrays$2(this._resolvers, [doResolve]) });
2288
+ };
2289
+ /**
2290
+ * Defer wretcher methods that will be chained and called just before the request is performed.
2291
+ */
2292
+ Wretcher.prototype.defer = function (callback, clear) {
2293
+ if (clear === void 0) { clear = false; }
2294
+ return this.selfFactory({
2295
+ deferredChain: clear ? [callback] : __spreadArrays$2(this._deferredChain, [callback])
2296
+ });
2297
+ };
2298
+ /**
2299
+ * Add middlewares to intercept a request before being sent.
2300
+ */
2301
+ Wretcher.prototype.middlewares = function (middlewares, clear) {
2302
+ if (clear === void 0) { clear = false; }
2303
+ return this.selfFactory({
2304
+ middlewares: clear ? middlewares : __spreadArrays$2(this._middlewares, middlewares)
2305
+ });
2306
+ };
2307
+ Wretcher.prototype.method = function (method, options, body) {
2308
+ if (options === void 0) { options = {}; }
2309
+ if (body === void 0) { body = null; }
2310
+ var headers = this._options.headers;
2311
+ var baseWretcher = !body ? this :
2312
+ typeof body === "object" && (!headers ||
2313
+ Object.entries(headers).every(function (_a) {
2314
+ var k = _a[0], v = _a[1];
2315
+ return k.toLowerCase() !== CONTENT_TYPE_HEADER.toLowerCase() ||
2316
+ v.startsWith(JSON_MIME);
2317
+ })) ? this.json(body) :
2318
+ this.body(body);
2319
+ baseWretcher = baseWretcher.options(__assign$1(__assign$1({}, options), { method: method }));
2320
+ var deferredWretcher = baseWretcher._deferredChain.reduce(function (acc, curr) { return curr(acc, acc._url, acc._options); }, baseWretcher);
2321
+ return resolver(deferredWretcher);
2322
+ };
2323
+ /**
2324
+ * Performs a get request.
2325
+ */
2326
+ Wretcher.prototype.get = function (options) {
2327
+ return this.method("GET", options);
2328
+ };
2329
+ /**
2330
+ * Performs a delete request.
2331
+ */
2332
+ Wretcher.prototype.delete = function (options) {
2333
+ return this.method("DELETE", options);
2334
+ };
2335
+ /**
2336
+ * Performs a put request.
2337
+ */
2338
+ Wretcher.prototype.put = function (body, options) {
2339
+ return this.method("PUT", options, body);
2340
+ };
2341
+ /**
2342
+ * Performs a post request.
2343
+ */
2344
+ Wretcher.prototype.post = function (body, options) {
2345
+ return this.method("POST", options, body);
2346
+ };
2347
+ /**
2348
+ * Performs a patch request.
2349
+ */
2350
+ Wretcher.prototype.patch = function (body, options) {
2351
+ return this.method("PATCH", options, body);
2352
+ };
2353
+ /**
2354
+ * Performs a head request.
2355
+ */
2356
+ Wretcher.prototype.head = function (options) {
2357
+ return this.method("HEAD", options);
2358
+ };
2359
+ /**
2360
+ * Performs an options request
2361
+ */
2362
+ Wretcher.prototype.opts = function (options) {
2363
+ return this.method("OPTIONS", options);
2364
+ };
2365
+ /**
2366
+ * Replay a request.
2367
+ */
2368
+ Wretcher.prototype.replay = function (options) {
2369
+ return this.method(this._options.method, options);
2370
+ };
2371
+ /**
2372
+ * Sets the request body with any content.
2373
+ * @param contents The body contents
2374
+ */
2375
+ Wretcher.prototype.body = function (contents) {
2376
+ return this.selfFactory({ options: __assign$1(__assign$1({}, this._options), { body: contents }) });
2377
+ };
2378
+ /**
2379
+ * Sets the content type header, stringifies an object and sets the request body.
2380
+ * @param jsObject An object which will be serialized into a JSON
2381
+ */
2382
+ Wretcher.prototype.json = function (jsObject) {
2383
+ var _a;
2384
+ var preservedContentType = (_a = Object.entries(this._options.headers || {}).find(function (_a) {
2385
+ var k = _a[0], v = _a[1];
2386
+ return k.toLowerCase() === CONTENT_TYPE_HEADER.toLowerCase() && v.startsWith(JSON_MIME);
2387
+ })) === null || _a === void 0 ? void 0 : _a[1];
2388
+ return this.content(preservedContentType || JSON_MIME).body(JSON.stringify(jsObject));
2389
+ };
2390
+ /**
2391
+ * Converts the javascript object to a FormData and sets the request body.
2392
+ * @param formObject An object which will be converted to a FormData
2393
+ * @param recursive If `true`, will recurse through all nested objects
2394
+ * Can be set as an array of string to exclude specific keys.
2395
+ * See https://github.com/elbywan/wretch/issues/68 for more details.
2396
+ */
2397
+ Wretcher.prototype.formData = function (formObject, recursive) {
2398
+ if (recursive === void 0) { recursive = false; }
2399
+ return this.body(convertFormData(formObject, recursive));
2400
+ };
2401
+ /**
2402
+ * Converts the input to an url encoded string and sets the content-type header and body.
2403
+ * If the input argument is already a string, skips the conversion part.
2404
+ *
2405
+ * @param input An object to convert into an url encoded string or an already encoded string
2406
+ */
2407
+ Wretcher.prototype.formUrl = function (input) {
2408
+ return this
2409
+ .body(typeof input === "string" ? input : convertFormUrl(input))
2410
+ .content("application/x-www-form-urlencoded");
2411
+ };
2412
+ return Wretcher;
2413
+ }());
2414
+ // Internal helpers
2415
+ var appendQueryParams = function (url, qp, replace) {
2416
+ var queryString;
2417
+ if (typeof qp === "string") {
2418
+ queryString = qp;
2419
+ }
2420
+ else {
2421
+ var usp = config.polyfill("URLSearchParams", { instance: true });
2422
+ for (var key in qp) {
2423
+ if (qp[key] instanceof Array) {
2424
+ for (var _i = 0, _a = qp[key]; _i < _a.length; _i++) {
2425
+ var val = _a[_i];
2426
+ usp.append(key, val);
2427
+ }
2428
+ }
2429
+ else {
2430
+ usp.append(key, qp[key]);
2431
+ }
2432
+ }
2433
+ queryString = usp.toString();
2434
+ }
2435
+ var split = url.split("?");
2436
+ if (replace || split.length < 2)
2437
+ return split[0] + "?" + queryString;
2438
+ return url + "&" + queryString;
2439
+ };
2440
+ function convertFormData(formObject, recursive, formData, ancestors) {
2441
+ if (recursive === void 0) { recursive = false; }
2442
+ if (formData === void 0) { formData = config.polyfill("FormData", { instance: true }); }
2443
+ if (ancestors === void 0) { ancestors = []; }
2444
+ Object.entries(formObject).forEach(function (_a) {
2445
+ var key = _a[0], value = _a[1];
2446
+ var formKey = ancestors.reduce(function (acc, ancestor) { return (acc ? acc + "[" + ancestor + "]" : ancestor); }, null);
2447
+ formKey = formKey ? formKey + "[" + key + "]" : key;
2448
+ if (value instanceof Array) {
2449
+ for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2450
+ var item = value_1[_i];
2451
+ formData.append(formKey + "[]", item);
2452
+ }
2453
+ }
2454
+ else if (recursive &&
2455
+ typeof value === "object" &&
2456
+ (!(recursive instanceof Array) ||
2457
+ !recursive.includes(key))) {
2458
+ if (value !== null) {
2459
+ convertFormData(value, recursive, formData, __spreadArrays$2(ancestors, [key]));
2460
+ }
2461
+ }
2462
+ else {
2463
+ formData.append(formKey, value);
2464
+ }
2465
+ });
2466
+ return formData;
2467
+ }
2468
+ function encodeQueryValue(key, value) {
2469
+ return encodeURIComponent(key) +
2470
+ "=" +
2471
+ encodeURIComponent(typeof value === "object" ?
2472
+ JSON.stringify(value) :
2473
+ "" + value);
2474
+ }
2475
+ function convertFormUrl(formObject) {
2476
+ return Object.keys(formObject)
2477
+ .map(function (key) {
2478
+ var value = formObject[key];
2479
+ if (value instanceof Array) {
2480
+ return value.map(function (v) { return encodeQueryValue(key, v); }).join("&");
2481
+ }
2482
+ return encodeQueryValue(key, value);
2483
+ })
2484
+ .join("&");
2485
+ }
2486
+
2487
+ var factory = Wretcher.factory;
2488
+ factory["default"] = Wretcher.factory;
2489
+
2490
+ function buildBackendApiClient() {
2491
+ const jwt = superSelectionAppService.jwt;
2492
+ const profileId = superSelectionAppService.profileId;
2493
+ const accountId = superSelectionAppService.accountIdOrDefault;
2494
+ const partnerId = superSelectionAppService.partnerIdOrDefault;
2495
+ return factory(superSelectionAppService.apiBaseUrl).headers({
2496
+ Authorization: `Bearer ${jwt}`,
2497
+ 'X-PROFILE-ID': profileId,
2498
+ 'X-PARTNER-ID': partnerId,
2499
+ 'X-ACCOUNT-ID': accountId
2500
+ });
2501
+ }
2502
+
2503
+ const slate = {
2504
+ fundId: 'slate',
2505
+ usi: '32367272075001'
2506
+ };
2507
+
2508
+ function hydratePromotedFundChoiceDtoKind(dto) {
2509
+ if ('slate' in dto) {
2510
+ dto.kind = 'slate';
2511
+ }
2512
+ else if ('australianRetirementTrust' in dto) {
2513
+ dto.kind = 'australianRetirementTrust';
2514
+ }
2515
+ else if ('aware' in dto) {
2516
+ dto.kind = 'aware';
2517
+ }
2518
+ else if ('active' in dto) {
2519
+ dto.kind = 'active';
2520
+ }
2521
+ else if ('australianEthical' in dto) {
2522
+ dto.kind = 'australianEthical';
2523
+ }
2524
+ else if ('virgin' in dto) {
2525
+ dto.kind = 'virgin';
2526
+ }
2527
+ else if ('spirit' in dto) {
2528
+ dto.kind = 'spirit';
2529
+ }
2530
+ else if ('firstSuper' in dto) {
2531
+ dto.kind = 'firstSuper';
2532
+ }
2533
+ else if ('mercerMyChoice' in dto) {
2534
+ dto.kind = 'mercerMyChoice';
2535
+ }
2536
+ else if ('generic' in dto) {
2537
+ dto.kind = 'generic';
2538
+ }
2539
+ }
2540
+ function getPromotedFundUsi(dto) {
2541
+ switch (dto.kind) {
2542
+ case 'slate':
2543
+ return slate.usi;
2544
+ case 'australianRetirementTrust':
2545
+ return dto.australianRetirementTrust.usi;
2546
+ case 'aware':
2547
+ return dto.aware.usi;
2548
+ case 'active':
2549
+ return dto.active.usi;
2550
+ case 'australianEthical':
2551
+ return dto.australianEthical.usi;
2552
+ case 'virgin':
2553
+ return dto.virgin.usi;
2554
+ case 'spirit':
2555
+ return dto.spirit.usi;
2556
+ case 'firstSuper':
2557
+ return dto.firstSuper.usi;
2558
+ case 'mercerMyChoice':
2559
+ return dto.mercerMyChoice.usi;
2560
+ case 'generic':
2561
+ return dto.generic.usi;
2562
+ default:
2563
+ return '';
2564
+ }
2565
+ }
2566
+ function getPromotedFundId(dto) {
2567
+ switch (dto.kind) {
2568
+ case 'slate':
2569
+ return slate.fundId;
2570
+ case 'australianRetirementTrust':
2571
+ return 'australian-retirement-trust';
2572
+ case 'aware':
2573
+ return 'aware';
2574
+ case 'active':
2575
+ return 'active';
2576
+ case 'australianEthical':
2577
+ return 'australian-ethical';
2578
+ case 'virgin':
2579
+ return 'virgin';
2580
+ case 'spirit':
2581
+ return 'spirit';
2582
+ case 'firstSuper':
2583
+ return 'first-super';
2584
+ case 'mercerMyChoice':
2585
+ return 'mercermychoice';
2586
+ case 'generic':
2587
+ return dto.generic.fundId;
2588
+ default:
2589
+ return '';
2590
+ }
2591
+ }
2592
+ function getSuperChoiceUsi(dto) {
2593
+ switch (dto.kind) {
2594
+ case 'Promoted':
2595
+ return some(getPromotedFundUsi(dto.promoted));
2596
+ case 'MyOwnFund':
2597
+ return some(dto.myOwnFund.usi);
2598
+ case 'SMSF':
2599
+ return none;
2600
+ case 'Default':
2601
+ return some(dto.default.usi);
2602
+ case 'PromotedDefault':
2603
+ return some(dto.promotedDefault.usi);
2604
+ case 'DefinedBenefits':
2605
+ return some(dto.definedBenefits.usi);
2606
+ case 'PromotedDefaultWithJoin':
2607
+ return some(dto.promotedDefaultWithJoin.usi);
2608
+ default:
2609
+ return none;
2610
+ }
2611
+ }
2612
+ function getPromotedFundMemberNumber(dto) {
2613
+ switch (dto.kind) {
2614
+ case 'slate':
2615
+ return dto.slate.memberNumber;
2616
+ case 'australianRetirementTrust':
2617
+ return dto.australianRetirementTrust.memberNumber;
2618
+ case 'aware':
2619
+ return dto.aware.memberNumber;
2620
+ case 'active':
2621
+ return dto.active.memberNumber;
2622
+ case 'australianEthical':
2623
+ return dto.australianEthical.memberNumber;
2624
+ case 'virgin':
2625
+ return dto.virgin.memberNumber;
2626
+ case 'spirit':
2627
+ return dto.spirit.memberNumber;
2628
+ case 'firstSuper':
2629
+ return dto.firstSuper.memberNumber;
2630
+ case 'mercerMyChoice':
2631
+ return dto.mercerMyChoice.memberNumber;
2632
+ case 'generic':
2633
+ return dto.generic.memberNumber;
2634
+ default:
2635
+ return '';
2636
+ }
2637
+ }
2638
+ function getSuperChoiceMemberNumber(dto) {
2639
+ switch (dto.kind) {
2640
+ case 'Promoted':
2641
+ return some(getPromotedFundMemberNumber(dto.promoted));
2642
+ case 'MyOwnFund':
2643
+ return some(dto.myOwnFund.memberNumber);
2644
+ case 'DefinedBenefits':
2645
+ return some(dto.definedBenefits.memberNumber);
2646
+ case 'PromotedDefaultWithJoin':
2647
+ return some(dto.promotedDefaultWithJoin.memberNumber);
2648
+ case 'SMSF':
2649
+ case 'Default':
2650
+ case 'PromotedDefault':
2651
+ return none;
2652
+ default:
2653
+ return none;
2654
+ }
2655
+ }
2656
+ function hydrateSuperChoiceDetailsDtoKind(dto) {
2657
+ if ('promoted' in dto) {
2658
+ dto.kind = 'Promoted';
2659
+ }
2660
+ else if ('myOwnFund' in dto) {
2661
+ dto.kind = 'MyOwnFund';
2662
+ }
2663
+ else if ('smsf' in dto) {
2664
+ dto.kind = 'SMSF';
2665
+ }
2666
+ else if ('default' in dto) {
2667
+ dto.kind = 'Default';
2668
+ }
2669
+ else if ('promotedDefault' in dto) {
2670
+ dto.kind = 'PromotedDefault';
2671
+ }
2672
+ else if ('definedBenefits' in dto) {
2673
+ dto.kind = 'DefinedBenefits';
2674
+ }
2675
+ else if ('promotedDefaultWithJoin' in dto) {
2676
+ dto.kind = 'PromotedDefaultWithJoin';
2677
+ }
2678
+ }
2679
+
2680
+ class SuperSelectionApi {
2681
+ async getAustralianFundsAsync(searchFilter, includeInactive = false) {
2682
+ return buildBackendApiClient()
2683
+ .url(`super-choice/australian-funds-v2?${this.toQueryString(includeInactive, searchFilter)}`)
2684
+ .get()
2685
+ .notFound(() => {
2686
+ throw new Error('Failed to fetch the list of australian super funds.');
2687
+ })
2688
+ .json();
2689
+ }
2690
+ async getAustralianFundAsync(usi, includeInactive) {
2691
+ const queryStr = includeInactive ? '?includeInactive=true' : '';
2692
+ return buildBackendApiClient()
2693
+ .url(`super-choice/australian-funds/${usi}${queryStr}`)
2694
+ .get()
2695
+ .notFound(() => {
2696
+ throw new Error('Failed to fetch australian super fund.');
2697
+ })
2698
+ .json();
2699
+ }
2700
+ async getAppStateAsync() {
2701
+ var _a;
2702
+ const response = await buildBackendApiClient()
2703
+ .url('client-app-state')
2704
+ .get()
2705
+ .notFound(() => {
2706
+ throw new Error('Failed to fetch application configuration.');
2707
+ })
2708
+ .json();
2709
+ if ((_a = response.superBuyer.superChoice) === null || _a === void 0 ? void 0 : _a.choiceDetails) {
2710
+ hydrateSuperChoiceDetailsDtoKind(response.superBuyer.superChoice.choiceDetails);
2711
+ switch (response.superBuyer.superChoice.choiceDetails.kind) {
2712
+ case 'Promoted':
2713
+ hydratePromotedFundChoiceDtoKind(response.superBuyer.superChoice.choiceDetails.promoted);
2714
+ break;
2715
+ }
2716
+ }
2717
+ return response;
2718
+ }
2719
+ async clickPromotedTileAsync(payload) {
2720
+ return buildBackendApiClient().url('click-promoted-tile').post(payload).res();
2721
+ }
2722
+ async viewSuperFundPanelAsync(payload) {
2723
+ return buildBackendApiClient().url('view-super-fund-panel').post(payload).res();
2724
+ }
2725
+ toSearchFilterQueryString(searchFilter) {
2726
+ return (`search=${searchFilter.searchString}` +
2727
+ (searchFilter.maxRecordCount > 0 ? '&maxRecordCount=' + searchFilter.maxRecordCount : ''));
2728
+ }
2729
+ toQueryString(includeInactive, searchFilter) {
2730
+ const search = this.toSearchFilterQueryString(searchFilter);
2731
+ const inactive = includeInactive ? 'includeInactive=true' : '';
2732
+ const isNotEmpty = (s) => s && s.length;
2733
+ return [search, inactive].filter(isNotEmpty).join('&');
2734
+ }
2735
+ }
2736
+ const superSelectionApi = new SuperSelectionApi();
2737
+
2738
+ var SuperCampaignComponentStatus;
2739
+ (function (SuperCampaignComponentStatus) {
2740
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["NotLoaded"] = 1] = "NotLoaded";
2741
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["Loaded"] = 2] = "Loaded";
2742
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["NotWorking"] = 3] = "NotWorking";
2743
+ })(SuperCampaignComponentStatus || (SuperCampaignComponentStatus = {}));
2744
+ class SuperCampaignState {
2745
+ constructor() {
2746
+ this._promotedFundsShown = [];
2747
+ }
2748
+ get PromotedFundIds() {
2749
+ return this._promotedFundsShown.map((p) => p.fundId);
2750
+ }
2751
+ set promotedFundsShown(value) {
2752
+ this._promotedFundsShown = value;
2753
+ }
2754
+ get DefaultFundPosition() {
2755
+ const index = this._promotedFundsShown.findIndex((value) => value.fundType === 'promoted-default');
2756
+ if (index === -1)
2757
+ return undefined;
2758
+ return index + 1;
2759
+ }
2760
+ }
2761
+ const initialState = {
2762
+ apiBaseUrl: Option.none,
2763
+ appBaseUrl: Option.none,
2764
+ profileId: Option.none,
2765
+ jwt: Option.none,
2766
+ superBuyer: Option.none,
2767
+ superChoicePrefill: Option.none,
2768
+ promotedFunds: Option.none,
2769
+ accountConfiguration: Option.none,
2770
+ profileConfiguration: Option.none,
2771
+ hasSuccessPageBeenAcknowledged: false,
2772
+ hasSuperSelectionBeenSubmitted: false,
2773
+ isDefinedBenefitsEligible: Option.none,
2774
+ superCampaignEnabled: true,
2775
+ superCampaignState: undefined,
2776
+ superCampaignComponentStatus: SuperCampaignComponentStatus.NotLoaded,
2777
+ hideFooterSection: false,
2778
+ bringYourOwnFundCustomStepEnabled: false,
2779
+ featuredFundsEnabled: false
2780
+ };
2781
+
2782
+ class SuperSelectionAppService {
2783
+ constructor() {
2784
+ const { state, onChange } = createStore(initialState);
2785
+ this._state = state;
2786
+ this._onChange = onChange;
2787
+ onChange('jwt', (jwt) => {
2788
+ this._state.profileId = _function.pipe(jwt, Option.chain((jwtValue) => Option.fromNullable(o(jwtValue).sub)));
2789
+ });
2790
+ }
2791
+ get state() {
2792
+ return this._state;
2793
+ }
2794
+ get onChange() {
2795
+ return this._onChange;
2796
+ }
2797
+ get superBuyer() {
2798
+ if (Option.isNone(this._state.superBuyer)) {
2799
+ throw Error('User information is not set');
2800
+ }
2801
+ return this._state.superBuyer.value;
2802
+ }
2803
+ get apiBaseUrl() {
2804
+ if (Option.isNone(this._state.apiBaseUrl)) {
2805
+ throw Error('API base URL is not set');
2806
+ }
2807
+ return this._state.apiBaseUrl.value;
2808
+ }
2809
+ get appBaseUrl() {
2810
+ if (Option.isNone(this._state.appBaseUrl)) {
2811
+ throw Error('App base URL is not set');
2812
+ }
2813
+ return this._state.appBaseUrl.value;
2814
+ }
2815
+ get promotedFunds() {
2816
+ if (this.state.superCampaignEnabled && this.superCampaignState !== undefined) {
2817
+ return this.superCampaignState.PromotedFundIds;
2818
+ }
2819
+ if (Option.isNone(this._state.promotedFunds)) {
2820
+ throw Error('Promoted Funds is not set');
2821
+ }
2822
+ return this._state.promotedFunds.value;
2823
+ }
2824
+ get promotedDefaultFundPosition() {
2825
+ if (this.state.superCampaignEnabled && this.superCampaignState !== undefined) {
2826
+ return Option.fromNullable(this.superCampaignState.DefaultFundPosition);
2827
+ }
2828
+ return Option.none;
2829
+ }
2830
+ get promotedFundsConfig() {
2831
+ return {
2832
+ shownFunds: this.promotedFunds,
2833
+ promotedDefaultFundPosition: Option.toUndefined(this.promotedDefaultFundPosition),
2834
+ promotedFundsConfigSource: this.isUsingSuperCampaign ? 'superCampaign' : 'superSelection'
2835
+ };
2836
+ }
2837
+ get profileId() {
2838
+ if (Option.isNone(this._state.profileId)) {
2839
+ throw Error('Failed to get Profile ID from JWT');
2840
+ }
2841
+ return this._state.profileId.value;
2842
+ }
2843
+ get defaultFundUsi() {
2844
+ const profileConfigDefaultFundUsi = _function.pipe(this._state.profileConfiguration, Option.map((config) => Option.fromNullable(config.defaultFundUsi)), Option.flatten);
2845
+ if (Option.isSome(profileConfigDefaultFundUsi)) {
2846
+ return profileConfigDefaultFundUsi;
2847
+ }
2848
+ return _function.pipe(this._state.accountConfiguration, Option.map((config) => Option.fromNullable(config.defaultFundUsi)), Option.flatten);
2849
+ }
2850
+ get accountIdOrDefault() {
2851
+ return _function.pipe(this._state.accountConfiguration, Option.map((config) => config.accountId), Option.getOrElse(() => ''));
2852
+ }
2853
+ get partnerIdOrDefault() {
2854
+ return _function.pipe(this._state.superBuyer, Option.map((superBuyer) => superBuyer.partnerId), Option.getOrElse(() => ''));
2855
+ }
2856
+ get jwt() {
2857
+ if (Option.isNone(this._state.jwt)) {
2858
+ throw Error('No authentication information was found');
2859
+ }
2860
+ return this._state.jwt.value;
2861
+ }
2862
+ completeSuperSelectionFlow() {
2863
+ this._state.hasSuccessPageBeenAcknowledged = true;
2864
+ }
2865
+ markSuperSelectionAsSubmitted() {
2866
+ this._state.hasSuperSelectionBeenSubmitted = true;
2867
+ }
2868
+ get isDefinedBenefitsEligible() {
2869
+ return this._state.isDefinedBenefitsEligible;
2870
+ }
2871
+ async loadAppStateAsync() {
2872
+ const appStateResponse = await superSelectionApi.getAppStateAsync();
2873
+ this._state.accountConfiguration = Option.fromNullable(appStateResponse.accountConfiguration);
2874
+ this._state.profileConfiguration = Option.fromNullable(appStateResponse.profileConfiguration);
2875
+ this._state.superBuyer = Option.fromNullable(appStateResponse.superBuyer);
2876
+ this._state.promotedFunds = Option.fromNullable(appStateResponse.promotedFunds);
2877
+ this._state.bringYourOwnFundCustomStepEnabled =
2878
+ appStateResponse.bringYourOwnFundCustomStepEnabled;
2879
+ this._state.featuredFundsEnabled = appStateResponse.featuredFundsEnabled;
2880
+ this._state.superChoicePrefill = Option.fromNullable(appStateResponse.prefill);
2881
+ this._state.isDefinedBenefitsEligible = Option.fromNullable(appStateResponse.isDefinedBenefitsEligible);
2882
+ if (Option.isSome(this._state.accountConfiguration)) {
2883
+ if (this._state.accountConfiguration.value.featureSet.type === 'basic') {
2884
+ this._state.superCampaignEnabled = false;
2885
+ }
2886
+ }
2887
+ }
2888
+ setSuperCampaignPromotedFundsShown(shownFunds) {
2889
+ if (this._state.superCampaignState !== undefined)
2890
+ this._state.superCampaignState.promotedFundsShown = shownFunds;
2891
+ else
2892
+ throw new Error('Cannot set shown funds for SuperCampaing state because it is undefined');
2893
+ }
2894
+ viewSuperFundPanelAsync(placementId, promotedFundIdListOverride) {
2895
+ return superSelectionApi.viewSuperFundPanelAsync(Object.assign(Object.assign({}, this.promotedFundsConfig), { shownFunds: promotedFundIdListOverride
2896
+ ? promotedFundIdListOverride
2897
+ : this.promotedFundsConfig.shownFunds, placementId }));
2898
+ }
2899
+ get superCampaignState() {
2900
+ return this._state.superCampaignState;
2901
+ }
2902
+ get superCampaignComponentStatus() {
2903
+ return this._state.superCampaignComponentStatus;
2904
+ }
2905
+ set superCampaignComponentStatus(value) {
2906
+ if (value === SuperCampaignComponentStatus.Loaded) {
2907
+ this._state.superCampaignComponentStatus = SuperCampaignComponentStatus.Loaded;
2908
+ this._state.superCampaignState = new SuperCampaignState();
2909
+ }
2910
+ else {
2911
+ this._state.superCampaignComponentStatus = value;
2912
+ this._state.superCampaignState = undefined;
2913
+ }
2914
+ }
2915
+ get isUsingSuperCampaign() {
2916
+ return this.state.superCampaignEnabled && this.superCampaignState !== undefined;
2917
+ }
2918
+ get isBringYourOwnFundCustomStepEnabled() {
2919
+ return this.state.bringYourOwnFundCustomStepEnabled;
2920
+ }
2921
+ get isFeaturedFundsEnabled() {
2922
+ return this.state.featuredFundsEnabled;
2923
+ }
2924
+ get superCampaignCanNotBeActivated() {
2925
+ return (!this.state.superCampaignEnabled ||
2926
+ this.superCampaignComponentStatus === SuperCampaignComponentStatus.NotWorking);
2927
+ }
2928
+ get hideFooterSection() {
2929
+ return this._state.hideFooterSection;
2930
+ }
2931
+ set hideFooterSection(value) {
2932
+ this._state.hideFooterSection = value;
2933
+ }
2934
+ get backendUrl() {
2935
+ return Option.map(this.getBaseUrl)(this.state.apiBaseUrl);
2936
+ }
2937
+ getBaseUrl(url) {
2938
+ const parsedUrl = new URL(url);
2939
+ return `${parsedUrl.protocol}//${parsedUrl.hostname}${parsedUrl.port.length > 0 ? `:${parsedUrl.port}` : ''}`;
2940
+ }
2941
+ }
2942
+ const superSelectionAppService = new SuperSelectionAppService();
2943
+
2944
+ class NavigationService {
2945
+ navigateInternally(history, route) {
2946
+ const path = `${this.appBaseUrl}${this.toRouteWithLeadingSlash(route)}`;
2947
+ iframe.navigation(path);
2948
+ history.push(path);
2949
+ }
2950
+ navigateInternallyToStandardChoice(options) {
2951
+ state.handleSubmitFn = options.handleSubmitFn;
2952
+ state.fundName = options.fundName;
2953
+ state.fundDetails = options.fundDetails;
2954
+ state.promotedFundId = options.promotedFundId;
2955
+ this.navigateInternally(options.history, SuperSelectionAppRoutes.StandardChoice);
2956
+ }
2957
+ toExternalUrl(url) {
2958
+ const externalUrl = new URL(url);
2959
+ externalUrl.searchParams.append('_extnav', 'true');
2960
+ return externalUrl.href;
2961
+ }
2962
+ get appBaseUrl() {
2963
+ const baseUrl = superSelectionAppService.appBaseUrl;
2964
+ return baseUrl.replace(/\/$/, '');
2965
+ }
2966
+ toRouteWithLeadingSlash(route) {
2967
+ return route.length > 0 && route[0] === '/' ? route : `/${route}`;
2968
+ }
2969
+ }
2970
+ const navigationService = new NavigationService();
2971
+
2972
+ class CustomFundChoiceApi {
2973
+ async submitDefaultFundChoiceAsync(dto) {
2974
+ return buildBackendApiClient()
2975
+ .url('super-choice/default')
2976
+ .post(dto)
2977
+ .badRequest(() => {
2978
+ throw new Error('Failed to process default fund join request');
2979
+ })
2980
+ .text();
2981
+ }
2982
+ async submitCustomFundChoiceAsync(dto) {
2983
+ return buildBackendApiClient()
2984
+ .url('super-choice/custom-fund')
2985
+ .post(dto)
2986
+ .badRequest(() => {
2987
+ throw new Error('Failed to process custom fund join request');
2988
+ })
2989
+ .text();
2990
+ }
2991
+ async submitSelfManagedFundChoiceAsync(dto) {
2992
+ return buildBackendApiClient()
2993
+ .url('super-choice/smsf')
2994
+ .post(dto)
2995
+ .badRequest(() => {
2996
+ throw new Error('Failed to process SMSF choice request');
2997
+ })
2998
+ .text();
2999
+ }
3000
+ async submitDefinedBenefitsChoiceAsync(dto) {
3001
+ return buildBackendApiClient()
3002
+ .url('super-choice/defined-benefits')
3003
+ .post(dto)
3004
+ .badRequest(() => {
3005
+ throw new Error('Failed to process Defined Benefits choice request');
3006
+ })
3007
+ .text();
3008
+ }
3009
+ async validateAbnForSMSF(abn) {
3010
+ const response = await buildBackendApiClient()
3011
+ .url(`super-choice/smsf/${abn}/validate`)
3012
+ .get()
3013
+ .badRequest(() => {
3014
+ throw new Error('Failed to verify that if the provided abn is used for regulated fund');
3015
+ })
3016
+ .json();
3017
+ return response.result;
3018
+ }
3019
+ }
3020
+ const customFundChoiceApi = new CustomFundChoiceApi();
3021
+
3022
+ export { Option as O, SuperSelectionAppRoutes as S, superSelectionAppService as a, navigationService as b, injectHistory as c, createStore as d, superSelectionApi as e, buildBackendApiClient as f, customFundChoiceApi as g, isNone as h, isSome as i, getPromotedFundId as j, getSuperChoiceUsi as k, getSuperChoiceMemberNumber as l, state as m, none as n, slate as o, SuperCampaignComponentStatus as p, iframe as q, superSelectionAppStencilRoutes as r, some as s, toUndefined as t, factory as u, fromNullable as v };