@justifi/webcomponents 0.0.6

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