@justifi/webcomponents 0.0.10 → 0.0.12

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 (44) hide show
  1. package/dist/cjs/{index-68222998.js → index-4f753ffd.js} +32 -1
  2. package/dist/cjs/index.cjs.js +0 -10
  3. package/dist/cjs/justifi-bank-account-form_4.cjs.entry.js +4352 -42
  4. package/dist/cjs/loader.cjs.js +4 -3
  5. package/dist/cjs/webcomponents.cjs.js +7 -3
  6. package/dist/collection/collection-manifest.json +4 -4
  7. package/dist/collection/components/bank-account-form/bank-account-form.js +43 -45
  8. package/dist/collection/components/card-form/card-form.js +66 -39
  9. package/dist/collection/components/payment-method-form/message-event-types.js +12 -0
  10. package/dist/collection/components/payment-method-form/payment-method-form.js +68 -73
  11. package/dist/collection/index.js +1 -3
  12. package/dist/components/index.d.ts +9 -0
  13. package/dist/components/index.js +4 -4
  14. package/dist/components/justifi-bank-account-form.js +17 -14
  15. package/dist/components/justifi-card-form.js +23 -11
  16. package/dist/components/justifi-payments-list.js +1 -1
  17. package/dist/components/payment-method-form.js +48 -39
  18. package/dist/esm/{index-e279d85e.js → index-3d88d85c.js} +32 -2
  19. package/dist/esm/index.js +1 -2
  20. package/dist/esm/justifi-bank-account-form_4.entry.js +4350 -40
  21. package/dist/esm/loader.js +4 -3
  22. package/dist/esm/polyfills/css-shim.js +1 -1
  23. package/dist/esm/webcomponents.js +4 -3
  24. package/dist/types/api/Api.d.ts +1 -1
  25. package/dist/types/api/Payment.d.ts +1 -1
  26. package/dist/types/components/bank-account-form/bank-account-form.d.ts +10 -5
  27. package/dist/types/components/card-form/card-form.d.ts +14 -3
  28. package/dist/types/components/payment-method-form/message-event-types.d.ts +12 -0
  29. package/dist/types/components/payment-method-form/payment-method-form.d.ts +5 -4
  30. package/dist/types/components.d.ts +13 -12
  31. package/dist/types/index.d.ts +1 -4
  32. package/dist/types/stencil-public-runtime.d.ts +48 -3
  33. package/dist/webcomponents/index.esm.js +0 -1
  34. package/dist/webcomponents/p-8ad58e9a.entry.js +1 -0
  35. package/dist/webcomponents/p-de108437.js +2 -0
  36. package/dist/webcomponents/webcomponents.esm.js +1 -1
  37. package/loader/index.d.ts +9 -0
  38. package/package.json +2 -3
  39. package/dist/cjs/payments-list-d2dfcef1.js +0 -4298
  40. package/dist/collection/components/card-form/card-form.css +0 -3
  41. package/dist/esm/payments-list-91eba70b.js +0 -4294
  42. package/dist/webcomponents/p-146348d6.js +0 -2
  43. package/dist/webcomponents/p-a688f9d3.entry.js +0 -1
  44. package/dist/webcomponents/p-c94a0f7f.js +0 -1
@@ -1,23 +1,103 @@
1
- export { B as justifi_bank_account_form, C as justifi_card_form, P as justifi_payments_list } from './payments-list-91eba70b.js';
2
- import { r as registerInstance, c as createEvent, h, H as Host } from './index-e279d85e.js';
1
+ import { r as registerInstance, c as createEvent, h, H as Host } from './index-3d88d85c.js';
2
+
3
+ const BankAccountForm = class {
4
+ constructor(hostRef) {
5
+ registerInstance(this, hostRef);
6
+ this.bankAccountFormReady = createEvent(this, "bankAccountFormReady", 7);
7
+ this.bankAccountFormTokenize = createEvent(this, "bankAccountFormTokenize", 7);
8
+ this.bankAccountFormValidate = createEvent(this, "bankAccountFormValidate", 7);
9
+ this.validationStrategy = undefined;
10
+ }
11
+ readyHandler(event) {
12
+ this.bankAccountFormReady.emit(event);
13
+ }
14
+ tokenizeHandler(event) {
15
+ this.bankAccountFormTokenize.emit(event);
16
+ }
17
+ validateHandler(event) {
18
+ this.bankAccountFormValidate.emit(event);
19
+ }
20
+ async tokenize(...args) {
21
+ if (!this.childRef) {
22
+ throw new Error('Cannot call tokenize');
23
+ }
24
+ return this.childRef.tokenize(...args);
25
+ }
26
+ async validate() {
27
+ if (!this.childRef) {
28
+ throw new Error('Cannot call validate');
29
+ }
30
+ return this.childRef.validate();
31
+ }
32
+ render() {
33
+ return (h("justifi-payment-method-form", { ref: el => {
34
+ if (el) {
35
+ this.childRef = el;
36
+ }
37
+ }, "payment-method-form-type": "bankAccount", "payment-method-form-ready": this.bankAccountFormReady, "payment-method-form-tokenize": this.bankAccountFormTokenize, "payment-method-form-validation-strategy": this.validationStrategy || 'onSubmit' }));
38
+ }
39
+ };
40
+
41
+ const CardForm = class {
42
+ constructor(hostRef) {
43
+ registerInstance(this, hostRef);
44
+ this.cardFormReady = createEvent(this, "cardFormReady", 7);
45
+ this.cardFormTokenize = createEvent(this, "cardFormTokenize", 7);
46
+ this.cardFormValidate = createEvent(this, "cardFormValidate", 7);
47
+ this.validationStrategy = undefined;
48
+ }
49
+ readyHandler(event) {
50
+ this.cardFormReady.emit(event);
51
+ }
52
+ tokenizeHandler(event) {
53
+ this.cardFormTokenize.emit(event);
54
+ }
55
+ validateHandler(event) {
56
+ this.cardFormValidate.emit(event);
57
+ }
58
+ async tokenize(...args) {
59
+ if (!this.childRef) {
60
+ throw new Error('Cannot call tokenize');
61
+ }
62
+ return this.childRef.tokenize(...args);
63
+ }
64
+ async validate() {
65
+ if (!this.childRef) {
66
+ throw new Error('Cannot call validate');
67
+ }
68
+ return this.childRef.validate();
69
+ }
70
+ render() {
71
+ return (h("justifi-payment-method-form", { ref: el => {
72
+ if (el) {
73
+ this.childRef = el;
74
+ }
75
+ }, "payment-method-form-type": "card", "payment-method-form-ready": this.cardFormReady, "payment-method-form-tokenize": this.cardFormTokenize, "payment-method-form-validation-strategy": this.validationStrategy || 'onSubmit' }));
76
+ }
77
+ };
78
+
79
+ const MessageEventType = {
80
+ card: {
81
+ ready: 'justifi.card.ready',
82
+ tokenize: 'justifi.card.tokenize',
83
+ validate: 'justifi.card.validate',
84
+ },
85
+ bankAccount: {
86
+ ready: 'justifi.bank_account.ready',
87
+ tokenize: 'justifi.bank_account.tokenize',
88
+ validate: 'justifi.bank_account.validate',
89
+ }
90
+ };
3
91
 
4
92
  const paymentMethodFormCss = ":host{display:block}justifi-payment-method-form iframe{border:none;width:100%}";
5
93
 
6
- var DispatchedEventTypes;
7
- (function (DispatchedEventTypes) {
8
- DispatchedEventTypes["blur"] = "blur";
9
- DispatchedEventTypes["change"] = "change";
10
- DispatchedEventTypes["ready"] = "ready";
11
- DispatchedEventTypes["tokenize"] = "tokenize";
12
- })(DispatchedEventTypes || (DispatchedEventTypes = {}));
13
94
  const PaymentMethodForm = class {
14
95
  constructor(hostRef) {
15
96
  registerInstance(this, hostRef);
16
97
  this.paymentMethodFormReady = createEvent(this, "paymentMethodFormReady", 7);
17
- this.paymentMethodFormChange = createEvent(this, "paymentMethodFormChange", 7);
18
- this.paymentMethodFormBlur = createEvent(this, "paymentMethodFormBlur", 7);
19
98
  this.paymentMethodFormTokenize = createEvent(this, "paymentMethodFormTokenize", 7);
20
- this.iframeOrigin = undefined;
99
+ this.paymentMethodFormType = undefined;
100
+ this.paymentMethodFormValidationStrategy = undefined;
21
101
  }
22
102
  connectedCallback() {
23
103
  window.addEventListener('message', this.dispatchMessageEvent.bind(this));
@@ -29,45 +109,4275 @@ const PaymentMethodForm = class {
29
109
  const messagePayload = messageEvent.data;
30
110
  const messageType = messagePayload.eventType;
31
111
  const messageData = messagePayload.data;
32
- switch (messageType) {
33
- case DispatchedEventTypes.ready:
34
- this.paymentMethodFormReady.emit(messageData);
35
- break;
36
- case DispatchedEventTypes.change:
37
- this.paymentMethodFormChange.emit(messageData);
38
- break;
39
- case DispatchedEventTypes.blur:
40
- this.paymentMethodFormBlur.emit(messageData);
41
- break;
42
- }
43
- }
44
- triggerTokenization(clientKey, paymentMethodMetadata, account) {
45
- if (this.iframeElement && this.iframeElement.contentWindow) {
46
- this.iframeElement.contentWindow.postMessage({
47
- eventType: DispatchedEventTypes.tokenize,
48
- clientKey: clientKey,
49
- paymentMethodMetadata: paymentMethodMetadata,
50
- account: account
51
- }, '*');
112
+ if (messageType === MessageEventType[this.paymentMethodFormType].ready) {
113
+ this.paymentMethodFormReady.emit(messageData);
52
114
  }
53
115
  }
54
- async tokenize(clientKey, paymentMethodMetadata, account) {
116
+ async postMessageWithResponseListener(eventType, payload) {
55
117
  return new Promise((resolve) => {
56
- const tokenizeEventListener = (event) => {
57
- if (event.data.eventType !== DispatchedEventTypes.tokenize)
118
+ const responseListener = (event) => {
119
+ if (event.data.eventType !== eventType)
58
120
  return;
59
- window.removeEventListener('message', tokenizeEventListener);
121
+ window.removeEventListener('message', responseListener);
60
122
  resolve(event.data.data);
61
123
  };
62
- window.addEventListener('message', tokenizeEventListener);
63
- this.triggerTokenization(clientKey, paymentMethodMetadata, account);
124
+ window.addEventListener('message', responseListener);
125
+ this.iframeElement.contentWindow.postMessage(Object.assign({ eventType: eventType }, payload), '*');
64
126
  });
65
127
  }
128
+ async tokenize(clientKey, paymentMethodMetadata, account) {
129
+ const eventType = MessageEventType[this.paymentMethodFormType].tokenize;
130
+ const payload = {
131
+ clientKey: clientKey,
132
+ paymentMethodMetadata: paymentMethodMetadata,
133
+ account: account
134
+ };
135
+ return this.postMessageWithResponseListener(eventType, payload);
136
+ }
137
+ ;
138
+ async validate() {
139
+ return this.postMessageWithResponseListener(MessageEventType[this.paymentMethodFormType].validate);
140
+ }
66
141
  ;
142
+ getIframeSrc() {
143
+ let iframeSrc = `https://js.justifi.ai/v2/${this.paymentMethodFormType}`;
144
+ if (this.paymentMethodFormValidationStrategy) {
145
+ iframeSrc += `?validationStrategy=${this.paymentMethodFormValidationStrategy}`;
146
+ }
147
+ return iframeSrc;
148
+ }
67
149
  render() {
68
- return (h(Host, null, h("iframe", { id: "justifi-payment-method-form", src: this.iframeOrigin, ref: (el) => this.iframeElement = el })));
150
+ return (h(Host, null, h("iframe", { id: `justifi-payment-method-form-${this.paymentMethodFormType}`, src: this.getIframeSrc(), ref: (el) => this.iframeElement = el })));
69
151
  }
70
152
  };
71
153
  PaymentMethodForm.style = paymentMethodFormCss;
72
154
 
73
- export { PaymentMethodForm as justifi_payment_method_form };
155
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
156
+ // require the crypto API and do not support built-in fallback to lower quality random number
157
+ // generators (like Math.random()).
158
+ let getRandomValues;
159
+ const rnds8 = new Uint8Array(16);
160
+ function rng() {
161
+ // lazy load so that environments that need to polyfill have a chance to do so
162
+ if (!getRandomValues) {
163
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
164
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
165
+
166
+ if (!getRandomValues) {
167
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
168
+ }
169
+ }
170
+
171
+ return getRandomValues(rnds8);
172
+ }
173
+
174
+ /**
175
+ * Convert array of 16 byte values to UUID string format of the form:
176
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
177
+ */
178
+
179
+ const byteToHex = [];
180
+
181
+ for (let i = 0; i < 256; ++i) {
182
+ byteToHex.push((i + 0x100).toString(16).slice(1));
183
+ }
184
+
185
+ function unsafeStringify(arr, offset = 0) {
186
+ // Note: Be careful editing this code! It's been tuned for performance
187
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
188
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
189
+ }
190
+
191
+ const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
192
+ const native = {
193
+ randomUUID
194
+ };
195
+
196
+ function v4(options, buf, offset) {
197
+ if (native.randomUUID && !buf && !options) {
198
+ return native.randomUUID();
199
+ }
200
+
201
+ options = options || {};
202
+ const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
203
+
204
+ rnds[6] = rnds[6] & 0x0f | 0x40;
205
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
206
+
207
+ if (buf) {
208
+ offset = offset || 0;
209
+
210
+ for (let i = 0; i < 16; ++i) {
211
+ buf[offset + i] = rnds[i];
212
+ }
213
+
214
+ return buf;
215
+ }
216
+
217
+ return unsafeStringify(rnds);
218
+ }
219
+
220
+ const Api = (authToken) => {
221
+ const apiOrigin = 'http://localhost:3000';
222
+ async function getAuthorizationHeader() {
223
+ return {
224
+ Authorization: `Bearer ${authToken}`,
225
+ 'Idempotency-Key': v4(),
226
+ 'Content-Type': 'application/json'
227
+ };
228
+ }
229
+ async function makeRequest(endpoint, method, params, body, signal) {
230
+ const url = `${apiOrigin}/v1/${endpoint}`;
231
+ const requestUrl = params ? `${url}?${new URLSearchParams(params)}` : url;
232
+ const response = await fetch(requestUrl, {
233
+ method: method,
234
+ headers: await getAuthorizationHeader(),
235
+ body: body,
236
+ signal: signal
237
+ });
238
+ if (response) {
239
+ return response.status === 204 ? {} : response.json();
240
+ }
241
+ handleError(requestUrl);
242
+ }
243
+ async function get(endpoint, params, signal) {
244
+ return makeRequest(endpoint, 'GET', params, null, signal);
245
+ }
246
+ async function post(endpoint, body, params, signal) {
247
+ return makeRequest(endpoint, 'POST', params, body, signal);
248
+ }
249
+ async function patch(endpoint, body, params, signal) {
250
+ return makeRequest(endpoint, 'PATCH', params, body, signal);
251
+ }
252
+ async function destroy(endpoint, params, signal) {
253
+ return makeRequest(endpoint, 'DELETE', params, null, signal);
254
+ }
255
+ return { get, post, patch, destroy };
256
+ };
257
+ function handleError(requestUrl) {
258
+ console.error(`Error fetching from ${requestUrl}`);
259
+ }
260
+
261
+ var CaptureStrategy;
262
+ (function (CaptureStrategy) {
263
+ CaptureStrategy["automatic"] = "automatic";
264
+ CaptureStrategy["manual"] = "manual";
265
+ })(CaptureStrategy || (CaptureStrategy = {}));
266
+ var PaymentMethodTypes;
267
+ (function (PaymentMethodTypes) {
268
+ PaymentMethodTypes["card"] = "card";
269
+ PaymentMethodTypes["bankAccount"] = "bank_account";
270
+ })(PaymentMethodTypes || (PaymentMethodTypes = {}));
271
+ var PaymentStatuses;
272
+ (function (PaymentStatuses) {
273
+ PaymentStatuses["pending"] = "pending";
274
+ PaymentStatuses["authorized"] = "authorized";
275
+ PaymentStatuses["succeeded"] = "succeeded";
276
+ PaymentStatuses["failed"] = "failed";
277
+ PaymentStatuses["disputed"] = "disputed";
278
+ PaymentStatuses["fully_refunded"] = "fully_refunded";
279
+ PaymentStatuses["partially_refunded"] = "partially_refunded";
280
+ })(PaymentStatuses || (PaymentStatuses = {}));
281
+ var PaymentDisputedStatuses;
282
+ (function (PaymentDisputedStatuses) {
283
+ // if a dispute is 'won', we don't show a dispute status, just general status
284
+ PaymentDisputedStatuses["lost"] = "lost";
285
+ PaymentDisputedStatuses["open"] = "open";
286
+ })(PaymentDisputedStatuses || (PaymentDisputedStatuses = {}));
287
+ class Payment {
288
+ constructor(payment) {
289
+ this.id = payment.id;
290
+ this.account_id = payment.account_id;
291
+ this.amount = payment.amount;
292
+ this.amount_disputed = payment.amount_disputed;
293
+ this.amount_refundable = payment.amount_refundable;
294
+ this.amount_refunded = payment.amount_refunded;
295
+ this.balance = payment.balance;
296
+ this.captured = payment.captured;
297
+ this.capture_strategy = payment.capture_strategy;
298
+ this.currency = payment.currency;
299
+ this.description = payment.description;
300
+ this.disputed = payment.disputed;
301
+ this.disputes = payment.disputes;
302
+ this.error_code = payment.error_code;
303
+ this.error_description = payment.error_description;
304
+ this.fee_amount = payment.fee_amount;
305
+ this.is_test = payment.is_test;
306
+ this.metadata = payment.metadata;
307
+ this.payment_method = payment.payment_method;
308
+ this.payment_intent_id = payment.payment_intent_id;
309
+ this.refunded = payment.refunded;
310
+ this.status = payment.status;
311
+ this.created_at = payment.created_at;
312
+ this.updated_at = payment.updated_at;
313
+ }
314
+ get disputedStatus() {
315
+ const lost = this.disputes.some((dispute) => dispute.status === PaymentDisputedStatuses.lost);
316
+ // if a dispute is 'won', we don't show a dispute status, just general status
317
+ if (!this.disputed) {
318
+ return null;
319
+ }
320
+ else if (lost) {
321
+ return PaymentDisputedStatuses.lost;
322
+ }
323
+ else {
324
+ return PaymentDisputedStatuses.open;
325
+ }
326
+ }
327
+ }
328
+
329
+ function toInteger(dirtyNumber) {
330
+ if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
331
+ return NaN;
332
+ }
333
+
334
+ var number = Number(dirtyNumber);
335
+
336
+ if (isNaN(number)) {
337
+ return number;
338
+ }
339
+
340
+ return number < 0 ? Math.ceil(number) : Math.floor(number);
341
+ }
342
+
343
+ function requiredArgs(required, args) {
344
+ if (args.length < required) {
345
+ throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
346
+ }
347
+ }
348
+
349
+ function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
350
+ /**
351
+ * @name toDate
352
+ * @category Common Helpers
353
+ * @summary Convert the given argument to an instance of Date.
354
+ *
355
+ * @description
356
+ * Convert the given argument to an instance of Date.
357
+ *
358
+ * If the argument is an instance of Date, the function returns its clone.
359
+ *
360
+ * If the argument is a number, it is treated as a timestamp.
361
+ *
362
+ * If the argument is none of the above, the function returns Invalid Date.
363
+ *
364
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
365
+ *
366
+ * @param {Date|Number} argument - the value to convert
367
+ * @returns {Date} the parsed date in the local time zone
368
+ * @throws {TypeError} 1 argument required
369
+ *
370
+ * @example
371
+ * // Clone the date:
372
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
373
+ * //=> Tue Feb 11 2014 11:30:30
374
+ *
375
+ * @example
376
+ * // Convert the timestamp to date:
377
+ * const result = toDate(1392098430000)
378
+ * //=> Tue Feb 11 2014 11:30:30
379
+ */
380
+
381
+ function toDate(argument) {
382
+ requiredArgs(1, arguments);
383
+ var argStr = Object.prototype.toString.call(argument); // Clone the date
384
+
385
+ if (argument instanceof Date || _typeof$2(argument) === 'object' && argStr === '[object Date]') {
386
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
387
+ return new Date(argument.getTime());
388
+ } else if (typeof argument === 'number' || argStr === '[object Number]') {
389
+ return new Date(argument);
390
+ } else {
391
+ if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
392
+ // eslint-disable-next-line no-console
393
+ console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console
394
+
395
+ console.warn(new Error().stack);
396
+ }
397
+
398
+ return new Date(NaN);
399
+ }
400
+ }
401
+
402
+ /**
403
+ * @name addMilliseconds
404
+ * @category Millisecond Helpers
405
+ * @summary Add the specified number of milliseconds to the given date.
406
+ *
407
+ * @description
408
+ * Add the specified number of milliseconds to the given date.
409
+ *
410
+ * @param {Date|Number} date - the date to be changed
411
+ * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
412
+ * @returns {Date} the new date with the milliseconds added
413
+ * @throws {TypeError} 2 arguments required
414
+ *
415
+ * @example
416
+ * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
417
+ * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
418
+ * //=> Thu Jul 10 2014 12:45:30.750
419
+ */
420
+
421
+ function addMilliseconds(dirtyDate, dirtyAmount) {
422
+ requiredArgs(2, arguments);
423
+ var timestamp = toDate(dirtyDate).getTime();
424
+ var amount = toInteger(dirtyAmount);
425
+ return new Date(timestamp + amount);
426
+ }
427
+
428
+ var defaultOptions = {};
429
+ function getDefaultOptions() {
430
+ return defaultOptions;
431
+ }
432
+
433
+ /**
434
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
435
+ * They usually appear for dates that denote time before the timezones were introduced
436
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
437
+ * and GMT+01:00:00 after that date)
438
+ *
439
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
440
+ * which would lead to incorrect calculations.
441
+ *
442
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
443
+ */
444
+ function getTimezoneOffsetInMilliseconds(date) {
445
+ var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
446
+ utcDate.setUTCFullYear(date.getFullYear());
447
+ return date.getTime() - utcDate.getTime();
448
+ }
449
+
450
+ function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }
451
+ /**
452
+ * @name isDate
453
+ * @category Common Helpers
454
+ * @summary Is the given value a date?
455
+ *
456
+ * @description
457
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
458
+ *
459
+ * @param {*} value - the value to check
460
+ * @returns {boolean} true if the given value is a date
461
+ * @throws {TypeError} 1 arguments required
462
+ *
463
+ * @example
464
+ * // For a valid date:
465
+ * const result = isDate(new Date())
466
+ * //=> true
467
+ *
468
+ * @example
469
+ * // For an invalid date:
470
+ * const result = isDate(new Date(NaN))
471
+ * //=> true
472
+ *
473
+ * @example
474
+ * // For some value:
475
+ * const result = isDate('2014-02-31')
476
+ * //=> false
477
+ *
478
+ * @example
479
+ * // For an object:
480
+ * const result = isDate({})
481
+ * //=> false
482
+ */
483
+
484
+ function isDate(value) {
485
+ requiredArgs(1, arguments);
486
+ return value instanceof Date || _typeof$1(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
487
+ }
488
+
489
+ /**
490
+ * @name isValid
491
+ * @category Common Helpers
492
+ * @summary Is the given date valid?
493
+ *
494
+ * @description
495
+ * Returns false if argument is Invalid Date and true otherwise.
496
+ * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
497
+ * Invalid Date is a Date, whose time value is NaN.
498
+ *
499
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
500
+ *
501
+ * @param {*} date - the date to check
502
+ * @returns {Boolean} the date is valid
503
+ * @throws {TypeError} 1 argument required
504
+ *
505
+ * @example
506
+ * // For the valid date:
507
+ * const result = isValid(new Date(2014, 1, 31))
508
+ * //=> true
509
+ *
510
+ * @example
511
+ * // For the value, convertable into a date:
512
+ * const result = isValid(1393804800000)
513
+ * //=> true
514
+ *
515
+ * @example
516
+ * // For the invalid date:
517
+ * const result = isValid(new Date(''))
518
+ * //=> false
519
+ */
520
+
521
+ function isValid(dirtyDate) {
522
+ requiredArgs(1, arguments);
523
+
524
+ if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
525
+ return false;
526
+ }
527
+
528
+ var date = toDate(dirtyDate);
529
+ return !isNaN(Number(date));
530
+ }
531
+
532
+ /**
533
+ * @name subMilliseconds
534
+ * @category Millisecond Helpers
535
+ * @summary Subtract the specified number of milliseconds from the given date.
536
+ *
537
+ * @description
538
+ * Subtract the specified number of milliseconds from the given date.
539
+ *
540
+ * @param {Date|Number} date - the date to be changed
541
+ * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
542
+ * @returns {Date} the new date with the milliseconds subtracted
543
+ * @throws {TypeError} 2 arguments required
544
+ *
545
+ * @example
546
+ * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
547
+ * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
548
+ * //=> Thu Jul 10 2014 12:45:29.250
549
+ */
550
+
551
+ function subMilliseconds(dirtyDate, dirtyAmount) {
552
+ requiredArgs(2, arguments);
553
+ var amount = toInteger(dirtyAmount);
554
+ return addMilliseconds(dirtyDate, -amount);
555
+ }
556
+
557
+ var MILLISECONDS_IN_DAY = 86400000;
558
+ function getUTCDayOfYear(dirtyDate) {
559
+ requiredArgs(1, arguments);
560
+ var date = toDate(dirtyDate);
561
+ var timestamp = date.getTime();
562
+ date.setUTCMonth(0, 1);
563
+ date.setUTCHours(0, 0, 0, 0);
564
+ var startOfYearTimestamp = date.getTime();
565
+ var difference = timestamp - startOfYearTimestamp;
566
+ return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
567
+ }
568
+
569
+ function startOfUTCISOWeek(dirtyDate) {
570
+ requiredArgs(1, arguments);
571
+ var weekStartsOn = 1;
572
+ var date = toDate(dirtyDate);
573
+ var day = date.getUTCDay();
574
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
575
+ date.setUTCDate(date.getUTCDate() - diff);
576
+ date.setUTCHours(0, 0, 0, 0);
577
+ return date;
578
+ }
579
+
580
+ function getUTCISOWeekYear(dirtyDate) {
581
+ requiredArgs(1, arguments);
582
+ var date = toDate(dirtyDate);
583
+ var year = date.getUTCFullYear();
584
+ var fourthOfJanuaryOfNextYear = new Date(0);
585
+ fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
586
+ fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
587
+ var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
588
+ var fourthOfJanuaryOfThisYear = new Date(0);
589
+ fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
590
+ fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
591
+ var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
592
+
593
+ if (date.getTime() >= startOfNextYear.getTime()) {
594
+ return year + 1;
595
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
596
+ return year;
597
+ } else {
598
+ return year - 1;
599
+ }
600
+ }
601
+
602
+ function startOfUTCISOWeekYear(dirtyDate) {
603
+ requiredArgs(1, arguments);
604
+ var year = getUTCISOWeekYear(dirtyDate);
605
+ var fourthOfJanuary = new Date(0);
606
+ fourthOfJanuary.setUTCFullYear(year, 0, 4);
607
+ fourthOfJanuary.setUTCHours(0, 0, 0, 0);
608
+ var date = startOfUTCISOWeek(fourthOfJanuary);
609
+ return date;
610
+ }
611
+
612
+ var MILLISECONDS_IN_WEEK$1 = 604800000;
613
+ function getUTCISOWeek(dirtyDate) {
614
+ requiredArgs(1, arguments);
615
+ var date = toDate(dirtyDate);
616
+ var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer
617
+ // because the number of milliseconds in a week is not constant
618
+ // (e.g. it's different in the week of the daylight saving time clock shift)
619
+
620
+ return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
621
+ }
622
+
623
+ function startOfUTCWeek(dirtyDate, options) {
624
+ var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
625
+
626
+ requiredArgs(1, arguments);
627
+ var defaultOptions = getDefaultOptions();
628
+ var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
629
+
630
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
631
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
632
+ }
633
+
634
+ var date = toDate(dirtyDate);
635
+ var day = date.getUTCDay();
636
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
637
+ date.setUTCDate(date.getUTCDate() - diff);
638
+ date.setUTCHours(0, 0, 0, 0);
639
+ return date;
640
+ }
641
+
642
+ function getUTCWeekYear(dirtyDate, options) {
643
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
644
+
645
+ requiredArgs(1, arguments);
646
+ var date = toDate(dirtyDate);
647
+ var year = date.getUTCFullYear();
648
+ var defaultOptions = getDefaultOptions();
649
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
650
+
651
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
652
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
653
+ }
654
+
655
+ var firstWeekOfNextYear = new Date(0);
656
+ firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
657
+ firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
658
+ var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
659
+ var firstWeekOfThisYear = new Date(0);
660
+ firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
661
+ firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
662
+ var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
663
+
664
+ if (date.getTime() >= startOfNextYear.getTime()) {
665
+ return year + 1;
666
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
667
+ return year;
668
+ } else {
669
+ return year - 1;
670
+ }
671
+ }
672
+
673
+ function startOfUTCWeekYear(dirtyDate, options) {
674
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
675
+
676
+ requiredArgs(1, arguments);
677
+ var defaultOptions = getDefaultOptions();
678
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
679
+ var year = getUTCWeekYear(dirtyDate, options);
680
+ var firstWeek = new Date(0);
681
+ firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
682
+ firstWeek.setUTCHours(0, 0, 0, 0);
683
+ var date = startOfUTCWeek(firstWeek, options);
684
+ return date;
685
+ }
686
+
687
+ var MILLISECONDS_IN_WEEK = 604800000;
688
+ function getUTCWeek(dirtyDate, options) {
689
+ requiredArgs(1, arguments);
690
+ var date = toDate(dirtyDate);
691
+ var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
692
+ // because the number of milliseconds in a week is not constant
693
+ // (e.g. it's different in the week of the daylight saving time clock shift)
694
+
695
+ return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
696
+ }
697
+
698
+ function addLeadingZeros(number, targetLength) {
699
+ var sign = number < 0 ? '-' : '';
700
+ var output = Math.abs(number).toString();
701
+
702
+ while (output.length < targetLength) {
703
+ output = '0' + output;
704
+ }
705
+
706
+ return sign + output;
707
+ }
708
+
709
+ /*
710
+ * | | Unit | | Unit |
711
+ * |-----|--------------------------------|-----|--------------------------------|
712
+ * | a | AM, PM | A* | |
713
+ * | d | Day of month | D | |
714
+ * | h | Hour [1-12] | H | Hour [0-23] |
715
+ * | m | Minute | M | Month |
716
+ * | s | Second | S | Fraction of second |
717
+ * | y | Year (abs) | Y | |
718
+ *
719
+ * Letters marked by * are not implemented but reserved by Unicode standard.
720
+ */
721
+
722
+ var formatters$1 = {
723
+ // Year
724
+ y: function y(date, token) {
725
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
726
+ // | Year | y | yy | yyy | yyyy | yyyyy |
727
+ // |----------|-------|----|-------|-------|-------|
728
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
729
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
730
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
731
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
732
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
733
+ var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
734
+
735
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
736
+ return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
737
+ },
738
+ // Month
739
+ M: function M(date, token) {
740
+ var month = date.getUTCMonth();
741
+ return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
742
+ },
743
+ // Day of the month
744
+ d: function d(date, token) {
745
+ return addLeadingZeros(date.getUTCDate(), token.length);
746
+ },
747
+ // AM or PM
748
+ a: function a(date, token) {
749
+ var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
750
+
751
+ switch (token) {
752
+ case 'a':
753
+ case 'aa':
754
+ return dayPeriodEnumValue.toUpperCase();
755
+
756
+ case 'aaa':
757
+ return dayPeriodEnumValue;
758
+
759
+ case 'aaaaa':
760
+ return dayPeriodEnumValue[0];
761
+
762
+ case 'aaaa':
763
+ default:
764
+ return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
765
+ }
766
+ },
767
+ // Hour [1-12]
768
+ h: function h(date, token) {
769
+ return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
770
+ },
771
+ // Hour [0-23]
772
+ H: function H(date, token) {
773
+ return addLeadingZeros(date.getUTCHours(), token.length);
774
+ },
775
+ // Minute
776
+ m: function m(date, token) {
777
+ return addLeadingZeros(date.getUTCMinutes(), token.length);
778
+ },
779
+ // Second
780
+ s: function s(date, token) {
781
+ return addLeadingZeros(date.getUTCSeconds(), token.length);
782
+ },
783
+ // Fraction of second
784
+ S: function S(date, token) {
785
+ var numberOfDigits = token.length;
786
+ var milliseconds = date.getUTCMilliseconds();
787
+ var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
788
+ return addLeadingZeros(fractionalSeconds, token.length);
789
+ }
790
+ };
791
+
792
+ var dayPeriodEnum = {
793
+ am: 'am',
794
+ pm: 'pm',
795
+ midnight: 'midnight',
796
+ noon: 'noon',
797
+ morning: 'morning',
798
+ afternoon: 'afternoon',
799
+ evening: 'evening',
800
+ night: 'night'
801
+ };
802
+
803
+ /*
804
+ * | | Unit | | Unit |
805
+ * |-----|--------------------------------|-----|--------------------------------|
806
+ * | a | AM, PM | A* | Milliseconds in day |
807
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
808
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
809
+ * | d | Day of month | D | Day of year |
810
+ * | e | Local day of week | E | Day of week |
811
+ * | f | | F* | Day of week in month |
812
+ * | g* | Modified Julian day | G | Era |
813
+ * | h | Hour [1-12] | H | Hour [0-23] |
814
+ * | i! | ISO day of week | I! | ISO week of year |
815
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
816
+ * | k | Hour [1-24] | K | Hour [0-11] |
817
+ * | l* | (deprecated) | L | Stand-alone month |
818
+ * | m | Minute | M | Month |
819
+ * | n | | N | |
820
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
821
+ * | p! | Long localized time | P! | Long localized date |
822
+ * | q | Stand-alone quarter | Q | Quarter |
823
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
824
+ * | s | Second | S | Fraction of second |
825
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
826
+ * | u | Extended year | U* | Cyclic year |
827
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
828
+ * | w | Local week of year | W* | Week of month |
829
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
830
+ * | y | Year (abs) | Y | Local week-numbering year |
831
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
832
+ *
833
+ * Letters marked by * are not implemented but reserved by Unicode standard.
834
+ *
835
+ * Letters marked by ! are non-standard, but implemented by date-fns:
836
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
837
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
838
+ * i.e. 7 for Sunday, 1 for Monday, etc.
839
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
840
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
841
+ * `R` is supposed to be used in conjunction with `I` and `i`
842
+ * for universal ISO week-numbering date, whereas
843
+ * `Y` is supposed to be used in conjunction with `w` and `e`
844
+ * for week-numbering date specific to the locale.
845
+ * - `P` is long localized date format
846
+ * - `p` is long localized time format
847
+ */
848
+ var formatters = {
849
+ // Era
850
+ G: function G(date, token, localize) {
851
+ var era = date.getUTCFullYear() > 0 ? 1 : 0;
852
+
853
+ switch (token) {
854
+ // AD, BC
855
+ case 'G':
856
+ case 'GG':
857
+ case 'GGG':
858
+ return localize.era(era, {
859
+ width: 'abbreviated'
860
+ });
861
+ // A, B
862
+
863
+ case 'GGGGG':
864
+ return localize.era(era, {
865
+ width: 'narrow'
866
+ });
867
+ // Anno Domini, Before Christ
868
+
869
+ case 'GGGG':
870
+ default:
871
+ return localize.era(era, {
872
+ width: 'wide'
873
+ });
874
+ }
875
+ },
876
+ // Year
877
+ y: function y(date, token, localize) {
878
+ // Ordinal number
879
+ if (token === 'yo') {
880
+ var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
881
+
882
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
883
+ return localize.ordinalNumber(year, {
884
+ unit: 'year'
885
+ });
886
+ }
887
+
888
+ return formatters$1.y(date, token);
889
+ },
890
+ // Local week-numbering year
891
+ Y: function Y(date, token, localize, options) {
892
+ var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
893
+
894
+ var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
895
+
896
+ if (token === 'YY') {
897
+ var twoDigitYear = weekYear % 100;
898
+ return addLeadingZeros(twoDigitYear, 2);
899
+ } // Ordinal number
900
+
901
+
902
+ if (token === 'Yo') {
903
+ return localize.ordinalNumber(weekYear, {
904
+ unit: 'year'
905
+ });
906
+ } // Padding
907
+
908
+
909
+ return addLeadingZeros(weekYear, token.length);
910
+ },
911
+ // ISO week-numbering year
912
+ R: function R(date, token) {
913
+ var isoWeekYear = getUTCISOWeekYear(date); // Padding
914
+
915
+ return addLeadingZeros(isoWeekYear, token.length);
916
+ },
917
+ // Extended year. This is a single number designating the year of this calendar system.
918
+ // The main difference between `y` and `u` localizers are B.C. years:
919
+ // | Year | `y` | `u` |
920
+ // |------|-----|-----|
921
+ // | AC 1 | 1 | 1 |
922
+ // | BC 1 | 1 | 0 |
923
+ // | BC 2 | 2 | -1 |
924
+ // Also `yy` always returns the last two digits of a year,
925
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
926
+ u: function u(date, token) {
927
+ var year = date.getUTCFullYear();
928
+ return addLeadingZeros(year, token.length);
929
+ },
930
+ // Quarter
931
+ Q: function Q(date, token, localize) {
932
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
933
+
934
+ switch (token) {
935
+ // 1, 2, 3, 4
936
+ case 'Q':
937
+ return String(quarter);
938
+ // 01, 02, 03, 04
939
+
940
+ case 'QQ':
941
+ return addLeadingZeros(quarter, 2);
942
+ // 1st, 2nd, 3rd, 4th
943
+
944
+ case 'Qo':
945
+ return localize.ordinalNumber(quarter, {
946
+ unit: 'quarter'
947
+ });
948
+ // Q1, Q2, Q3, Q4
949
+
950
+ case 'QQQ':
951
+ return localize.quarter(quarter, {
952
+ width: 'abbreviated',
953
+ context: 'formatting'
954
+ });
955
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
956
+
957
+ case 'QQQQQ':
958
+ return localize.quarter(quarter, {
959
+ width: 'narrow',
960
+ context: 'formatting'
961
+ });
962
+ // 1st quarter, 2nd quarter, ...
963
+
964
+ case 'QQQQ':
965
+ default:
966
+ return localize.quarter(quarter, {
967
+ width: 'wide',
968
+ context: 'formatting'
969
+ });
970
+ }
971
+ },
972
+ // Stand-alone quarter
973
+ q: function q(date, token, localize) {
974
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
975
+
976
+ switch (token) {
977
+ // 1, 2, 3, 4
978
+ case 'q':
979
+ return String(quarter);
980
+ // 01, 02, 03, 04
981
+
982
+ case 'qq':
983
+ return addLeadingZeros(quarter, 2);
984
+ // 1st, 2nd, 3rd, 4th
985
+
986
+ case 'qo':
987
+ return localize.ordinalNumber(quarter, {
988
+ unit: 'quarter'
989
+ });
990
+ // Q1, Q2, Q3, Q4
991
+
992
+ case 'qqq':
993
+ return localize.quarter(quarter, {
994
+ width: 'abbreviated',
995
+ context: 'standalone'
996
+ });
997
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
998
+
999
+ case 'qqqqq':
1000
+ return localize.quarter(quarter, {
1001
+ width: 'narrow',
1002
+ context: 'standalone'
1003
+ });
1004
+ // 1st quarter, 2nd quarter, ...
1005
+
1006
+ case 'qqqq':
1007
+ default:
1008
+ return localize.quarter(quarter, {
1009
+ width: 'wide',
1010
+ context: 'standalone'
1011
+ });
1012
+ }
1013
+ },
1014
+ // Month
1015
+ M: function M(date, token, localize) {
1016
+ var month = date.getUTCMonth();
1017
+
1018
+ switch (token) {
1019
+ case 'M':
1020
+ case 'MM':
1021
+ return formatters$1.M(date, token);
1022
+ // 1st, 2nd, ..., 12th
1023
+
1024
+ case 'Mo':
1025
+ return localize.ordinalNumber(month + 1, {
1026
+ unit: 'month'
1027
+ });
1028
+ // Jan, Feb, ..., Dec
1029
+
1030
+ case 'MMM':
1031
+ return localize.month(month, {
1032
+ width: 'abbreviated',
1033
+ context: 'formatting'
1034
+ });
1035
+ // J, F, ..., D
1036
+
1037
+ case 'MMMMM':
1038
+ return localize.month(month, {
1039
+ width: 'narrow',
1040
+ context: 'formatting'
1041
+ });
1042
+ // January, February, ..., December
1043
+
1044
+ case 'MMMM':
1045
+ default:
1046
+ return localize.month(month, {
1047
+ width: 'wide',
1048
+ context: 'formatting'
1049
+ });
1050
+ }
1051
+ },
1052
+ // Stand-alone month
1053
+ L: function L(date, token, localize) {
1054
+ var month = date.getUTCMonth();
1055
+
1056
+ switch (token) {
1057
+ // 1, 2, ..., 12
1058
+ case 'L':
1059
+ return String(month + 1);
1060
+ // 01, 02, ..., 12
1061
+
1062
+ case 'LL':
1063
+ return addLeadingZeros(month + 1, 2);
1064
+ // 1st, 2nd, ..., 12th
1065
+
1066
+ case 'Lo':
1067
+ return localize.ordinalNumber(month + 1, {
1068
+ unit: 'month'
1069
+ });
1070
+ // Jan, Feb, ..., Dec
1071
+
1072
+ case 'LLL':
1073
+ return localize.month(month, {
1074
+ width: 'abbreviated',
1075
+ context: 'standalone'
1076
+ });
1077
+ // J, F, ..., D
1078
+
1079
+ case 'LLLLL':
1080
+ return localize.month(month, {
1081
+ width: 'narrow',
1082
+ context: 'standalone'
1083
+ });
1084
+ // January, February, ..., December
1085
+
1086
+ case 'LLLL':
1087
+ default:
1088
+ return localize.month(month, {
1089
+ width: 'wide',
1090
+ context: 'standalone'
1091
+ });
1092
+ }
1093
+ },
1094
+ // Local week of year
1095
+ w: function w(date, token, localize, options) {
1096
+ var week = getUTCWeek(date, options);
1097
+
1098
+ if (token === 'wo') {
1099
+ return localize.ordinalNumber(week, {
1100
+ unit: 'week'
1101
+ });
1102
+ }
1103
+
1104
+ return addLeadingZeros(week, token.length);
1105
+ },
1106
+ // ISO week of year
1107
+ I: function I(date, token, localize) {
1108
+ var isoWeek = getUTCISOWeek(date);
1109
+
1110
+ if (token === 'Io') {
1111
+ return localize.ordinalNumber(isoWeek, {
1112
+ unit: 'week'
1113
+ });
1114
+ }
1115
+
1116
+ return addLeadingZeros(isoWeek, token.length);
1117
+ },
1118
+ // Day of the month
1119
+ d: function d(date, token, localize) {
1120
+ if (token === 'do') {
1121
+ return localize.ordinalNumber(date.getUTCDate(), {
1122
+ unit: 'date'
1123
+ });
1124
+ }
1125
+
1126
+ return formatters$1.d(date, token);
1127
+ },
1128
+ // Day of year
1129
+ D: function D(date, token, localize) {
1130
+ var dayOfYear = getUTCDayOfYear(date);
1131
+
1132
+ if (token === 'Do') {
1133
+ return localize.ordinalNumber(dayOfYear, {
1134
+ unit: 'dayOfYear'
1135
+ });
1136
+ }
1137
+
1138
+ return addLeadingZeros(dayOfYear, token.length);
1139
+ },
1140
+ // Day of week
1141
+ E: function E(date, token, localize) {
1142
+ var dayOfWeek = date.getUTCDay();
1143
+
1144
+ switch (token) {
1145
+ // Tue
1146
+ case 'E':
1147
+ case 'EE':
1148
+ case 'EEE':
1149
+ return localize.day(dayOfWeek, {
1150
+ width: 'abbreviated',
1151
+ context: 'formatting'
1152
+ });
1153
+ // T
1154
+
1155
+ case 'EEEEE':
1156
+ return localize.day(dayOfWeek, {
1157
+ width: 'narrow',
1158
+ context: 'formatting'
1159
+ });
1160
+ // Tu
1161
+
1162
+ case 'EEEEEE':
1163
+ return localize.day(dayOfWeek, {
1164
+ width: 'short',
1165
+ context: 'formatting'
1166
+ });
1167
+ // Tuesday
1168
+
1169
+ case 'EEEE':
1170
+ default:
1171
+ return localize.day(dayOfWeek, {
1172
+ width: 'wide',
1173
+ context: 'formatting'
1174
+ });
1175
+ }
1176
+ },
1177
+ // Local day of week
1178
+ e: function e(date, token, localize, options) {
1179
+ var dayOfWeek = date.getUTCDay();
1180
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1181
+
1182
+ switch (token) {
1183
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
1184
+ case 'e':
1185
+ return String(localDayOfWeek);
1186
+ // Padded numerical value
1187
+
1188
+ case 'ee':
1189
+ return addLeadingZeros(localDayOfWeek, 2);
1190
+ // 1st, 2nd, ..., 7th
1191
+
1192
+ case 'eo':
1193
+ return localize.ordinalNumber(localDayOfWeek, {
1194
+ unit: 'day'
1195
+ });
1196
+
1197
+ case 'eee':
1198
+ return localize.day(dayOfWeek, {
1199
+ width: 'abbreviated',
1200
+ context: 'formatting'
1201
+ });
1202
+ // T
1203
+
1204
+ case 'eeeee':
1205
+ return localize.day(dayOfWeek, {
1206
+ width: 'narrow',
1207
+ context: 'formatting'
1208
+ });
1209
+ // Tu
1210
+
1211
+ case 'eeeeee':
1212
+ return localize.day(dayOfWeek, {
1213
+ width: 'short',
1214
+ context: 'formatting'
1215
+ });
1216
+ // Tuesday
1217
+
1218
+ case 'eeee':
1219
+ default:
1220
+ return localize.day(dayOfWeek, {
1221
+ width: 'wide',
1222
+ context: 'formatting'
1223
+ });
1224
+ }
1225
+ },
1226
+ // Stand-alone local day of week
1227
+ c: function c(date, token, localize, options) {
1228
+ var dayOfWeek = date.getUTCDay();
1229
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1230
+
1231
+ switch (token) {
1232
+ // Numerical value (same as in `e`)
1233
+ case 'c':
1234
+ return String(localDayOfWeek);
1235
+ // Padded numerical value
1236
+
1237
+ case 'cc':
1238
+ return addLeadingZeros(localDayOfWeek, token.length);
1239
+ // 1st, 2nd, ..., 7th
1240
+
1241
+ case 'co':
1242
+ return localize.ordinalNumber(localDayOfWeek, {
1243
+ unit: 'day'
1244
+ });
1245
+
1246
+ case 'ccc':
1247
+ return localize.day(dayOfWeek, {
1248
+ width: 'abbreviated',
1249
+ context: 'standalone'
1250
+ });
1251
+ // T
1252
+
1253
+ case 'ccccc':
1254
+ return localize.day(dayOfWeek, {
1255
+ width: 'narrow',
1256
+ context: 'standalone'
1257
+ });
1258
+ // Tu
1259
+
1260
+ case 'cccccc':
1261
+ return localize.day(dayOfWeek, {
1262
+ width: 'short',
1263
+ context: 'standalone'
1264
+ });
1265
+ // Tuesday
1266
+
1267
+ case 'cccc':
1268
+ default:
1269
+ return localize.day(dayOfWeek, {
1270
+ width: 'wide',
1271
+ context: 'standalone'
1272
+ });
1273
+ }
1274
+ },
1275
+ // ISO day of week
1276
+ i: function i(date, token, localize) {
1277
+ var dayOfWeek = date.getUTCDay();
1278
+ var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
1279
+
1280
+ switch (token) {
1281
+ // 2
1282
+ case 'i':
1283
+ return String(isoDayOfWeek);
1284
+ // 02
1285
+
1286
+ case 'ii':
1287
+ return addLeadingZeros(isoDayOfWeek, token.length);
1288
+ // 2nd
1289
+
1290
+ case 'io':
1291
+ return localize.ordinalNumber(isoDayOfWeek, {
1292
+ unit: 'day'
1293
+ });
1294
+ // Tue
1295
+
1296
+ case 'iii':
1297
+ return localize.day(dayOfWeek, {
1298
+ width: 'abbreviated',
1299
+ context: 'formatting'
1300
+ });
1301
+ // T
1302
+
1303
+ case 'iiiii':
1304
+ return localize.day(dayOfWeek, {
1305
+ width: 'narrow',
1306
+ context: 'formatting'
1307
+ });
1308
+ // Tu
1309
+
1310
+ case 'iiiiii':
1311
+ return localize.day(dayOfWeek, {
1312
+ width: 'short',
1313
+ context: 'formatting'
1314
+ });
1315
+ // Tuesday
1316
+
1317
+ case 'iiii':
1318
+ default:
1319
+ return localize.day(dayOfWeek, {
1320
+ width: 'wide',
1321
+ context: 'formatting'
1322
+ });
1323
+ }
1324
+ },
1325
+ // AM or PM
1326
+ a: function a(date, token, localize) {
1327
+ var hours = date.getUTCHours();
1328
+ var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1329
+
1330
+ switch (token) {
1331
+ case 'a':
1332
+ case 'aa':
1333
+ return localize.dayPeriod(dayPeriodEnumValue, {
1334
+ width: 'abbreviated',
1335
+ context: 'formatting'
1336
+ });
1337
+
1338
+ case 'aaa':
1339
+ return localize.dayPeriod(dayPeriodEnumValue, {
1340
+ width: 'abbreviated',
1341
+ context: 'formatting'
1342
+ }).toLowerCase();
1343
+
1344
+ case 'aaaaa':
1345
+ return localize.dayPeriod(dayPeriodEnumValue, {
1346
+ width: 'narrow',
1347
+ context: 'formatting'
1348
+ });
1349
+
1350
+ case 'aaaa':
1351
+ default:
1352
+ return localize.dayPeriod(dayPeriodEnumValue, {
1353
+ width: 'wide',
1354
+ context: 'formatting'
1355
+ });
1356
+ }
1357
+ },
1358
+ // AM, PM, midnight, noon
1359
+ b: function b(date, token, localize) {
1360
+ var hours = date.getUTCHours();
1361
+ var dayPeriodEnumValue;
1362
+
1363
+ if (hours === 12) {
1364
+ dayPeriodEnumValue = dayPeriodEnum.noon;
1365
+ } else if (hours === 0) {
1366
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
1367
+ } else {
1368
+ dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1369
+ }
1370
+
1371
+ switch (token) {
1372
+ case 'b':
1373
+ case 'bb':
1374
+ return localize.dayPeriod(dayPeriodEnumValue, {
1375
+ width: 'abbreviated',
1376
+ context: 'formatting'
1377
+ });
1378
+
1379
+ case 'bbb':
1380
+ return localize.dayPeriod(dayPeriodEnumValue, {
1381
+ width: 'abbreviated',
1382
+ context: 'formatting'
1383
+ }).toLowerCase();
1384
+
1385
+ case 'bbbbb':
1386
+ return localize.dayPeriod(dayPeriodEnumValue, {
1387
+ width: 'narrow',
1388
+ context: 'formatting'
1389
+ });
1390
+
1391
+ case 'bbbb':
1392
+ default:
1393
+ return localize.dayPeriod(dayPeriodEnumValue, {
1394
+ width: 'wide',
1395
+ context: 'formatting'
1396
+ });
1397
+ }
1398
+ },
1399
+ // in the morning, in the afternoon, in the evening, at night
1400
+ B: function B(date, token, localize) {
1401
+ var hours = date.getUTCHours();
1402
+ var dayPeriodEnumValue;
1403
+
1404
+ if (hours >= 17) {
1405
+ dayPeriodEnumValue = dayPeriodEnum.evening;
1406
+ } else if (hours >= 12) {
1407
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
1408
+ } else if (hours >= 4) {
1409
+ dayPeriodEnumValue = dayPeriodEnum.morning;
1410
+ } else {
1411
+ dayPeriodEnumValue = dayPeriodEnum.night;
1412
+ }
1413
+
1414
+ switch (token) {
1415
+ case 'B':
1416
+ case 'BB':
1417
+ case 'BBB':
1418
+ return localize.dayPeriod(dayPeriodEnumValue, {
1419
+ width: 'abbreviated',
1420
+ context: 'formatting'
1421
+ });
1422
+
1423
+ case 'BBBBB':
1424
+ return localize.dayPeriod(dayPeriodEnumValue, {
1425
+ width: 'narrow',
1426
+ context: 'formatting'
1427
+ });
1428
+
1429
+ case 'BBBB':
1430
+ default:
1431
+ return localize.dayPeriod(dayPeriodEnumValue, {
1432
+ width: 'wide',
1433
+ context: 'formatting'
1434
+ });
1435
+ }
1436
+ },
1437
+ // Hour [1-12]
1438
+ h: function h(date, token, localize) {
1439
+ if (token === 'ho') {
1440
+ var hours = date.getUTCHours() % 12;
1441
+ if (hours === 0) hours = 12;
1442
+ return localize.ordinalNumber(hours, {
1443
+ unit: 'hour'
1444
+ });
1445
+ }
1446
+
1447
+ return formatters$1.h(date, token);
1448
+ },
1449
+ // Hour [0-23]
1450
+ H: function H(date, token, localize) {
1451
+ if (token === 'Ho') {
1452
+ return localize.ordinalNumber(date.getUTCHours(), {
1453
+ unit: 'hour'
1454
+ });
1455
+ }
1456
+
1457
+ return formatters$1.H(date, token);
1458
+ },
1459
+ // Hour [0-11]
1460
+ K: function K(date, token, localize) {
1461
+ var hours = date.getUTCHours() % 12;
1462
+
1463
+ if (token === 'Ko') {
1464
+ return localize.ordinalNumber(hours, {
1465
+ unit: 'hour'
1466
+ });
1467
+ }
1468
+
1469
+ return addLeadingZeros(hours, token.length);
1470
+ },
1471
+ // Hour [1-24]
1472
+ k: function k(date, token, localize) {
1473
+ var hours = date.getUTCHours();
1474
+ if (hours === 0) hours = 24;
1475
+
1476
+ if (token === 'ko') {
1477
+ return localize.ordinalNumber(hours, {
1478
+ unit: 'hour'
1479
+ });
1480
+ }
1481
+
1482
+ return addLeadingZeros(hours, token.length);
1483
+ },
1484
+ // Minute
1485
+ m: function m(date, token, localize) {
1486
+ if (token === 'mo') {
1487
+ return localize.ordinalNumber(date.getUTCMinutes(), {
1488
+ unit: 'minute'
1489
+ });
1490
+ }
1491
+
1492
+ return formatters$1.m(date, token);
1493
+ },
1494
+ // Second
1495
+ s: function s(date, token, localize) {
1496
+ if (token === 'so') {
1497
+ return localize.ordinalNumber(date.getUTCSeconds(), {
1498
+ unit: 'second'
1499
+ });
1500
+ }
1501
+
1502
+ return formatters$1.s(date, token);
1503
+ },
1504
+ // Fraction of second
1505
+ S: function S(date, token) {
1506
+ return formatters$1.S(date, token);
1507
+ },
1508
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
1509
+ X: function X(date, token, _localize, options) {
1510
+ var originalDate = options._originalDate || date;
1511
+ var timezoneOffset = originalDate.getTimezoneOffset();
1512
+
1513
+ if (timezoneOffset === 0) {
1514
+ return 'Z';
1515
+ }
1516
+
1517
+ switch (token) {
1518
+ // Hours and optional minutes
1519
+ case 'X':
1520
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1521
+ // Hours, minutes and optional seconds without `:` delimiter
1522
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1523
+ // so this token always has the same output as `XX`
1524
+
1525
+ case 'XXXX':
1526
+ case 'XX':
1527
+ // Hours and minutes without `:` delimiter
1528
+ return formatTimezone(timezoneOffset);
1529
+ // Hours, minutes and optional seconds with `:` delimiter
1530
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1531
+ // so this token always has the same output as `XXX`
1532
+
1533
+ case 'XXXXX':
1534
+ case 'XXX': // Hours and minutes with `:` delimiter
1535
+
1536
+ default:
1537
+ return formatTimezone(timezoneOffset, ':');
1538
+ }
1539
+ },
1540
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
1541
+ x: function x(date, token, _localize, options) {
1542
+ var originalDate = options._originalDate || date;
1543
+ var timezoneOffset = originalDate.getTimezoneOffset();
1544
+
1545
+ switch (token) {
1546
+ // Hours and optional minutes
1547
+ case 'x':
1548
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1549
+ // Hours, minutes and optional seconds without `:` delimiter
1550
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1551
+ // so this token always has the same output as `xx`
1552
+
1553
+ case 'xxxx':
1554
+ case 'xx':
1555
+ // Hours and minutes without `:` delimiter
1556
+ return formatTimezone(timezoneOffset);
1557
+ // Hours, minutes and optional seconds with `:` delimiter
1558
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1559
+ // so this token always has the same output as `xxx`
1560
+
1561
+ case 'xxxxx':
1562
+ case 'xxx': // Hours and minutes with `:` delimiter
1563
+
1564
+ default:
1565
+ return formatTimezone(timezoneOffset, ':');
1566
+ }
1567
+ },
1568
+ // Timezone (GMT)
1569
+ O: function O(date, token, _localize, options) {
1570
+ var originalDate = options._originalDate || date;
1571
+ var timezoneOffset = originalDate.getTimezoneOffset();
1572
+
1573
+ switch (token) {
1574
+ // Short
1575
+ case 'O':
1576
+ case 'OO':
1577
+ case 'OOO':
1578
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1579
+ // Long
1580
+
1581
+ case 'OOOO':
1582
+ default:
1583
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1584
+ }
1585
+ },
1586
+ // Timezone (specific non-location)
1587
+ z: function z(date, token, _localize, options) {
1588
+ var originalDate = options._originalDate || date;
1589
+ var timezoneOffset = originalDate.getTimezoneOffset();
1590
+
1591
+ switch (token) {
1592
+ // Short
1593
+ case 'z':
1594
+ case 'zz':
1595
+ case 'zzz':
1596
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1597
+ // Long
1598
+
1599
+ case 'zzzz':
1600
+ default:
1601
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1602
+ }
1603
+ },
1604
+ // Seconds timestamp
1605
+ t: function t(date, token, _localize, options) {
1606
+ var originalDate = options._originalDate || date;
1607
+ var timestamp = Math.floor(originalDate.getTime() / 1000);
1608
+ return addLeadingZeros(timestamp, token.length);
1609
+ },
1610
+ // Milliseconds timestamp
1611
+ T: function T(date, token, _localize, options) {
1612
+ var originalDate = options._originalDate || date;
1613
+ var timestamp = originalDate.getTime();
1614
+ return addLeadingZeros(timestamp, token.length);
1615
+ }
1616
+ };
1617
+
1618
+ function formatTimezoneShort(offset, dirtyDelimiter) {
1619
+ var sign = offset > 0 ? '-' : '+';
1620
+ var absOffset = Math.abs(offset);
1621
+ var hours = Math.floor(absOffset / 60);
1622
+ var minutes = absOffset % 60;
1623
+
1624
+ if (minutes === 0) {
1625
+ return sign + String(hours);
1626
+ }
1627
+
1628
+ var delimiter = dirtyDelimiter || '';
1629
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
1630
+ }
1631
+
1632
+ function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
1633
+ if (offset % 60 === 0) {
1634
+ var sign = offset > 0 ? '-' : '+';
1635
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
1636
+ }
1637
+
1638
+ return formatTimezone(offset, dirtyDelimiter);
1639
+ }
1640
+
1641
+ function formatTimezone(offset, dirtyDelimiter) {
1642
+ var delimiter = dirtyDelimiter || '';
1643
+ var sign = offset > 0 ? '-' : '+';
1644
+ var absOffset = Math.abs(offset);
1645
+ var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
1646
+ var minutes = addLeadingZeros(absOffset % 60, 2);
1647
+ return sign + hours + delimiter + minutes;
1648
+ }
1649
+
1650
+ var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
1651
+ switch (pattern) {
1652
+ case 'P':
1653
+ return formatLong.date({
1654
+ width: 'short'
1655
+ });
1656
+
1657
+ case 'PP':
1658
+ return formatLong.date({
1659
+ width: 'medium'
1660
+ });
1661
+
1662
+ case 'PPP':
1663
+ return formatLong.date({
1664
+ width: 'long'
1665
+ });
1666
+
1667
+ case 'PPPP':
1668
+ default:
1669
+ return formatLong.date({
1670
+ width: 'full'
1671
+ });
1672
+ }
1673
+ };
1674
+
1675
+ var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
1676
+ switch (pattern) {
1677
+ case 'p':
1678
+ return formatLong.time({
1679
+ width: 'short'
1680
+ });
1681
+
1682
+ case 'pp':
1683
+ return formatLong.time({
1684
+ width: 'medium'
1685
+ });
1686
+
1687
+ case 'ppp':
1688
+ return formatLong.time({
1689
+ width: 'long'
1690
+ });
1691
+
1692
+ case 'pppp':
1693
+ default:
1694
+ return formatLong.time({
1695
+ width: 'full'
1696
+ });
1697
+ }
1698
+ };
1699
+
1700
+ var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
1701
+ var matchResult = pattern.match(/(P+)(p+)?/) || [];
1702
+ var datePattern = matchResult[1];
1703
+ var timePattern = matchResult[2];
1704
+
1705
+ if (!timePattern) {
1706
+ return dateLongFormatter(pattern, formatLong);
1707
+ }
1708
+
1709
+ var dateTimeFormat;
1710
+
1711
+ switch (datePattern) {
1712
+ case 'P':
1713
+ dateTimeFormat = formatLong.dateTime({
1714
+ width: 'short'
1715
+ });
1716
+ break;
1717
+
1718
+ case 'PP':
1719
+ dateTimeFormat = formatLong.dateTime({
1720
+ width: 'medium'
1721
+ });
1722
+ break;
1723
+
1724
+ case 'PPP':
1725
+ dateTimeFormat = formatLong.dateTime({
1726
+ width: 'long'
1727
+ });
1728
+ break;
1729
+
1730
+ case 'PPPP':
1731
+ default:
1732
+ dateTimeFormat = formatLong.dateTime({
1733
+ width: 'full'
1734
+ });
1735
+ break;
1736
+ }
1737
+
1738
+ return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
1739
+ };
1740
+
1741
+ var longFormatters = {
1742
+ p: timeLongFormatter,
1743
+ P: dateTimeLongFormatter
1744
+ };
1745
+
1746
+ var protectedDayOfYearTokens = ['D', 'DD'];
1747
+ var protectedWeekYearTokens = ['YY', 'YYYY'];
1748
+ function isProtectedDayOfYearToken(token) {
1749
+ return protectedDayOfYearTokens.indexOf(token) !== -1;
1750
+ }
1751
+ function isProtectedWeekYearToken(token) {
1752
+ return protectedWeekYearTokens.indexOf(token) !== -1;
1753
+ }
1754
+ function throwProtectedError(token, format, input) {
1755
+ if (token === 'YYYY') {
1756
+ throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1757
+ } else if (token === 'YY') {
1758
+ throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1759
+ } else if (token === 'D') {
1760
+ throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1761
+ } else if (token === 'DD') {
1762
+ throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1763
+ }
1764
+ }
1765
+
1766
+ var formatDistanceLocale = {
1767
+ lessThanXSeconds: {
1768
+ one: 'less than a second',
1769
+ other: 'less than {{count}} seconds'
1770
+ },
1771
+ xSeconds: {
1772
+ one: '1 second',
1773
+ other: '{{count}} seconds'
1774
+ },
1775
+ halfAMinute: 'half a minute',
1776
+ lessThanXMinutes: {
1777
+ one: 'less than a minute',
1778
+ other: 'less than {{count}} minutes'
1779
+ },
1780
+ xMinutes: {
1781
+ one: '1 minute',
1782
+ other: '{{count}} minutes'
1783
+ },
1784
+ aboutXHours: {
1785
+ one: 'about 1 hour',
1786
+ other: 'about {{count}} hours'
1787
+ },
1788
+ xHours: {
1789
+ one: '1 hour',
1790
+ other: '{{count}} hours'
1791
+ },
1792
+ xDays: {
1793
+ one: '1 day',
1794
+ other: '{{count}} days'
1795
+ },
1796
+ aboutXWeeks: {
1797
+ one: 'about 1 week',
1798
+ other: 'about {{count}} weeks'
1799
+ },
1800
+ xWeeks: {
1801
+ one: '1 week',
1802
+ other: '{{count}} weeks'
1803
+ },
1804
+ aboutXMonths: {
1805
+ one: 'about 1 month',
1806
+ other: 'about {{count}} months'
1807
+ },
1808
+ xMonths: {
1809
+ one: '1 month',
1810
+ other: '{{count}} months'
1811
+ },
1812
+ aboutXYears: {
1813
+ one: 'about 1 year',
1814
+ other: 'about {{count}} years'
1815
+ },
1816
+ xYears: {
1817
+ one: '1 year',
1818
+ other: '{{count}} years'
1819
+ },
1820
+ overXYears: {
1821
+ one: 'over 1 year',
1822
+ other: 'over {{count}} years'
1823
+ },
1824
+ almostXYears: {
1825
+ one: 'almost 1 year',
1826
+ other: 'almost {{count}} years'
1827
+ }
1828
+ };
1829
+
1830
+ var formatDistance = function formatDistance(token, count, options) {
1831
+ var result;
1832
+ var tokenValue = formatDistanceLocale[token];
1833
+
1834
+ if (typeof tokenValue === 'string') {
1835
+ result = tokenValue;
1836
+ } else if (count === 1) {
1837
+ result = tokenValue.one;
1838
+ } else {
1839
+ result = tokenValue.other.replace('{{count}}', count.toString());
1840
+ }
1841
+
1842
+ if (options !== null && options !== void 0 && options.addSuffix) {
1843
+ if (options.comparison && options.comparison > 0) {
1844
+ return 'in ' + result;
1845
+ } else {
1846
+ return result + ' ago';
1847
+ }
1848
+ }
1849
+
1850
+ return result;
1851
+ };
1852
+
1853
+ function buildFormatLongFn(args) {
1854
+ return function () {
1855
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1856
+ // TODO: Remove String()
1857
+ var width = options.width ? String(options.width) : args.defaultWidth;
1858
+ var format = args.formats[width] || args.formats[args.defaultWidth];
1859
+ return format;
1860
+ };
1861
+ }
1862
+
1863
+ var dateFormats = {
1864
+ full: 'EEEE, MMMM do, y',
1865
+ long: 'MMMM do, y',
1866
+ medium: 'MMM d, y',
1867
+ short: 'MM/dd/yyyy'
1868
+ };
1869
+ var timeFormats = {
1870
+ full: 'h:mm:ss a zzzz',
1871
+ long: 'h:mm:ss a z',
1872
+ medium: 'h:mm:ss a',
1873
+ short: 'h:mm a'
1874
+ };
1875
+ var dateTimeFormats = {
1876
+ full: "{{date}} 'at' {{time}}",
1877
+ long: "{{date}} 'at' {{time}}",
1878
+ medium: '{{date}}, {{time}}',
1879
+ short: '{{date}}, {{time}}'
1880
+ };
1881
+ var formatLong = {
1882
+ date: buildFormatLongFn({
1883
+ formats: dateFormats,
1884
+ defaultWidth: 'full'
1885
+ }),
1886
+ time: buildFormatLongFn({
1887
+ formats: timeFormats,
1888
+ defaultWidth: 'full'
1889
+ }),
1890
+ dateTime: buildFormatLongFn({
1891
+ formats: dateTimeFormats,
1892
+ defaultWidth: 'full'
1893
+ })
1894
+ };
1895
+
1896
+ var formatRelativeLocale = {
1897
+ lastWeek: "'last' eeee 'at' p",
1898
+ yesterday: "'yesterday at' p",
1899
+ today: "'today at' p",
1900
+ tomorrow: "'tomorrow at' p",
1901
+ nextWeek: "eeee 'at' p",
1902
+ other: 'P'
1903
+ };
1904
+
1905
+ var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
1906
+ return formatRelativeLocale[token];
1907
+ };
1908
+
1909
+ function buildLocalizeFn(args) {
1910
+ return function (dirtyIndex, options) {
1911
+ var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
1912
+ var valuesArray;
1913
+
1914
+ if (context === 'formatting' && args.formattingValues) {
1915
+ var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1916
+ var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
1917
+ valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
1918
+ } else {
1919
+ var _defaultWidth = args.defaultWidth;
1920
+
1921
+ var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
1922
+
1923
+ valuesArray = args.values[_width] || args.values[_defaultWidth];
1924
+ }
1925
+
1926
+ var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
1927
+
1928
+ return valuesArray[index];
1929
+ };
1930
+ }
1931
+
1932
+ var eraValues = {
1933
+ narrow: ['B', 'A'],
1934
+ abbreviated: ['BC', 'AD'],
1935
+ wide: ['Before Christ', 'Anno Domini']
1936
+ };
1937
+ var quarterValues = {
1938
+ narrow: ['1', '2', '3', '4'],
1939
+ abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
1940
+ wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
1941
+ }; // Note: in English, the names of days of the week and months are capitalized.
1942
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1943
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1944
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1945
+
1946
+ var monthValues = {
1947
+ narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
1948
+ abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
1949
+ wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
1950
+ };
1951
+ var dayValues = {
1952
+ narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
1953
+ short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
1954
+ abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
1955
+ wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
1956
+ };
1957
+ var dayPeriodValues = {
1958
+ narrow: {
1959
+ am: 'a',
1960
+ pm: 'p',
1961
+ midnight: 'mi',
1962
+ noon: 'n',
1963
+ morning: 'morning',
1964
+ afternoon: 'afternoon',
1965
+ evening: 'evening',
1966
+ night: 'night'
1967
+ },
1968
+ abbreviated: {
1969
+ am: 'AM',
1970
+ pm: 'PM',
1971
+ midnight: 'midnight',
1972
+ noon: 'noon',
1973
+ morning: 'morning',
1974
+ afternoon: 'afternoon',
1975
+ evening: 'evening',
1976
+ night: 'night'
1977
+ },
1978
+ wide: {
1979
+ am: 'a.m.',
1980
+ pm: 'p.m.',
1981
+ midnight: 'midnight',
1982
+ noon: 'noon',
1983
+ morning: 'morning',
1984
+ afternoon: 'afternoon',
1985
+ evening: 'evening',
1986
+ night: 'night'
1987
+ }
1988
+ };
1989
+ var formattingDayPeriodValues = {
1990
+ narrow: {
1991
+ am: 'a',
1992
+ pm: 'p',
1993
+ midnight: 'mi',
1994
+ noon: 'n',
1995
+ morning: 'in the morning',
1996
+ afternoon: 'in the afternoon',
1997
+ evening: 'in the evening',
1998
+ night: 'at night'
1999
+ },
2000
+ abbreviated: {
2001
+ am: 'AM',
2002
+ pm: 'PM',
2003
+ midnight: 'midnight',
2004
+ noon: 'noon',
2005
+ morning: 'in the morning',
2006
+ afternoon: 'in the afternoon',
2007
+ evening: 'in the evening',
2008
+ night: 'at night'
2009
+ },
2010
+ wide: {
2011
+ am: 'a.m.',
2012
+ pm: 'p.m.',
2013
+ midnight: 'midnight',
2014
+ noon: 'noon',
2015
+ morning: 'in the morning',
2016
+ afternoon: 'in the afternoon',
2017
+ evening: 'in the evening',
2018
+ night: 'at night'
2019
+ }
2020
+ };
2021
+
2022
+ var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
2023
+ var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
2024
+ // if they are different for different grammatical genders,
2025
+ // use `options.unit`.
2026
+ //
2027
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
2028
+ // 'day', 'hour', 'minute', 'second'.
2029
+
2030
+ var rem100 = number % 100;
2031
+
2032
+ if (rem100 > 20 || rem100 < 10) {
2033
+ switch (rem100 % 10) {
2034
+ case 1:
2035
+ return number + 'st';
2036
+
2037
+ case 2:
2038
+ return number + 'nd';
2039
+
2040
+ case 3:
2041
+ return number + 'rd';
2042
+ }
2043
+ }
2044
+
2045
+ return number + 'th';
2046
+ };
2047
+
2048
+ var localize = {
2049
+ ordinalNumber: ordinalNumber,
2050
+ era: buildLocalizeFn({
2051
+ values: eraValues,
2052
+ defaultWidth: 'wide'
2053
+ }),
2054
+ quarter: buildLocalizeFn({
2055
+ values: quarterValues,
2056
+ defaultWidth: 'wide',
2057
+ argumentCallback: function argumentCallback(quarter) {
2058
+ return quarter - 1;
2059
+ }
2060
+ }),
2061
+ month: buildLocalizeFn({
2062
+ values: monthValues,
2063
+ defaultWidth: 'wide'
2064
+ }),
2065
+ day: buildLocalizeFn({
2066
+ values: dayValues,
2067
+ defaultWidth: 'wide'
2068
+ }),
2069
+ dayPeriod: buildLocalizeFn({
2070
+ values: dayPeriodValues,
2071
+ defaultWidth: 'wide',
2072
+ formattingValues: formattingDayPeriodValues,
2073
+ defaultFormattingWidth: 'wide'
2074
+ })
2075
+ };
2076
+
2077
+ function buildMatchFn(args) {
2078
+ return function (string) {
2079
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2080
+ var width = options.width;
2081
+ var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
2082
+ var matchResult = string.match(matchPattern);
2083
+
2084
+ if (!matchResult) {
2085
+ return null;
2086
+ }
2087
+
2088
+ var matchedString = matchResult[0];
2089
+ var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
2090
+ var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
2091
+ return pattern.test(matchedString);
2092
+ }) : findKey(parsePatterns, function (pattern) {
2093
+ return pattern.test(matchedString);
2094
+ });
2095
+ var value;
2096
+ value = args.valueCallback ? args.valueCallback(key) : key;
2097
+ value = options.valueCallback ? options.valueCallback(value) : value;
2098
+ var rest = string.slice(matchedString.length);
2099
+ return {
2100
+ value: value,
2101
+ rest: rest
2102
+ };
2103
+ };
2104
+ }
2105
+
2106
+ function findKey(object, predicate) {
2107
+ for (var key in object) {
2108
+ if (object.hasOwnProperty(key) && predicate(object[key])) {
2109
+ return key;
2110
+ }
2111
+ }
2112
+
2113
+ return undefined;
2114
+ }
2115
+
2116
+ function findIndex(array, predicate) {
2117
+ for (var key = 0; key < array.length; key++) {
2118
+ if (predicate(array[key])) {
2119
+ return key;
2120
+ }
2121
+ }
2122
+
2123
+ return undefined;
2124
+ }
2125
+
2126
+ function buildMatchPatternFn(args) {
2127
+ return function (string) {
2128
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2129
+ var matchResult = string.match(args.matchPattern);
2130
+ if (!matchResult) return null;
2131
+ var matchedString = matchResult[0];
2132
+ var parseResult = string.match(args.parsePattern);
2133
+ if (!parseResult) return null;
2134
+ var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
2135
+ value = options.valueCallback ? options.valueCallback(value) : value;
2136
+ var rest = string.slice(matchedString.length);
2137
+ return {
2138
+ value: value,
2139
+ rest: rest
2140
+ };
2141
+ };
2142
+ }
2143
+
2144
+ var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
2145
+ var parseOrdinalNumberPattern = /\d+/i;
2146
+ var matchEraPatterns = {
2147
+ narrow: /^(b|a)/i,
2148
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
2149
+ wide: /^(before christ|before common era|anno domini|common era)/i
2150
+ };
2151
+ var parseEraPatterns = {
2152
+ any: [/^b/i, /^(a|c)/i]
2153
+ };
2154
+ var matchQuarterPatterns = {
2155
+ narrow: /^[1234]/i,
2156
+ abbreviated: /^q[1234]/i,
2157
+ wide: /^[1234](th|st|nd|rd)? quarter/i
2158
+ };
2159
+ var parseQuarterPatterns = {
2160
+ any: [/1/i, /2/i, /3/i, /4/i]
2161
+ };
2162
+ var matchMonthPatterns = {
2163
+ narrow: /^[jfmasond]/i,
2164
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
2165
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
2166
+ };
2167
+ var parseMonthPatterns = {
2168
+ narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
2169
+ any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
2170
+ };
2171
+ var matchDayPatterns = {
2172
+ narrow: /^[smtwf]/i,
2173
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
2174
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
2175
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
2176
+ };
2177
+ var parseDayPatterns = {
2178
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
2179
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
2180
+ };
2181
+ var matchDayPeriodPatterns = {
2182
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
2183
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
2184
+ };
2185
+ var parseDayPeriodPatterns = {
2186
+ any: {
2187
+ am: /^a/i,
2188
+ pm: /^p/i,
2189
+ midnight: /^mi/i,
2190
+ noon: /^no/i,
2191
+ morning: /morning/i,
2192
+ afternoon: /afternoon/i,
2193
+ evening: /evening/i,
2194
+ night: /night/i
2195
+ }
2196
+ };
2197
+ var match = {
2198
+ ordinalNumber: buildMatchPatternFn({
2199
+ matchPattern: matchOrdinalNumberPattern,
2200
+ parsePattern: parseOrdinalNumberPattern,
2201
+ valueCallback: function valueCallback(value) {
2202
+ return parseInt(value, 10);
2203
+ }
2204
+ }),
2205
+ era: buildMatchFn({
2206
+ matchPatterns: matchEraPatterns,
2207
+ defaultMatchWidth: 'wide',
2208
+ parsePatterns: parseEraPatterns,
2209
+ defaultParseWidth: 'any'
2210
+ }),
2211
+ quarter: buildMatchFn({
2212
+ matchPatterns: matchQuarterPatterns,
2213
+ defaultMatchWidth: 'wide',
2214
+ parsePatterns: parseQuarterPatterns,
2215
+ defaultParseWidth: 'any',
2216
+ valueCallback: function valueCallback(index) {
2217
+ return index + 1;
2218
+ }
2219
+ }),
2220
+ month: buildMatchFn({
2221
+ matchPatterns: matchMonthPatterns,
2222
+ defaultMatchWidth: 'wide',
2223
+ parsePatterns: parseMonthPatterns,
2224
+ defaultParseWidth: 'any'
2225
+ }),
2226
+ day: buildMatchFn({
2227
+ matchPatterns: matchDayPatterns,
2228
+ defaultMatchWidth: 'wide',
2229
+ parsePatterns: parseDayPatterns,
2230
+ defaultParseWidth: 'any'
2231
+ }),
2232
+ dayPeriod: buildMatchFn({
2233
+ matchPatterns: matchDayPeriodPatterns,
2234
+ defaultMatchWidth: 'any',
2235
+ parsePatterns: parseDayPeriodPatterns,
2236
+ defaultParseWidth: 'any'
2237
+ })
2238
+ };
2239
+
2240
+ /**
2241
+ * @type {Locale}
2242
+ * @category Locales
2243
+ * @summary English locale (United States).
2244
+ * @language English
2245
+ * @iso-639-2 eng
2246
+ * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
2247
+ * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
2248
+ */
2249
+ var locale = {
2250
+ code: 'en-US',
2251
+ formatDistance: formatDistance,
2252
+ formatLong: formatLong,
2253
+ formatRelative: formatRelative,
2254
+ localize: localize,
2255
+ match: match,
2256
+ options: {
2257
+ weekStartsOn: 0
2258
+ /* Sunday */
2259
+ ,
2260
+ firstWeekContainsDate: 1
2261
+ }
2262
+ };
2263
+
2264
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2265
+ // (one of the certain letters followed by `o`)
2266
+ // - (\w)\1* matches any sequences of the same letter
2267
+ // - '' matches two quote characters in a row
2268
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2269
+ // except a single quote symbol, which ends the sequence.
2270
+ // Two quote characters do not end the sequence.
2271
+ // If there is no matching single quote
2272
+ // then the sequence will continue until the end of the string.
2273
+ // - . matches any single character unmatched by previous parts of the RegExps
2274
+
2275
+ var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
2276
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2277
+
2278
+ var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2279
+ var escapedStringRegExp = /^'([^]*?)'?$/;
2280
+ var doubleQuoteRegExp = /''/g;
2281
+ var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2282
+ /**
2283
+ * @name format
2284
+ * @category Common Helpers
2285
+ * @summary Format the date.
2286
+ *
2287
+ * @description
2288
+ * Return the formatted date string in the given format. The result may vary by locale.
2289
+ *
2290
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2291
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2292
+ *
2293
+ * The characters wrapped between two single quotes characters (') are escaped.
2294
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2295
+ * (see the last example)
2296
+ *
2297
+ * Format of the string is based on Unicode Technical Standard #35:
2298
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2299
+ * with a few additions (see note 7 below the table).
2300
+ *
2301
+ * Accepted patterns:
2302
+ * | Unit | Pattern | Result examples | Notes |
2303
+ * |---------------------------------|---------|-----------------------------------|-------|
2304
+ * | Era | G..GGG | AD, BC | |
2305
+ * | | GGGG | Anno Domini, Before Christ | 2 |
2306
+ * | | GGGGG | A, B | |
2307
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
2308
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
2309
+ * | | yy | 44, 01, 00, 17 | 5 |
2310
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
2311
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
2312
+ * | | yyyyy | ... | 3,5 |
2313
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
2314
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
2315
+ * | | YY | 44, 01, 00, 17 | 5,8 |
2316
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
2317
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
2318
+ * | | YYYYY | ... | 3,5 |
2319
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
2320
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
2321
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
2322
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
2323
+ * | | RRRRR | ... | 3,5,7 |
2324
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
2325
+ * | | uu | -43, 01, 1900, 2017 | 5 |
2326
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
2327
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
2328
+ * | | uuuuu | ... | 3,5 |
2329
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
2330
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
2331
+ * | | QQ | 01, 02, 03, 04 | |
2332
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
2333
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2334
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
2335
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
2336
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
2337
+ * | | qq | 01, 02, 03, 04 | |
2338
+ * | | qqq | Q1, Q2, Q3, Q4 | |
2339
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2340
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
2341
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
2342
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
2343
+ * | | MM | 01, 02, ..., 12 | |
2344
+ * | | MMM | Jan, Feb, ..., Dec | |
2345
+ * | | MMMM | January, February, ..., December | 2 |
2346
+ * | | MMMMM | J, F, ..., D | |
2347
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
2348
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
2349
+ * | | LL | 01, 02, ..., 12 | |
2350
+ * | | LLL | Jan, Feb, ..., Dec | |
2351
+ * | | LLLL | January, February, ..., December | 2 |
2352
+ * | | LLLLL | J, F, ..., D | |
2353
+ * | Local week of year | w | 1, 2, ..., 53 | |
2354
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
2355
+ * | | ww | 01, 02, ..., 53 | |
2356
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
2357
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
2358
+ * | | II | 01, 02, ..., 53 | 7 |
2359
+ * | Day of month | d | 1, 2, ..., 31 | |
2360
+ * | | do | 1st, 2nd, ..., 31st | 7 |
2361
+ * | | dd | 01, 02, ..., 31 | |
2362
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
2363
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
2364
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
2365
+ * | | DDD | 001, 002, ..., 365, 366 | |
2366
+ * | | DDDD | ... | 3 |
2367
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
2368
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2369
+ * | | EEEEE | M, T, W, T, F, S, S | |
2370
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2371
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
2372
+ * | | io | 1st, 2nd, ..., 7th | 7 |
2373
+ * | | ii | 01, 02, ..., 07 | 7 |
2374
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
2375
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
2376
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
2377
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
2378
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
2379
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
2380
+ * | | ee | 02, 03, ..., 01 | |
2381
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
2382
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2383
+ * | | eeeee | M, T, W, T, F, S, S | |
2384
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2385
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
2386
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
2387
+ * | | cc | 02, 03, ..., 01 | |
2388
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
2389
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2390
+ * | | ccccc | M, T, W, T, F, S, S | |
2391
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2392
+ * | AM, PM | a..aa | AM, PM | |
2393
+ * | | aaa | am, pm | |
2394
+ * | | aaaa | a.m., p.m. | 2 |
2395
+ * | | aaaaa | a, p | |
2396
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
2397
+ * | | bbb | am, pm, noon, midnight | |
2398
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
2399
+ * | | bbbbb | a, p, n, mi | |
2400
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
2401
+ * | | BBBB | at night, in the morning, ... | 2 |
2402
+ * | | BBBBB | at night, in the morning, ... | |
2403
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
2404
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
2405
+ * | | hh | 01, 02, ..., 11, 12 | |
2406
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
2407
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
2408
+ * | | HH | 00, 01, 02, ..., 23 | |
2409
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
2410
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
2411
+ * | | KK | 01, 02, ..., 11, 00 | |
2412
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
2413
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
2414
+ * | | kk | 24, 01, 02, ..., 23 | |
2415
+ * | Minute | m | 0, 1, ..., 59 | |
2416
+ * | | mo | 0th, 1st, ..., 59th | 7 |
2417
+ * | | mm | 00, 01, ..., 59 | |
2418
+ * | Second | s | 0, 1, ..., 59 | |
2419
+ * | | so | 0th, 1st, ..., 59th | 7 |
2420
+ * | | ss | 00, 01, ..., 59 | |
2421
+ * | Fraction of second | S | 0, 1, ..., 9 | |
2422
+ * | | SS | 00, 01, ..., 99 | |
2423
+ * | | SSS | 000, 001, ..., 999 | |
2424
+ * | | SSSS | ... | 3 |
2425
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
2426
+ * | | XX | -0800, +0530, Z | |
2427
+ * | | XXX | -08:00, +05:30, Z | |
2428
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
2429
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2430
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
2431
+ * | | xx | -0800, +0530, +0000 | |
2432
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
2433
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
2434
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2435
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
2436
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
2437
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
2438
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
2439
+ * | Seconds timestamp | t | 512969520 | 7 |
2440
+ * | | tt | ... | 3,7 |
2441
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
2442
+ * | | TT | ... | 3,7 |
2443
+ * | Long localized date | P | 04/29/1453 | 7 |
2444
+ * | | PP | Apr 29, 1453 | 7 |
2445
+ * | | PPP | April 29th, 1453 | 7 |
2446
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
2447
+ * | Long localized time | p | 12:00 AM | 7 |
2448
+ * | | pp | 12:00:00 AM | 7 |
2449
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
2450
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
2451
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
2452
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
2453
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
2454
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
2455
+ * Notes:
2456
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2457
+ * are the same as "stand-alone" units, but are different in some languages.
2458
+ * "Formatting" units are declined according to the rules of the language
2459
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2460
+ *
2461
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2462
+ *
2463
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2464
+ *
2465
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2466
+ * the single quote characters (see below).
2467
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2468
+ * the output will be the same as default pattern for this unit, usually
2469
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2470
+ * are marked with "2" in the last column of the table.
2471
+ *
2472
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2473
+ *
2474
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2475
+ *
2476
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2477
+ *
2478
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2479
+ *
2480
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2481
+ *
2482
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2483
+ * The output will be padded with zeros to match the length of the pattern.
2484
+ *
2485
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2486
+ *
2487
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2488
+ * These tokens represent the shortest form of the quarter.
2489
+ *
2490
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2491
+ *
2492
+ * | Year | `y` | `u` |
2493
+ * |------|-----|-----|
2494
+ * | AC 1 | 1 | 1 |
2495
+ * | BC 1 | 1 | 0 |
2496
+ * | BC 2 | 2 | -1 |
2497
+ *
2498
+ * Also `yy` always returns the last two digits of a year,
2499
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2500
+ *
2501
+ * | Year | `yy` | `uu` |
2502
+ * |------|------|------|
2503
+ * | 1 | 01 | 01 |
2504
+ * | 14 | 14 | 14 |
2505
+ * | 376 | 76 | 376 |
2506
+ * | 1453 | 53 | 1453 |
2507
+ *
2508
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2509
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2510
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
2511
+ * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
2512
+ *
2513
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2514
+ * so right now these tokens fall back to GMT timezones.
2515
+ *
2516
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2517
+ * - `i`: ISO day of week
2518
+ * - `I`: ISO week of year
2519
+ * - `R`: ISO week-numbering year
2520
+ * - `t`: seconds timestamp
2521
+ * - `T`: milliseconds timestamp
2522
+ * - `o`: ordinal number modifier
2523
+ * - `P`: long localized date
2524
+ * - `p`: long localized time
2525
+ *
2526
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2527
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2528
+ *
2529
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2530
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2531
+ *
2532
+ * @param {Date|Number} date - the original date
2533
+ * @param {String} format - the string of tokens
2534
+ * @param {Object} [options] - an object with options.
2535
+ * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
2536
+ * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
2537
+ * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
2538
+ * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
2539
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2540
+ * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
2541
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2542
+ * @returns {String} the formatted date string
2543
+ * @throws {TypeError} 2 arguments required
2544
+ * @throws {RangeError} `date` must not be Invalid Date
2545
+ * @throws {RangeError} `options.locale` must contain `localize` property
2546
+ * @throws {RangeError} `options.locale` must contain `formatLong` property
2547
+ * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
2548
+ * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
2549
+ * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2550
+ * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2551
+ * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2552
+ * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2553
+ * @throws {RangeError} format string contains an unescaped latin alphabet character
2554
+ *
2555
+ * @example
2556
+ * // Represent 11 February 2014 in middle-endian format:
2557
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2558
+ * //=> '02/11/2014'
2559
+ *
2560
+ * @example
2561
+ * // Represent 2 July 2014 in Esperanto:
2562
+ * import { eoLocale } from 'date-fns/locale/eo'
2563
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2564
+ * locale: eoLocale
2565
+ * })
2566
+ * //=> '2-a de julio 2014'
2567
+ *
2568
+ * @example
2569
+ * // Escape string by single quote characters:
2570
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2571
+ * //=> "3 o'clock"
2572
+ */
2573
+
2574
+ function format(dirtyDate, dirtyFormatStr, options) {
2575
+ var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
2576
+
2577
+ requiredArgs(2, arguments);
2578
+ var formatStr = String(dirtyFormatStr);
2579
+ var defaultOptions = getDefaultOptions();
2580
+ var locale$1 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : locale;
2581
+ var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
2582
+
2583
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
2584
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
2585
+ }
2586
+
2587
+ var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
2588
+
2589
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
2590
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
2591
+ }
2592
+
2593
+ if (!locale$1.localize) {
2594
+ throw new RangeError('locale must contain localize property');
2595
+ }
2596
+
2597
+ if (!locale$1.formatLong) {
2598
+ throw new RangeError('locale must contain formatLong property');
2599
+ }
2600
+
2601
+ var originalDate = toDate(dirtyDate);
2602
+
2603
+ if (!isValid(originalDate)) {
2604
+ throw new RangeError('Invalid time value');
2605
+ } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
2606
+ // This ensures that when UTC functions will be implemented, locales will be compatible with them.
2607
+ // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
2608
+
2609
+
2610
+ var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
2611
+ var utcDate = subMilliseconds(originalDate, timezoneOffset);
2612
+ var formatterOptions = {
2613
+ firstWeekContainsDate: firstWeekContainsDate,
2614
+ weekStartsOn: weekStartsOn,
2615
+ locale: locale$1,
2616
+ _originalDate: originalDate
2617
+ };
2618
+ var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
2619
+ var firstCharacter = substring[0];
2620
+
2621
+ if (firstCharacter === 'p' || firstCharacter === 'P') {
2622
+ var longFormatter = longFormatters[firstCharacter];
2623
+ return longFormatter(substring, locale$1.formatLong);
2624
+ }
2625
+
2626
+ return substring;
2627
+ }).join('').match(formattingTokensRegExp).map(function (substring) {
2628
+ // Replace two single quote characters with one single quote character
2629
+ if (substring === "''") {
2630
+ return "'";
2631
+ }
2632
+
2633
+ var firstCharacter = substring[0];
2634
+
2635
+ if (firstCharacter === "'") {
2636
+ return cleanEscapedString(substring);
2637
+ }
2638
+
2639
+ var formatter = formatters[firstCharacter];
2640
+
2641
+ if (formatter) {
2642
+ if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
2643
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2644
+ }
2645
+
2646
+ if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
2647
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2648
+ }
2649
+
2650
+ return formatter(utcDate, substring, locale$1.localize, formatterOptions);
2651
+ }
2652
+
2653
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2654
+ throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
2655
+ }
2656
+
2657
+ return substring;
2658
+ }).join('');
2659
+ return result;
2660
+ }
2661
+
2662
+ function cleanEscapedString(input) {
2663
+ var matched = input.match(escapedStringRegExp);
2664
+
2665
+ if (!matched) {
2666
+ return input;
2667
+ }
2668
+
2669
+ return matched[1].replace(doubleQuoteRegExp, "'");
2670
+ }
2671
+
2672
+ /**
2673
+ * Default values for all Dinero objects.
2674
+ *
2675
+ * You can override default values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2676
+ * Existing instances won't be affected.
2677
+ *
2678
+ * @property {Number} defaultAmount - The default amount for new Dinero objects (see {@link module:Dinero Dinero} for format).
2679
+ * @property {String} defaultCurrency - The default currency for new Dinero objects (see {@link module:Dinero Dinero} for format).
2680
+ * @property {Number} defaultPrecision - The default precision for new Dinero objects (see {@link module:Dinero Dinero} for format).
2681
+ *
2682
+ * @example
2683
+ * // Will set currency to 'EUR' for all Dinero objects.
2684
+ * Dinero.defaultCurrency = 'EUR'
2685
+ *
2686
+ * @type {Object}
2687
+ */
2688
+ var Defaults = {
2689
+ defaultAmount: 0,
2690
+ defaultCurrency: 'USD',
2691
+ defaultPrecision: 2
2692
+ };
2693
+ /**
2694
+ * Global settings for all Dinero objects.
2695
+ *
2696
+ * You can override global values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2697
+ * Existing instances won't be affected.
2698
+ *
2699
+ * @property {String} globalLocale - The global locale for new Dinero objects (see {@link module:Dinero~setLocale setLocale} for format).
2700
+ * @property {String} globalFormat - The global format for new Dinero objects (see {@link module:Dinero~toFormat toFormat} for format).
2701
+ * @property {String} globalRoundingMode - The global rounding mode for new Dinero objects (see {@link module:Dinero~multiply multiply} or {@link module:Dinero~divide divide} for format).
2702
+ * @property {String} globalFormatRoundingMode - The global rounding mode to format new Dinero objects (see {@link module:Dinero~toFormat toFormat} or {@link module:Dinero~toRoundedUnit toRoundedUnit} for format).
2703
+ * @property {(String|Promise)} globalExchangeRatesApi.endpoint - The global exchange rate API endpoint for new Dinero objects, or the global promise that resolves to the exchanges rates (see {@link module:Dinero~convert convert} for format).
2704
+ * @property {String} globalExchangeRatesApi.propertyPath - The global exchange rate API property path for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2705
+ * @property {Object} globalExchangeRatesApi.headers - The global exchange rate API headers for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2706
+ *
2707
+ * @example
2708
+ * // Will set locale to 'fr-FR' for all Dinero objects.
2709
+ * Dinero.globalLocale = 'fr-FR'
2710
+ * @example
2711
+ * // Will set global exchange rate API parameters for all Dinero objects.
2712
+ * Dinero.globalExchangeRatesApi = {
2713
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
2714
+ * propertyPath: 'data.rates.{{to}}',
2715
+ * headers: {
2716
+ * 'user-key': 'xxxxxxxxx'
2717
+ * }
2718
+ * }
2719
+ *
2720
+ * @type {Object}
2721
+ */
2722
+
2723
+ var Globals = {
2724
+ globalLocale: 'en-US',
2725
+ globalFormat: '$0,0.00',
2726
+ globalRoundingMode: 'HALF_EVEN',
2727
+ globalFormatRoundingMode: 'HALF_AWAY_FROM_ZERO',
2728
+ globalExchangeRatesApi: {
2729
+ endpoint: undefined,
2730
+ headers: undefined,
2731
+ propertyPath: undefined
2732
+ }
2733
+ };
2734
+
2735
+ function _typeof(obj) {
2736
+ "@babel/helpers - typeof";
2737
+
2738
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
2739
+ _typeof = function (obj) {
2740
+ return typeof obj;
2741
+ };
2742
+ } else {
2743
+ _typeof = function (obj) {
2744
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
2745
+ };
2746
+ }
2747
+
2748
+ return _typeof(obj);
2749
+ }
2750
+
2751
+ function _toArray(arr) {
2752
+ return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
2753
+ }
2754
+
2755
+ function _arrayWithHoles(arr) {
2756
+ if (Array.isArray(arr)) return arr;
2757
+ }
2758
+
2759
+ function _iterableToArray(iter) {
2760
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
2761
+ }
2762
+
2763
+ function _unsupportedIterableToArray(o, minLen) {
2764
+ if (!o) return;
2765
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
2766
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2767
+ if (n === "Object" && o.constructor) n = o.constructor.name;
2768
+ if (n === "Map" || n === "Set") return Array.from(o);
2769
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2770
+ }
2771
+
2772
+ function _arrayLikeToArray(arr, len) {
2773
+ if (len == null || len > arr.length) len = arr.length;
2774
+
2775
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
2776
+
2777
+ return arr2;
2778
+ }
2779
+
2780
+ function _nonIterableRest() {
2781
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2782
+ }
2783
+
2784
+ /**
2785
+ * Static methods for Dinero.
2786
+ * @ignore
2787
+ *
2788
+ * @type {Object}
2789
+ */
2790
+ var Static = {
2791
+ /**
2792
+ * Returns an array of Dinero objects, normalized to the same precision (the highest).
2793
+ *
2794
+ * @memberof module:Dinero
2795
+ * @method
2796
+ *
2797
+ * @param {Dinero[]} objects - An array of Dinero objects
2798
+ *
2799
+ * @example
2800
+ * // returns an array of Dinero objects
2801
+ * // both with a precision of 3
2802
+ * // and an amount of 1000
2803
+ * Dinero.normalizePrecision([
2804
+ * Dinero({ amount: 100, precision: 2 }),
2805
+ * Dinero({ amount: 1000, precision: 3 })
2806
+ * ])
2807
+ *
2808
+ * @return {Dinero[]}
2809
+ */
2810
+ normalizePrecision: function normalizePrecision(objects) {
2811
+ var highestPrecision = objects.reduce(function (a, b) {
2812
+ return Math.max(a.getPrecision(), b.getPrecision());
2813
+ });
2814
+ return objects.map(function (object) {
2815
+ return object.getPrecision() !== highestPrecision ? object.convertPrecision(highestPrecision) : object;
2816
+ });
2817
+ },
2818
+
2819
+ /**
2820
+ * Returns the smallest Dinero object from an array of Dinero objects
2821
+ *
2822
+ * @memberof module:Dinero
2823
+ * @method
2824
+ *
2825
+ * @param {Dinero[]} objects - An array of Dinero objects
2826
+ *
2827
+ * @example
2828
+ * // returns the smallest Dinero object with amount of 500 from an array of Dinero objects with different precisions
2829
+ * Dinero.minimum([
2830
+ * Dinero({ amount: 500, precision: 3 }),
2831
+ * Dinero({ amount: 100, precision: 2 })
2832
+ * ])
2833
+ * @example
2834
+ * // returns the smallest Dinero object with amount of 50 from an array of Dinero objects
2835
+ * Dinero.minimum([
2836
+ * Dinero({ amount: 50 }),
2837
+ * Dinero({ amount: 100 })
2838
+ * ])
2839
+ *
2840
+ * @return {Dinero[]}
2841
+ */
2842
+ minimum: function minimum(objects) {
2843
+ var _objects = _toArray(objects),
2844
+ firstObject = _objects[0],
2845
+ tailObjects = _objects.slice(1);
2846
+
2847
+ var currentMinimum = firstObject;
2848
+ tailObjects.forEach(function (obj) {
2849
+ currentMinimum = currentMinimum.lessThan(obj) ? currentMinimum : obj;
2850
+ });
2851
+ return currentMinimum;
2852
+ },
2853
+
2854
+ /**
2855
+ * Returns the biggest Dinero object from an array of Dinero objects
2856
+ *
2857
+ * @memberof module:Dinero
2858
+ * @method
2859
+ *
2860
+ * @param {Dinero[]} objects - An array of Dinero objects
2861
+ *
2862
+ * @example
2863
+ * // returns the biggest Dinero object with amount of 20, from an array of Dinero objects with different precisions
2864
+ * Dinero.maximum([
2865
+ * Dinero({ amount: 20, precision: 2 }),
2866
+ * Dinero({ amount: 150, precision: 3 })
2867
+ * ])
2868
+ * @example
2869
+ * // returns the biggest Dinero object with amount of 100, from an array of Dinero objects
2870
+ * Dinero.maximum([
2871
+ * Dinero({ amount: 100 }),
2872
+ * Dinero({ amount: 50 })
2873
+ * ])
2874
+ *
2875
+ * @return {Dinero[]}
2876
+ */
2877
+ maximum: function maximum(objects) {
2878
+ var _objects2 = _toArray(objects),
2879
+ firstObject = _objects2[0],
2880
+ tailObjects = _objects2.slice(1);
2881
+
2882
+ var currentMaximum = firstObject;
2883
+ tailObjects.forEach(function (obj) {
2884
+ currentMaximum = currentMaximum.greaterThan(obj) ? currentMaximum : obj;
2885
+ });
2886
+ return currentMaximum;
2887
+ }
2888
+ };
2889
+
2890
+ /**
2891
+ * Returns whether a value is numeric.
2892
+ * @ignore
2893
+ *
2894
+ * @param {} value - The value to test.
2895
+ *
2896
+ * @return {Boolean}
2897
+ */
2898
+ function isNumeric(value) {
2899
+ return !isNaN(parseInt(value)) && isFinite(value);
2900
+ }
2901
+ /**
2902
+ * Returns whether a value is a percentage.
2903
+ * @ignore
2904
+ *
2905
+ * @param {} percentage - The percentage to test.
2906
+ *
2907
+ * @return {Boolean}
2908
+ */
2909
+
2910
+ function isPercentage(percentage) {
2911
+ return isNumeric(percentage) && percentage <= 100 && percentage >= 0;
2912
+ }
2913
+ /**
2914
+ * Returns whether an array of ratios is valid.
2915
+ * @ignore
2916
+ *
2917
+ * @param {} ratios - The ratios to test.
2918
+ *
2919
+ * @return {Boolean}
2920
+ */
2921
+
2922
+ function areValidRatios(ratios) {
2923
+ return ratios.length > 0 && ratios.every(function (ratio) {
2924
+ return ratio >= 0;
2925
+ }) && ratios.some(function (ratio) {
2926
+ return ratio > 0;
2927
+ });
2928
+ }
2929
+ /**
2930
+ * Returns whether a value is even.
2931
+ * @ignore
2932
+ *
2933
+ * @param {Number} value - The value to test.
2934
+ *
2935
+ * @return {Boolean}
2936
+ */
2937
+
2938
+ function isEven(value) {
2939
+ return value % 2 === 0;
2940
+ }
2941
+ /**
2942
+ * Returns whether a value is a float.
2943
+ * @ignore
2944
+ *
2945
+ * @param {} value - The value to test.
2946
+ *
2947
+ * @return {Boolean}
2948
+ */
2949
+
2950
+ function isFloat(value) {
2951
+ return isNumeric(value) && !Number.isInteger(value);
2952
+ }
2953
+ /**
2954
+ * Returns how many fraction digits a number has.
2955
+ * @ignore
2956
+ *
2957
+ * @param {Number} [number=0] - The number to test.
2958
+ *
2959
+ * @return {Number}
2960
+ */
2961
+
2962
+ function countFractionDigits() {
2963
+ var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
2964
+ var stringRepresentation = number.toString();
2965
+
2966
+ if (stringRepresentation.indexOf('e-') > 0) {
2967
+ // It's too small for a normal string representation, e.g. 1e-7 instead of 0.00000001
2968
+ return parseInt(stringRepresentation.split('e-')[1]);
2969
+ } else {
2970
+ var fractionDigits = stringRepresentation.split('.')[1];
2971
+ return fractionDigits ? fractionDigits.length : 0;
2972
+ }
2973
+ }
2974
+ /**
2975
+ * Returns whether a number is half.
2976
+ * @ignore
2977
+ *
2978
+ * @param {Number} number - The number to test.
2979
+ *
2980
+ * @return {Number}
2981
+ */
2982
+
2983
+ function isHalf(number) {
2984
+ return Math.abs(number) % 1 === 0.5;
2985
+ }
2986
+ /**
2987
+ * Fetches a JSON resource.
2988
+ * @ignore
2989
+ *
2990
+ * @param {String} url - The resource to fetch.
2991
+ * @param {Object} [options.headers] - The headers to pass.
2992
+ *
2993
+ * @throws {Error} If `request.status` is lesser than 200 or greater or equal to 400.
2994
+ * @throws {Error} If network fails.
2995
+ *
2996
+ * @return {JSON}
2997
+ */
2998
+
2999
+ function getJSON(url) {
3000
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3001
+ return new Promise(function (resolve, reject) {
3002
+ var request = Object.assign(new XMLHttpRequest(), {
3003
+ onreadystatechange: function onreadystatechange() {
3004
+ if (request.readyState === 4) {
3005
+ if (request.status >= 200 && request.status < 400) resolve(JSON.parse(request.responseText));else reject(new Error(request.statusText));
3006
+ }
3007
+ },
3008
+ onerror: function onerror() {
3009
+ reject(new Error('Network error'));
3010
+ }
3011
+ });
3012
+ request.open('GET', url, true);
3013
+ setXHRHeaders(request, options.headers);
3014
+ request.send();
3015
+ });
3016
+ }
3017
+ /**
3018
+ * Returns an XHR object with attached headers.
3019
+ * @ignore
3020
+ *
3021
+ * @param {XMLHttpRequest} xhr - The XHR request to set headers to.
3022
+ * @param {Object} headers - The headers to set.
3023
+ *
3024
+ * @return {XMLHttpRequest}
3025
+ */
3026
+
3027
+ function setXHRHeaders(xhr) {
3028
+ var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3029
+
3030
+ for (var header in headers) {
3031
+ xhr.setRequestHeader(header, headers[header]);
3032
+ }
3033
+
3034
+ return xhr;
3035
+ }
3036
+ /**
3037
+ * Returns whether a value is undefined.
3038
+ * @ignore
3039
+ *
3040
+ * @param {} value - The value to test.
3041
+ *
3042
+ * @return {Boolean}
3043
+ */
3044
+
3045
+ function isUndefined(value) {
3046
+ return typeof value === 'undefined';
3047
+ }
3048
+ /**
3049
+ * Returns an object flattened to one level deep.
3050
+ * @ignore
3051
+ *
3052
+ * @param {Object} object - The object to flatten.
3053
+ * @param {String} separator - The separator to use between flattened nodes.
3054
+ *
3055
+ * @return {Object}
3056
+ */
3057
+
3058
+ function flattenObject(object) {
3059
+ var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
3060
+ var finalObject = {};
3061
+ Object.entries(object).forEach(function (item) {
3062
+ if (_typeof(item[1]) === 'object') {
3063
+ var flatObject = flattenObject(item[1]);
3064
+ Object.entries(flatObject).forEach(function (node) {
3065
+ finalObject[item[0] + separator + node[0]] = node[1];
3066
+ });
3067
+ } else {
3068
+ finalObject[item[0]] = item[1];
3069
+ }
3070
+ });
3071
+ return finalObject;
3072
+ }
3073
+ /**
3074
+ * Returns whether a value is thenable.
3075
+ * @ignore
3076
+ *
3077
+ * @param {} value - The value to test.
3078
+ *
3079
+ * @return {Boolean}
3080
+ */
3081
+
3082
+ function isThenable(value) {
3083
+ return Boolean(value) && (_typeof(value) === 'object' || typeof value === 'function') && typeof value.then === 'function';
3084
+ }
3085
+
3086
+ function Calculator() {
3087
+ var floatMultiply = function floatMultiply(a, b) {
3088
+ var getFactor = function getFactor(number) {
3089
+ return Math.pow(10, countFractionDigits(number));
3090
+ };
3091
+
3092
+ var factor = Math.max(getFactor(a), getFactor(b));
3093
+ return Math.round(a * factor) * Math.round(b * factor) / (factor * factor);
3094
+ };
3095
+
3096
+ var roundingModes = {
3097
+ HALF_ODD: function HALF_ODD(number) {
3098
+ var rounded = Math.round(number);
3099
+ return isHalf(number) ? isEven(rounded) ? rounded - 1 : rounded : rounded;
3100
+ },
3101
+ HALF_EVEN: function HALF_EVEN(number) {
3102
+ var rounded = Math.round(number);
3103
+ return isHalf(number) ? isEven(rounded) ? rounded : rounded - 1 : rounded;
3104
+ },
3105
+ HALF_UP: function HALF_UP(number) {
3106
+ return Math.round(number);
3107
+ },
3108
+ HALF_DOWN: function HALF_DOWN(number) {
3109
+ return isHalf(number) ? Math.floor(number) : Math.round(number);
3110
+ },
3111
+ HALF_TOWARDS_ZERO: function HALF_TOWARDS_ZERO(number) {
3112
+ return isHalf(number) ? Math.sign(number) * Math.floor(Math.abs(number)) : Math.round(number);
3113
+ },
3114
+ HALF_AWAY_FROM_ZERO: function HALF_AWAY_FROM_ZERO(number) {
3115
+ return isHalf(number) ? Math.sign(number) * Math.ceil(Math.abs(number)) : Math.round(number);
3116
+ },
3117
+ DOWN: function DOWN(number) {
3118
+ return Math.floor(number);
3119
+ }
3120
+ };
3121
+ return {
3122
+ /**
3123
+ * Returns the sum of two numbers.
3124
+ * @ignore
3125
+ *
3126
+ * @param {Number} a - The first number to add.
3127
+ * @param {Number} b - The second number to add.
3128
+ *
3129
+ * @return {Number}
3130
+ */
3131
+ add: function add(a, b) {
3132
+ return a + b;
3133
+ },
3134
+
3135
+ /**
3136
+ * Returns the difference of two numbers.
3137
+ * @ignore
3138
+ *
3139
+ * @param {Number} a - The first number to subtract.
3140
+ * @param {Number} b - The second number to subtract.
3141
+ *
3142
+ * @return {Number}
3143
+ */
3144
+ subtract: function subtract(a, b) {
3145
+ return a - b;
3146
+ },
3147
+
3148
+ /**
3149
+ * Returns the product of two numbers.
3150
+ * @ignore
3151
+ *
3152
+ * @param {Number} a - The first number to multiply.
3153
+ * @param {Number} b - The second number to multiply.
3154
+ *
3155
+ * @return {Number}
3156
+ */
3157
+ multiply: function multiply(a, b) {
3158
+ return isFloat(a) || isFloat(b) ? floatMultiply(a, b) : a * b;
3159
+ },
3160
+
3161
+ /**
3162
+ * Returns the quotient of two numbers.
3163
+ * @ignore
3164
+ *
3165
+ * @param {Number} a - The first number to divide.
3166
+ * @param {Number} b - The second number to divide.
3167
+ *
3168
+ * @return {Number}
3169
+ */
3170
+ divide: function divide(a, b) {
3171
+ return a / b;
3172
+ },
3173
+
3174
+ /**
3175
+ * Returns the remainder of two numbers.
3176
+ * @ignore
3177
+ *
3178
+ * @param {Number} a - The first number to divide.
3179
+ * @param {Number} b - The second number to divide.
3180
+ *
3181
+ * @return {Number}
3182
+ */
3183
+ modulo: function modulo(a, b) {
3184
+ return a % b;
3185
+ },
3186
+
3187
+ /**
3188
+ * Returns a rounded number based off a specific rounding mode.
3189
+ * @ignore
3190
+ *
3191
+ * @param {Number} number - The number to round.
3192
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use.
3193
+ *
3194
+ * @returns {Number}
3195
+ */
3196
+ round: function round(number) {
3197
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'HALF_EVEN';
3198
+ return roundingModes[roundingMode](number);
3199
+ }
3200
+ };
3201
+ }
3202
+
3203
+ var calculator = Calculator();
3204
+ function Format(format) {
3205
+ var matches = /^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(format);
3206
+ return {
3207
+ /**
3208
+ * Returns the matches.
3209
+ * @ignore
3210
+ *
3211
+ * @return {Array}
3212
+ */
3213
+ getMatches: function getMatches() {
3214
+ return matches !== null ? matches.slice(1).filter(function (match) {
3215
+ return !isUndefined(match);
3216
+ }) : [];
3217
+ },
3218
+
3219
+ /**
3220
+ * Returns the amount of fraction digits to display.
3221
+ * @ignore
3222
+ *
3223
+ * @return {Number}
3224
+ */
3225
+ getMinimumFractionDigits: function getMinimumFractionDigits() {
3226
+ var decimalPosition = function decimalPosition(match) {
3227
+ return match === '.';
3228
+ };
3229
+
3230
+ return !isUndefined(this.getMatches().find(decimalPosition)) ? this.getMatches()[calculator.add(this.getMatches().findIndex(decimalPosition), 1)].split('').length : 0;
3231
+ },
3232
+
3233
+ /**
3234
+ * Returns the currency display mode.
3235
+ * @ignore
3236
+ *
3237
+ * @return {String}
3238
+ */
3239
+ getCurrencyDisplay: function getCurrencyDisplay() {
3240
+ var modes = {
3241
+ USD: 'code',
3242
+ dollar: 'name',
3243
+ $: 'symbol'
3244
+ };
3245
+ return modes[this.getMatches().find(function (match) {
3246
+ return match === 'USD' || match === 'dollar' || match === '$';
3247
+ })];
3248
+ },
3249
+
3250
+ /**
3251
+ * Returns the formatting style.
3252
+ * @ignore
3253
+ *
3254
+ * @return {String}
3255
+ */
3256
+ getStyle: function getStyle() {
3257
+ return !isUndefined(this.getCurrencyDisplay(this.getMatches())) ? 'currency' : 'decimal';
3258
+ },
3259
+
3260
+ /**
3261
+ * Returns whether grouping should be used or not.
3262
+ * @ignore
3263
+ *
3264
+ * @return {Boolean}
3265
+ */
3266
+ getUseGrouping: function getUseGrouping() {
3267
+ return !isUndefined(this.getMatches().find(function (match) {
3268
+ return match === ',';
3269
+ }));
3270
+ }
3271
+ };
3272
+ }
3273
+
3274
+ function CurrencyConverter(options) {
3275
+ /* istanbul ignore next */
3276
+ var mergeTags = function mergeTags() {
3277
+ var string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3278
+ var tags = arguments.length > 1 ? arguments[1] : undefined;
3279
+
3280
+ for (var tag in tags) {
3281
+ string = string.replace("{{".concat(tag, "}}"), tags[tag]);
3282
+ }
3283
+
3284
+ return string;
3285
+ };
3286
+ /* istanbul ignore next */
3287
+
3288
+
3289
+ var getRatesFromRestApi = function getRatesFromRestApi(from, to) {
3290
+ return getJSON(mergeTags(options.endpoint, {
3291
+ from: from,
3292
+ to: to
3293
+ }), {
3294
+ headers: options.headers
3295
+ });
3296
+ };
3297
+
3298
+ return {
3299
+ /**
3300
+ * Returns the exchange rate.
3301
+ * @ignore
3302
+ *
3303
+ * @param {String} from - The base currency.
3304
+ * @param {String} to - The destination currency.
3305
+ *
3306
+ * @return {Promise}
3307
+ */
3308
+ getExchangeRate: function getExchangeRate(from, to) {
3309
+ return (isThenable(options.endpoint) ? options.endpoint : getRatesFromRestApi(from, to)).then(function (data) {
3310
+ return flattenObject(data)[mergeTags(options.propertyPath, {
3311
+ from: from,
3312
+ to: to
3313
+ })];
3314
+ });
3315
+ }
3316
+ };
3317
+ }
3318
+
3319
+ /**
3320
+ * Performs an assertion.
3321
+ * @ignore
3322
+ *
3323
+ * @param {Boolean} condition - The expression to assert.
3324
+ * @param {String} errorMessage - The message to throw if the assertion fails
3325
+ * @param {ErrorConstructor} [ErrorType=Error] - The error to throw if the assertion fails.
3326
+ *
3327
+ * @throws {Error} If `condition` returns `false`.
3328
+ */
3329
+
3330
+ function assert(condition, errorMessage) {
3331
+ var ErrorType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Error;
3332
+ if (!condition) throw new ErrorType(errorMessage);
3333
+ }
3334
+ /**
3335
+ * Asserts a value is a percentage.
3336
+ * @ignore
3337
+ *
3338
+ * @param {} percentage - The percentage to test.
3339
+ *
3340
+ * @throws {RangeError} If `percentage` is out of range.
3341
+ */
3342
+
3343
+ function assertPercentage(percentage) {
3344
+ assert(isPercentage(percentage), 'You must provide a numeric value between 0 and 100.', RangeError);
3345
+ }
3346
+ /**
3347
+ * Asserts an array of ratios is valid.
3348
+ * @ignore
3349
+ *
3350
+ * @param {} ratios - The ratios to test.
3351
+ *
3352
+ * @throws {TypeError} If `ratios` are invalid.
3353
+ */
3354
+
3355
+ function assertValidRatios(ratios) {
3356
+ assert(areValidRatios(ratios), 'You must provide a non-empty array of numeric values greater than 0.', TypeError);
3357
+ }
3358
+ /**
3359
+ * Asserts a value is an integer.
3360
+ * @ignore
3361
+ *
3362
+ * @param {} number - The value to test.
3363
+ *
3364
+ * @throws {TypeError}
3365
+ */
3366
+
3367
+ function assertInteger(number) {
3368
+ assert(Number.isInteger(number), 'You must provide an integer.', TypeError);
3369
+ }
3370
+
3371
+ var calculator$1 = Calculator();
3372
+ /**
3373
+ * A Dinero object is an immutable data structure representing a specific monetary value.
3374
+ * It comes with methods for creating, parsing, manipulating, testing, transforming and formatting them.
3375
+ *
3376
+ * A Dinero object has:
3377
+ *
3378
+ * * An `amount`, expressed in minor currency units, as an integer.
3379
+ * * A `currency`, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3380
+ * * A `precision`, expressed as an integer, to represent the number of decimal places in the `amount`.
3381
+ * This is helpful when you want to represent fractional minor currency units (e.g.: $10.4545).
3382
+ * You can also use it to represent a currency with a different [exponent](https://en.wikipedia.org/wiki/ISO_4217#Treatment_of_minor_currency_units_.28the_.22exponent.22.29) than `2` (e.g.: Iraqi dinar with 1000 fils in 1 dinar (exponent of `3`), Japanese yen with no sub-units (exponent of `0`)).
3383
+ * * An optional `locale` property that affects how output strings are formatted.
3384
+ *
3385
+ * Here's an overview of the public API:
3386
+ *
3387
+ * * **Access:** {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~getCurrency getCurrency}, {@link module:Dinero~getLocale getLocale} and {@link module:Dinero~getPrecision getPrecision}.
3388
+ * * **Manipulation:** {@link module:Dinero~add add}, {@link module:Dinero~subtract subtract}, {@link module:Dinero~multiply multiply}, {@link module:Dinero~divide divide}, {@link module:Dinero~percentage percentage}, {@link module:Dinero~allocate allocate} and {@link module:Dinero~convert convert}.
3389
+ * * **Testing:** {@link module:Dinero~equalsTo equalsTo}, {@link module:Dinero~lessThan lessThan}, {@link module:Dinero~lessThanOrEqual lessThanOrEqual}, {@link module:Dinero~greaterThan greaterThan}, {@link module:Dinero~greaterThanOrEqual greaterThanOrEqual}, {@link module:Dinero~isZero isZero}, {@link module:Dinero~isPositive isPositive}, {@link module:Dinero~isNegative isNegative}, {@link module:Dinero~hasSubUnits hasSubUnits}, {@link module:Dinero~hasSameCurrency hasSameCurrency} and {@link module:Dinero~hasSameAmount hasSameAmount}.
3390
+ * * **Configuration:** {@link module:Dinero~setLocale setLocale}.
3391
+ * * **Conversion & formatting:** {@link module:Dinero~toFormat toFormat}, {@link module:Dinero~toUnit toUnit}, {@link module:Dinero~toRoundedUnit toRoundedUnit}, {@link module:Dinero~toObject toObject}, {@link module:Dinero~toJSON toJSON}, {@link module:Dinero~convertPrecision convertPrecision} and {@link module:Dinero.normalizePrecision normalizePrecision}.
3392
+ *
3393
+ * Dinero.js uses `number`s under the hood, so it's constrained by the [double-precision floating-point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Using values over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) will yield unpredictable results.
3394
+ * Same goes with performing calculations: once the internal `amount` value exceeds those limits, precision is no longer guaranteed.
3395
+ *
3396
+ * @module Dinero
3397
+ * @param {Number} [options.amount=0] - The amount in minor currency units (as an integer).
3398
+ * @param {String} [options.currency='USD'] - An ISO 4217 currency code.
3399
+ * @param {String} [options.precision=2] - The number of decimal places to represent.
3400
+ *
3401
+ * @throws {TypeError} If `amount` or `precision` is invalid. Integers over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) are considered valid, even though they can lead to imprecise amounts.
3402
+ *
3403
+ * @return {Object}
3404
+ */
3405
+
3406
+ var Dinero = function Dinero(options) {
3407
+ var _Object$assign = Object.assign({}, {
3408
+ amount: Dinero.defaultAmount,
3409
+ currency: Dinero.defaultCurrency,
3410
+ precision: Dinero.defaultPrecision
3411
+ }, options),
3412
+ amount = _Object$assign.amount,
3413
+ currency = _Object$assign.currency,
3414
+ precision = _Object$assign.precision;
3415
+
3416
+ assertInteger(amount);
3417
+ assertInteger(precision);
3418
+ var globalLocale = Dinero.globalLocale,
3419
+ globalFormat = Dinero.globalFormat,
3420
+ globalRoundingMode = Dinero.globalRoundingMode,
3421
+ globalFormatRoundingMode = Dinero.globalFormatRoundingMode;
3422
+ var globalExchangeRatesApi = Object.assign({}, Dinero.globalExchangeRatesApi);
3423
+ /**
3424
+ * Uses ES5 function notation so `this` can be passed through call, apply and bind
3425
+ * @ignore
3426
+ */
3427
+
3428
+ var create = function create(options) {
3429
+ var obj = Object.assign({}, Object.assign({}, {
3430
+ amount: amount,
3431
+ currency: currency,
3432
+ precision: precision
3433
+ }, options), Object.assign({}, {
3434
+ locale: this.locale
3435
+ }, options));
3436
+ return Object.assign(Dinero({
3437
+ amount: obj.amount,
3438
+ currency: obj.currency,
3439
+ precision: obj.precision
3440
+ }), {
3441
+ locale: obj.locale
3442
+ });
3443
+ };
3444
+ /**
3445
+ * Uses ES5 function notation so `this` can be passed through call, apply and bind
3446
+ * @ignore
3447
+ */
3448
+
3449
+
3450
+ var assertSameCurrency = function assertSameCurrency(comparator) {
3451
+ assert(this.hasSameCurrency(comparator), 'You must provide a Dinero instance with the same currency.', TypeError);
3452
+ };
3453
+
3454
+ return {
3455
+ /**
3456
+ * Returns the amount.
3457
+ *
3458
+ * @example
3459
+ * // returns 500
3460
+ * Dinero({ amount: 500 }).getAmount()
3461
+ *
3462
+ * @return {Number}
3463
+ */
3464
+ getAmount: function getAmount() {
3465
+ return amount;
3466
+ },
3467
+
3468
+ /**
3469
+ * Returns the currency.
3470
+ *
3471
+ * @example
3472
+ * // returns 'EUR'
3473
+ * Dinero({ currency: 'EUR' }).getCurrency()
3474
+ *
3475
+ * @return {String}
3476
+ */
3477
+ getCurrency: function getCurrency() {
3478
+ return currency;
3479
+ },
3480
+
3481
+ /**
3482
+ * Returns the locale.
3483
+ *
3484
+ * @example
3485
+ * // returns 'fr-FR'
3486
+ * Dinero().setLocale('fr-FR').getLocale()
3487
+ *
3488
+ * @return {String}
3489
+ */
3490
+ getLocale: function getLocale() {
3491
+ return this.locale || globalLocale;
3492
+ },
3493
+
3494
+ /**
3495
+ * Returns a new Dinero object with an embedded locale.
3496
+ *
3497
+ * @param {String} newLocale - The new locale as an {@link http://tools.ietf.org/html/rfc5646 BCP 47 language tag}.
3498
+ *
3499
+ * @example
3500
+ * // Returns a Dinero object with locale 'ja-JP'
3501
+ * Dinero().setLocale('ja-JP')
3502
+ *
3503
+ * @return {Dinero}
3504
+ */
3505
+ setLocale: function setLocale(newLocale) {
3506
+ return create.call(this, {
3507
+ locale: newLocale
3508
+ });
3509
+ },
3510
+
3511
+ /**
3512
+ * Returns the precision.
3513
+ *
3514
+ * @example
3515
+ * // returns 3
3516
+ * Dinero({ precision: 3 }).getPrecision()
3517
+ *
3518
+ * @return {Number}
3519
+ */
3520
+ getPrecision: function getPrecision() {
3521
+ return precision;
3522
+ },
3523
+
3524
+ /**
3525
+ * Returns a new Dinero object with a new precision and a converted amount.
3526
+ *
3527
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3528
+ * This can be necessary when you need to convert objects to a smaller precision.
3529
+ *
3530
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent conversions for safer results.
3531
+ * You can also specify a different `roundingMode` to better fit your needs.
3532
+ *
3533
+ * @param {Number} newPrecision - The new precision.
3534
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3535
+ *
3536
+ * @example
3537
+ * // Returns a Dinero object with precision 3 and amount 1000
3538
+ * Dinero({ amount: 100, precision: 2 }).convertPrecision(3)
3539
+ *
3540
+ * @throws {TypeError} If `newPrecision` is invalid.
3541
+ *
3542
+ * @return {Dinero}
3543
+ */
3544
+ convertPrecision: function convertPrecision(newPrecision) {
3545
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
3546
+ assertInteger(newPrecision);
3547
+ var precision = this.getPrecision();
3548
+ var isNewPrecisionLarger = newPrecision > precision;
3549
+ var operation = isNewPrecisionLarger ? calculator$1.multiply : calculator$1.divide;
3550
+ var terms = isNewPrecisionLarger ? [newPrecision, precision] : [precision, newPrecision];
3551
+ var factor = Math.pow(10, calculator$1.subtract.apply(calculator$1, terms));
3552
+ return create.call(this, {
3553
+ amount: calculator$1.round(operation(this.getAmount(), factor), roundingMode),
3554
+ precision: newPrecision
3555
+ });
3556
+ },
3557
+
3558
+ /**
3559
+ * Returns a new Dinero object that represents the sum of this and an other Dinero object.
3560
+ *
3561
+ * If Dinero objects have a different `precision`, they will be first converted to the highest.
3562
+ *
3563
+ * @param {Dinero} addend - The Dinero object to add.
3564
+ *
3565
+ * @example
3566
+ * // returns a Dinero object with amount 600
3567
+ * Dinero({ amount: 400 }).add(Dinero({ amount: 200 }))
3568
+ * @example
3569
+ * // returns a Dinero object with amount 144545 and precision 4
3570
+ * Dinero({ amount: 400 }).add(Dinero({ amount: 104545, precision: 4 }))
3571
+ *
3572
+ * @throws {TypeError} If `addend` has a different currency.
3573
+ *
3574
+ * @return {Dinero}
3575
+ */
3576
+ add: function add(addend) {
3577
+ assertSameCurrency.call(this, addend);
3578
+ var addends = Dinero.normalizePrecision([this, addend]);
3579
+ return create.call(this, {
3580
+ amount: calculator$1.add(addends[0].getAmount(), addends[1].getAmount()),
3581
+ precision: addends[0].getPrecision()
3582
+ });
3583
+ },
3584
+
3585
+ /**
3586
+ * Returns a new Dinero object that represents the difference of this and an other Dinero object.
3587
+ *
3588
+ * If Dinero objects have a different `precision`, they will be first converted to the highest.
3589
+ *
3590
+ * @param {Dinero} subtrahend - The Dinero object to subtract.
3591
+ *
3592
+ * @example
3593
+ * // returns a Dinero object with amount 200
3594
+ * Dinero({ amount: 400 }).subtract(Dinero({ amount: 200 }))
3595
+ * @example
3596
+ * // returns a Dinero object with amount 64545 and precision 4
3597
+ * Dinero({ amount: 104545, precision: 4 }).subtract(Dinero({ amount: 400 }))
3598
+ *
3599
+ * @throws {TypeError} If `subtrahend` has a different currency.
3600
+ *
3601
+ * @return {Dinero}
3602
+ */
3603
+ subtract: function subtract(subtrahend) {
3604
+ assertSameCurrency.call(this, subtrahend);
3605
+ var subtrahends = Dinero.normalizePrecision([this, subtrahend]);
3606
+ return create.call(this, {
3607
+ amount: calculator$1.subtract(subtrahends[0].getAmount(), subtrahends[1].getAmount()),
3608
+ precision: subtrahends[0].getPrecision()
3609
+ });
3610
+ },
3611
+
3612
+ /**
3613
+ * Returns a new Dinero object that represents the multiplied value by the given factor.
3614
+ *
3615
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3616
+ *
3617
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3618
+ * You can also specify a different `roundingMode` to better fit your needs.
3619
+ *
3620
+ * @param {Number} multiplier - The factor to multiply by.
3621
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3622
+ *
3623
+ * @example
3624
+ * // returns a Dinero object with amount 1600
3625
+ * Dinero({ amount: 400 }).multiply(4)
3626
+ * @example
3627
+ * // returns a Dinero object with amount 800
3628
+ * Dinero({ amount: 400 }).multiply(2.001)
3629
+ * @example
3630
+ * // returns a Dinero object with amount 801
3631
+ * Dinero({ amount: 400 }).multiply(2.00125, 'HALF_UP')
3632
+ *
3633
+ * @return {Dinero}
3634
+ */
3635
+ multiply: function multiply(multiplier) {
3636
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3637
+ return create.call(this, {
3638
+ amount: calculator$1.round(calculator$1.multiply(this.getAmount(), multiplier), roundingMode)
3639
+ });
3640
+ },
3641
+
3642
+ /**
3643
+ * Returns a new Dinero object that represents the divided value by the given factor.
3644
+ *
3645
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3646
+ *
3647
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3648
+ * You can also specify a different `roundingMode` to better fit your needs.
3649
+ *
3650
+ * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3651
+ *
3652
+ * @param {Number} divisor - The factor to divide by.
3653
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3654
+ *
3655
+ * @example
3656
+ * // returns a Dinero object with amount 100
3657
+ * Dinero({ amount: 400 }).divide(4)
3658
+ * @example
3659
+ * // returns a Dinero object with amount 52
3660
+ * Dinero({ amount: 105 }).divide(2)
3661
+ * @example
3662
+ * // returns a Dinero object with amount 53
3663
+ * Dinero({ amount: 105 }).divide(2, 'HALF_UP')
3664
+ *
3665
+ * @return {Dinero}
3666
+ */
3667
+ divide: function divide(divisor) {
3668
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3669
+ return create.call(this, {
3670
+ amount: calculator$1.round(calculator$1.divide(this.getAmount(), divisor), roundingMode)
3671
+ });
3672
+ },
3673
+
3674
+ /**
3675
+ * Returns a new Dinero object that represents a percentage of this.
3676
+ *
3677
+ * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3678
+ *
3679
+ * @param {Number} percentage - The percentage to extract (between 0 and 100).
3680
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3681
+ *
3682
+ * @example
3683
+ * // returns a Dinero object with amount 5000
3684
+ * Dinero({ amount: 10000 }).percentage(50)
3685
+ * @example
3686
+ * // returns a Dinero object with amount 29
3687
+ * Dinero({ amount: 57 }).percentage(50, "HALF_ODD")
3688
+ *
3689
+ * @throws {RangeError} If `percentage` is out of range.
3690
+ *
3691
+ * @return {Dinero}
3692
+ */
3693
+ percentage: function percentage(_percentage) {
3694
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3695
+ assertPercentage(_percentage);
3696
+ return this.multiply(calculator$1.divide(_percentage, 100), roundingMode);
3697
+ },
3698
+
3699
+ /**
3700
+ * Allocates the amount of a Dinero object according to a list of ratios.
3701
+ *
3702
+ * Sometimes you need to split monetary values but percentages can't cut it without adding or losing pennies.
3703
+ * A good example is invoicing: let's say you need to bill $1,000.03 and you want a 50% downpayment.
3704
+ * If you use {@link module:Dinero~percentage percentage}, you'll get an accurate Dinero object but the amount won't be billable: you can't split a penny.
3705
+ * If you round it, you'll bill a penny extra.
3706
+ * With {@link module:Dinero~allocate allocate}, you can split a monetary amount then distribute the remainder as evenly as possible.
3707
+ *
3708
+ * You can use percentage style or ratio style for `ratios`: `[25, 75]` and `[1, 3]` will do the same thing.
3709
+ *
3710
+ * Since v1.8.0, you can use zero ratios (such as [0, 50, 50]). If there's a remainder to distribute, zero ratios are skipped and return a Dinero object with amount zero.
3711
+ *
3712
+ * @param {Number[]} ratios - The ratios to allocate the money to.
3713
+ *
3714
+ * @example
3715
+ * // returns an array of two Dinero objects
3716
+ * // the first one with an amount of 502
3717
+ * // the second one with an amount of 501
3718
+ * Dinero({ amount: 1003 }).allocate([50, 50])
3719
+ * @example
3720
+ * // returns an array of two Dinero objects
3721
+ * // the first one with an amount of 25
3722
+ * // the second one with an amount of 75
3723
+ * Dinero({ amount: 100 }).allocate([1, 3])
3724
+ * @example
3725
+ * // since version 1.8.0
3726
+ * // returns an array of three Dinero objects
3727
+ * // the first one with an amount of 0
3728
+ * // the second one with an amount of 502
3729
+ * // the third one with an amount of 501
3730
+ * Dinero({ amount: 1003 }).allocate([0, 50, 50])
3731
+ *
3732
+ * @throws {TypeError} If ratios are invalid.
3733
+ *
3734
+ * @return {Dinero[]}
3735
+ */
3736
+ allocate: function allocate(ratios) {
3737
+ var _this = this;
3738
+
3739
+ assertValidRatios(ratios);
3740
+ var total = ratios.reduce(function (a, b) {
3741
+ return calculator$1.add(a, b);
3742
+ });
3743
+ var remainder = this.getAmount();
3744
+ var shares = ratios.map(function (ratio) {
3745
+ var share = Math.floor(calculator$1.divide(calculator$1.multiply(_this.getAmount(), ratio), total));
3746
+ remainder = calculator$1.subtract(remainder, share);
3747
+ return create.call(_this, {
3748
+ amount: share
3749
+ });
3750
+ });
3751
+ var i = 0;
3752
+
3753
+ while (remainder > 0) {
3754
+ if (ratios[i] > 0) {
3755
+ shares[i] = shares[i].add(create.call(this, {
3756
+ amount: 1
3757
+ }));
3758
+ remainder = calculator$1.subtract(remainder, 1);
3759
+ }
3760
+
3761
+ i += 1;
3762
+ }
3763
+
3764
+ return shares;
3765
+ },
3766
+
3767
+ /**
3768
+ * Returns a Promise containing a new Dinero object converted to another currency.
3769
+ *
3770
+ * You have two options to provide the exchange rates:
3771
+ *
3772
+ * 1. **Use an exchange rate REST API, and let Dinero handle the fetching and conversion.**
3773
+ * This is a simple option if you have access to an exchange rate REST API and want Dinero to do the rest.
3774
+ * 2. **Fetch the exchange rates on your own and provide them directly.**
3775
+ * This is useful if you're fetching your rates from somewhere else (a file, a database), use a different protocol or query language than REST (SOAP, GraphQL) or want to fetch rates once and cache them instead of making new requests every time.
3776
+ *
3777
+ * **If you want to use a REST API**, you must provide a third-party endpoint yourself. Dinero doesn't come bundled with an exchange rates endpoint.
3778
+ *
3779
+ * Here are some exchange rate APIs you can use:
3780
+ *
3781
+ * * [Fixer](https://fixer.io)
3782
+ * * [Open Exchange Rates](https://openexchangerates.org)
3783
+ * * [Coinbase](https://api.coinbase.com/v2/exchange-rates)
3784
+ * * More [foreign](https://github.com/toddmotto/public-apis#currency-exchange) and [crypto](https://github.com/toddmotto/public-apis#cryptocurrency) exchange rate APIs.
3785
+ *
3786
+ * **If you want to fetch your own rates and provide them directly**, you need to pass a promise that resolves to the exchanges rates.
3787
+ *
3788
+ * In both cases, you need to specify at least:
3789
+ *
3790
+ * * a **destination currency**: the currency in which you want to convert your Dinero object. You can specify it with `currency`.
3791
+ * * an **endpoint**: the API URL to query exchange rates, with parameters, or a promise that resolves to the exchange rates. You can specify it with `options.endpoint`.
3792
+ * * a **property path**: the path to access the wanted rate in your API's JSON response (or the custom promise's payload). For example, with a response of:
3793
+ * ```json
3794
+ * {
3795
+ * "data": {
3796
+ * "base": "USD",
3797
+ * "destination": "EUR",
3798
+ * "rate": "0.827728919"
3799
+ * }
3800
+ * }
3801
+ * ```
3802
+ * Then the property path is `'data.rate'`. You can specify it with `options.propertyPath`.
3803
+ *
3804
+ * The base currency (the one of your Dinero object) and the destination currency can be used as "merge tags" with the mustache syntax, respectively `{{from}}` and `{{to}}`.
3805
+ * You can use these tags to refer to these values in `options.endpoint` and `options.propertyPath`.
3806
+ *
3807
+ * For example, if you need to specify the base currency as a query parameter, you can do the following:
3808
+ *
3809
+ * ```js
3810
+ * {
3811
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}'
3812
+ * }
3813
+ * ```
3814
+ *
3815
+ * @param {String} currency - The destination currency, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3816
+ * @param {(String|Promise)} options.endpoint - The API endpoint to retrieve exchange rates. You can substitute this with a promise that resolves to the exchanges rates if you already have them.
3817
+ * @param {String} [options.propertyPath='rates.{{to}}'] - The property path to the rate.
3818
+ * @param {Object} [options.headers] - The HTTP headers to provide, if needed.
3819
+ * @param {String} [options.roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3820
+ *
3821
+ * @example
3822
+ * // your global API parameters
3823
+ * Dinero.globalExchangeRatesApi = { ... }
3824
+ *
3825
+ * // returns a Promise containing a Dinero object with the destination currency
3826
+ * // and the initial amount converted to the new currency.
3827
+ * Dinero({ amount: 500 }).convert('EUR')
3828
+ * @example
3829
+ * // returns a Promise containing a Dinero object,
3830
+ * // with specific API parameters and rounding mode for this specific instance.
3831
+ * Dinero({ amount: 500 })
3832
+ * .convert('XBT', {
3833
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
3834
+ * propertyPath: 'data.rates.{{to}}',
3835
+ * headers: {
3836
+ * 'user-key': 'xxxxxxxxx'
3837
+ * },
3838
+ * roundingMode: 'HALF_UP'
3839
+ * })
3840
+ * @example
3841
+ * // usage with exchange rates provided as a custom promise
3842
+ * // using the default `propertyPath` format (so it doesn't have to be specified)
3843
+ * const rates = {
3844
+ * rates: {
3845
+ * EUR: 0.81162
3846
+ * }
3847
+ * }
3848
+ *
3849
+ * Dinero({ amount: 500 })
3850
+ * .convert('EUR', {
3851
+ * endpoint: new Promise(resolve => resolve(rates))
3852
+ * })
3853
+ * @example
3854
+ * // usage with Promise.prototype.then and Promise.prototype.catch
3855
+ * Dinero({ amount: 500 })
3856
+ * .convert('EUR')
3857
+ * .then(dinero => {
3858
+ * dinero.getCurrency() // returns 'EUR'
3859
+ * })
3860
+ * .catch(err => {
3861
+ * // handle errors
3862
+ * })
3863
+ * @example
3864
+ * // usage with async/await
3865
+ * (async () => {
3866
+ * const price = await Dinero({ amount: 500 }).convert('EUR')
3867
+ * price.getCurrency() // returns 'EUR'
3868
+ * })()
3869
+ *
3870
+ * @return {Promise}
3871
+ */
3872
+ convert: function convert(currency) {
3873
+ var _this2 = this;
3874
+
3875
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
3876
+ _ref$endpoint = _ref.endpoint,
3877
+ endpoint = _ref$endpoint === void 0 ? globalExchangeRatesApi.endpoint : _ref$endpoint,
3878
+ _ref$propertyPath = _ref.propertyPath,
3879
+ propertyPath = _ref$propertyPath === void 0 ? globalExchangeRatesApi.propertyPath || 'rates.{{to}}' : _ref$propertyPath,
3880
+ _ref$headers = _ref.headers,
3881
+ headers = _ref$headers === void 0 ? globalExchangeRatesApi.headers : _ref$headers,
3882
+ _ref$roundingMode = _ref.roundingMode,
3883
+ roundingMode = _ref$roundingMode === void 0 ? globalRoundingMode : _ref$roundingMode;
3884
+
3885
+ var options = Object.assign({}, {
3886
+ endpoint: endpoint,
3887
+ propertyPath: propertyPath,
3888
+ headers: headers,
3889
+ roundingMode: roundingMode
3890
+ });
3891
+ return CurrencyConverter(options).getExchangeRate(this.getCurrency(), currency).then(function (rate) {
3892
+ assert(!isUndefined(rate), "No rate was found for the destination currency \"".concat(currency, "\"."), TypeError);
3893
+ return create.call(_this2, {
3894
+ amount: calculator$1.round(calculator$1.multiply(_this2.getAmount(), parseFloat(rate)), options.roundingMode),
3895
+ currency: currency
3896
+ });
3897
+ });
3898
+ },
3899
+
3900
+ /**
3901
+ * Checks whether the value represented by this object equals to the other.
3902
+ *
3903
+ * @param {Dinero} comparator - The Dinero object to compare to.
3904
+ *
3905
+ * @example
3906
+ * // returns true
3907
+ * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3908
+ * @example
3909
+ * // returns false
3910
+ * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3911
+ * @example
3912
+ * // returns false
3913
+ * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3914
+ * @example
3915
+ * // returns false
3916
+ * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3917
+ * @example
3918
+ * // returns true
3919
+ * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3920
+ * @example
3921
+ * // returns false
3922
+ * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3923
+ *
3924
+ * @return {Boolean}
3925
+ */
3926
+ equalsTo: function equalsTo(comparator) {
3927
+ return this.hasSameAmount(comparator) && this.hasSameCurrency(comparator);
3928
+ },
3929
+
3930
+ /**
3931
+ * Checks whether the value represented by this object is less than the other.
3932
+ *
3933
+ * @param {Dinero} comparator - The Dinero object to compare to.
3934
+ *
3935
+ * @example
3936
+ * // returns true
3937
+ * Dinero({ amount: 500 }).lessThan(Dinero({ amount: 800 }))
3938
+ * @example
3939
+ * // returns false
3940
+ * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 500 }))
3941
+ * @example
3942
+ * // returns true
3943
+ * Dinero({ amount: 5000, precision: 3 }).lessThan(Dinero({ amount: 800 }))
3944
+ * @example
3945
+ * // returns false
3946
+ * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 5000, precision: 3 }))
3947
+ *
3948
+ * @throws {TypeError} If `comparator` has a different currency.
3949
+ *
3950
+ * @return {Boolean}
3951
+ */
3952
+ lessThan: function lessThan(comparator) {
3953
+ assertSameCurrency.call(this, comparator);
3954
+ var comparators = Dinero.normalizePrecision([this, comparator]);
3955
+ return comparators[0].getAmount() < comparators[1].getAmount();
3956
+ },
3957
+
3958
+ /**
3959
+ * Checks whether the value represented by this object is less than or equal to the other.
3960
+ *
3961
+ * @param {Dinero} comparator - The Dinero object to compare to.
3962
+ *
3963
+ * @example
3964
+ * // returns true
3965
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 800 }))
3966
+ * @example
3967
+ * // returns true
3968
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 500 }))
3969
+ * @example
3970
+ * // returns false
3971
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 300 }))
3972
+ * @example
3973
+ * // returns true
3974
+ * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 800 }))
3975
+ * @example
3976
+ * // returns true
3977
+ * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 500 }))
3978
+ * @example
3979
+ * // returns false
3980
+ * Dinero({ amount: 800 }).lessThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
3981
+ *
3982
+ * @throws {TypeError} If `comparator` has a different currency.
3983
+ *
3984
+ * @return {Boolean}
3985
+ */
3986
+ lessThanOrEqual: function lessThanOrEqual(comparator) {
3987
+ assertSameCurrency.call(this, comparator);
3988
+ var comparators = Dinero.normalizePrecision([this, comparator]);
3989
+ return comparators[0].getAmount() <= comparators[1].getAmount();
3990
+ },
3991
+
3992
+ /**
3993
+ * Checks whether the value represented by this object is greater than the other.
3994
+ *
3995
+ * @param {Dinero} comparator - The Dinero object to compare to.
3996
+ *
3997
+ * @example
3998
+ * // returns false
3999
+ * Dinero({ amount: 500 }).greaterThan(Dinero({ amount: 800 }))
4000
+ * @example
4001
+ * // returns true
4002
+ * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 500 }))
4003
+ * @example
4004
+ * // returns true
4005
+ * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 5000, precision: 3 }))
4006
+ * @example
4007
+ * // returns false
4008
+ * Dinero({ amount: 5000, precision: 3 }).greaterThan(Dinero({ amount: 800 }))
4009
+ *
4010
+ * @throws {TypeError} If `comparator` has a different currency.
4011
+ *
4012
+ * @return {Boolean}
4013
+ */
4014
+ greaterThan: function greaterThan(comparator) {
4015
+ assertSameCurrency.call(this, comparator);
4016
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4017
+ return comparators[0].getAmount() > comparators[1].getAmount();
4018
+ },
4019
+
4020
+ /**
4021
+ * Checks whether the value represented by this object is greater than or equal to the other.
4022
+ *
4023
+ * @param {Dinero} comparator - The Dinero object to compare to.
4024
+ *
4025
+ * @example
4026
+ * // returns true
4027
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 300 }))
4028
+ * @example
4029
+ * // returns true
4030
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 500 }))
4031
+ * @example
4032
+ * // returns false
4033
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 800 }))
4034
+ * @example
4035
+ * // returns true
4036
+ * Dinero({ amount: 800 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
4037
+ * @example
4038
+ * // returns true
4039
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
4040
+ * @example
4041
+ * // returns false
4042
+ * Dinero({ amount: 5000, precision: 3 }).greaterThanOrEqual(Dinero({ amount: 800 }))
4043
+ *
4044
+ * @throws {TypeError} If `comparator` has a different currency.
4045
+ *
4046
+ * @return {Boolean}
4047
+ */
4048
+ greaterThanOrEqual: function greaterThanOrEqual(comparator) {
4049
+ assertSameCurrency.call(this, comparator);
4050
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4051
+ return comparators[0].getAmount() >= comparators[1].getAmount();
4052
+ },
4053
+
4054
+ /**
4055
+ * Checks if the value represented by this object is zero.
4056
+ *
4057
+ * @example
4058
+ * // returns true
4059
+ * Dinero({ amount: 0 }).isZero()
4060
+ * @example
4061
+ * // returns false
4062
+ * Dinero({ amount: 100 }).isZero()
4063
+ *
4064
+ * @return {Boolean}
4065
+ */
4066
+ isZero: function isZero() {
4067
+ return this.getAmount() === 0;
4068
+ },
4069
+
4070
+ /**
4071
+ * Checks if the value represented by this object is positive.
4072
+ *
4073
+ * @example
4074
+ * // returns false
4075
+ * Dinero({ amount: -10 }).isPositive()
4076
+ * @example
4077
+ * // returns true
4078
+ * Dinero({ amount: 10 }).isPositive()
4079
+ * @example
4080
+ * // returns true
4081
+ * Dinero({ amount: 0 }).isPositive()
4082
+ *
4083
+ * @return {Boolean}
4084
+ */
4085
+ isPositive: function isPositive() {
4086
+ return this.getAmount() >= 0;
4087
+ },
4088
+
4089
+ /**
4090
+ * Checks if the value represented by this object is negative.
4091
+ *
4092
+ * @example
4093
+ * // returns true
4094
+ * Dinero({ amount: -10 }).isNegative()
4095
+ * @example
4096
+ * // returns false
4097
+ * Dinero({ amount: 10 }).isNegative()
4098
+ * @example
4099
+ * // returns false
4100
+ * Dinero({ amount: 0 }).isNegative()
4101
+ *
4102
+ * @return {Boolean}
4103
+ */
4104
+ isNegative: function isNegative() {
4105
+ return this.getAmount() < 0;
4106
+ },
4107
+
4108
+ /**
4109
+ * Checks if this has minor currency units.
4110
+ * Deprecates {@link module:Dinero~hasCents hasCents}.
4111
+ *
4112
+ * @example
4113
+ * // returns false
4114
+ * Dinero({ amount: 1100 }).hasSubUnits()
4115
+ * @example
4116
+ * // returns true
4117
+ * Dinero({ amount: 1150 }).hasSubUnits()
4118
+ *
4119
+ * @return {Boolean}
4120
+ */
4121
+ hasSubUnits: function hasSubUnits() {
4122
+ return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4123
+ },
4124
+
4125
+ /**
4126
+ * Checks if this has minor currency units.
4127
+ *
4128
+ * @deprecated since version 1.4.0, will be removed in 2.0.0
4129
+ * Use {@link module:Dinero~hasSubUnits hasSubUnits} instead.
4130
+ *
4131
+ * @example
4132
+ * // returns false
4133
+ * Dinero({ amount: 1100 }).hasCents()
4134
+ * @example
4135
+ * // returns true
4136
+ * Dinero({ amount: 1150 }).hasCents()
4137
+ *
4138
+ * @return {Boolean}
4139
+ */
4140
+ hasCents: function hasCents() {
4141
+ return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4142
+ },
4143
+
4144
+ /**
4145
+ * Checks whether the currency represented by this object equals to the other.
4146
+ *
4147
+ * @param {Dinero} comparator - The Dinero object to compare to.
4148
+ *
4149
+ * @example
4150
+ * // returns true
4151
+ * Dinero({ amount: 2000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'EUR' }))
4152
+ * @example
4153
+ * // returns false
4154
+ * Dinero({ amount: 1000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'USD' }))
4155
+ *
4156
+ * @return {Boolean}
4157
+ */
4158
+ hasSameCurrency: function hasSameCurrency(comparator) {
4159
+ return this.getCurrency() === comparator.getCurrency();
4160
+ },
4161
+
4162
+ /**
4163
+ * Checks whether the amount represented by this object equals to the other.
4164
+ *
4165
+ * @param {Dinero} comparator - The Dinero object to compare to.
4166
+ *
4167
+ * @example
4168
+ * // returns true
4169
+ * Dinero({ amount: 1000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000 }))
4170
+ * @example
4171
+ * // returns false
4172
+ * Dinero({ amount: 2000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000, currency: 'EUR' }))
4173
+ * @example
4174
+ * // returns true
4175
+ * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4176
+ * @example
4177
+ * // returns false
4178
+ * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4179
+ *
4180
+ * @return {Boolean}
4181
+ */
4182
+ hasSameAmount: function hasSameAmount(comparator) {
4183
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4184
+ return comparators[0].getAmount() === comparators[1].getAmount();
4185
+ },
4186
+
4187
+ /**
4188
+ * Returns this object formatted as a string.
4189
+ *
4190
+ * The format is a mask which defines how the output string will be formatted.
4191
+ * It defines whether to display a currency, in what format, how many fraction digits to display and whether to use grouping separators.
4192
+ * The output is formatted according to the applying locale.
4193
+ *
4194
+ * Object | Format | String
4195
+ * :--------------------------- | :---------------- | :---
4196
+ * `Dinero({ amount: 500050 })` | `'$0,0.00'` | $5,000.50
4197
+ * `Dinero({ amount: 500050 })` | `'$0,0'` | $5,001
4198
+ * `Dinero({ amount: 500050 })` | `'$0'` | $5001
4199
+ * `Dinero({ amount: 500050 })` | `'$0.0'` | $5000.5
4200
+ * `Dinero({ amount: 500050 })` | `'USD0,0.0'` | USD5,000.5
4201
+ * `Dinero({ amount: 500050 })` | `'0,0.0 dollar'` | 5,000.5 dollars
4202
+ *
4203
+ * Don't try to substitute the `$` sign or the `USD` code with your target currency, nor adapt the format string to the exact format you want.
4204
+ * The format is a mask which defines a pattern and returns a valid, localized currency string.
4205
+ * If you want to display the object in a custom way, either use {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~toUnit toUnit} or {@link module:Dinero~toRoundedUnit toRoundedUnit} and manipulate the output string as you wish.
4206
+ *
4207
+ * {@link module:Dinero~toFormat toFormat} wraps around `Number.prototype.toLocaleString`. For that reason, **format will vary depending on how it's implemented in the end user's environment**.
4208
+ *
4209
+ * You can also use `toLocaleString` directly:
4210
+ * `Dinero().toRoundedUnit(digits, roundingMode).toLocaleString(locale, options)`.
4211
+ *
4212
+ * By default, amounts are rounded using the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4213
+ * You can also specify a different `roundingMode` to better fit your needs.
4214
+ *
4215
+ * @param {String} [format='$0,0.00'] - The format mask to format to.
4216
+ * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4217
+ *
4218
+ * @example
4219
+ * // returns $2,000
4220
+ * Dinero({ amount: 200000 }).toFormat('$0,0')
4221
+ * @example
4222
+ * // returns €50.5
4223
+ * Dinero({ amount: 5050, currency: 'EUR' }).toFormat('$0,0.0')
4224
+ * @example
4225
+ * // returns 100 euros
4226
+ * Dinero({ amount: 10000, currency: 'EUR' }).setLocale('fr-FR').toFormat('0,0 dollar')
4227
+ * @example
4228
+ * // returns 2000
4229
+ * Dinero({ amount: 200000, currency: 'EUR' }).toFormat()
4230
+ * @example
4231
+ * // returns $10
4232
+ * Dinero({ amount: 1050 }).toFormat('$0', 'HALF_EVEN')
4233
+ *
4234
+ * @return {String}
4235
+ */
4236
+ toFormat: function toFormat() {
4237
+ var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : globalFormat;
4238
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4239
+ var formatter = Format(format);
4240
+ return this.toRoundedUnit(formatter.getMinimumFractionDigits(), roundingMode).toLocaleString(this.getLocale(), {
4241
+ currencyDisplay: formatter.getCurrencyDisplay(),
4242
+ useGrouping: formatter.getUseGrouping(),
4243
+ minimumFractionDigits: formatter.getMinimumFractionDigits(),
4244
+ style: formatter.getStyle(),
4245
+ currency: this.getCurrency()
4246
+ });
4247
+ },
4248
+
4249
+ /**
4250
+ * Returns the amount represented by this object in units.
4251
+ *
4252
+ * @example
4253
+ * // returns 10.5
4254
+ * Dinero({ amount: 1050 }).toUnit()
4255
+ * @example
4256
+ * // returns 10.545
4257
+ * Dinero({ amount: 10545, precision: 3 }).toUnit()
4258
+ *
4259
+ * @return {Number}
4260
+ */
4261
+ toUnit: function toUnit() {
4262
+ return calculator$1.divide(this.getAmount(), Math.pow(10, precision));
4263
+ },
4264
+
4265
+ /**
4266
+ * Returns the amount represented by this object in rounded units.
4267
+ *
4268
+ * By default, the method uses the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4269
+ * You can also specify a different `roundingMode` to better fit your needs.
4270
+ *
4271
+ * @example
4272
+ * // returns 10.6
4273
+ * Dinero({ amount: 1055 }).toRoundedUnit(1)
4274
+ * @example
4275
+ * // returns 10
4276
+ * Dinero({ amount: 1050 }).toRoundedUnit(0, 'HALF_EVEN')
4277
+ *
4278
+ * @param {Number} digits - The number of fraction digits to round to.
4279
+ * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4280
+ *
4281
+ * @return {Number}
4282
+ */
4283
+ toRoundedUnit: function toRoundedUnit(digits) {
4284
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4285
+ var factor = Math.pow(10, digits);
4286
+ return calculator$1.divide(calculator$1.round(calculator$1.multiply(this.toUnit(), factor), roundingMode), factor);
4287
+ },
4288
+
4289
+ /**
4290
+ * Returns the object's data as an object literal.
4291
+ *
4292
+ * @example
4293
+ * // returns { amount: 500, currency: 'EUR', precision: 2 }
4294
+ * Dinero({ amount: 500, currency: 'EUR', precision: 2 }).toObject()
4295
+ *
4296
+ * @return {Object}
4297
+ */
4298
+ toObject: function toObject() {
4299
+ return {
4300
+ amount: amount,
4301
+ currency: currency,
4302
+ precision: precision
4303
+ };
4304
+ },
4305
+
4306
+ /**
4307
+ * Returns the object's data as an object literal.
4308
+ *
4309
+ * Alias of {@link module:Dinero~toObject toObject}.
4310
+ * It is defined so that calling `JSON.stringify` on a Dinero object will automatically extract the relevant data.
4311
+ *
4312
+ * @example
4313
+ * // returns '{"amount":500,"currency":"EUR","precision":2}'
4314
+ * JSON.stringify(Dinero({ amount: 500, currency: 'EUR', precision: 2 }))
4315
+ *
4316
+ * @return {Object}
4317
+ */
4318
+ toJSON: function toJSON() {
4319
+ return this.toObject();
4320
+ }
4321
+ };
4322
+ };
4323
+
4324
+ var dinero = Object.assign(Dinero, Defaults, Globals, Static);
4325
+
4326
+ function formatCurrency(amount, withSymbol = true) {
4327
+ if (!amount)
4328
+ amount = 0;
4329
+ function format(amount) {
4330
+ const formattedString = withSymbol ? '$0,0.00' : '0,0.00';
4331
+ return dinero({ amount: amount, currency: 'USD' }).toFormat(formattedString);
4332
+ }
4333
+ return (amount < 0) ? `(${format(-amount)})` : format(amount);
4334
+ }
4335
+ function formatDate(dateString) {
4336
+ if (!dateString)
4337
+ return '';
4338
+ const date = new Date(dateString);
4339
+ return format(date, 'MMM d, yyyy');
4340
+ }
4341
+ function formatTime(dateString) {
4342
+ if (!dateString)
4343
+ return '';
4344
+ const date = new Date(dateString);
4345
+ return format(date, 'h:mmaaa');
4346
+ }
4347
+
4348
+ const paymentsListCss = ":host{display:block}";
4349
+
4350
+ const PaymentsList = class {
4351
+ constructor(hostRef) {
4352
+ registerInstance(this, hostRef);
4353
+ this.accountId = undefined;
4354
+ this.auth = {};
4355
+ this.payments = [];
4356
+ }
4357
+ requestPropsChanged() {
4358
+ this.fetchData();
4359
+ }
4360
+ fetchData() {
4361
+ const accountId = this.accountId;
4362
+ const endpoint = `account/${accountId}/payments`;
4363
+ Api(this.auth.token).get(endpoint)
4364
+ .then((response) => {
4365
+ const data = response.data.map((dataItem) => new Payment(dataItem));
4366
+ this.payments = data;
4367
+ });
4368
+ }
4369
+ ;
4370
+ render() {
4371
+ return (h(Host, null, h("table", { class: "justifi-table" }, h("thead", null, h("tr", null, h("th", { scope: "col", title: "The date and time each payment was made" }, "Made on"), h("th", { scope: "col", title: "The dollar amount of each payment" }, "Amount"), h("th", { scope: "col" }, "Account"), h("th", { scope: "col" }, "Description"), h("th", { scope: "col" }, "Payment ID"), h("th", { scope: "col" }, "Cardholder"), h("th", { scope: "col" }, "Payment Method"), h("th", { scope: "col" }, "Status"))), h("tbody", null, this.payments.map((payment) => {
4372
+ var _a, _b, _c, _d;
4373
+ h("tr", null, h("td", null, h("div", null, formatDate(payment.created_at)), h("div", null, formatTime(payment.created_at))), h("td", null, formatCurrency(payment.amount)), h("td", null, payment.account_id), h("td", null, payment.description), h("td", null, payment.id), h("td", null, (_b = (_a = payment.payment_method) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.name), h("td", null, (_d = (_c = payment.payment_method) === null || _c === void 0 ? void 0 : _c.card) === null || _d === void 0 ? void 0 : _d.acct_last_four), h("td", null, payment.status));
4374
+ })))));
4375
+ }
4376
+ static get watchers() { return {
4377
+ "accountId": ["requestPropsChanged"],
4378
+ "auth": ["requestPropsChanged"]
4379
+ }; }
4380
+ };
4381
+ PaymentsList.style = paymentsListCss;
4382
+
4383
+ export { BankAccountForm as justifi_bank_account_form, CardForm as justifi_card_form, PaymentMethodForm as justifi_payment_method_form, PaymentsList as justifi_payments_list };