UNPKG

@farris/devkit-vue

Version:
1,558 lines (1,557 loc) 539 kB
(function(global2, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("axios"), require("vue")) : typeof define === "function" && define.amd ? define(["exports", "axios", "vue"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.FarrisDevkitVue = {}, global2.axios, global2.Vue)); })(this, function(exports2, axios, vue) { "use strict";var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; const Type = Function; const ENTITY_STORE_SUFFIX = "-entitystore"; var ValidationState = /* @__PURE__ */ ((ValidationState2) => { ValidationState2[ValidationState2["Initialize"] = 0] = "Initialize"; ValidationState2[ValidationState2["Validating"] = 1] = "Validating"; ValidationState2[ValidationState2["Reset"] = 2] = "Reset"; return ValidationState2; })(ValidationState || {}); const DEFAULT_LOCALE = "zh-CHS"; function isType(v) { return typeof v === "function"; } var InjectFlags = /* @__PURE__ */ ((InjectFlags2) => { InjectFlags2[InjectFlags2["Default"] = 0] = "Default"; InjectFlags2[InjectFlags2["Self"] = 1] = "Self"; InjectFlags2[InjectFlags2["SkipSelf"] = 2] = "SkipSelf"; InjectFlags2[InjectFlags2["Optional"] = 4] = "Optional"; return InjectFlags2; })(InjectFlags || {}); var OptionFlags = /* @__PURE__ */ ((OptionFlags2) => { OptionFlags2[OptionFlags2["Optional"] = 1] = "Optional"; OptionFlags2[OptionFlags2["CheckSelf"] = 2] = "CheckSelf"; OptionFlags2[OptionFlags2["CheckParent"] = 4] = "CheckParent"; OptionFlags2[OptionFlags2["Default"] = 6] = "Default"; return OptionFlags2; })(OptionFlags || {}); const EMPTY = []; const IDENT = function(value) { return value; }; const CIRCULAR = IDENT; const MULTI_PROVIDER_FN = function() { return Array.prototype.slice.call(arguments); }; const NEW_LINE = /\n/gm; const NO_NEW_LINE = "ɵ"; const _THROW_IF_NOT_FOUND = {}; const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; const NG_TEMP_TOKEN_PATH = "ngTempTokenPath"; function stringify(token) { if (typeof token === "string") { return token; } if (Array.isArray(token)) { return "[" + token.map(stringify).join(", ") + "]"; } if (token == null) { return "" + token; } if (token.overriddenName) { return `${token.overriddenName}`; } if (token.name) { return `${token.name}`; } const res = token.toString(); if (res == null) { return "" + res; } const newLineIndex = res.indexOf("\n"); return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } function getClosureSafeProperty(objWithPropertyToExtract) { for (const key in objWithPropertyToExtract) { if (objWithPropertyToExtract[key] === getClosureSafeProperty) { return key; } } throw Error("Could not find renamed property on target object."); } function formatError(text, obj, injectorErrorName, source = null) { text = text && text.charAt(0) === "\n" && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text; let context = stringify(obj); if (Array.isArray(obj)) { context = obj.map(stringify).join(" -> "); } else if (typeof obj === "object") { const parts = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; parts.push( key + ":" + (typeof value === "string" ? JSON.stringify(value) : stringify(value)) ); } } context = `{${parts.join(", ")}}`; } return `${injectorErrorName}${source ? "(" + source + ")" : ""}[${context}]: ${text.replace(NEW_LINE, "\n ")}`; } function staticError(text, obj) { return new Error(formatError(text, obj, "StaticInjectorError")); } function ɵɵdefineInjectable(opts) { return { token: opts.token, providedIn: opts.providedIn || null, factory: opts.factory, value: void 0 }; } const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty }); getClosureSafeProperty({ ɵinj: getClosureSafeProperty }); const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty }); function getOwnDefinition(type, def) { return def && def.token === type ? def : null; } function getInjectableDef(type) { return getOwnDefinition(type, type[NG_PROV_DEF]) || getOwnDefinition(type, type[NG_INJECTABLE_DEF]); } class InjectionToken { constructor(_desc, options) { __publicField(this, "ngMetadataName", "InjectionToken"); __publicField(this, "ɵprov"); this._desc = _desc; this.ɵprov = void 0; if (typeof options === "number") { this.__NG_ELEMENT_ID__ = options; } else if (options !== void 0) { this.ɵprov = ɵɵdefineInjectable({ token: this, providedIn: options.providedIn || "root", factory: options.factory }); } } toString() { return `InjectionToken ${this._desc}`; } } function createInjectionToken(token) { return new InjectionToken(token); } class Injector { } class NullInjector { get(token, notFoundValue = THROW_IF_NOT_FOUND) { if (notFoundValue === THROW_IF_NOT_FOUND) { const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`); error.name = "NullInjectorError"; throw error; } return notFoundValue; } } const NULL_INJECTOR = new NullInjector(); const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty }); function resolveForwardRef(type) { return isForwardRef(type) ? type() : type; } function forwardRef(forwardRefFn) { forwardRefFn.__forward_ref__ = forwardRef; forwardRefFn.toString = function() { return stringify(this()); }; return forwardRefFn; } function isForwardRef(fn) { return typeof fn === "function" && fn.hasOwnProperty(__forward_ref__) && fn.__forward_ref__ === forwardRef; } const INJECTOR = new InjectionToken("INJECTOR", -1); const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: getClosureSafeProperty }); let _currentInjector = void 0; function setCurrentInjector(injector) { const former = _currentInjector; _currentInjector = injector; return former; } class StaticInjector { constructor(providers, parent = NULL_INJECTOR, source = null) { __publicField(this, "parent"); __publicField(this, "source"); __publicField(this, "scope"); __publicField(this, "_records"); parent = parent ? parent : NULL_INJECTOR; this.parent = parent; this.source = source; const records = this._records = /* @__PURE__ */ new Map(); records.set(Injector, { token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false }); records.set(INJECTOR, { token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false }); this.scope = recursivelyProcessProviders(records, providers); } get(token, notFoundValue, flags = InjectFlags.Default) { const records = this._records; let record = records.get(token); if (record === void 0) { const injectableDef = getInjectableDef(token); if (injectableDef) { const providedIn = injectableDef && injectableDef.providedIn; if (providedIn === "any" || providedIn != null && providedIn === this.scope) { records.set( token, record = resolveProvider({ provide: token, useFactory: injectableDef.factory, deps: EMPTY }) ); } } if (record === void 0) { records.set(token, null); } } const lastInjector = setCurrentInjector(this); try { return tryResolveToken(token, record, records, this.parent, notFoundValue, flags); } catch (e) { throw e; } finally { setCurrentInjector(lastInjector); } } toString() { const tokens = []; const records = this._records; records.forEach((v, token) => tokens.push(stringify(token))); return `StaticInjector[${tokens.join(", ")}]`; } } function multiProviderMixError(token) { return staticError("Cannot mix multi providers and regular providers", token); } const INJECTOR_SCOPE = new InjectionToken("Set Injector scope."); function recursivelyProcessProviders(records, provider) { let scope = null; if (provider) { provider = resolveForwardRef(provider); if (Array.isArray(provider)) { for (let i = 0; i < provider.length; i++) { scope = recursivelyProcessProviders(records, provider[i]) || scope; } } else if (typeof provider === "function") { throw staticError("Function/Class not supported", provider); } else if (provider && typeof provider === "object" && provider.provide) { let token = resolveForwardRef(provider.provide); const resolvedProvider = resolveProvider(provider); if (provider.multi === true) { let multiProvider = records.get(token); if (multiProvider) { if (multiProvider.fn !== MULTI_PROVIDER_FN) { throw multiProviderMixError(token); } } else { records.set(token, multiProvider = { token: provider.provide, deps: [], useNew: false, fn: MULTI_PROVIDER_FN, value: EMPTY }); } token = provider; multiProvider.deps.push({ token, options: OptionFlags.Default }); } const record = records.get(token); if (record && record.fn === MULTI_PROVIDER_FN) { throw multiProviderMixError(token); } if (token === INJECTOR_SCOPE) { scope = resolvedProvider.value; } records.set(token, resolvedProvider); } else { throw staticError("Unexpected provider", provider); } } return scope; } function resolveProvider(provider) { const deps = computeDeps(provider); let fn = IDENT; let value = EMPTY; let useNew = false; const provide = resolveForwardRef(provider.provide); if (USE_VALUE in provider) { value = provider.useValue; } else if (provider.useFactory) { fn = provider.useFactory; } else if (provider.useExisting) ; else if (provider.useClass) { useNew = true; fn = resolveForwardRef(provider.useClass); } else if (typeof provide === "function") { useNew = true; fn = provide; } else { throw staticError( "StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable", provider ); } return { deps, fn, useNew, value }; } function computeDeps(provider) { let deps = EMPTY; const providerDeps = provider.deps; if (providerDeps && providerDeps.length) { deps = []; for (let i = 0; i < providerDeps.length; i++) { const options = OptionFlags.Default; const token = resolveForwardRef(providerDeps[i]); deps.push({ token, options }); } } else if (provider.useExisting) { const token = resolveForwardRef(provider.useExisting); deps = [{ token, options: OptionFlags.Default }]; } else if (!providerDeps && !(USE_VALUE in provider)) { throw staticError("'deps' required", provider); } return deps; } function tryResolveToken(token, record, records, parent, notFoundValue, flags) { try { return resolveToken(token, record, records, parent, notFoundValue, flags); } catch (e) { const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []; path.unshift(token); if (record && record.value === CIRCULAR) { record.value = EMPTY; } throw e; } } function resolveToken(token, record, records, parent, notFoundValue, flags) { let value; if (record && !(flags & InjectFlags.SkipSelf)) { value = record.value; if (value === CIRCULAR) { throw Error(NO_NEW_LINE + "Circular dependency"); } else if (value === EMPTY) { record.value = CIRCULAR; const useNew = record.useNew; const fn = record.fn; const depRecords = record.deps; let deps = EMPTY; if (depRecords.length) { deps = []; for (let i = 0; i < depRecords.length; i++) { const depRecord = depRecords[i]; const options = depRecord.options; const childRecord = options & OptionFlags.CheckSelf ? records.get(depRecord.token) : void 0; deps.push( tryResolveToken( depRecord.token, childRecord, records, !childRecord && !(options & OptionFlags.CheckParent) ? NULL_INJECTOR : parent, options & OptionFlags.Optional ? null : THROW_IF_NOT_FOUND, InjectFlags.Default ) ); } } record.value = value = useNew ? new fn(...deps) : fn.apply(void 0, deps); } } else if (!(flags & InjectFlags.Self)) { value = parent.get(token, notFoundValue, InjectFlags.Default); } else if (!(flags & InjectFlags.Optional)) { value = NULL_INJECTOR.get(token, notFoundValue); } else { value = NULL_INJECTOR.get(token, typeof notFoundValue !== "undefined" ? notFoundValue : null); } return value; } function INJECTOR_IMPL__PRE_R3__(providers, parent, name) { return new StaticInjector(providers, parent, name); } const INJECTOR_IMPL = INJECTOR_IMPL__PRE_R3__; function createInjector(options, parent) { if (Array.isArray(options)) { return INJECTOR_IMPL(options, parent, ""); } else { return INJECTOR_IMPL(options.providers, options.parent, options.name || ""); } } const ANNOTATIONS = "__annotations__"; const PROP_METADATA = "__prop__metadata__"; function makeMetaCtor(metaFactory) { return function ctor(...args) { if (metaFactory) { const values = metaFactory(...args); for (const propName in values) { this[propName] = values[propName]; } } }; } function makeTypeMetadataDecorator(name, props, parentClass, chainFn, typeFn) { const metaCtor = makeMetaCtor(props); function DecoratorFactory(...args) { if (this instanceof DecoratorFactory) { metaCtor.call(this, ...args); return this; } const annotationInstance = new DecoratorFactory(...args); const typeDecorator = function createTypeDecorator(cls) { typeFn && typeFn(cls, ...args); const annotations = cls.hasOwnProperty(ANNOTATIONS) ? cls[ANNOTATIONS] : Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS]; annotations.push(annotationInstance); return cls; }; if (chainFn) { chainFn(typeDecorator); } return typeDecorator; } if (parentClass) { DecoratorFactory.prototype = Object.create(parentClass.prototype); } DecoratorFactory.prototype.ngMetadataName = name; DecoratorFactory.annotationCls = DecoratorFactory; return DecoratorFactory; } function getAllPropMetas(target) { const constructor = target.constructor; let allPropMetas = null; if (constructor.hasOwnProperty(PROP_METADATA)) { allPropMetas = constructor[PROP_METADATA]; } else { allPropMetas = Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA]; } return allPropMetas; } function getSinglePropMetas(target, propName) { const allPropMetas = getAllPropMetas(target); if (allPropMetas.hasOwnProperty(propName)) { return allPropMetas[propName]; } return []; } function makePropMetadataDecorator(name, metaFactory, parentClass) { const metaCtor = makeMetaCtor(metaFactory); function PropDecoratorFactory(...args) { if (this instanceof PropDecoratorFactory) { metaCtor.apply(this, args); return this; } const decoratorInstance = new PropDecoratorFactory(...args); function PropDecorator(target, propName) { const allPropMetas = getAllPropMetas(target); allPropMetas[propName] = getSinglePropMetas(target, propName); allPropMetas[propName].unshift(decoratorInstance); } return PropDecorator; } if (parentClass) { PropDecoratorFactory.prototype = Object.create(parentClass.prototype); } PropDecoratorFactory.prototype.metadataName = name; PropDecoratorFactory.annotationClass = PropDecoratorFactory; return PropDecoratorFactory; } class TypeMetadataReader { /** * 获取所有的元数据 */ static getMetas(constructor) { const metas = constructor[ANNOTATIONS]; if (!metas) { return {}; } return metas; } /** * 根据名称获取元数据 */ static getMataByName(constructor, metaName) { const metas = this.getMetas(constructor); if (!metas) { return {}; } const targetMeta = metas.find((meta) => { return meta.ngMetadataName = metaName; }); return targetMeta; } } class PropMetadataReader { /** * 获取所有属性的所有类型元数据 */ static getPropsMetas(constructor) { const propsMetas = constructor[PROP_METADATA]; if (!propsMetas) { return {}; } return propsMetas; } /** * 获取所有属性某一类型的元数据 */ static getPropsMetasByName(constructor, metaName) { const propsMetas = this.getPropsMetas(constructor); if (!propsMetas) { return {}; } const sameNamePropsMetas = {}; Object.keys(propsMetas).forEach((propName) => { const propMetas = propsMetas[propName]; const targetPropMeta = propMetas.find((propMeta) => { return propMeta.metadataName === metaName; }); if (!targetPropMeta) { return; } sameNamePropsMetas[propName] = targetPropMeta; }); return sameNamePropsMetas; } } class Effect { /** * 副作用构造器 * @param effectFunction 副作用方法 */ constructor(effectFunction) { /** * 副作用方法 */ __publicField(this, "internalFunction"); this.effectFunction = effectFunction; this.internalFunction = this.effectFunction; } /** * 执行副作用 * @param change 变更 */ run(change) { this.internalFunction(change); } } class EffectManager { /** * 构造函数 */ constructor() { /** * 副作用集合 */ __publicField(this, "innerEffects", []); } /** * 添加副作用 */ addEffect(effect) { if (this.innerEffects.indexOf(effect) > -1) { return; } this.innerEffects.push(effect); } /** * 删除副作用 */ removeEffect(effect) { this.innerEffects = this.innerEffects.filter((internalEffect) => effect !== internalEffect); } /** * 获取全部副作用 */ getEffects() { return this.innerEffects; } /** * 执行全部副作用 */ trigger(change) { this.innerEffects.forEach((effect) => { effect.run(change); }); } } const _Token = class _Token { static create(redix) { const timestamp = Date.now().valueOf(); let uuid = 0; if (timestamp > _Token.previous) { _Token.previous = timestamp; uuid = timestamp; } else { _Token.previous = _Token.previous + 100; uuid = _Token.previous; } return uuid.toString(redix); } }; __publicField(_Token, "previous", 0); let Token = _Token; const EXCEPTION_HANDLER_TOKEN = new InjectionToken("@farris/exception_handler_token"); const BA_EXCEPTION_HANDLER_TOKEN = new InjectionToken("@farris/ba-exception_handler_token"); const RENDER_ENGINE_TOKEN = new InjectionToken("@farris/render_engine_token"); const BA_RENDER_ENGINE_TOKEN = new InjectionToken("@farris/ba-render_engine_token"); const BA_DATA_TRANSFORMATION_SERVICE_TOKEN = new InjectionToken("@farris/ba-data_transformation_service_token"); const NAMESPACE_TOKEN = new InjectionToken("@farris/namespace_token"); const MODULE_CONFIG_ID_TOKEN = new InjectionToken("@farris/module_config_id_token"); const RESPONSE_REQUIRED_VALIDATOR_TOKEN = new InjectionToken("@farris/response_required_validator_token"); const EXPRESSION_VALIDATOR_TOKEN = new InjectionToken("@farris/expression_validator_token"); const LOCALE_TOKEN = new InjectionToken("@farris/locale_id_token"); const TRANSLATE_TOKEN = new InjectionToken("@farris/translate_token"); const DEVKIT_TYPE_TOKEN = new InjectionToken("@farris/devkit_type_token"); class TypeUtil { /** * 是否为Promsie对象 */ static isPromise(obj) { return obj instanceof Promise && Object.getPrototypeOf(obj) === Promise.prototype; } } class ObjectUtil { /** * 是否是对象 */ static isObject(value) { return value && typeof value === "object"; } /** * 判断对象是否为空 */ static isEmpty(value) { if (value === null || value === void 0) { return true; } if (typeof value === "object" && Object.keys(value).length === 0) { return true; } return false; } } class StringUtil { /** * 是否为字符串 */ static isString(value) { return typeof value === "string"; } /** * 判断为空字符串 */ static isEmptyString(value) { if (value === void 0 || value == null) { return true; } if (this.isString(value) === true) { return value.length === 0; } return false; } } class NumberUtil { /** * 是否为字符串 */ static isNumber(value) { return typeof value === "number"; } /** * 是否为空数字 */ static isEmptyNumber(value) { return value === void 0 || value == null; } } function toDate(argument) { const argStr = Object.prototype.toString.call(argument); if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") { return new argument.constructor(+argument); } else if (typeof argument === "number" || argStr === "[object Number]" || typeof argument === "string" || argStr === "[object String]") { return new Date(argument); } else { return /* @__PURE__ */ new Date(NaN); } } function constructFrom(date, value) { if (date instanceof Date) { return new date.constructor(value); } else { return new Date(value); } } const millisecondsInWeek = 6048e5; const millisecondsInDay = 864e5; const millisecondsInMinute = 6e4; const millisecondsInHour = 36e5; let defaultOptions = {}; function getDefaultOptions() { return defaultOptions; } function startOfWeek(date, options) { var _a, _b, _c, _d; const defaultOptions2 = getDefaultOptions(); const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_b = (_a = options == null ? void 0 : options.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.weekStartsOn) ?? 0; const _date = toDate(date); const day = _date.getDay(); const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; _date.setDate(_date.getDate() - diff); _date.setHours(0, 0, 0, 0); return _date; } function startOfISOWeek(date) { return startOfWeek(date, { weekStartsOn: 1 }); } function getISOWeekYear(date) { const _date = toDate(date); const year = _date.getFullYear(); const fourthOfJanuaryOfNextYear = constructFrom(date, 0); fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); const fourthOfJanuaryOfThisYear = constructFrom(date, 0); fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); if (_date.getTime() >= startOfNextYear.getTime()) { return year + 1; } else if (_date.getTime() >= startOfThisYear.getTime()) { return year; } else { return year - 1; } } function startOfDay(date) { const _date = toDate(date); _date.setHours(0, 0, 0, 0); return _date; } function getTimezoneOffsetInMilliseconds(date) { const _date = toDate(date); const utcDate = new Date( Date.UTC( _date.getFullYear(), _date.getMonth(), _date.getDate(), _date.getHours(), _date.getMinutes(), _date.getSeconds(), _date.getMilliseconds() ) ); utcDate.setUTCFullYear(_date.getFullYear()); return +date - +utcDate; } function differenceInCalendarDays(dateLeft, dateRight) { const startOfDayLeft = startOfDay(dateLeft); const startOfDayRight = startOfDay(dateRight); const timestampLeft = +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft); const timestampRight = +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight); return Math.round((timestampLeft - timestampRight) / millisecondsInDay); } function startOfISOWeekYear(date) { const year = getISOWeekYear(date); const fourthOfJanuary = constructFrom(date, 0); fourthOfJanuary.setFullYear(year, 0, 4); fourthOfJanuary.setHours(0, 0, 0, 0); return startOfISOWeek(fourthOfJanuary); } function isDate(value) { return value instanceof Date || typeof value === "object" && Object.prototype.toString.call(value) === "[object Date]"; } function isValid(date) { if (!isDate(date) && typeof date !== "number") { return false; } const _date = toDate(date); return !isNaN(Number(_date)); } function startOfYear(date) { const cleanDate = toDate(date); const _date = constructFrom(date, 0); _date.setFullYear(cleanDate.getFullYear(), 0, 1); _date.setHours(0, 0, 0, 0); return _date; } const formatDistanceLocale = { lessThanXSeconds: { one: "less than a second", other: "less than {{count}} seconds" }, xSeconds: { one: "1 second", other: "{{count}} seconds" }, halfAMinute: "half a minute", lessThanXMinutes: { one: "less than a minute", other: "less than {{count}} minutes" }, xMinutes: { one: "1 minute", other: "{{count}} minutes" }, aboutXHours: { one: "about 1 hour", other: "about {{count}} hours" }, xHours: { one: "1 hour", other: "{{count}} hours" }, xDays: { one: "1 day", other: "{{count}} days" }, aboutXWeeks: { one: "about 1 week", other: "about {{count}} weeks" }, xWeeks: { one: "1 week", other: "{{count}} weeks" }, aboutXMonths: { one: "about 1 month", other: "about {{count}} months" }, xMonths: { one: "1 month", other: "{{count}} months" }, aboutXYears: { one: "about 1 year", other: "about {{count}} years" }, xYears: { one: "1 year", other: "{{count}} years" }, overXYears: { one: "over 1 year", other: "over {{count}} years" }, almostXYears: { one: "almost 1 year", other: "almost {{count}} years" } }; const formatDistance = (token, count, options) => { let result; const tokenValue = formatDistanceLocale[token]; if (typeof tokenValue === "string") { result = tokenValue; } else if (count === 1) { result = tokenValue.one; } else { result = tokenValue.other.replace("{{count}}", count.toString()); } if (options == null ? void 0 : options.addSuffix) { if (options.comparison && options.comparison > 0) { return "in " + result; } else { return result + " ago"; } } return result; }; function buildFormatLongFn(args) { return (options = {}) => { const width = options.width ? String(options.width) : args.defaultWidth; const format2 = args.formats[width] || args.formats[args.defaultWidth]; return format2; }; } const dateFormats = { full: "EEEE, MMMM do, y", long: "MMMM do, y", medium: "MMM d, y", short: "MM/dd/yyyy" }; const timeFormats = { full: "h:mm:ss a zzzz", long: "h:mm:ss a z", medium: "h:mm:ss a", short: "h:mm a" }; const dateTimeFormats = { full: "{{date}} 'at' {{time}}", long: "{{date}} 'at' {{time}}", medium: "{{date}}, {{time}}", short: "{{date}}, {{time}}" }; const formatLong = { date: buildFormatLongFn({ formats: dateFormats, defaultWidth: "full" }), time: buildFormatLongFn({ formats: timeFormats, defaultWidth: "full" }), dateTime: buildFormatLongFn({ formats: dateTimeFormats, defaultWidth: "full" }) }; const formatRelativeLocale = { lastWeek: "'last' eeee 'at' p", yesterday: "'yesterday at' p", today: "'today at' p", tomorrow: "'tomorrow at' p", nextWeek: "eeee 'at' p", other: "P" }; const formatRelative = (token, _date, _baseDate, _options) => formatRelativeLocale[token]; function buildLocalizeFn(args) { return (value, options) => { const context = (options == null ? void 0 : options.context) ? String(options.context) : "standalone"; let valuesArray; if (context === "formatting" && args.formattingValues) { const defaultWidth = args.defaultFormattingWidth || args.defaultWidth; const width = (options == null ? void 0 : options.width) ? String(options.width) : defaultWidth; valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; } else { const defaultWidth = args.defaultWidth; const width = (options == null ? void 0 : options.width) ? String(options.width) : args.defaultWidth; valuesArray = args.values[width] || args.values[defaultWidth]; } const index = args.argumentCallback ? args.argumentCallback(value) : value; return valuesArray[index]; }; } const eraValues = { narrow: ["B", "A"], abbreviated: ["BC", "AD"], wide: ["Before Christ", "Anno Domini"] }; const quarterValues = { narrow: ["1", "2", "3", "4"], abbreviated: ["Q1", "Q2", "Q3", "Q4"], wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] }; const monthValues = { narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], abbreviated: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], wide: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; const dayValues = { narrow: ["S", "M", "T", "W", "T", "F", "S"], short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], wide: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }; const dayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" } }; const formattingDayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" } }; const ordinalNumber = (dirtyNumber, _options) => { const number = Number(dirtyNumber); const rem100 = number % 100; if (rem100 > 20 || rem100 < 10) { switch (rem100 % 10) { case 1: return number + "st"; case 2: return number + "nd"; case 3: return number + "rd"; } } return number + "th"; }; const localize = { ordinalNumber, era: buildLocalizeFn({ values: eraValues, defaultWidth: "wide" }), quarter: buildLocalizeFn({ values: quarterValues, defaultWidth: "wide", argumentCallback: (quarter) => quarter - 1 }), month: buildLocalizeFn({ values: monthValues, defaultWidth: "wide" }), day: buildLocalizeFn({ values: dayValues, defaultWidth: "wide" }), dayPeriod: buildLocalizeFn({ values: dayPeriodValues, defaultWidth: "wide", formattingValues: formattingDayPeriodValues, defaultFormattingWidth: "wide" }) }; function buildMatchFn(args) { return (string, options = {}) => { const width = options.width; const matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; const matchResult = string.match(matchPattern); if (!matchResult) { return null; } const matchedString = matchResult[0]; const parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; const key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString)) : ( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type findKey(parsePatterns, (pattern) => pattern.test(matchedString)) ); let value; value = args.valueCallback ? args.valueCallback(key) : key; value = options.valueCallback ? ( // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type options.valueCallback(value) ) : value; const rest = string.slice(matchedString.length); return { value, rest }; }; } function findKey(object, predicate) { for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key) && predicate(object[key])) { return key; } } return void 0; } function findIndex(array, predicate) { for (let key = 0; key < array.length; key++) { if (predicate(array[key])) { return key; } } return void 0; } function buildMatchPatternFn(args) { return (string, options = {}) => { const matchResult = string.match(args.matchPattern); if (!matchResult) return null; const matchedString = matchResult[0]; const parseResult = string.match(args.parsePattern); if (!parseResult) return null; let value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; value = options.valueCallback ? options.valueCallback(value) : value; const rest = string.slice(matchedString.length); return { value, rest }; }; } const matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; const parseOrdinalNumberPattern = /\d+/i; const matchEraPatterns = { narrow: /^(b|a)/i, abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, wide: /^(before christ|before common era|anno domini|common era)/i }; const parseEraPatterns = { any: [/^b/i, /^(a|c)/i] }; const matchQuarterPatterns = { narrow: /^[1234]/i, abbreviated: /^q[1234]/i, wide: /^[1234](th|st|nd|rd)? quarter/i }; const parseQuarterPatterns = { any: [/1/i, /2/i, /3/i, /4/i] }; const matchMonthPatterns = { narrow: /^[jfmasond]/i, abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i }; const parseMonthPatterns = { 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 ], 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 ] }; const matchDayPatterns = { narrow: /^[smtwf]/i, short: /^(su|mo|tu|we|th|fr|sa)/i, abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i }; const parseDayPatterns = { narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] }; const matchDayPeriodPatterns = { narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i }; const parseDayPeriodPatterns = { any: { am: /^a/i, pm: /^p/i, midnight: /^mi/i, noon: /^no/i, morning: /morning/i, afternoon: /afternoon/i, evening: /evening/i, night: /night/i } }; const match = { ordinalNumber: buildMatchPatternFn({ matchPattern: matchOrdinalNumberPattern, parsePattern: parseOrdinalNumberPattern, valueCallback: (value) => parseInt(value, 10) }), era: buildMatchFn({ matchPatterns: matchEraPatterns, defaultMatchWidth: "wide", parsePatterns: parseEraPatterns, defaultParseWidth: "any" }), quarter: buildMatchFn({ matchPatterns: matchQuarterPatterns, defaultMatchWidth: "wide", parsePatterns: parseQuarterPatterns, defaultParseWidth: "any", valueCallback: (index) => index + 1 }), month: buildMatchFn({ matchPatterns: matchMonthPatterns, defaultMatchWidth: "wide", parsePatterns: parseMonthPatterns, defaultParseWidth: "any" }), day: buildMatchFn({ matchPatterns: matchDayPatterns, defaultMatchWidth: "wide", parsePatterns: parseDayPatterns, defaultParseWidth: "any" }), dayPeriod: buildMatchFn({ matchPatterns: matchDayPeriodPatterns, defaultMatchWidth: "any", parsePatterns: parseDayPeriodPatterns, defaultParseWidth: "any" }) }; const enUS = { code: "en-US", formatDistance, formatLong, formatRelative, localize, match, options: { weekStartsOn: 0, firstWeekContainsDate: 1 } }; function getDayOfYear(date) { const _date = toDate(date); const diff = differenceInCalendarDays(_date, startOfYear(_date)); const dayOfYear = diff + 1; return dayOfYear; } function getISOWeek(date) { const _date = toDate(date); const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date); return Math.round(diff / millisecondsInWeek) + 1; } function getWeekYear(date, options) { var _a, _b, _c, _d; const _date = toDate(date); const year = _date.getFullYear(); const defaultOptions2 = getDefaultOptions(); const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b = (_a = options == null ? void 0 : options.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1; const firstWeekOfNextYear = constructFrom(date, 0); firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate); firstWeekOfNextYear.setHours(0, 0, 0, 0); const startOfNextYear = startOfWeek(firstWeekOfNextYear, options); const firstWeekOfThisYear = constructFrom(date, 0); firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate); firstWeekOfThisYear.setHours(0, 0, 0, 0); const startOfThisYear = startOfWeek(firstWeekOfThisYear, options); if (_date.getTime() >= startOfNextYear.getTime()) { return year + 1; } else if (_date.getTime() >= startOfThisYear.getTime()) { return year; } else { return year - 1; } } function startOfWeekYear(date, options) { var _a, _b, _c, _d; const defaultOptions2 = getDefaultOptions(); const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b = (_a = options == null ? void 0 : options.locale) == null ? void 0 : _a.options) == null ? void 0 : _b.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d = (_c = defaultOptions2.locale) == null ? void 0 : _c.options) == null ? void 0 : _d.firstWeekContainsDate) ?? 1; const year = getWeekYear(date, options); const firstWeek = constructFrom(date, 0); firstWeek.setFullYear(year, 0, firstWeekContainsDate); firstWeek.setHours(0, 0, 0, 0); const _date = startOfWeek(firstWeek, options); return _date; } function getWeek(date, options) { const _date = toDate(date); const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options); return Math.round(diff / millisecondsInWeek) + 1; } function addLeadingZeros(number, targetLength) { const sign = number < 0 ? "-" : ""; const output = Math.abs(number).toString().padStart(targetLength, "0"); return sign + output; } const lightFormatters = { // Year y(date, token) { const signedYear = date.getFullYear(); const year = signedYear > 0 ? signedYear : 1 - signedYear; return addLeadingZeros(token === "yy" ? year % 100 : year, token.length); }, // Month M(date, token) { const month = date.getMonth(); return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); }, // Day of the month d(date, token) { return addLeadingZeros(date.getDate(), token.length); }, // AM or PM a(date, token) { const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am"; switch (token) { case "a": case "aa": return dayPeriodEnumValue.toUpperCase(); case "aaa": return dayPeriodEnumValue; case "aaaaa": return dayPeriodEnumValue[0]; case "aaaa": default: return dayPeriodEnumValue === "am" ? "a.m." : "p.m."; } }, // Hour [1-12] h(date, token) { return addLeadingZeros(date.getHours() % 12 || 12, token.length); }, // Hour [0-23] H(date, token) { return addLeadingZeros(date.getHours(), token.length); }, // Minute m(date, token) { return addLeadingZeros(date.getMinutes(), token.length); }, // Second s(date, token) { return addLeadingZeros(date.getSeconds(), token.length); }, // Fraction of second S(date, token) { const numberOfDigits = token.length; const milliseconds = date.getMilliseconds(); const fractionalSeconds = Math.trunc( milliseconds * Math.pow(10, numberOfDigits - 3) ); return addLeadingZeros(fractionalSeconds, token.length); } }; const dayPeriodEnum = { am: "am", pm: "pm", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }; const formatters = { // Era G: function(date, token, localize2) { const era = date.getFullYear() > 0 ? 1 : 0; switch (token) { case "G": case "GG": case "GGG": return localize2.era(era, { width: "abbreviated" }); case "GGGGG": return localize2.era(era, { width: "narrow" }); case "GGGG": default: return localize2.era(era, { width: "wide" }); } }, // Year y: function(date, token, localize2) { if (token === "yo") { const signedYear = date.getFullYear(); const year = signedYear > 0 ? signedYear : 1 - signedYear; return localize2.ordinalNumber(year, { unit: "year" }); } return lightFormatters.y(date, token); }, // Local week-numbering year Y: function(date, token, localize2, options) { const signedWeekYear = getWeekYear(date, options); const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; if (token === "YY") { const twoDigitYear = weekYear % 100; return addLeadingZeros(twoDigitYear, 2); } if (token === "Yo") { return localize2.ordinalNumber(weekYear, { unit: "year" }); } return addLeadingZeros(weekYear, token.length); }, // ISO week-numbering year R: function(date, token) { const isoWeekYear = getISOWeekYear(date); return addLeadingZeros(isoWeekYear, token.length); }, // Extended year. This is a single number designating the year of this calendar system. // The main difference between `y` and `u` localizers are B.C. years: // | Year | `y` | `u` | // |------|-----|-----| // | AC 1 | 1 | 1 | // | BC 1 | 1 | 0 | // | BC 2 | 2 | -1 | // Also `yy` always returns the last two digits of a year, // while `uu` pads single digit years to 2 characters and returns other years unchanged. u: function(date, token) { const year = date.getFullYear(); return addLeadingZeros(year, token.length); }, // Quarter Q: function(date, token, localize2) { const quarter = Math.ceil((date.getMonth() + 1) / 3); switch (token) { case "Q": return String(quarter); case "QQ": return addLeadingZeros(quarter, 2); case "Qo": return localize2.ordinalNumber(quarter, { unit: "quarter" }); case "QQQ": return localize2.quarter(quarter, { width: "abbreviated", context: "formatting" }); case "QQQQQ": return localize2.quarter(quarter, { width: "narrow", context: "formatting" }); case "QQQQ": default: return localize2.quarter(quarter, { width: "wide", context: "formatting" }); } }, // Stand-alone quarter q: function(date, token, localize2) { const quarter = Math.ceil((date.getMonth() + 1) / 3); switch (token) { case "q": return String(quarter); case "qq": return addLeadingZeros(quarter, 2); case "qo": return localize2.ordinalNumber(quarter, { unit: "quarter" }); case "qqq": return localize2.quarter(quarter, { width: "abbreviated", context: "standalone" }); case "qqqqq": return localize2.quarter(quarter, { width: "narrow", context: "standalone" }); case "qqqq": default: return localize2.quarter(quarter, { width: "wide", context: "standalone" }); } }, // Month M: function(date, token, localize2) { const month = date.getMonth(); switch (token) { case "M": case "MM": return lightFormatters.M(date, token); case "Mo": return localize2.ordinalNumber(month + 1, { unit: "month" }); case "MMM": return localize2.month(month, { width: "abbreviated", context: "formatting" }); case "MMMMM": return localize2.month(month, { width: "narrow", context: "formatting" }); case "MMMM": default: return localize2.month(month, { width: "wide", context: "formatting" }); } }, // Stand-alone month L: function(date, token, localize2) { const month = date.getMonth(); switch (token) { case "L": return String(month + 1); case "LL": return addLeadingZeros(month + 1, 2); case "Lo": return localize2.ordinalNumber(month + 1, { unit: "month" }); case "LLL": return localize2.month(month, { width: "abbreviated", context: "standalone" }); case "LLLLL": return localize2.month(month, { width: "narrow", context: "standalone" }); case "LLLL": default: return localize2.month(month, { width: "wide", context: "standalone" }); } }, // Local week of year w: function(date, token, localize2, options) { const week = getWeek(date, options); if (token === "wo") { return localize2.ordinalNumber(week, { unit: "week" }); }