@agnostack/next-shopify
Version:
Please contact agnoStack via info@agnostack.com for any questions
322 lines • 15.5 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatRequiredTimestamps = exports.formatTimestamps = exports.compareDate = exports.convertFormatted = exports.toFormatted = exports.toRFC822String = exports.toUTCString = exports.toISOString = exports.toUnixString = exports.toUnixInteger = exports.toJSDate = exports.ensureDateTime = exports.isSameDay = exports.isSameHour = exports.getWeeksBetween = exports.getDaysBetween = exports.getCurrentDateTime = exports.getDuration = exports.convertDuration = exports.convertDateTime = exports.getDateTimeFromString = exports.getDateTimeFormat = exports.setDateTimeZone = exports.setDateTimeLocale = exports.getDaysInMonth = exports.LOCALE_FORMATS = exports.CUSTOM_FORMATS = exports.DATE_FORMAT_ORGANIZED = exports.DATE_FORMAT_TRACKING = exports.DATE_FORMAT_LONG = exports.DATE_FORMAT_MED = exports.TIME_FORMAT_AMPM = exports.TIME_FORMAT_LONG = void 0;
/* eslint-disable no-use-before-define */
const luxon_1 = require("luxon");
const display_1 = require("./display");
// TODO!!!: keep in sync between next-shopify and lib-core
// TODO: consolidate these to export as COMMON_FORMATS
exports.TIME_FORMAT_LONG = 'HH:mm';
exports.TIME_FORMAT_AMPM = 'h:mm a';
const DATE_FORMAT_RFC822 = 'EEE, dd LLL yyyy HH:mm:ss ZZZ';
exports.DATE_FORMAT_MED = 'M/d/yyyy';
exports.DATE_FORMAT_LONG = 'MM/dd/yyyy';
exports.DATE_FORMAT_TRACKING = 'MMddyyyy';
exports.DATE_FORMAT_ORGANIZED = 'yyyy-MM-dd';
const { DATE_SHORT, DATE_MED, DATE_FULL, DATE_HUGE, DATETIME_SHORT, DATETIME_MED, DATETIME_MED_WITH_WEEKDAY, DATETIME_MED_WITH_SECONDS, DATETIME_FULL, DATETIME_HUGE, TIME_SIMPLE, } = luxon_1.DateTime;
const DATE_MINI = Object.assign(Object.assign({}, DATE_SHORT), { year: '2-digit' });
const DATETIME_MINI = Object.assign(Object.assign({}, DATETIME_SHORT), { year: '2-digit' });
const {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
timeZoneName: _timeZoneNameF } = DATETIME_FULL, DATETIME_FULL_NO_ZONE = __rest(DATETIME_FULL, ["timeZoneName"]);
const {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
timeZoneName: _timeZoneNameH } = DATETIME_HUGE, DATETIME_HUGE_NO_ZONE = __rest(DATETIME_HUGE, ["timeZoneName"]);
exports.CUSTOM_FORMATS = {
UTC: 'UTC',
ISO: 'ISO',
UNIX: 'UNIX',
RFC822: 'RFC822',
};
exports.LOCALE_FORMATS = {
DATE_MINI,
DATE_SHORT,
DATE_MED,
DATE_FULL,
DATE_HUGE,
DATETIME_MINI,
DATETIME_SHORT,
DATETIME_MED,
DATETIME_MED_WITH_WEEKDAY,
DATETIME_MED_WITH_SECONDS,
DATETIME_FULL_NO_ZONE,
DATETIME_HUGE_NO_ZONE,
TIME_SIMPLE,
};
const DATE_PARTS = {
day: 'dd',
month: 'MM',
year: 'yyyy',
};
const STANDARD_LOCALE_FORMATS = Object.values(exports.LOCALE_FORMATS);
const hasSomeNumbers = (value) => /\d/.test(value);
const hasOnlyValidCharacters = (value) => /^[\w-+:,\\/\s.]+$/.test(value); // TODO: confirm if these are all needed?
const getDaysInMonth = (year, month) => (new Date(year, month, 0).getDate());
exports.getDaysInMonth = getDaysInMonth;
const setDateTimeLocale = (locale) => {
if ((0, display_1.stringNotEmpty)(locale)) {
luxon_1.Settings.defaultLocale = locale;
}
};
exports.setDateTimeLocale = setDateTimeLocale;
const setDateTimeZone = (zone) => {
if ((0, display_1.stringNotEmpty)(zone)) {
luxon_1.Settings.defaultZone = zone;
}
};
exports.setDateTimeZone = setDateTimeZone;
const matchDateTimeByFormat = (input, options) => {
if (!(0, display_1.isTypeEnhanced)(input, 'string')) {
return undefined;
}
let validDateTime;
// NOTE: intentionally using for/of loop instead of map so we can break to exit quickly soon as matched
// eslint-disable-next-line no-restricted-syntax
for (const format of [exports.DATE_FORMAT_MED, exports.DATE_FORMAT_LONG, exports.DATE_FORMAT_TRACKING, exports.DATE_FORMAT_ORGANIZED]) {
if (input.length === format.length) {
const dateTime = luxon_1.DateTime.fromFormat(input, format, options);
if (dateTime === null || dateTime === void 0 ? void 0 : dateTime.isValid) {
validDateTime = dateTime;
break;
}
}
}
return validDateTime;
};
const getDateTimeFormat = ({ locale, mappings = DATE_PARTS } = {}) => {
const localeParts = (0, exports.getCurrentDateTime)().toLocaleParts({ locale });
return localeParts.map(({ type, value }) => {
if (type === 'literal') {
return value;
}
return mappings[type];
}).filter(display_1.stringNotEmpty).join('');
};
exports.getDateTimeFormat = getDateTimeFormat;
const getDateTimeFromString = (_a = {}) => {
var { format, value } = _a, options = __rest(_a, ["format", "value"]);
if (!hasSomeNumbers(value) ||
!hasOnlyValidCharacters(value) ||
((0, display_1.isTypeEnhanced)(value, 'string') && (0, display_1.stringEmpty)(value))) {
return undefined;
}
if ((0, display_1.stringNotEmpty)(format)) {
return luxon_1.DateTime.fromFormat(value, format, options);
}
const matchedDateTime = matchDateTimeByFormat(value, options);
if (matchedDateTime === null || matchedDateTime === void 0 ? void 0 : matchedDateTime.isValid) {
return matchedDateTime;
}
if ((0, display_1.isNumericNegatable)(value)) {
return luxon_1.DateTime.fromSeconds((0, display_1.ensureNumericNegatable)(value));
}
let dateTime = luxon_1.DateTime.fromISO(value, options);
if (!(dateTime === null || dateTime === void 0 ? void 0 : dateTime.isValid)) {
dateTime = luxon_1.DateTime.fromSQL(value, options);
}
if (!(dateTime === null || dateTime === void 0 ? void 0 : dateTime.isValid)) {
dateTime = luxon_1.DateTime.fromRFC2822(value, options);
}
return dateTime;
};
exports.getDateTimeFromString = getDateTimeFromString;
const convertDateTime = (value, _a = {}) => {
var { shouldThrow = true, shouldLog = shouldThrow } = _a, options = __rest(_a, ["shouldThrow", "shouldLog"]);
let dateTime;
try {
switch (true) {
// eslint-disable-next-line eqeqeq
case (value == undefined): {
break;
}
case luxon_1.DateTime.isDateTime(value): {
dateTime = value;
break;
}
case (value instanceof Date): {
dateTime = luxon_1.DateTime.fromJSDate(value, options);
break;
}
case (0, display_1.isTypeEnhanced)(value, 'object'): {
dateTime = luxon_1.DateTime.fromObject(value, options);
break;
}
default: {
dateTime = (0, exports.getDateTimeFromString)(Object.assign({ value }, options));
break;
}
}
if (dateTime && !dateTime.isValid) {
if (shouldLog) {
console.info('Issue converting timestamp', { value, dateTime });
}
throw new Error(['Error converting timestamp', dateTime === null || dateTime === void 0 ? void 0 : dateTime.invalidExplanation].filter(display_1.stringNotEmpty).join('. '));
}
}
catch (error) {
if (shouldThrow) {
throw error;
}
dateTime = undefined;
}
return dateTime;
};
exports.convertDateTime = convertDateTime;
const convertDuration = (value, _a = {}) => {
var { shouldThrow = true } = _a, options = __rest(_a, ["shouldThrow"]);
let duration;
try {
switch (true) {
// eslint-disable-next-line eqeqeq
case (value == undefined): {
break;
}
case luxon_1.Duration.isDuration(value): {
duration = value;
break;
}
case (0, display_1.isTypeEnhanced)(value, 'object'): {
duration = luxon_1.Duration.fromObject(value, options);
break;
}
case (0, display_1.isNumericNegatable)(value): {
duration = luxon_1.Duration.fromMillis(value, options);
break;
}
case ((0, display_1.isTypeEnhanced)(value, 'string') &&
(0, display_1.stringNotEmpty)(value) &&
hasSomeNumbers(value) &&
hasOnlyValidCharacters(value)):
{
duration = luxon_1.Duration.fromISOTime(value, options);
if (!(duration === null || duration === void 0 ? void 0 : duration.isValid)) {
duration = luxon_1.Duration.fromISO(value, options);
}
break;
}
default: {
break;
}
}
if (duration && !duration.isValid) {
console.error('Error converting duration', { value, duration });
throw new Error(['Error converting duration', duration === null || duration === void 0 ? void 0 : duration.invalidExplanation].filter(display_1.stringNotEmpty).join('. '));
}
}
catch (error) {
if (shouldThrow) {
throw error;
}
duration = undefined;
}
return duration;
};
exports.convertDuration = convertDuration;
const getDuration = (dt1, dt2) => (luxon_1.Interval.fromDateTimes((0, exports.convertDateTime)(dt1), (0, exports.convertDateTime)(dt2)).toDuration());
exports.getDuration = getDuration;
const getCurrentDateTime = () => (luxon_1.DateTime.now());
exports.getCurrentDateTime = getCurrentDateTime;
const getDateTimeDifference = (dt1, dt2 = (0, exports.getCurrentDateTime)(), unit) => {
var _a;
return ((_a = dt2.diff((0, exports.ensureDateTime)(dt1), unit)) === null || _a === void 0 ? void 0 : _a[unit]);
};
const getDaysBetween = (dt1, dt2) => (Math.abs(getDateTimeDifference(dt1, dt2, 'days')));
exports.getDaysBetween = getDaysBetween;
const getWeeksBetween = (dt1, dt2) => (Math.abs(getDateTimeDifference(dt1, dt2, 'weeks')));
exports.getWeeksBetween = getWeeksBetween;
const isSameDateTime = (dt1, dt2 = (0, exports.getCurrentDateTime)(), unit) => (
// eslint-disable-next-line eqeqeq
dt1.startOf(unit).ts == dt2.startOf(unit).ts);
const isSameHour = (dt1, dt2) => (isSameDateTime(dt1, dt2, 'hour'));
exports.isSameHour = isSameHour;
const isSameDay = (dt1, dt2) => (isSameDateTime(dt1, dt2, 'day'));
exports.isSameDay = isSameDay;
const ensureDateTime = (value, options) => {
var _a;
return ((_a = (0, exports.convertDateTime)(value, options)) !== null && _a !== void 0 ? _a : (0, exports.getCurrentDateTime)());
};
exports.ensureDateTime = ensureDateTime;
const toJSDate = (value, options) => ((0, exports.ensureDateTime)(value, options).toJSDate());
exports.toJSDate = toJSDate;
const toUnixInteger = (value, options) => ((0, exports.ensureDateTime)(value, options).toUnixInteger());
exports.toUnixInteger = toUnixInteger;
// consolidate w/ toFormatted({ value, CUSTOM_FORMATS.UNIX })
const toUnixString = (value, options) => (`${(0, exports.toUnixInteger)((0, exports.convertDateTime)(value, options), options)}`);
exports.toUnixString = toUnixString;
// consolidate w/ toFormatted({ value, format: CUSTOM_FORMATS.ISO })
const toISOString = (value, options) => ((0, exports.ensureDateTime)(value, options).toISO());
exports.toISOString = toISOString;
// consolidate w/ toFormatted({ value, format: CUSTOM_FORMATS.UTC })
const toUTCString = (value, options) => ((0, exports.ensureDateTime)(value, options).toUTC().toString());
exports.toUTCString = toUTCString;
const toRFC822String = (value, options) => ((0, exports.toFormatted)(Object.assign({ value, format: exports.CUSTOM_FORMATS.RFC822 }, options)));
exports.toRFC822String = toRFC822String;
// HMMM: return toString if no format (or similar)??
const toFormatted = (_a = {}) => {
var { format, value, zone } = _a, options = __rest(_a, ["format", "value", "zone"]);
// eslint-disable-next-line eqeqeq
if (format == undefined) {
throw new Error('Please supply a format');
}
let datetime = (0, exports.ensureDateTime)(value, options);
if ((0, display_1.stringNotEmpty)(zone)) {
datetime = datetime.setZone(zone);
}
switch (true) {
case (format === exports.CUSTOM_FORMATS.UTC): {
return datetime.toUTC().toString();
}
case (format === exports.CUSTOM_FORMATS.ISO): {
return datetime.toISO();
}
case (format === exports.CUSTOM_FORMATS.UNIX): {
return `${(0, exports.toUnixInteger)(datetime)}`;
}
case (format === exports.CUSTOM_FORMATS.RFC822): {
return datetime.toFormat(DATE_FORMAT_RFC822, options);
}
case ((0, display_1.isTypeEnhanced)(format, 'string')): {
return datetime.toFormat(format, options);
}
default: {
if (!STANDARD_LOCALE_FORMATS.includes(format)) {
console.warn('Please consider using a standard format from LOCALE_FORMATS');
}
return datetime.toLocaleString(format, options);
}
}
};
exports.toFormatted = toFormatted;
const convertFormatted = (_a = {}) => {
var { value } = _a, _b = _a.to, _c = _b === void 0 ? {} : _b, { format: toFormat } = _c, toOptions = __rest(_c, ["format"]), _d = _a.from, _e = _d === void 0 ? {} : _d, { format: fromFormat } = _e, fromOptions = __rest(_e, ["format"]);
if ((0, display_1.stringEmpty)(value)) {
return undefined;
}
return (0, exports.toFormatted)(Object.assign({ format: toFormat, value: (0, exports.getDateTimeFromString)(Object.assign({ value, format: fromFormat }, fromOptions)) }, toOptions));
};
exports.convertFormatted = convertFormatted;
const compareDate = (date1, date2) => (-(0, exports.convertDateTime)(date1).diff((0, exports.convertDateTime)(date2)).as('milliseconds'));
exports.compareDate = compareDate;
const formatTimestamps = (timestamps, defaultValue) => (Object.entries((0, display_1.ensureObject)(timestamps)).reduce((_timestamps, [name, value]) => (Object.assign(Object.assign({}, _timestamps), { [name]: value ? (0, exports.toUnixString)(value) : defaultValue })), {}));
exports.formatTimestamps = formatTimestamps;
const formatRequiredTimestamps = (_a = {}) => {
var { created_at, updated_at } = _a, timestamps = __rest(_a, ["created_at", "updated_at"]);
const _createdTimestamp = (0, exports.toUnixString)(created_at);
const updatedTimestamp = updated_at ? (0, exports.toUnixString)(updated_at) : _createdTimestamp;
const createdTimestamp = `${Math.min(_createdTimestamp, updatedTimestamp)}`; // HMMM: why doing math on strings??
const otherTimestamps = (0, exports.formatTimestamps)(timestamps, createdTimestamp);
return Object.assign({ created_at: createdTimestamp, updated_at: updatedTimestamp }, otherTimestamps);
};
exports.formatRequiredTimestamps = formatRequiredTimestamps;
//# sourceMappingURL=datetime.js.map
;