@mediacubeco/base 0.0.1
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.
- package/dist/helpers/index.cjs +1 -0
- package/dist/helpers/index.d.ts +513 -0
- package/dist/helpers/index.mjs +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +1243 -0
- package/dist/index.mjs +1 -0
- package/dist/services/index.cjs +1 -0
- package/dist/services/index.d.ts +174 -0
- package/dist/services/index.mjs +1 -0
- package/dist/types/index.cjs +1 -0
- package/dist/types/index.d.ts +195 -0
- package/dist/types/index.mjs +1 -0
- package/dist/utils/index.cjs +1 -0
- package/dist/utils/index.d.ts +587 -0
- package/dist/utils/index.mjs +1 -0
- package/package.json +51 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=t=>void 0===t,e=t=>null===t,s=s=>t(s)||e(s),n=t=>"string"==typeof t,i=t=>"number"==typeof t,r=t=>"bigint"==typeof t,o=t=>Number.isNaN(t),a=t=>"boolean"==typeof t,c=t=>"symbol"==typeof t,u=t=>"object"==typeof t,f=t=>{const e=[l,h,g,m,d,p,b,y,D,v,E].some(e=>e(t));return!!t&&"object"==typeof t&&!e},l=t=>Array.isArray(t),h=t=>t instanceof ArrayBuffer,g=t=>t instanceof Map,m=t=>t instanceof Set,d=t=>t instanceof Map,p=t=>t instanceof Set,b=t=>t instanceof Date,y=t=>t instanceof Error,w=t=>t instanceof Proxy,D=t=>t instanceof RegExp,v=t=>t instanceof Promise,E=t=>t instanceof Function,k=t=>new Promise(e=>setTimeout(e,t));function x(t,e,n){const i=!f(t);return!s(n)&&{...e,...i?{[n]:t}:t}||!s(e)&&{...e,...t}||{...t}}function L(t,e,n){return s(t)?n:2===arguments.length?e[t]:e[t]??n}const S=(t,e)=>{const s=Object.entries(t);return Object.fromEntries(s.map(([t,s],n,i)=>[t,e(t,s,n,i)]))},N=(t,...e)=>{if(E(t))return t(...e)},P=(t,e)=>{let s;return(...n)=>{s&&clearTimeout(s),s=setTimeout(()=>N(t,...n),e)}},j=(t,e)=>{let s=!0;return(...n)=>{s&&(N(t,...n),s=!1),setTimeout(()=>s=!0,e)}};function G(t){for(const e in t)return!1;return!0}function O(t){return 0===t.length}function C(t,e){return!(!u(e)||!(t in e))}function T(t,e){return!!F(t,e).length}function A(t,e="isVisible"){return t.filter(t=>!C(e,t)||t[e])}function B(t,e){return t.reduce((t,s)=>t.some(t=>t[e]===s[e])?t:[...t,s],[])}function F(t,e){return t.filter(t=>e.includes(t))}function I(t){return t.filter(t=>!s(t))}function J(t){return l(t)?t:[t]}function M(t,e){const s=[];for(let n=0;n<t.length;n+=e)s.push(t.slice(n,n+e));return s}class V{isDefaultPrevented=!1;constructor(){this.preventDefault=this.preventDefault.bind(this),this.overrideDefault=this.overrideDefault.bind(this)}preventDefault(){this.isDefaultPrevented=!0}overrideDefault(){this.isDefaultPrevented=!1}}class W{subscriptions={};constructor(){this.emit=this.emit.bind(this),this.on=this.on.bind(this),this.off=this.off.bind(this),this.clear=this.clear.bind(this)}emit(t,e,s){const n=this.subscriptions[t];if(n){const{event:t,listenerList:i}=n;i.forEach(s=>N(s,Object.assign(t,e))),t.isDefaultPrevented||N(s)}else N(s)}on(t,e){const s=this.subscriptions[t];return s?s.listenerList.push(e):this.subscriptions[t]={event:new V,listenerList:[e]},()=>this.off(t,e)}off(t,e){const s=this.subscriptions[t];if(s){const{event:n,listenerList:i}=s;this.subscriptions[t]={event:n,listenerList:i.filter(t=>t!==e)},n.overrideDefault()}}clear(t){delete this.subscriptions[t]}}const $=(t="?",...e)=>[`[${(t&&n(t)?t:"?").toUpperCase()}]`,...e.reduce((t,e,s,{length:n})=>{const i=s===n-1?[]:["|"];return t.push(e,...i),t},e.length?["-"]:[])];var z,R,U;!function(t){t.StartGroup="group",t.EndGroup="groupEnd",t.Default="log"}(z||(z={})),function(t){t.Info="[36m%s[0m",t.Success="[32m%s[0m",t.Warning="[33m%s[0m",t.Danger="[31m%s[0m"}(R||(R={}));class q{static formatted={info:(...t)=>q.info(...$(...t)),success:(...t)=>q.success(...$(...t)),warning:(...t)=>q.warning(...$(...t)),danger:(...t)=>q.danger(...$(...t))};static#t(t,...e){console[t](...e)}static startGroup(t,e,...s){q.#t(z.StartGroup,...((t,...e)=>["%c%s",t,...e])(`font-size: 16px;${e}`,...$(t,...s)))}static endGroup(){q.#t(z.EndGroup)}static info(...t){q.#t(z.Default,R.Info,...t)}static success(...t){q.#t(z.Default,R.Success,...t)}static warning(...t){q.#t(z.Default,R.Warning,...t)}static danger(...t){q.#t(z.Default,R.Danger,...t)}}!function(t){t.Capture="capture",t.Forward="forward"}(U||(U={}));class H{static eventEmitter=new W;static caseList=[];static log(t,e){const{signal:s,message:n,payload:i,stack:r}=e,o=[n,y(t)?t.message:void 0].filter(Boolean);q.formatted.danger(s,...o,{error:t,payload:i,stack:r})}static get on(){return H.eventEmitter.on}static get off(){return H.eventEmitter.off}static get clear(){return H.eventEmitter.clear}static create(t,e){return new Error(t,{cause:e})}static throw(t,e){throw H.create(t,e)}static capture(t,e){H.log(t,e),H.eventEmitter.emit(U.Capture,{error:t,config:e})}static forward(t,e){throw H.log(t,e),H.eventEmitter.emit(U.Capture,{error:t,config:e}),t}static case(t){H.caseList.push(t)}static parse(t){const e={message:"Error!",status:0,errors:{},isExternal:!0};for(const{check:s,parse:n}of H.caseList)if(s(t,e))return n(t,e);return!0===y(t)?{message:t.message,status:e.status,errors:e.errors,isExternal:e.isExternal}:{message:e.message,status:e.status,errors:e.errors,isExternal:e.isExternal}}}class K{key;model;config;constructor(t,e,s){this.key=t,this.model=e,this.config=s}async get(t){const{defaultValue:e,withDebug:s}={...this.config,...t},n=await this.model.get(this.key),i=n&&JSON.parse(n)||e;return s&&q.formatted.info("get",this.key,i),i}async set(t,e){const{withDebug:s}={...this.config,...e};await this.model.set(this.key,JSON.stringify(t)),s&&q.formatted.info("set",this.key,t)}async delete(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});await this.model.delete(this.key),e&&q.formatted.info("delete",this.key,s)}async has(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});return e&&q.formatted.info("has",this.key,s),!!s}}class Q{model;config;constructor(t,e){this.model=t,this.config=e}async all(){H.throw("Not implemented")}async clear(){H.throw("Not implemented")}create(t){const e={[t]:new K(t,this.model,this.config)};return Object.assign(this,e)}}export{H as ErrorHandler,U as ErrorHandlerEventName,W as EventEmitter,q as Log,Q as Storage,M as chunkList,x as compose,P as debounce,A as filterByKey,B as filterDuplicateByKey,F as filterEqualValues,I as filterNullableValues,J as forceList,L as getValueByKey,T as hasEqualValues,C as hasKey,u as isAnyObject,l as isArray,h as isArrayBuffer,O as isArrayEmpty,r as isBigint,a as isBoolean,b as isDate,y as isError,E as isFunction,g as isMap,o as isNaN,e as isNull,s as isNullable,i as isNumber,f as isObject,G as isObjectEmpty,v as isPromise,w as isProxy,D as isRegExp,m as isSet,n as isString,c as isSymbol,t as isUndefined,d as isWeakMap,p as isWeakSet,S as mapRecord,N as runCallback,j as throttle,k as wait};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t=t=>t instanceof Error,e=(t,...e)=>{if(t instanceof Function)return t(...e)};class s{isDefaultPrevented=!1;constructor(){this.preventDefault=this.preventDefault.bind(this),this.overrideDefault=this.overrideDefault.bind(this)}preventDefault(){this.isDefaultPrevented=!0}overrideDefault(){this.isDefaultPrevented=!1}}class i{subscriptions={};constructor(){this.emit=this.emit.bind(this),this.on=this.on.bind(this),this.off=this.off.bind(this),this.clear=this.clear.bind(this)}emit(t,s,i){const r=this.subscriptions[t];if(r){const{event:t,listenerList:n}=r;n.forEach(i=>e(i,Object.assign(t,s))),t.isDefaultPrevented||e(i)}else e(i)}on(t,e){const i=this.subscriptions[t];return i?i.listenerList.push(e):this.subscriptions[t]={event:new s,listenerList:[e]},()=>this.off(t,e)}off(t,e){const s=this.subscriptions[t];if(s){const{event:i,listenerList:r}=s;this.subscriptions[t]={event:i,listenerList:r.filter(t=>t!==e)},i.overrideDefault()}}clear(t){delete this.subscriptions[t]}}const r=(t="?",...e)=>{const s=(t&&(i=t,"string"==typeof i)?t:"?").toUpperCase();var i;const r=e.reduce((t,e,s,{length:i})=>{const r=s===i-1?[]:["|"];return t.push(e,...r),t},e.length?["-"]:[]);return[`[${s}]`,...r]};var n,o,a;!function(t){t.StartGroup="group",t.EndGroup="groupEnd",t.Default="log"}(n||(n={})),function(t){t.Info="[36m%s[0m",t.Success="[32m%s[0m",t.Warning="[33m%s[0m",t.Danger="[31m%s[0m"}(o||(o={}));class c{static formatted={info:(...t)=>c.info(...r(...t)),success:(...t)=>c.success(...r(...t)),warning:(...t)=>c.warning(...r(...t)),danger:(...t)=>c.danger(...r(...t))};static#t(t,...e){console[t](...e)}static startGroup(t,e,...s){c.#t(n.StartGroup,...((t,...e)=>["%c%s",t,...e])(`font-size: 16px;${e}`,...r(t,...s)))}static endGroup(){c.#t(n.EndGroup)}static info(...t){c.#t(n.Default,o.Info,...t)}static success(...t){c.#t(n.Default,o.Success,...t)}static warning(...t){c.#t(n.Default,o.Warning,...t)}static danger(...t){c.#t(n.Default,o.Danger,...t)}}!function(t){t.Capture="capture",t.Forward="forward"}(a||(a={}));class u{static eventEmitter=new i;static caseList=[];static log(e,s){const{signal:i,message:r,payload:n,stack:o}=s,a=[r,t(e)?e.message:void 0].filter(Boolean);c.formatted.danger(i,...a,{error:e,payload:n,stack:o})}static get on(){return u.eventEmitter.on}static get off(){return u.eventEmitter.off}static get clear(){return u.eventEmitter.clear}static create(t,e){return new Error(t,{cause:e})}static throw(t,e){throw u.create(t,e)}static capture(t,e){u.log(t,e),u.eventEmitter.emit(a.Capture,{error:t,config:e})}static forward(t,e){throw u.log(t,e),u.eventEmitter.emit(a.Capture,{error:t,config:e}),t}static case(t){u.caseList.push(t)}static parse(e){const s={message:"Error!",status:0,errors:{},isExternal:!0};for(const{check:t,parse:i}of u.caseList)if(t(e,s))return i(e,s);return!0===t(e)?{message:e.message,status:s.status,errors:s.errors,isExternal:s.isExternal}:{message:s.message,status:s.status,errors:s.errors,isExternal:s.isExternal}}}class l{key;model;config;constructor(t,e,s){this.key=t,this.model=e,this.config=s}async get(t){const{defaultValue:e,withDebug:s}={...this.config,...t},i=await this.model.get(this.key),r=i&&JSON.parse(i)||e;return s&&c.formatted.info("get",this.key,r),r}async set(t,e){const{withDebug:s}={...this.config,...e};await this.model.set(this.key,JSON.stringify(t)),s&&c.formatted.info("set",this.key,t)}async delete(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});await this.model.delete(this.key),e&&c.formatted.info("delete",this.key,s)}async has(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});return e&&c.formatted.info("has",this.key,s),!!s}}exports.Storage=class{model;config;constructor(t,e){this.model=t,this.config=e}async all(){u.throw("Not implemented")}async clear(){u.throw("Not implemented")}create(t){const e={[t]:new l(t,this.model,this.config)};return Object.assign(this,e)}};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* @description
|
|
4
|
+
* Общие утилитарные типы для проектов на TypeScript.
|
|
5
|
+
* Содержит типы для примитивов (Nullable, NotNullable), структур данных
|
|
6
|
+
* (BaseRecord, Entry, List), функций (Callback, AsyncCallback) и вспомогательные
|
|
7
|
+
* утилиты (KeyOf, ValueOf, Decrement, Increment и др.).
|
|
8
|
+
* Модуль не содержит рантайм-кода — только типы.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* type User = { id: number; name?: string | null }
|
|
13
|
+
*
|
|
14
|
+
* type UserId = ValueOf<Pick<User, 'id'>>
|
|
15
|
+
* type SafeName = NotNullable<User['name']>
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
type NullablePrimitive = undefined | null;
|
|
19
|
+
/**
|
|
20
|
+
* Тип, допускающий null или undefined (например для опциональных полей).
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* type MaybeName = Nullable<string> // string | null | undefined
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
type Nullable<Data = undefined> = Data | NullablePrimitive;
|
|
28
|
+
/** Значение, которое может быть как синхронным, так и обёрнутым в Promise. */
|
|
29
|
+
type MaybeAsync<Data = never> = Data | Promise<Data>;
|
|
30
|
+
/**
|
|
31
|
+
* Массив элементов (базовый тип для списков).
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* type IdList = BaseList<number> // number[]
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
type BaseList<Item = unknown> = Item[];
|
|
39
|
+
/**
|
|
40
|
+
* Синхронная функция с заданным списком параметров и результатом.
|
|
41
|
+
* @template ParamList - кортеж типов аргументов
|
|
42
|
+
* @template Result - тип возвращаемого значения
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* type Sum = Callback<[number, number], number>
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
type Callback<ParamList extends BaseList = BaseList, Result = void> = (...paramList: ParamList) => Result;
|
|
50
|
+
|
|
51
|
+
type StorageItemConfig<Value = string> = Partial<StorageConfig> & {
|
|
52
|
+
defaultValue?: Value;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
declare class StorageItem<Value = unknown> {
|
|
56
|
+
private key;
|
|
57
|
+
private model;
|
|
58
|
+
private config?;
|
|
59
|
+
constructor(key: string, model: StorageModel, config?: StorageConfig);
|
|
60
|
+
get(): Promise<Nullable<Value>>;
|
|
61
|
+
get(config: StorageItemConfig<Value>): Promise<Value>;
|
|
62
|
+
set(value: Value, config?: StorageItemConfig<Value>): Promise<void>;
|
|
63
|
+
delete(config?: StorageItemConfig<Value>): Promise<void>;
|
|
64
|
+
has(config?: StorageItemConfig<Value>): Promise<boolean>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Тип экземпляра Storage после вызова .create(key): объект с полем key типа StorageItem<Value>.
|
|
69
|
+
* Позволяет типизировать storage.user, storage.settings и т.д.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* type UserStorage = StorageInstance<'user', { name: string }>
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
type StorageInstance<Key extends string = string, Value = unknown> = {
|
|
77
|
+
[key in Key]: StorageItem<Value>;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Абстрактная модель хранилища ключ–значение.
|
|
81
|
+
* Реализация может быть localStorage, sessionStorage, серверный API и т.д.
|
|
82
|
+
* Значения передаются как строки; сериализация/десериализация (например JSON) — в StorageItem.
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* const model: StorageModel = {
|
|
87
|
+
* get: (key) => localStorage.getItem(key),
|
|
88
|
+
* set: (key, value) => localStorage.setItem(key, value),
|
|
89
|
+
* delete: (key) => localStorage.removeItem(key)
|
|
90
|
+
* }
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
type StorageModel = {
|
|
94
|
+
get: Callback<[string], MaybeAsync<Nullable<string>>>;
|
|
95
|
+
set: Callback<[string, string], MaybeAsync<void>>;
|
|
96
|
+
delete: Callback<[string], MaybeAsync<void>>;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Конфиг Storage/StorageItem: опция отладочного логирования через Log.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* const config: StorageConfig = { withDebug: true }
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
type StorageConfig = {
|
|
107
|
+
withDebug?: boolean;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Абстракция над ключ–значение хранилищем. Принимает модель (get/set/delete) и через .create(key)
|
|
112
|
+
* добавляет на экземпляр поле с StorageItem для данного ключа. Данные сериализуются в JSON в StorageItem.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* const model = { get: k => Promise.resolve(localStorage.getItem(k)), set: (k,v) => ..., delete: k => ... }
|
|
116
|
+
* const storage = new Storage(model).create('user')
|
|
117
|
+
* await storage.user.set({ name: 'John' })
|
|
118
|
+
* const user = await storage.user.get()
|
|
119
|
+
*/
|
|
120
|
+
declare class Storage {
|
|
121
|
+
private readonly model;
|
|
122
|
+
private readonly config?;
|
|
123
|
+
/**
|
|
124
|
+
* @param model - Реализация хранилища (например обёртка над localStorage или API)
|
|
125
|
+
* @param config - Опции (withDebug для отладочного логирования)
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```typescript
|
|
129
|
+
* const storage = new Storage(model, { withDebug: true })
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
constructor(model: StorageModel, config?: StorageConfig);
|
|
133
|
+
/**
|
|
134
|
+
* Должен вернуть все элементы хранилища.
|
|
135
|
+
* В базовой реализации не поддержан и выбрасывает `Not implemented`.
|
|
136
|
+
*
|
|
137
|
+
* @returns Никогда не завершается успешно в базовом классе
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* await storage.all() // Error: Not implemented
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
all(): Promise<never>;
|
|
145
|
+
/**
|
|
146
|
+
* Должен очистить всё хранилище.
|
|
147
|
+
* В базовой реализации не поддержан и выбрасывает `Not implemented`.
|
|
148
|
+
*
|
|
149
|
+
* @returns Никогда не завершается успешно в базовом классе
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```typescript
|
|
153
|
+
* await storage.clear() // Error: Not implemented
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
clear(): Promise<never>;
|
|
157
|
+
/**
|
|
158
|
+
* Создаёт и привязывает к экземпляру Storage элемент хранилища с заданным ключом.
|
|
159
|
+
* Возвращает this с новым полем key типа StorageItem<Value> (типизация через StorageInstance).
|
|
160
|
+
*
|
|
161
|
+
* @param key - Имя ключа (и имени поля на экземпляре, например 'user' → storage.user)
|
|
162
|
+
* @returns this с добавленным полем key
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* const storage = new Storage(model).create<'user', { name: string }>('user')
|
|
167
|
+
* await storage.user.set({ name: 'John' })
|
|
168
|
+
* ```
|
|
169
|
+
*/
|
|
170
|
+
create<Key extends string = string, Value = unknown>(key: Key): this & StorageInstance<Key, Value>;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export { Storage };
|
|
174
|
+
export type { StorageConfig, StorageInstance, StorageModel };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=t=>t instanceof Error,e=(t,...e)=>{if(t instanceof Function)return t(...e)};class s{isDefaultPrevented=!1;constructor(){this.preventDefault=this.preventDefault.bind(this),this.overrideDefault=this.overrideDefault.bind(this)}preventDefault(){this.isDefaultPrevented=!0}overrideDefault(){this.isDefaultPrevented=!1}}class i{subscriptions={};constructor(){this.emit=this.emit.bind(this),this.on=this.on.bind(this),this.off=this.off.bind(this),this.clear=this.clear.bind(this)}emit(t,s,i){const r=this.subscriptions[t];if(r){const{event:t,listenerList:n}=r;n.forEach(i=>e(i,Object.assign(t,s))),t.isDefaultPrevented||e(i)}else e(i)}on(t,e){const i=this.subscriptions[t];return i?i.listenerList.push(e):this.subscriptions[t]={event:new s,listenerList:[e]},()=>this.off(t,e)}off(t,e){const s=this.subscriptions[t];if(s){const{event:i,listenerList:r}=s;this.subscriptions[t]={event:i,listenerList:r.filter(t=>t!==e)},i.overrideDefault()}}clear(t){delete this.subscriptions[t]}}const r=(t="?",...e)=>{const s=(t&&(i=t,"string"==typeof i)?t:"?").toUpperCase();var i;const r=e.reduce((t,e,s,{length:i})=>{const r=s===i-1?[]:["|"];return t.push(e,...r),t},e.length?["-"]:[]);return[`[${s}]`,...r]};var n,o,a;!function(t){t.StartGroup="group",t.EndGroup="groupEnd",t.Default="log"}(n||(n={})),function(t){t.Info="[36m%s[0m",t.Success="[32m%s[0m",t.Warning="[33m%s[0m",t.Danger="[31m%s[0m"}(o||(o={}));class c{static formatted={info:(...t)=>c.info(...r(...t)),success:(...t)=>c.success(...r(...t)),warning:(...t)=>c.warning(...r(...t)),danger:(...t)=>c.danger(...r(...t))};static#t(t,...e){console[t](...e)}static startGroup(t,e,...s){c.#t(n.StartGroup,...((t,...e)=>["%c%s",t,...e])(`font-size: 16px;${e}`,...r(t,...s)))}static endGroup(){c.#t(n.EndGroup)}static info(...t){c.#t(n.Default,o.Info,...t)}static success(...t){c.#t(n.Default,o.Success,...t)}static warning(...t){c.#t(n.Default,o.Warning,...t)}static danger(...t){c.#t(n.Default,o.Danger,...t)}}!function(t){t.Capture="capture",t.Forward="forward"}(a||(a={}));class u{static eventEmitter=new i;static caseList=[];static log(e,s){const{signal:i,message:r,payload:n,stack:o}=s,a=[r,t(e)?e.message:void 0].filter(Boolean);c.formatted.danger(i,...a,{error:e,payload:n,stack:o})}static get on(){return u.eventEmitter.on}static get off(){return u.eventEmitter.off}static get clear(){return u.eventEmitter.clear}static create(t,e){return new Error(t,{cause:e})}static throw(t,e){throw u.create(t,e)}static capture(t,e){u.log(t,e),u.eventEmitter.emit(a.Capture,{error:t,config:e})}static forward(t,e){throw u.log(t,e),u.eventEmitter.emit(a.Capture,{error:t,config:e}),t}static case(t){u.caseList.push(t)}static parse(e){const s={message:"Error!",status:0,errors:{},isExternal:!0};for(const{check:t,parse:i}of u.caseList)if(t(e,s))return i(e,s);return!0===t(e)?{message:e.message,status:s.status,errors:s.errors,isExternal:s.isExternal}:{message:s.message,status:s.status,errors:s.errors,isExternal:s.isExternal}}}class l{key;model;config;constructor(t,e,s){this.key=t,this.model=e,this.config=s}async get(t){const{defaultValue:e,withDebug:s}={...this.config,...t},i=await this.model.get(this.key),r=i&&JSON.parse(i)||e;return s&&c.formatted.info("get",this.key,r),r}async set(t,e){const{withDebug:s}={...this.config,...e};await this.model.set(this.key,JSON.stringify(t)),s&&c.formatted.info("set",this.key,t)}async delete(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});await this.model.delete(this.key),e&&c.formatted.info("delete",this.key,s)}async has(t){const{withDebug:e}={...this.config,...t},s=await this.get({...t,withDebug:!1});return e&&c.formatted.info("has",this.key,s),!!s}}class f{model;config;constructor(t,e){this.model=t,this.config=e}async all(){u.throw("Not implemented")}async clear(){u.throw("Not implemented")}create(t){const e={[t]:new l(t,this.model,this.config)};return Object.assign(this,e)}}export{f as Storage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* @description
|
|
4
|
+
* Общие утилитарные типы для проектов на TypeScript.
|
|
5
|
+
* Содержит типы для примитивов (Nullable, NotNullable), структур данных
|
|
6
|
+
* (BaseRecord, Entry, List), функций (Callback, AsyncCallback) и вспомогательные
|
|
7
|
+
* утилиты (KeyOf, ValueOf, Decrement, Increment и др.).
|
|
8
|
+
* Модуль не содержит рантайм-кода — только типы.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* type User = { id: number; name?: string | null }
|
|
13
|
+
*
|
|
14
|
+
* type UserId = ValueOf<Pick<User, 'id'>>
|
|
15
|
+
* type SafeName = NotNullable<User['name']>
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
type NullablePrimitive = undefined | null;
|
|
19
|
+
/**
|
|
20
|
+
* Ключи объекта `Data`. Удобный псевдоним для `keyof`.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* type UserKeys = KeyOf<{ id: number; name: string }> // 'id' | 'name'
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
type KeyOf<Data> = keyof Data;
|
|
28
|
+
/**
|
|
29
|
+
* Объединение всех возможных значений объекта `Data`.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```typescript
|
|
33
|
+
* type UserValue = ValueOf<{ id: number; name: string }> // number | string
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
type ValueOf<Data> = Data[KeyOf<Data>];
|
|
37
|
+
/** Тип одного элемента массива или кортежа. */
|
|
38
|
+
type IterableOf<Data extends unknown[]> = Data[number];
|
|
39
|
+
/** Служебный псевдоним для `never` или другого "пустого" значения. */
|
|
40
|
+
type Nothing<Data = never> = Data;
|
|
41
|
+
/**
|
|
42
|
+
* Тип, допускающий null или undefined (например для опциональных полей).
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* type MaybeName = Nullable<string> // string | null | undefined
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
type Nullable<Data = undefined> = Data | NullablePrimitive;
|
|
50
|
+
/**
|
|
51
|
+
* Тип, исключающий null и undefined (гарантированно заданное значение).
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* type Name = NotNullable<string | null | undefined> // string
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
type NotNullable<Data = undefined> = Exclude<Data, NullablePrimitive>;
|
|
59
|
+
/** Число или значение, которое можно привести к числу, включая строковый литерал числа. */
|
|
60
|
+
type Numerable<Data = number> = Data | number | `${number}`;
|
|
61
|
+
/** Значение, которое может быть как синхронным, так и обёрнутым в Promise. */
|
|
62
|
+
type MaybeAsync<Data = never> = Data | Promise<Data>;
|
|
63
|
+
/**
|
|
64
|
+
* Допустимые ключи объекта (как в Record).
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* type Key = BaseKey // string | number | symbol
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
type BaseKey = string | number | symbol;
|
|
72
|
+
/**
|
|
73
|
+
* Массив элементов (базовый тип для списков).
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```typescript
|
|
77
|
+
* type IdList = BaseList<number> // number[]
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
type BaseList<Item = unknown> = Item[];
|
|
81
|
+
/**
|
|
82
|
+
* Объект с ключами Key и значениями Value (обобщение Record).
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* type UserMap = BaseRecord<string, 'name' | 'role'>
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
type BaseRecord<Value = unknown, Key extends BaseKey = BaseKey> = Record<Key, Value>;
|
|
90
|
+
/** Объединение `{ key, value }` для каждой пары ключ-значение объекта. */
|
|
91
|
+
type Entry<Data> = {
|
|
92
|
+
[Key in KeyOf<Data>]: {
|
|
93
|
+
key: Key;
|
|
94
|
+
value: Data[Key];
|
|
95
|
+
};
|
|
96
|
+
}[KeyOf<Data>];
|
|
97
|
+
/** Делает указанные ключи обязательными, а остальные оставляет опциональными. */
|
|
98
|
+
type Include<Data, Key extends KeyOf<Data>> = Required<Pick<Data, Key>> & Partial<Omit<Data, Key>>;
|
|
99
|
+
/** Разделяет объект на кортеж из выбранных и оставшихся свойств. */
|
|
100
|
+
type Divide<Data, Key extends KeyOf<Data>> = [Pick<Data, Key>, Omit<Data, Key>];
|
|
101
|
+
/** Заполняет набор ключей значениями из `Data` или `DefaultValue`, если ключ отсутствует. */
|
|
102
|
+
type Filled<Data, Key extends BaseKey, DefaultValue = undefined> = {
|
|
103
|
+
[SomeKey in Key]: SomeKey extends KeyOf<Data> ? Data[SomeKey] : DefaultValue;
|
|
104
|
+
};
|
|
105
|
+
/** Общая часть нескольких объектов: только совпадающие ключи и совместимые типы значений. */
|
|
106
|
+
type Shared<DataList extends BaseList[], FirstData extends IterableOf<DataList> = IterableOf<DataList>, SecondData extends IterableOf<DataList> = IterableOf<DataList>> = {
|
|
107
|
+
[Key in KeyOf<FirstData> & KeyOf<SecondData>]: FirstData[Key] extends SecondData[Key] ? FirstData[Key] : never;
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Кортеж фиксированной длины `Length`, заполненный элементами типа `Item`.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* type Pair = List<2, string> // [string, string]
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
type List<Length extends number, Item = unknown, ResultList extends Item[] = []> = Length extends ResultList['length'] ? ResultList : List<Length, Item, [...ResultList, Item]>;
|
|
118
|
+
/**
|
|
119
|
+
* Уменьшает числовой литерал на единицу.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* type Two = Decrement<3> // 2
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
type Decrement<Value extends number> = List<Value> extends [infer _, ...infer Rest] ? Rest['length'] : never;
|
|
127
|
+
/**
|
|
128
|
+
* Увеличивает числовой литерал на единицу.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* ```typescript
|
|
132
|
+
* type Four = Increment<3> // 4
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
type Increment<Value extends number> = [...List<Value>, IterableOf<List<Value>>]['length'];
|
|
136
|
+
/**
|
|
137
|
+
* Функция без аргументов и возвращаемого значения.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* const noop: Noop = () => {}
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
type Noop = () => void;
|
|
145
|
+
/**
|
|
146
|
+
* Синхронная функция с заданным списком параметров и результатом.
|
|
147
|
+
* @template ParamList - кортеж типов аргументов
|
|
148
|
+
* @template Result - тип возвращаемого значения
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```typescript
|
|
152
|
+
* type Sum = Callback<[number, number], number>
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
type Callback<ParamList extends BaseList = BaseList, Result = void> = (...paramList: ParamList) => Result;
|
|
156
|
+
/**
|
|
157
|
+
* Асинхронная функция с заданным списком параметров и результатом.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```typescript
|
|
161
|
+
* type FetchUser = AsyncCallback<[string], { id: string }>
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
type AsyncCallback<ParamList extends BaseList = BaseList, Result = void> = (...paramList: ParamList) => Promise<Result>;
|
|
165
|
+
/** Любая синхронная функция без ограничений на аргументы и результат. */
|
|
166
|
+
type AnyCallback = Callback<any[], any>;
|
|
167
|
+
/** Любая асинхронная функция без ограничений на аргументы и результат. */
|
|
168
|
+
type AnyAsyncCallback = AsyncCallback<any[], any>;
|
|
169
|
+
/** Извлекает кортеж аргументов из типа функции. */
|
|
170
|
+
type CallbackParamList<Callback> = Callback extends (...args: infer ParamList) => any ? ParamList : never;
|
|
171
|
+
/** Извлекает тип возвращаемого значения из типа функции. */
|
|
172
|
+
type CallbackResult<Callback> = Callback extends (...args: any) => infer Result ? Result : any;
|
|
173
|
+
|
|
174
|
+
type ExtraSizeRange<Level extends number, Value extends string, Result extends string = `x${Value}`> = Level extends 1 ? Result : ExtraSizeRange<Decrement<Level>, Value, `${Level}x${Value}` | Result>;
|
|
175
|
+
/**
|
|
176
|
+
* Набор строковых размеров относительно базовых `s`, `m`, `l`.
|
|
177
|
+
* Позволяет расширять диапазон вниз (`xs`, `2xs`, ...) и вверх (`xl`, `2xl`, ...).
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```typescript
|
|
181
|
+
* type ButtonSize = SizeRange<2, 1> // '2xs' | 'xs' | 's' | 'm' | 'l' | 'xl'
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
184
|
+
type SizeRange<ExtraLevelDown extends number = 1, ExtraLevelUp extends number = 1> = ExtraSizeRange<ExtraLevelDown, 's'> | 's' | 'm' | 'l' | ExtraSizeRange<ExtraLevelUp, 'l'>;
|
|
185
|
+
/**
|
|
186
|
+
* Объединение чисел от `1` до `Level`.
|
|
187
|
+
*
|
|
188
|
+
* @example
|
|
189
|
+
* ```typescript
|
|
190
|
+
* type Steps = LevelRange<3> // 1 | 2 | 3
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
type LevelRange<Level extends number, Result extends number = Level> = Level extends 1 ? Result : LevelRange<Decrement<Level>, Result | Decrement<Level>>;
|
|
194
|
+
|
|
195
|
+
export type { AnyAsyncCallback, AnyCallback, AsyncCallback, BaseKey, BaseList, BaseRecord, Callback, CallbackParamList, CallbackResult, Decrement, Divide, Entry, Filled, Include, Increment, IterableOf, KeyOf, LevelRange, List, MaybeAsync, Noop, NotNullable, Nothing, Nullable, Numerable, Shared, SizeRange, ValueOf };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=e=>void 0===e,t=e=>null===e,r=r=>e(r)||t(r),s=e=>"object"==typeof e,o=e=>{const t=[n,i,p,u,c,f,a,x,l,y,m].some(t=>t(e));return!!e&&"object"==typeof e&&!t},n=e=>Array.isArray(e),i=e=>e instanceof ArrayBuffer,p=e=>e instanceof Map,u=e=>e instanceof Set,c=e=>e instanceof Map,f=e=>e instanceof Set,a=e=>e instanceof Date,x=e=>e instanceof Error,l=e=>e instanceof RegExp,y=e=>e instanceof Promise,m=e=>e instanceof Function;const b=(e,...t)=>{if(m(e))return e(...t)};function g(e,t){return!(!s(t)||!(e in t))}function h(e,t){return e.filter(e=>t.includes(e))}exports.chunkList=function(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r},exports.compose=function(e,t,s){const n=!o(e);return!r(s)&&{...t,...n?{[s]:e}:e}||!r(t)&&{...t,...e}||{...e}},exports.debounce=(e,t)=>{let r;return(...s)=>{r&&clearTimeout(r),r=setTimeout(()=>b(e,...s),t)}},exports.filterByKey=function(e,t="isVisible"){return e.filter(e=>!g(t,e)||e[t])},exports.filterDuplicateByKey=function(e,t){return e.reduce((e,r)=>e.some(e=>e[t]===r[t])?e:[...e,r],[])},exports.filterEqualValues=h,exports.filterNullableValues=function(e){return e.filter(e=>!r(e))},exports.forceList=function(e){return n(e)?e:[e]},exports.getValueByKey=function(e,t,s){return r(e)?s:2===arguments.length?t[e]:t[e]??s},exports.hasEqualValues=function(e,t){return!!h(e,t).length},exports.hasKey=g,exports.isAnyObject=s,exports.isArray=n,exports.isArrayBuffer=i,exports.isArrayEmpty=function(e){return 0===e.length},exports.isBigint=e=>"bigint"==typeof e,exports.isBoolean=e=>"boolean"==typeof e,exports.isDate=a,exports.isError=x,exports.isFunction=m,exports.isMap=p,exports.isNaN=e=>Number.isNaN(e),exports.isNull=t,exports.isNullable=r,exports.isNumber=e=>"number"==typeof e,exports.isObject=o,exports.isObjectEmpty=function(e){for(const t in e)return!1;return!0},exports.isPromise=y,exports.isProxy=e=>e instanceof Proxy,exports.isRegExp=l,exports.isSet=u,exports.isString=e=>"string"==typeof e,exports.isSymbol=e=>"symbol"==typeof e,exports.isUndefined=e,exports.isWeakMap=c,exports.isWeakSet=f,exports.mapRecord=(e,t)=>{const r=Object.entries(e);return Object.fromEntries(r.map(([e,r],s,o)=>[e,t(e,r,s,o)]))},exports.runCallback=b,exports.throttle=(e,t)=>{let r=!0;return(...s)=>{r&&(b(e,...s),r=!1),setTimeout(()=>r=!0,t)}},exports.wait=e=>new Promise(t=>setTimeout(t,e));
|