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