yummies 7.10.0 → 7.11.0
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/async.cjs +11 -11
- package/async.cjs.map +1 -1
- package/async.d.ts +9 -11
- package/async.js +11 -11
- package/async.js.map +1 -1
- package/complex.cjs +32 -8
- package/complex.cjs.map +1 -1
- package/complex.d.ts +133 -13
- package/complex.js +32 -8
- package/complex.js.map +1 -1
- package/css.cjs.map +1 -1
- package/css.d.ts +3 -3
- package/css.js.map +1 -1
- package/date-time.cjs.map +1 -1
- package/date-time.js.map +1 -1
- package/format.cjs.map +1 -1
- package/format.d.ts +89 -4
- package/format.js.map +1 -1
- package/html.cjs.map +1 -1
- package/html.d.ts +3 -3
- package/html.js.map +1 -1
- package/id.cjs.map +1 -1
- package/id.d.ts +10 -10
- package/id.js.map +1 -1
- package/imports.cjs.map +1 -1
- package/imports.d.ts +5 -4
- package/imports.js.map +1 -1
- package/math.cjs.map +1 -1
- package/math.d.ts +1 -1
- package/math.js.map +1 -1
- package/media.cjs.map +1 -1
- package/media.d.ts +1 -1
- package/media.js.map +1 -1
- package/mobx.cjs.map +1 -1
- package/mobx.d.ts +165 -6
- package/mobx.js.map +1 -1
- package/ms.cjs.map +1 -1
- package/ms.d.ts +1 -1
- package/ms.js.map +1 -1
- package/package.json +5 -5
- package/parser.cjs.map +1 -1
- package/parser.d.ts +63 -0
- package/parser.js.map +1 -1
- package/react.cjs.map +1 -1
- package/react.d.ts +407 -9
- package/react.js.map +1 -1
- package/sound.cjs.map +1 -1
- package/sound.d.ts +1 -1
- package/sound.js.map +1 -1
- package/storage.cjs.map +1 -1
- package/storage.d.ts +7 -6
- package/storage.js.map +1 -1
- package/text.cjs.map +1 -1
- package/text.d.ts +5 -5
- package/text.js.map +1 -1
- package/type-guard.cjs.map +1 -1
- package/type-guard.d.ts +199 -42
- package/type-guard.js.map +1 -1
- package/vibrate.cjs.map +1 -1
- package/vibrate.d.ts +1 -1
- package/vibrate.js.map +1 -1
package/async.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const sleep = (time = 0, signal) => new Promise((resolve, reject) => {
|
|
4
|
-
const timerId = setTimeout(resolve, time);
|
|
5
4
|
if (signal) {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
()
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
5
|
+
const abortListener = () => {
|
|
6
|
+
clearTimeout(timerId);
|
|
7
|
+
reject(signal?.reason);
|
|
8
|
+
};
|
|
9
|
+
const timerId = setTimeout(() => {
|
|
10
|
+
signal.removeEventListener("abort", abortListener);
|
|
11
|
+
resolve();
|
|
12
|
+
}, time);
|
|
13
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
14
|
+
} else {
|
|
15
|
+
setTimeout(resolve, time);
|
|
16
16
|
}
|
|
17
17
|
});
|
|
18
18
|
const waitAsync = async (ms = 1e3) => new Promise((resolve) => setTimeout(resolve, ms));
|
package/async.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async.cjs","sources":["../src/async.ts"],"sourcesContent":["/**\n *
|
|
1
|
+
{"version":3,"file":"async.cjs","sources":["../src/async.ts"],"sourcesContent":["/**\n * Creates a promise that resolves after the specified number of milliseconds.\n *\n * @param time Delay in milliseconds.\n * @returns Promise\n */\nexport const sleep = (time: number = 0, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal) {\n const abortListener = () => {\n clearTimeout(timerId);\n reject(signal?.reason);\n };\n const timerId = setTimeout(() => {\n signal.removeEventListener('abort', abortListener);\n resolve();\n }, time);\n signal.addEventListener('abort', abortListener, { once: true });\n } else {\n setTimeout(resolve, time);\n }\n });\n\n/**\n * Creates a promise that resolves after the specified number of milliseconds.\n *\n * @deprecated Use `sleep` instead.\n * @param ms Delay in milliseconds.\n * @returns Promise\n */\nexport const waitAsync = async (ms = 1000) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Repeatedly schedules `requestAnimationFrame` until `quitFunction` returns `true`.\n *\n * @param quitFunction Function executed on each animation frame.\n * @param asMicrotask Additionally wraps the RAF scheduling in `queueMicrotask`.\n * @returns void\n */\nexport const endlessRAF = (\n quitFunction: () => boolean | void,\n asMicrotask?: boolean,\n) => {\n if (quitFunction()) return;\n\n const raf = () =>\n requestAnimationFrame(() => endlessRAF(quitFunction, asMicrotask));\n\n if (asMicrotask) {\n queueMicrotask(raf);\n } else {\n raf();\n }\n};\n\nexport function setAbortableTimeout(\n callback: VoidFunction,\n delayInMs?: number,\n signal?: AbortSignal,\n) {\n let internalTimer: number | null = null;\n\n const handleAbort = () => {\n if (internalTimer == null) {\n return;\n }\n clearTimeout(internalTimer);\n internalTimer = null;\n };\n\n signal?.addEventListener('abort', handleAbort, { once: true });\n\n internalTimer = setTimeout(() => {\n signal?.removeEventListener('abort', handleAbort);\n callback();\n }, delayInMs);\n}\n\nexport function setAbortableInterval(\n callback: VoidFunction,\n delayInMs?: number,\n signal?: AbortSignal,\n) {\n let timer: number | null = null;\n\n const handleAbort = () => {\n if (timer == null) {\n return;\n }\n clearInterval(timer);\n timer = null;\n };\n\n signal?.addEventListener('abort', handleAbort, { once: true });\n\n timer = setInterval(callback, delayInMs);\n}\n"],"names":[],"mappings":";;AAMO,MAAM,QAAQ,CAAC,OAAe,GAAG,WACtC,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,MAAI,QAAQ;AACV,UAAM,gBAAgB,MAAM;AAC1B,mBAAa,OAAO;AACpB,aAAO,QAAQ,MAAM;AAAA,IACvB;AACA,UAAM,UAAU,WAAW,MAAM;AAC/B,aAAO,oBAAoB,SAAS,aAAa;AACjD,cAAA;AAAA,IACF,GAAG,IAAI;AACP,WAAO,iBAAiB,SAAS,eAAe,EAAE,MAAM,MAAM;AAAA,EAChE,OAAO;AACL,eAAW,SAAS,IAAI;AAAA,EAC1B;AACF,CAAC;AASI,MAAM,YAAY,OAAO,KAAK,QACnC,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAS3C,MAAM,aAAa,CACxB,cACA,gBACG;AACH,MAAI,eAAgB;AAEpB,QAAM,MAAM,MACV,sBAAsB,MAAM,WAAW,cAAc,WAAW,CAAC;AAEnE,MAAI,aAAa;AACf,mBAAe,GAAG;AAAA,EACpB,OAAO;AACL,QAAA;AAAA,EACF;AACF;AAEO,SAAS,oBACd,UACA,WACA,QACA;AACA,MAAI,gBAA+B;AAEnC,QAAM,cAAc,MAAM;AACxB,QAAI,iBAAiB,MAAM;AACzB;AAAA,IACF;AACA,iBAAa,aAAa;AAC1B,oBAAgB;AAAA,EAClB;AAEA,UAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,MAAM;AAE7D,kBAAgB,WAAW,MAAM;AAC/B,YAAQ,oBAAoB,SAAS,WAAW;AAChD,aAAA;AAAA,EACF,GAAG,SAAS;AACd;AAEO,SAAS,qBACd,UACA,WACA,QACA;AACA,MAAI,QAAuB;AAE3B,QAAM,cAAc,MAAM;AACxB,QAAI,SAAS,MAAM;AACjB;AAAA,IACF;AACA,kBAAc,KAAK;AACnB,YAAQ;AAAA,EACV;AAEA,UAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,MAAM;AAE7D,UAAQ,YAAY,UAAU,SAAS;AACzC;;;;;;"}
|
package/async.d.ts
CHANGED
|
@@ -1,25 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Creates a promise that resolves after the specified number of milliseconds.
|
|
3
3
|
*
|
|
4
|
-
* @param
|
|
4
|
+
* @param time Delay in milliseconds.
|
|
5
5
|
* @returns Promise
|
|
6
6
|
*/
|
|
7
|
-
declare const sleep: (time?: number, signal?: AbortSignal) => Promise<
|
|
7
|
+
declare const sleep: (time?: number, signal?: AbortSignal) => Promise<void>;
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
9
|
+
* Creates a promise that resolves after the specified number of milliseconds.
|
|
10
10
|
*
|
|
11
|
-
* @deprecated
|
|
12
|
-
* @param ms
|
|
11
|
+
* @deprecated Use `sleep` instead.
|
|
12
|
+
* @param ms Delay in milliseconds.
|
|
13
13
|
* @returns Promise
|
|
14
14
|
*/
|
|
15
15
|
declare const waitAsync: (ms?: number) => Promise<unknown>;
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
* тогда повторно не будет создан вызов requestAnimationFrame, иначе будут создаваться повторно
|
|
19
|
-
* вызовы requestAnimationFrame до тем пор, пока эта функция не вернёт true
|
|
17
|
+
* Repeatedly schedules `requestAnimationFrame` until `quitFunction` returns `true`.
|
|
20
18
|
*
|
|
21
|
-
* @param
|
|
22
|
-
* @param asMicrotask
|
|
19
|
+
* @param quitFunction Function executed on each animation frame.
|
|
20
|
+
* @param asMicrotask Additionally wraps the RAF scheduling in `queueMicrotask`.
|
|
23
21
|
* @returns void
|
|
24
22
|
*/
|
|
25
23
|
declare const endlessRAF: (quitFunction: () => boolean | void, asMicrotask?: boolean) => void;
|
package/async.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
const sleep = (time = 0, signal) => new Promise((resolve, reject) => {
|
|
2
|
-
const timerId = setTimeout(resolve, time);
|
|
3
2
|
if (signal) {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
()
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
3
|
+
const abortListener = () => {
|
|
4
|
+
clearTimeout(timerId);
|
|
5
|
+
reject(signal?.reason);
|
|
6
|
+
};
|
|
7
|
+
const timerId = setTimeout(() => {
|
|
8
|
+
signal.removeEventListener("abort", abortListener);
|
|
9
|
+
resolve();
|
|
10
|
+
}, time);
|
|
11
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
12
|
+
} else {
|
|
13
|
+
setTimeout(resolve, time);
|
|
14
14
|
}
|
|
15
15
|
});
|
|
16
16
|
const waitAsync = async (ms = 1e3) => new Promise((resolve) => setTimeout(resolve, ms));
|
package/async.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async.js","sources":["../src/async.ts"],"sourcesContent":["/**\n *
|
|
1
|
+
{"version":3,"file":"async.js","sources":["../src/async.ts"],"sourcesContent":["/**\n * Creates a promise that resolves after the specified number of milliseconds.\n *\n * @param time Delay in milliseconds.\n * @returns Promise\n */\nexport const sleep = (time: number = 0, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal) {\n const abortListener = () => {\n clearTimeout(timerId);\n reject(signal?.reason);\n };\n const timerId = setTimeout(() => {\n signal.removeEventListener('abort', abortListener);\n resolve();\n }, time);\n signal.addEventListener('abort', abortListener, { once: true });\n } else {\n setTimeout(resolve, time);\n }\n });\n\n/**\n * Creates a promise that resolves after the specified number of milliseconds.\n *\n * @deprecated Use `sleep` instead.\n * @param ms Delay in milliseconds.\n * @returns Promise\n */\nexport const waitAsync = async (ms = 1000) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Repeatedly schedules `requestAnimationFrame` until `quitFunction` returns `true`.\n *\n * @param quitFunction Function executed on each animation frame.\n * @param asMicrotask Additionally wraps the RAF scheduling in `queueMicrotask`.\n * @returns void\n */\nexport const endlessRAF = (\n quitFunction: () => boolean | void,\n asMicrotask?: boolean,\n) => {\n if (quitFunction()) return;\n\n const raf = () =>\n requestAnimationFrame(() => endlessRAF(quitFunction, asMicrotask));\n\n if (asMicrotask) {\n queueMicrotask(raf);\n } else {\n raf();\n }\n};\n\nexport function setAbortableTimeout(\n callback: VoidFunction,\n delayInMs?: number,\n signal?: AbortSignal,\n) {\n let internalTimer: number | null = null;\n\n const handleAbort = () => {\n if (internalTimer == null) {\n return;\n }\n clearTimeout(internalTimer);\n internalTimer = null;\n };\n\n signal?.addEventListener('abort', handleAbort, { once: true });\n\n internalTimer = setTimeout(() => {\n signal?.removeEventListener('abort', handleAbort);\n callback();\n }, delayInMs);\n}\n\nexport function setAbortableInterval(\n callback: VoidFunction,\n delayInMs?: number,\n signal?: AbortSignal,\n) {\n let timer: number | null = null;\n\n const handleAbort = () => {\n if (timer == null) {\n return;\n }\n clearInterval(timer);\n timer = null;\n };\n\n signal?.addEventListener('abort', handleAbort, { once: true });\n\n timer = setInterval(callback, delayInMs);\n}\n"],"names":[],"mappings":"AAMO,MAAM,QAAQ,CAAC,OAAe,GAAG,WACtC,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,MAAI,QAAQ;AACV,UAAM,gBAAgB,MAAM;AAC1B,mBAAa,OAAO;AACpB,aAAO,QAAQ,MAAM;AAAA,IACvB;AACA,UAAM,UAAU,WAAW,MAAM;AAC/B,aAAO,oBAAoB,SAAS,aAAa;AACjD,cAAA;AAAA,IACF,GAAG,IAAI;AACP,WAAO,iBAAiB,SAAS,eAAe,EAAE,MAAM,MAAM;AAAA,EAChE,OAAO;AACL,eAAW,SAAS,IAAI;AAAA,EAC1B;AACF,CAAC;AASI,MAAM,YAAY,OAAO,KAAK,QACnC,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAS3C,MAAM,aAAa,CACxB,cACA,gBACG;AACH,MAAI,eAAgB;AAEpB,QAAM,MAAM,MACV,sBAAsB,MAAM,WAAW,cAAc,WAAW,CAAC;AAEnE,MAAI,aAAa;AACf,mBAAe,GAAG;AAAA,EACpB,OAAO;AACL,QAAA;AAAA,EACF;AACF;AAEO,SAAS,oBACd,UACA,WACA,QACA;AACA,MAAI,gBAA+B;AAEnC,QAAM,cAAc,MAAM;AACxB,QAAI,iBAAiB,MAAM;AACzB;AAAA,IACF;AACA,iBAAa,aAAa;AAC1B,oBAAgB;AAAA,EAClB;AAEA,UAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,MAAM;AAE7D,kBAAgB,WAAW,MAAM;AAC/B,YAAQ,oBAAoB,SAAS,WAAW;AAChD,aAAA;AAAA,EACF,GAAG,SAAS;AACd;AAEO,SAAS,qBACd,UACA,WACA,QACA;AACA,MAAI,QAAuB;AAE3B,QAAM,cAAc,MAAM;AACxB,QAAI,SAAS,MAAM;AACjB;AAAA,IACF;AACA,kBAAc,KAAK;AACnB,YAAQ;AAAA,EACV;AAEA,UAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,MAAM;AAE7D,UAAQ,YAAY,UAAU,SAAS;AACzC;"}
|
package/complex.cjs
CHANGED
|
@@ -64,23 +64,47 @@ const createGlobalDynamicConfig = (processFn, accessSymbol) => {
|
|
|
64
64
|
};
|
|
65
65
|
class ModulesFactory {
|
|
66
66
|
/**
|
|
67
|
-
*
|
|
67
|
+
* Creates a new module factory.
|
|
68
68
|
*
|
|
69
|
-
* @param config
|
|
69
|
+
* @param config Factory strategy and predefined dependencies.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```ts
|
|
73
|
+
* const factory = new ModulesFactory({
|
|
74
|
+
* factory: (Module, deps) => new Module(deps),
|
|
75
|
+
* });
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const factory = new ModulesFactory({
|
|
81
|
+
* factory: (Module, deps) => new Module(deps),
|
|
82
|
+
* deps: { api },
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
70
85
|
*/
|
|
71
86
|
constructor(config) {
|
|
72
87
|
this.config = config;
|
|
73
88
|
}
|
|
74
89
|
/**
|
|
75
|
-
*
|
|
90
|
+
* Creates an instance of the provided class by merging predefined and
|
|
91
|
+
* per-call dependencies.
|
|
76
92
|
*
|
|
77
|
-
* @template TInstance
|
|
78
|
-
* @template TDeps
|
|
93
|
+
* @template TInstance Instance type produced by the constructor.
|
|
94
|
+
* @template TDeps Full dependency object expected by the constructor.
|
|
95
|
+
* @param Constructor Class constructor receiving a single dependency object.
|
|
96
|
+
* @param args Additional dependencies merged over predefined ones.
|
|
97
|
+
* @returns Created class instance.
|
|
79
98
|
*
|
|
80
|
-
* @
|
|
81
|
-
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```ts
|
|
101
|
+
* const service = factory.create(UserService, { logger });
|
|
102
|
+
* ```
|
|
82
103
|
*
|
|
83
|
-
* @
|
|
104
|
+
* @example
|
|
105
|
+
* ```ts
|
|
106
|
+
* const store = factory.create(UserStore);
|
|
107
|
+
* ```
|
|
84
108
|
*/
|
|
85
109
|
create(Constructor, ...args) {
|
|
86
110
|
return this.config.factory(Constructor, {
|
package/complex.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"complex.cjs","sources":["../src/complex/counter.ts","../src/complex/global-point.ts","../src/complex/global-config.ts","../src/complex/modules-factory.ts","../src/complex/pub-sub.ts"],"sourcesContent":["export interface Counter<TValue = number> {\n (): TValue;\n counter: number;\n value: TValue;\n increment(): TValue;\n decrement(): TValue;\n reset(): void;\n}\n\n/**\n * @deprecated use {`Counter`}. Will be removed in next major release\n */\nexport interface CounterFn<TValue = number> extends Counter<TValue> {}\n\nexport const createCounter = <TValue = number>(\n processValue?: (value: number) => TValue,\n initial: number = 0,\n): Counter<TValue> => {\n const update = (counter: number) => {\n fn.value = processValue?.(counter) ?? (counter as TValue);\n return fn.value;\n };\n\n const increment = () => update(++fn.counter);\n const decrement = () => update(--fn.counter);\n\n const fn: Counter<TValue> = increment as any;\n\n fn.increment = increment;\n fn.decrement = decrement;\n\n fn.reset = () => {\n fn.counter = initial;\n fn.value = processValue?.(initial) ?? (initial as TValue);\n };\n\n fn.reset();\n\n return fn as Counter<TValue>;\n};\n","import type { AnyObject } from 'yummies/types';\n\nexport interface GlobalPoint<TValue> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n}\n\nexport const createGlobalPoint = <TValue>(\n accessSymbol?: keyof any,\n): GlobalPoint<TValue> => {\n if (accessSymbol == null) {\n let storedValue: TValue | undefined;\n\n return {\n get: (): TValue => storedValue!,\n unset: () => {\n storedValue = undefined;\n },\n set: (value: TValue): TValue => {\n storedValue = value;\n return value;\n },\n };\n }\n\n const _globalThis = globalThis as AnyObject;\n\n return {\n get: (): TValue => _globalThis[accessSymbol],\n unset: () => {\n delete _globalThis[accessSymbol];\n },\n set: (value: TValue): TValue => {\n _globalThis[accessSymbol] = value;\n return value;\n },\n };\n};\n","import type { AnyObject, Maybe } from 'yummies/types';\nimport { createGlobalPoint } from './global-point.js';\n\n/**\n * Создает глобальный конфиг, который может быть доступен в любой точке в коде\n */\nexport const createGlobalConfig = <T extends AnyObject>(\n defaultValue: T,\n accessSymbol?: keyof any,\n): T => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n return globalPoint.get() || globalPoint.set(defaultValue);\n};\n\nexport interface GlobalDynamicConfig<TValue extends AnyObject> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n update(value: Partial<TValue>): void;\n}\n\nexport const createGlobalDynamicConfig = <T extends AnyObject>(\n processFn: (change: Maybe<Partial<T>>, current: Maybe<T>) => T,\n accessSymbol?: keyof any,\n): GlobalDynamicConfig<T> => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n\n const getValue = () => {\n return globalPoint.get() ?? globalPoint.set(processFn(null, null))!;\n };\n\n return {\n get: getValue,\n set: globalPoint.set,\n unset: globalPoint.unset,\n update: (value: Partial<T>) => {\n const currentValue = getValue();\n Object.assign(currentValue, processFn(value, currentValue));\n },\n };\n};\n","import type { AnyObject, Class, EmptyObject, IsPartial } from 'yummies/types';\n\ntype ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {\n factory<TInstance, TDeps extends TPredefinedDeps>(\n moduleClass: Class<TInstance, [TDeps]>,\n deps: TDeps,\n ): TInstance;\n} & (TPredefinedDeps extends EmptyObject\n ? { deps?: TPredefinedDeps }\n : { deps: TPredefinedDeps });\n\n/**\n * Класс `ModulesFactory` является универсальной фабрикой для создания экземпляров указанного класса с зависимостями.\n * Он использует объект конфигурации для определения того, как эти экземпляры создаются.\n *\n * Важное примечание - эта сущность работает только с классами конструктор которых имеет один параметр\n *\n * @template TPredefinedDeps - Тип, расширяющий `AnyObject`, представляющий предопределенные зависимости, которые использует фабрика.\n *\n * @example\n * ```\n * const factory = new ModulesFactory({\n * factory: (MyClass, deps) => new MyClass(deps),\n * deps: { someDependency: new Dependency() }\n * });\n *\n * const instance = factory.create(MyClass, { extraDependency: new ExtraDependency() });\n * ```\n */\nexport class ModulesFactory<TPredefinedDeps extends AnyObject = EmptyObject> {\n /**\n * Создает новый экземпляр `ModulesFactory`.\n *\n * @param config - Объект конфигурации для фабрики, включающий функцию фабрики и необязательные зависимости.\n */\n constructor(private config: ModuleLoaderConfig<TPredefinedDeps>) {}\n\n /**\n * Создает экземпляр указанного класса, внедряя необходимые зависимости.\n *\n * @template TInstance - Тип создаваемого экземпляра.\n * @template TDeps - Тип зависимостей, необходимых для экземпляра.\n *\n * @param Constructor - Конструктор класса для создаваемого экземпляра.\n * @param args - Необязательные дополнительные зависимости для объединения с предопределенными зависимостями.\n *\n * @returns Экземпляр указанного класса с внедренными зависимостями.\n */\n create<TInstance, TDeps extends TPredefinedDeps = TPredefinedDeps>(\n Constructor: Class<TInstance, [TDeps]>,\n ...args: IsPartial<Omit<TDeps, keyof TPredefinedDeps>> extends true\n ? [extraDeps?: Omit<TDeps, keyof TPredefinedDeps>]\n : [extraDeps: Omit<TDeps, keyof TPredefinedDeps>]\n ) {\n return this.config.factory(Constructor, {\n ...this.config.deps!,\n ...args[0],\n } as any);\n }\n}\n","export type SubFn<PubArgs extends any[] = any[]> = (...args: PubArgs) => void;\n\n/**\n * The Publish-Subscribe pattern, which allows objects to interact with each other\n * through an event system. Subscribers can subscribe to events and receive notifications\n * when these events occur. The last published data can be accessed through the `data` property.\n */\nexport interface PubSub<PubArgs extends any[] = any[]> {\n (...args: PubArgs): void;\n\n /**\n * Last published arguments\n */\n lastPub: PubArgs | undefined;\n\n /**\n * An array of subscriber functions (sub) that will be called\n * when an event is published. Each subscriber must match the type SubFn,\n * taking the arguments that will be passed to it when the publisher calls pub.\n */\n subs: SubFn<PubArgs>[];\n\n /**\n * A function to unsubscribe from events. When a subscriber function (sub) is passed,\n * it will be removed from the `subs` array, and will no longer receive notifications.\n */\n unsub(sub: SubFn<PubArgs>): void;\n /**\n * A function to subscribe to events. When a subscriber function (sub) is passed,\n * it will be added to the `subs` array, and will receive notifications when the publisher calls pub.\n * Returns a function that can be used to unsubscribe from events.\n */\n sub(sub: SubFn<PubArgs>): VoidFunction;\n}\n\nexport const createPubSub = <PubArgs extends any[] = any[]>() => {\n const pubSub = ((...args: PubArgs) => {\n pubSub.lastPub = args;\n pubSub.subs.forEach((sub) => {\n sub(...args);\n });\n }) as PubSub<PubArgs>;\n pubSub.lastPub = undefined;\n\n pubSub.subs = [];\n\n pubSub.unsub = (sub: SubFn<PubArgs>) => {\n pubSub.subs = pubSub.subs.filter((it) => it !== sub);\n };\n pubSub.sub = (sub: SubFn<PubArgs>) => {\n pubSub.subs.push(sub);\n return () => pubSub.unsub(sub);\n };\n\n return pubSub;\n};\n"],"names":[],"mappings":";;AAcO,MAAM,gBAAgB,CAC3B,cACA,UAAkB,MACE;AACpB,QAAM,SAAS,CAAC,YAAoB;AAClC,OAAG,QAAQ,eAAe,OAAO,KAAM;AACvC,WAAO,GAAG;AAAA,EACZ;AAEA,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAC3C,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAE3C,QAAM,KAAsB;AAE5B,KAAG,YAAY;AACf,KAAG,YAAY;AAEf,KAAG,QAAQ,MAAM;AACf,OAAG,UAAU;AACb,OAAG,QAAQ,eAAe,OAAO,KAAM;AAAA,EACzC;AAEA,KAAG,MAAA;AAEH,SAAO;AACT;AC/BO,MAAM,oBAAoB,CAC/B,iBACwB;AACxB,MAAI,gBAAgB,MAAM;AACxB,QAAI;AAEJ,WAAO;AAA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AAM,eAAe,MAAqC;AAC/D,QAAM,UAAU,IAAI,SAAkB;AACpC,WAAO,UAAU;AACjB,WAAO,KAAK,QAAQ,CAAC,QAAQ;AAC3B,UAAI,GAAG,IAAI;AAAA,IACb,CAAC;AAAA,EACH;AACA,SAAO,UAAU;AAEjB,SAAO,OAAO,CAAA;AAEd,SAAO,QAAQ,CAAC,QAAwB;AACtC,WAAO,OAAO,OAAO,KAAK,OAAO,CAAC,OAAO,OAAO,GAAG;AAAA,EACrD;AACA,SAAO,MAAM,CAAC,QAAwB;AACpC,WAAO,KAAK,KAAK,GAAG;AACpB,WAAO,MAAM,OAAO,MAAM,GAAG;AAAA,EAC/B;AAEA,SAAO;AACT;;;;;;"}
|
|
1
|
+
{"version":3,"file":"complex.cjs","sources":["../src/complex/counter.ts","../src/complex/global-point.ts","../src/complex/global-config.ts","../src/complex/modules-factory.ts","../src/complex/pub-sub.ts"],"sourcesContent":["export interface Counter<TValue = number> {\n (): TValue;\n counter: number;\n value: TValue;\n increment(): TValue;\n decrement(): TValue;\n reset(): void;\n}\n\n/**\n * @deprecated use {`Counter`}. Will be removed in next major release\n */\nexport interface CounterFn<TValue = number> extends Counter<TValue> {}\n\n/**\n * Creates a callable counter object with increment, decrement and reset helpers.\n *\n * The returned function increments the internal numeric counter when called and\n * exposes both the raw counter value and an optionally transformed `value`.\n *\n * @template TValue Public value type returned by the counter.\n * @param processValue Optional mapper that transforms the numeric counter value.\n * @param initial Initial numeric counter value.\n * @returns Callable counter with state and control methods.\n *\n * @example\n * ```ts\n * const counter = createCounter();\n * counter.increment(); // 1\n * ```\n *\n * @example\n * ```ts\n * const idCounter = createCounter((value) => `id-${value}`, 10);\n * idCounter(); // 'id-11'\n * ```\n */\nexport const createCounter = <TValue = number>(\n processValue?: (value: number) => TValue,\n initial: number = 0,\n): Counter<TValue> => {\n const update = (counter: number) => {\n fn.value = processValue?.(counter) ?? (counter as TValue);\n return fn.value;\n };\n\n const increment = () => update(++fn.counter);\n const decrement = () => update(--fn.counter);\n\n const fn: Counter<TValue> = increment as any;\n\n fn.increment = increment;\n fn.decrement = decrement;\n\n fn.reset = () => {\n fn.counter = initial;\n fn.value = processValue?.(initial) ?? (initial as TValue);\n };\n\n fn.reset();\n\n return fn as Counter<TValue>;\n};\n","import type { AnyObject } from 'yummies/types';\n\nexport interface GlobalPoint<TValue> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n}\n\n/**\n * Creates a simple storage point that can live either in `globalThis` under a\n * provided key or in a local closure when no key is given.\n *\n * @template TValue Stored value type.\n * @param accessSymbol Optional global property name used for storage.\n * @returns Getter/setter API for the stored value.\n *\n * @example\n * ```ts\n * const point = createGlobalPoint<number>();\n * point.set(10);\n * ```\n *\n * @example\n * ```ts\n * const point = createGlobalPoint<string>('__token__');\n * point.get();\n * ```\n */\nexport const createGlobalPoint = <TValue>(\n accessSymbol?: keyof any,\n): GlobalPoint<TValue> => {\n if (accessSymbol == null) {\n let storedValue: TValue | undefined;\n\n return {\n get: (): TValue => storedValue!,\n unset: () => {\n storedValue = undefined;\n },\n set: (value: TValue): TValue => {\n storedValue = value;\n return value;\n },\n };\n }\n\n const _globalThis = globalThis as AnyObject;\n\n return {\n get: (): TValue => _globalThis[accessSymbol],\n unset: () => {\n delete _globalThis[accessSymbol];\n },\n set: (value: TValue): TValue => {\n _globalThis[accessSymbol] = value;\n return value;\n },\n };\n};\n","import type { AnyObject, Maybe } from 'yummies/types';\nimport { createGlobalPoint } from './global-point.js';\n\n/**\n * Creates or reuses a globally accessible config object.\n *\n * The config is stored in a global point identified by `accessSymbol`, or in a\n * local closure when no symbol is provided.\n *\n * @template T Config object type.\n * @param defaultValue Default value used when no config has been created yet.\n * @param accessSymbol Optional global key used to store the config.\n * @returns Existing or newly initialized global config object.\n *\n * @example\n * ```ts\n * const config = createGlobalConfig({ locale: 'en' }, '__app_config__');\n * ```\n *\n * @example\n * ```ts\n * const config = createGlobalConfig({ debug: false });\n * config.debug;\n * ```\n */\nexport const createGlobalConfig = <T extends AnyObject>(\n defaultValue: T,\n accessSymbol?: keyof any,\n): T => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n return globalPoint.get() || globalPoint.set(defaultValue);\n};\n\nexport interface GlobalDynamicConfig<TValue extends AnyObject> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n update(value: Partial<TValue>): void;\n}\n\n/**\n * Creates a mutable global config manager whose value is produced and updated\n * through a custom processor function.\n *\n * @template T Config object type.\n * @param processFn Function that builds the next config state from a partial change and current value.\n * @param accessSymbol Optional global key used to store the config.\n * @returns API for reading, replacing, resetting and partially updating the config.\n *\n * @example\n * ```ts\n * const config = createGlobalDynamicConfig(\n * (change, current) => ({ theme: 'light', ...current, ...change }),\n * '__theme__',\n * );\n * ```\n *\n * @example\n * ```ts\n * const config = createGlobalDynamicConfig((change, current) => ({ ...current, ...change }));\n * config.update({ locale: 'ru' });\n * ```\n */\nexport const createGlobalDynamicConfig = <T extends AnyObject>(\n processFn: (change: Maybe<Partial<T>>, current: Maybe<T>) => T,\n accessSymbol?: keyof any,\n): GlobalDynamicConfig<T> => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n\n const getValue = () => {\n return globalPoint.get() ?? globalPoint.set(processFn(null, null))!;\n };\n\n return {\n get: getValue,\n set: globalPoint.set,\n unset: globalPoint.unset,\n update: (value: Partial<T>) => {\n const currentValue = getValue();\n Object.assign(currentValue, processFn(value, currentValue));\n },\n };\n};\n","import type { AnyObject, Class, EmptyObject, IsPartial } from 'yummies/types';\n\ntype ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {\n factory<TInstance, TDeps extends TPredefinedDeps>(\n moduleClass: Class<TInstance, [TDeps]>,\n deps: TDeps,\n ): TInstance;\n} & (TPredefinedDeps extends EmptyObject\n ? { deps?: TPredefinedDeps }\n : { deps: TPredefinedDeps });\n\n/**\n * Universal factory for creating class instances with predefined and per-call\n * dependencies.\n *\n * Works with classes whose constructor accepts a single dependency object.\n *\n * @template TPredefinedDeps Dependency shape that is always injected by the factory.\n *\n * @example\n * ```\n * const factory = new ModulesFactory({\n * factory: (MyClass, deps) => new MyClass(deps),\n * deps: { someDependency: new Dependency() }\n * });\n *\n * const instance = factory.create(MyClass, { extraDependency: new ExtraDependency() });\n * ```\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * });\n * ```\n *\n * @example\n * ```ts\n * const service = factory.create(UserService, { api });\n * ```\n */\nexport class ModulesFactory<TPredefinedDeps extends AnyObject = EmptyObject> {\n /**\n * Creates a new module factory.\n *\n * @param config Factory strategy and predefined dependencies.\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * });\n * ```\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * deps: { api },\n * });\n * ```\n */\n constructor(private config: ModuleLoaderConfig<TPredefinedDeps>) {}\n\n /**\n * Creates an instance of the provided class by merging predefined and\n * per-call dependencies.\n *\n * @template TInstance Instance type produced by the constructor.\n * @template TDeps Full dependency object expected by the constructor.\n * @param Constructor Class constructor receiving a single dependency object.\n * @param args Additional dependencies merged over predefined ones.\n * @returns Created class instance.\n *\n * @example\n * ```ts\n * const service = factory.create(UserService, { logger });\n * ```\n *\n * @example\n * ```ts\n * const store = factory.create(UserStore);\n * ```\n */\n create<TInstance, TDeps extends TPredefinedDeps = TPredefinedDeps>(\n Constructor: Class<TInstance, [TDeps]>,\n ...args: IsPartial<Omit<TDeps, keyof TPredefinedDeps>> extends true\n ? [extraDeps?: Omit<TDeps, keyof TPredefinedDeps>]\n : [extraDeps: Omit<TDeps, keyof TPredefinedDeps>]\n ) {\n return this.config.factory(Constructor, {\n ...this.config.deps!,\n ...args[0],\n } as any);\n }\n}\n","export type SubFn<PubArgs extends any[] = any[]> = (...args: PubArgs) => void;\n\n/**\n * The Publish-Subscribe pattern, which allows objects to interact with each other\n * through an event system. Subscribers can subscribe to events and receive notifications\n * when these events occur. The last published data can be accessed through the `data` property.\n */\nexport interface PubSub<PubArgs extends any[] = any[]> {\n (...args: PubArgs): void;\n\n /**\n * Last published arguments\n */\n lastPub: PubArgs | undefined;\n\n /**\n * An array of subscriber functions (sub) that will be called\n * when an event is published. Each subscriber must match the type SubFn,\n * taking the arguments that will be passed to it when the publisher calls pub.\n */\n subs: SubFn<PubArgs>[];\n\n /**\n * A function to unsubscribe from events. When a subscriber function (sub) is passed,\n * it will be removed from the `subs` array, and will no longer receive notifications.\n */\n unsub(sub: SubFn<PubArgs>): void;\n /**\n * A function to subscribe to events. When a subscriber function (sub) is passed,\n * it will be added to the `subs` array, and will receive notifications when the publisher calls pub.\n * Returns a function that can be used to unsubscribe from events.\n */\n sub(sub: SubFn<PubArgs>): VoidFunction;\n}\n\n/**\n * Creates a simple publish-subscribe dispatcher that stores the last published\n * arguments and allows subscription management.\n *\n * @template PubArgs Argument tuple delivered to subscribers.\n * @returns Callable publisher with subscribe and unsubscribe helpers.\n *\n * @example\n * ```ts\n * const pub = createPubSub<[string]>();\n * pub('ready');\n * ```\n *\n * @example\n * ```ts\n * const pub = createPubSub<[number]>();\n * const unsub = pub.sub((value) => console.log(value));\n * ```\n */\nexport const createPubSub = <PubArgs extends any[] = any[]>() => {\n const pubSub = ((...args: PubArgs) => {\n pubSub.lastPub = args;\n pubSub.subs.forEach((sub) => {\n sub(...args);\n });\n }) as PubSub<PubArgs>;\n pubSub.lastPub = undefined;\n\n pubSub.subs = [];\n\n pubSub.unsub = (sub: SubFn<PubArgs>) => {\n pubSub.subs = pubSub.subs.filter((it) => it !== sub);\n };\n pubSub.sub = (sub: SubFn<PubArgs>) => {\n pubSub.subs.push(sub);\n return () => pubSub.unsub(sub);\n };\n\n return pubSub;\n};\n"],"names":[],"mappings":";;AAqCO,MAAM,gBAAgB,CAC3B,cACA,UAAkB,MACE;AACpB,QAAM,SAAS,CAAC,YAAoB;AAClC,OAAG,QAAQ,eAAe,OAAO,KAAM;AACv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c,UAAU,OAAO,YAAY,CAAC;AAAA,IAC5D;AAAA,EAAA;AAEJ;ACzCO,MAAM,eAAgE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB3E,YAAoB,QAA6C;AAA7C,SAAA,SAAA;AAAA,EAA8C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBlE,OACE,gBACG,MAGH;AACA,WAAO,KAAK,OAAO,QAAQ,aAAa;AAAA,MACtC,GAAG,KAAK,OAAO;AAAA,MACf,GAAG,KAAK,CAAC;AAAA,IAAA,CACH;AAAA,EACV;AACF;ACzCO,MAAM,eAAe,MAAqC;AAC/D,QAAM,UAAU,IAAI,SAAkB;AACpC,WAAO,UAAU;AACjB,WAAO,KAAK,QAAQ,CAAC,QAAQ;AAC3B,UAAI,GAAG,IAAI;AAAA,IACb,CAAC;AAAA,EACH;AACA,SAAO,UAAU;AAEjB,SAAO,OAAO,CAAA;AAEd,SAAO,QAAQ,CAAC,QAAwB;AACtC,WAAO,OAAO,OAAO,KAAK,OAAO,CAAC,OAAO,OAAO,GAAG;AAAA,EACrD;AACA,SAAO,MAAM,CAAC,QAAwB;AACpC,WAAO,KAAK,KAAK,GAAG;AACpB,WAAO,MAAM,OAAO,MAAM,GAAG;AAAA,EAC/B;AAEA,SAAO;AACT;;;;;;"}
|
package/complex.d.ts
CHANGED
|
@@ -13,10 +13,52 @@ interface Counter<TValue = number> {
|
|
|
13
13
|
*/
|
|
14
14
|
interface CounterFn<TValue = number> extends Counter<TValue> {
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates a callable counter object with increment, decrement and reset helpers.
|
|
18
|
+
*
|
|
19
|
+
* The returned function increments the internal numeric counter when called and
|
|
20
|
+
* exposes both the raw counter value and an optionally transformed `value`.
|
|
21
|
+
*
|
|
22
|
+
* @template TValue Public value type returned by the counter.
|
|
23
|
+
* @param processValue Optional mapper that transforms the numeric counter value.
|
|
24
|
+
* @param initial Initial numeric counter value.
|
|
25
|
+
* @returns Callable counter with state and control methods.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const counter = createCounter();
|
|
30
|
+
* counter.increment(); // 1
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* const idCounter = createCounter((value) => `id-${value}`, 10);
|
|
36
|
+
* idCounter(); // 'id-11'
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
16
39
|
declare const createCounter: <TValue = number>(processValue?: (value: number) => TValue, initial?: number) => Counter<TValue>;
|
|
17
40
|
|
|
18
41
|
/**
|
|
19
|
-
*
|
|
42
|
+
* Creates or reuses a globally accessible config object.
|
|
43
|
+
*
|
|
44
|
+
* The config is stored in a global point identified by `accessSymbol`, or in a
|
|
45
|
+
* local closure when no symbol is provided.
|
|
46
|
+
*
|
|
47
|
+
* @template T Config object type.
|
|
48
|
+
* @param defaultValue Default value used when no config has been created yet.
|
|
49
|
+
* @param accessSymbol Optional global key used to store the config.
|
|
50
|
+
* @returns Existing or newly initialized global config object.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* const config = createGlobalConfig({ locale: 'en' }, '__app_config__');
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* const config = createGlobalConfig({ debug: false });
|
|
60
|
+
* config.debug;
|
|
61
|
+
* ```
|
|
20
62
|
*/
|
|
21
63
|
declare const createGlobalConfig: <T extends AnyObject>(defaultValue: T, accessSymbol?: keyof any) => T;
|
|
22
64
|
interface GlobalDynamicConfig<TValue extends AnyObject> {
|
|
@@ -25,6 +67,29 @@ interface GlobalDynamicConfig<TValue extends AnyObject> {
|
|
|
25
67
|
unset(): void;
|
|
26
68
|
update(value: Partial<TValue>): void;
|
|
27
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates a mutable global config manager whose value is produced and updated
|
|
72
|
+
* through a custom processor function.
|
|
73
|
+
*
|
|
74
|
+
* @template T Config object type.
|
|
75
|
+
* @param processFn Function that builds the next config state from a partial change and current value.
|
|
76
|
+
* @param accessSymbol Optional global key used to store the config.
|
|
77
|
+
* @returns API for reading, replacing, resetting and partially updating the config.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const config = createGlobalDynamicConfig(
|
|
82
|
+
* (change, current) => ({ theme: 'light', ...current, ...change }),
|
|
83
|
+
* '__theme__',
|
|
84
|
+
* );
|
|
85
|
+
* ```
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* const config = createGlobalDynamicConfig((change, current) => ({ ...current, ...change }));
|
|
90
|
+
* config.update({ locale: 'ru' });
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
28
93
|
declare const createGlobalDynamicConfig: <T extends AnyObject>(processFn: (change: Maybe<Partial<T>>, current: Maybe<T>) => T, accessSymbol?: keyof any) => GlobalDynamicConfig<T>;
|
|
29
94
|
|
|
30
95
|
type ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {
|
|
@@ -35,12 +100,12 @@ type ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {
|
|
|
35
100
|
deps: TPredefinedDeps;
|
|
36
101
|
});
|
|
37
102
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
103
|
+
* Universal factory for creating class instances with predefined and per-call
|
|
104
|
+
* dependencies.
|
|
40
105
|
*
|
|
41
|
-
*
|
|
106
|
+
* Works with classes whose constructor accepts a single dependency object.
|
|
42
107
|
*
|
|
43
|
-
* @template TPredefinedDeps
|
|
108
|
+
* @template TPredefinedDeps Dependency shape that is always injected by the factory.
|
|
44
109
|
*
|
|
45
110
|
* @example
|
|
46
111
|
* ```
|
|
@@ -51,25 +116,61 @@ type ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {
|
|
|
51
116
|
*
|
|
52
117
|
* const instance = factory.create(MyClass, { extraDependency: new ExtraDependency() });
|
|
53
118
|
* ```
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* const factory = new ModulesFactory({
|
|
123
|
+
* factory: (Module, deps) => new Module(deps),
|
|
124
|
+
* });
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* ```ts
|
|
129
|
+
* const service = factory.create(UserService, { api });
|
|
130
|
+
* ```
|
|
54
131
|
*/
|
|
55
132
|
declare class ModulesFactory<TPredefinedDeps extends AnyObject = EmptyObject> {
|
|
56
133
|
private config;
|
|
57
134
|
/**
|
|
58
|
-
*
|
|
135
|
+
* Creates a new module factory.
|
|
59
136
|
*
|
|
60
|
-
* @param config
|
|
137
|
+
* @param config Factory strategy and predefined dependencies.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* const factory = new ModulesFactory({
|
|
142
|
+
* factory: (Module, deps) => new Module(deps),
|
|
143
|
+
* });
|
|
144
|
+
* ```
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```ts
|
|
148
|
+
* const factory = new ModulesFactory({
|
|
149
|
+
* factory: (Module, deps) => new Module(deps),
|
|
150
|
+
* deps: { api },
|
|
151
|
+
* });
|
|
152
|
+
* ```
|
|
61
153
|
*/
|
|
62
154
|
constructor(config: ModuleLoaderConfig<TPredefinedDeps>);
|
|
63
155
|
/**
|
|
64
|
-
*
|
|
156
|
+
* Creates an instance of the provided class by merging predefined and
|
|
157
|
+
* per-call dependencies.
|
|
65
158
|
*
|
|
66
|
-
* @template TInstance
|
|
67
|
-
* @template TDeps
|
|
159
|
+
* @template TInstance Instance type produced by the constructor.
|
|
160
|
+
* @template TDeps Full dependency object expected by the constructor.
|
|
161
|
+
* @param Constructor Class constructor receiving a single dependency object.
|
|
162
|
+
* @param args Additional dependencies merged over predefined ones.
|
|
163
|
+
* @returns Created class instance.
|
|
68
164
|
*
|
|
69
|
-
* @
|
|
70
|
-
*
|
|
165
|
+
* @example
|
|
166
|
+
* ```ts
|
|
167
|
+
* const service = factory.create(UserService, { logger });
|
|
168
|
+
* ```
|
|
71
169
|
*
|
|
72
|
-
* @
|
|
170
|
+
* @example
|
|
171
|
+
* ```ts
|
|
172
|
+
* const store = factory.create(UserStore);
|
|
173
|
+
* ```
|
|
73
174
|
*/
|
|
74
175
|
create<TInstance, TDeps extends TPredefinedDeps = TPredefinedDeps>(Constructor: Class<TInstance, [TDeps]>, ...args: IsPartial<Omit<TDeps, keyof TPredefinedDeps>> extends true ? [extraDeps?: Omit<TDeps, keyof TPredefinedDeps>] : [extraDeps: Omit<TDeps, keyof TPredefinedDeps>]): TInstance;
|
|
75
176
|
}
|
|
@@ -104,6 +205,25 @@ interface PubSub<PubArgs extends any[] = any[]> {
|
|
|
104
205
|
*/
|
|
105
206
|
sub(sub: SubFn<PubArgs>): VoidFunction;
|
|
106
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Creates a simple publish-subscribe dispatcher that stores the last published
|
|
210
|
+
* arguments and allows subscription management.
|
|
211
|
+
*
|
|
212
|
+
* @template PubArgs Argument tuple delivered to subscribers.
|
|
213
|
+
* @returns Callable publisher with subscribe and unsubscribe helpers.
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```ts
|
|
217
|
+
* const pub = createPubSub<[string]>();
|
|
218
|
+
* pub('ready');
|
|
219
|
+
* ```
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* const pub = createPubSub<[number]>();
|
|
224
|
+
* const unsub = pub.sub((value) => console.log(value));
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
107
227
|
declare const createPubSub: <PubArgs extends any[] = any[]>() => PubSub<PubArgs>;
|
|
108
228
|
|
|
109
229
|
export { ModulesFactory, createCounter, createGlobalConfig, createGlobalDynamicConfig, createPubSub };
|
package/complex.js
CHANGED
|
@@ -62,23 +62,47 @@ const createGlobalDynamicConfig = (processFn, accessSymbol) => {
|
|
|
62
62
|
};
|
|
63
63
|
class ModulesFactory {
|
|
64
64
|
/**
|
|
65
|
-
*
|
|
65
|
+
* Creates a new module factory.
|
|
66
66
|
*
|
|
67
|
-
* @param config
|
|
67
|
+
* @param config Factory strategy and predefined dependencies.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const factory = new ModulesFactory({
|
|
72
|
+
* factory: (Module, deps) => new Module(deps),
|
|
73
|
+
* });
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* const factory = new ModulesFactory({
|
|
79
|
+
* factory: (Module, deps) => new Module(deps),
|
|
80
|
+
* deps: { api },
|
|
81
|
+
* });
|
|
82
|
+
* ```
|
|
68
83
|
*/
|
|
69
84
|
constructor(config) {
|
|
70
85
|
this.config = config;
|
|
71
86
|
}
|
|
72
87
|
/**
|
|
73
|
-
*
|
|
88
|
+
* Creates an instance of the provided class by merging predefined and
|
|
89
|
+
* per-call dependencies.
|
|
74
90
|
*
|
|
75
|
-
* @template TInstance
|
|
76
|
-
* @template TDeps
|
|
91
|
+
* @template TInstance Instance type produced by the constructor.
|
|
92
|
+
* @template TDeps Full dependency object expected by the constructor.
|
|
93
|
+
* @param Constructor Class constructor receiving a single dependency object.
|
|
94
|
+
* @param args Additional dependencies merged over predefined ones.
|
|
95
|
+
* @returns Created class instance.
|
|
77
96
|
*
|
|
78
|
-
* @
|
|
79
|
-
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const service = factory.create(UserService, { logger });
|
|
100
|
+
* ```
|
|
80
101
|
*
|
|
81
|
-
* @
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* const store = factory.create(UserStore);
|
|
105
|
+
* ```
|
|
82
106
|
*/
|
|
83
107
|
create(Constructor, ...args) {
|
|
84
108
|
return this.config.factory(Constructor, {
|
package/complex.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"complex.js","sources":["../src/complex/counter.ts","../src/complex/global-point.ts","../src/complex/global-config.ts","../src/complex/modules-factory.ts","../src/complex/pub-sub.ts"],"sourcesContent":["export interface Counter<TValue = number> {\n (): TValue;\n counter: number;\n value: TValue;\n increment(): TValue;\n decrement(): TValue;\n reset(): void;\n}\n\n/**\n * @deprecated use {`Counter`}. Will be removed in next major release\n */\nexport interface CounterFn<TValue = number> extends Counter<TValue> {}\n\nexport const createCounter = <TValue = number>(\n processValue?: (value: number) => TValue,\n initial: number = 0,\n): Counter<TValue> => {\n const update = (counter: number) => {\n fn.value = processValue?.(counter) ?? (counter as TValue);\n return fn.value;\n };\n\n const increment = () => update(++fn.counter);\n const decrement = () => update(--fn.counter);\n\n const fn: Counter<TValue> = increment as any;\n\n fn.increment = increment;\n fn.decrement = decrement;\n\n fn.reset = () => {\n fn.counter = initial;\n fn.value = processValue?.(initial) ?? (initial as TValue);\n };\n\n fn.reset();\n\n return fn as Counter<TValue>;\n};\n","import type { AnyObject } from 'yummies/types';\n\nexport interface GlobalPoint<TValue> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n}\n\nexport const createGlobalPoint = <TValue>(\n accessSymbol?: keyof any,\n): GlobalPoint<TValue> => {\n if (accessSymbol == null) {\n let storedValue: TValue | undefined;\n\n return {\n get: (): TValue => storedValue!,\n unset: () => {\n storedValue = undefined;\n },\n set: (value: TValue): TValue => {\n storedValue = value;\n return value;\n },\n };\n }\n\n const _globalThis = globalThis as AnyObject;\n\n return {\n get: (): TValue => _globalThis[accessSymbol],\n unset: () => {\n delete _globalThis[accessSymbol];\n },\n set: (value: TValue): TValue => {\n _globalThis[accessSymbol] = value;\n return value;\n },\n };\n};\n","import type { AnyObject, Maybe } from 'yummies/types';\nimport { createGlobalPoint } from './global-point.js';\n\n/**\n * Создает глобальный конфиг, который может быть доступен в любой точке в коде\n */\nexport const createGlobalConfig = <T extends AnyObject>(\n defaultValue: T,\n accessSymbol?: keyof any,\n): T => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n return globalPoint.get() || globalPoint.set(defaultValue);\n};\n\nexport interface GlobalDynamicConfig<TValue extends AnyObject> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n update(value: Partial<TValue>): void;\n}\n\nexport const createGlobalDynamicConfig = <T extends AnyObject>(\n processFn: (change: Maybe<Partial<T>>, current: Maybe<T>) => T,\n accessSymbol?: keyof any,\n): GlobalDynamicConfig<T> => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n\n const getValue = () => {\n return globalPoint.get() ?? globalPoint.set(processFn(null, null))!;\n };\n\n return {\n get: getValue,\n set: globalPoint.set,\n unset: globalPoint.unset,\n update: (value: Partial<T>) => {\n const currentValue = getValue();\n Object.assign(currentValue, processFn(value, currentValue));\n },\n };\n};\n","import type { AnyObject, Class, EmptyObject, IsPartial } from 'yummies/types';\n\ntype ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {\n factory<TInstance, TDeps extends TPredefinedDeps>(\n moduleClass: Class<TInstance, [TDeps]>,\n deps: TDeps,\n ): TInstance;\n} & (TPredefinedDeps extends EmptyObject\n ? { deps?: TPredefinedDeps }\n : { deps: TPredefinedDeps });\n\n/**\n * Класс `ModulesFactory` является универсальной фабрикой для создания экземпляров указанного класса с зависимостями.\n * Он использует объект конфигурации для определения того, как эти экземпляры создаются.\n *\n * Важное примечание - эта сущность работает только с классами конструктор которых имеет один параметр\n *\n * @template TPredefinedDeps - Тип, расширяющий `AnyObject`, представляющий предопределенные зависимости, которые использует фабрика.\n *\n * @example\n * ```\n * const factory = new ModulesFactory({\n * factory: (MyClass, deps) => new MyClass(deps),\n * deps: { someDependency: new Dependency() }\n * });\n *\n * const instance = factory.create(MyClass, { extraDependency: new ExtraDependency() });\n * ```\n */\nexport class ModulesFactory<TPredefinedDeps extends AnyObject = EmptyObject> {\n /**\n * Создает новый экземпляр `ModulesFactory`.\n *\n * @param config - Объект конфигурации для фабрики, включающий функцию фабрики и необязательные зависимости.\n */\n constructor(private config: ModuleLoaderConfig<TPredefinedDeps>) {}\n\n /**\n * Создает экземпляр указанного класса, внедряя необходимые зависимости.\n *\n * @template TInstance - Тип создаваемого экземпляра.\n * @template TDeps - Тип зависимостей, необходимых для экземпляра.\n *\n * @param Constructor - Конструктор класса для создаваемого экземпляра.\n * @param args - Необязательные дополнительные зависимости для объединения с предопределенными зависимостями.\n *\n * @returns Экземпляр указанного класса с внедренными зависимостями.\n */\n create<TInstance, TDeps extends TPredefinedDeps = TPredefinedDeps>(\n Constructor: Class<TInstance, [TDeps]>,\n ...args: IsPartial<Omit<TDeps, keyof TPredefinedDeps>> extends true\n ? [extraDeps?: Omit<TDeps, keyof TPredefinedDeps>]\n : [extraDeps: Omit<TDeps, keyof TPredefinedDeps>]\n ) {\n return this.config.factory(Constructor, {\n ...this.config.deps!,\n ...args[0],\n } as any);\n }\n}\n","export type SubFn<PubArgs extends any[] = any[]> = (...args: PubArgs) => void;\n\n/**\n * The Publish-Subscribe pattern, which allows objects to interact with each other\n * through an event system. Subscribers can subscribe to events and receive notifications\n * when these events occur. The last published data can be accessed through the `data` property.\n */\nexport interface PubSub<PubArgs extends any[] = any[]> {\n (...args: PubArgs): void;\n\n /**\n * Last published arguments\n */\n lastPub: PubArgs | undefined;\n\n /**\n * An array of subscriber functions (sub) that will be called\n * when an event is published. Each subscriber must match the type SubFn,\n * taking the arguments that will be passed to it when the publisher calls pub.\n */\n subs: SubFn<PubArgs>[];\n\n /**\n * A function to unsubscribe from events. When a subscriber function (sub) is passed,\n * it will be removed from the `subs` array, and will no longer receive notifications.\n */\n unsub(sub: SubFn<PubArgs>): void;\n /**\n * A function to subscribe to events. When a subscriber function (sub) is passed,\n * it will be added to the `subs` array, and will receive notifications when the publisher calls pub.\n * Returns a function that can be used to unsubscribe from events.\n */\n sub(sub: SubFn<PubArgs>): VoidFunction;\n}\n\nexport const createPubSub = <PubArgs extends any[] = any[]>() => {\n const pubSub = ((...args: PubArgs) => {\n pubSub.lastPub = args;\n pubSub.subs.forEach((sub) => {\n sub(...args);\n });\n }) as PubSub<PubArgs>;\n pubSub.lastPub = undefined;\n\n pubSub.subs = [];\n\n pubSub.unsub = (sub: SubFn<PubArgs>) => {\n pubSub.subs = pubSub.subs.filter((it) => it !== sub);\n };\n pubSub.sub = (sub: SubFn<PubArgs>) => {\n pubSub.subs.push(sub);\n return () => pubSub.unsub(sub);\n };\n\n return pubSub;\n};\n"],"names":[],"mappings":"AAcO,MAAM,gBAAgB,CAC3B,cACA,UAAkB,MACE;AACpB,QAAM,SAAS,CAAC,YAAoB;AAClC,OAAG,QAAQ,eAAe,OAAO,KAAM;AACvC,WAAO,GAAG;AAAA,EACZ;AAEA,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAC3C,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAE3C,QAAM,KAAsB;AAE5B,KAAG,YAAY;AACf,KAAG,YAAY;AAEf,KAAG,QAAQ,MAAM;AACf,OAAG,UAAU;AACb,OAAG,QAAQ,eAAe,OAAO,KAAM;AAAA,EACzC;AAEA,KAAG,MAAA;AAEH,SAAO;AACT;AC/BO,MAAM,oBAAoB,CAC/B,iBACwB;AACxB,MAAI,gBAAgB,MAAM;AACxB,QAAI;AAEJ,WAAO;AAAA,MACL,KAAK,MAAc;AAAA,MACnB,OAAO,MAAM;AACX,sBAAc;AAAA,MAChB;AAAA,MACA,KAAK,CAAC,UAA0B;AAC9B,sBAAc;AACd,eAAO;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AAEA,Q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AAO,UAAU;AAEjB,SAAO,OAAO,CAAA;AAEd,SAAO,QAAQ,CAAC,QAAwB;AACtC,WAAO,OAAO,OAAO,KAAK,OAAO,CAAC,OAAO,OAAO,GAAG;AAAA,EACrD;AACA,SAAO,MAAM,CAAC,QAAwB;AACpC,WAAO,KAAK,KAAK,GAAG;AACpB,WAAO,MAAM,OAAO,MAAM,GAAG;AAAA,EAC/B;AAEA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"complex.js","sources":["../src/complex/counter.ts","../src/complex/global-point.ts","../src/complex/global-config.ts","../src/complex/modules-factory.ts","../src/complex/pub-sub.ts"],"sourcesContent":["export interface Counter<TValue = number> {\n (): TValue;\n counter: number;\n value: TValue;\n increment(): TValue;\n decrement(): TValue;\n reset(): void;\n}\n\n/**\n * @deprecated use {`Counter`}. Will be removed in next major release\n */\nexport interface CounterFn<TValue = number> extends Counter<TValue> {}\n\n/**\n * Creates a callable counter object with increment, decrement and reset helpers.\n *\n * The returned function increments the internal numeric counter when called and\n * exposes both the raw counter value and an optionally transformed `value`.\n *\n * @template TValue Public value type returned by the counter.\n * @param processValue Optional mapper that transforms the numeric counter value.\n * @param initial Initial numeric counter value.\n * @returns Callable counter with state and control methods.\n *\n * @example\n * ```ts\n * const counter = createCounter();\n * counter.increment(); // 1\n * ```\n *\n * @example\n * ```ts\n * const idCounter = createCounter((value) => `id-${value}`, 10);\n * idCounter(); // 'id-11'\n * ```\n */\nexport const createCounter = <TValue = number>(\n processValue?: (value: number) => TValue,\n initial: number = 0,\n): Counter<TValue> => {\n const update = (counter: number) => {\n fn.value = processValue?.(counter) ?? (counter as TValue);\n return fn.value;\n };\n\n const increment = () => update(++fn.counter);\n const decrement = () => update(--fn.counter);\n\n const fn: Counter<TValue> = increment as any;\n\n fn.increment = increment;\n fn.decrement = decrement;\n\n fn.reset = () => {\n fn.counter = initial;\n fn.value = processValue?.(initial) ?? (initial as TValue);\n };\n\n fn.reset();\n\n return fn as Counter<TValue>;\n};\n","import type { AnyObject } from 'yummies/types';\n\nexport interface GlobalPoint<TValue> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n}\n\n/**\n * Creates a simple storage point that can live either in `globalThis` under a\n * provided key or in a local closure when no key is given.\n *\n * @template TValue Stored value type.\n * @param accessSymbol Optional global property name used for storage.\n * @returns Getter/setter API for the stored value.\n *\n * @example\n * ```ts\n * const point = createGlobalPoint<number>();\n * point.set(10);\n * ```\n *\n * @example\n * ```ts\n * const point = createGlobalPoint<string>('__token__');\n * point.get();\n * ```\n */\nexport const createGlobalPoint = <TValue>(\n accessSymbol?: keyof any,\n): GlobalPoint<TValue> => {\n if (accessSymbol == null) {\n let storedValue: TValue | undefined;\n\n return {\n get: (): TValue => storedValue!,\n unset: () => {\n storedValue = undefined;\n },\n set: (value: TValue): TValue => {\n storedValue = value;\n return value;\n },\n };\n }\n\n const _globalThis = globalThis as AnyObject;\n\n return {\n get: (): TValue => _globalThis[accessSymbol],\n unset: () => {\n delete _globalThis[accessSymbol];\n },\n set: (value: TValue): TValue => {\n _globalThis[accessSymbol] = value;\n return value;\n },\n };\n};\n","import type { AnyObject, Maybe } from 'yummies/types';\nimport { createGlobalPoint } from './global-point.js';\n\n/**\n * Creates or reuses a globally accessible config object.\n *\n * The config is stored in a global point identified by `accessSymbol`, or in a\n * local closure when no symbol is provided.\n *\n * @template T Config object type.\n * @param defaultValue Default value used when no config has been created yet.\n * @param accessSymbol Optional global key used to store the config.\n * @returns Existing or newly initialized global config object.\n *\n * @example\n * ```ts\n * const config = createGlobalConfig({ locale: 'en' }, '__app_config__');\n * ```\n *\n * @example\n * ```ts\n * const config = createGlobalConfig({ debug: false });\n * config.debug;\n * ```\n */\nexport const createGlobalConfig = <T extends AnyObject>(\n defaultValue: T,\n accessSymbol?: keyof any,\n): T => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n return globalPoint.get() || globalPoint.set(defaultValue);\n};\n\nexport interface GlobalDynamicConfig<TValue extends AnyObject> {\n get(): TValue;\n set(value: TValue): TValue;\n unset(): void;\n update(value: Partial<TValue>): void;\n}\n\n/**\n * Creates a mutable global config manager whose value is produced and updated\n * through a custom processor function.\n *\n * @template T Config object type.\n * @param processFn Function that builds the next config state from a partial change and current value.\n * @param accessSymbol Optional global key used to store the config.\n * @returns API for reading, replacing, resetting and partially updating the config.\n *\n * @example\n * ```ts\n * const config = createGlobalDynamicConfig(\n * (change, current) => ({ theme: 'light', ...current, ...change }),\n * '__theme__',\n * );\n * ```\n *\n * @example\n * ```ts\n * const config = createGlobalDynamicConfig((change, current) => ({ ...current, ...change }));\n * config.update({ locale: 'ru' });\n * ```\n */\nexport const createGlobalDynamicConfig = <T extends AnyObject>(\n processFn: (change: Maybe<Partial<T>>, current: Maybe<T>) => T,\n accessSymbol?: keyof any,\n): GlobalDynamicConfig<T> => {\n const globalPoint = createGlobalPoint<T>(accessSymbol);\n\n const getValue = () => {\n return globalPoint.get() ?? globalPoint.set(processFn(null, null))!;\n };\n\n return {\n get: getValue,\n set: globalPoint.set,\n unset: globalPoint.unset,\n update: (value: Partial<T>) => {\n const currentValue = getValue();\n Object.assign(currentValue, processFn(value, currentValue));\n },\n };\n};\n","import type { AnyObject, Class, EmptyObject, IsPartial } from 'yummies/types';\n\ntype ModuleLoaderConfig<TPredefinedDeps extends AnyObject = EmptyObject> = {\n factory<TInstance, TDeps extends TPredefinedDeps>(\n moduleClass: Class<TInstance, [TDeps]>,\n deps: TDeps,\n ): TInstance;\n} & (TPredefinedDeps extends EmptyObject\n ? { deps?: TPredefinedDeps }\n : { deps: TPredefinedDeps });\n\n/**\n * Universal factory for creating class instances with predefined and per-call\n * dependencies.\n *\n * Works with classes whose constructor accepts a single dependency object.\n *\n * @template TPredefinedDeps Dependency shape that is always injected by the factory.\n *\n * @example\n * ```\n * const factory = new ModulesFactory({\n * factory: (MyClass, deps) => new MyClass(deps),\n * deps: { someDependency: new Dependency() }\n * });\n *\n * const instance = factory.create(MyClass, { extraDependency: new ExtraDependency() });\n * ```\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * });\n * ```\n *\n * @example\n * ```ts\n * const service = factory.create(UserService, { api });\n * ```\n */\nexport class ModulesFactory<TPredefinedDeps extends AnyObject = EmptyObject> {\n /**\n * Creates a new module factory.\n *\n * @param config Factory strategy and predefined dependencies.\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * });\n * ```\n *\n * @example\n * ```ts\n * const factory = new ModulesFactory({\n * factory: (Module, deps) => new Module(deps),\n * deps: { api },\n * });\n * ```\n */\n constructor(private config: ModuleLoaderConfig<TPredefinedDeps>) {}\n\n /**\n * Creates an instance of the provided class by merging predefined and\n * per-call dependencies.\n *\n * @template TInstance Instance type produced by the constructor.\n * @template TDeps Full dependency object expected by the constructor.\n * @param Constructor Class constructor receiving a single dependency object.\n * @param args Additional dependencies merged over predefined ones.\n * @returns Created class instance.\n *\n * @example\n * ```ts\n * const service = factory.create(UserService, { logger });\n * ```\n *\n * @example\n * ```ts\n * const store = factory.create(UserStore);\n * ```\n */\n create<TInstance, TDeps extends TPredefinedDeps = TPredefinedDeps>(\n Constructor: Class<TInstance, [TDeps]>,\n ...args: IsPartial<Omit<TDeps, keyof TPredefinedDeps>> extends true\n ? [extraDeps?: Omit<TDeps, keyof TPredefinedDeps>]\n : [extraDeps: Omit<TDeps, keyof TPredefinedDeps>]\n ) {\n return this.config.factory(Constructor, {\n ...this.config.deps!,\n ...args[0],\n } as any);\n }\n}\n","export type SubFn<PubArgs extends any[] = any[]> = (...args: PubArgs) => void;\n\n/**\n * The Publish-Subscribe pattern, which allows objects to interact with each other\n * through an event system. Subscribers can subscribe to events and receive notifications\n * when these events occur. The last published data can be accessed through the `data` property.\n */\nexport interface PubSub<PubArgs extends any[] = any[]> {\n (...args: PubArgs): void;\n\n /**\n * Last published arguments\n */\n lastPub: PubArgs | undefined;\n\n /**\n * An array of subscriber functions (sub) that will be called\n * when an event is published. Each subscriber must match the type SubFn,\n * taking the arguments that will be passed to it when the publisher calls pub.\n */\n subs: SubFn<PubArgs>[];\n\n /**\n * A function to unsubscribe from events. When a subscriber function (sub) is passed,\n * it will be removed from the `subs` array, and will no longer receive notifications.\n */\n unsub(sub: SubFn<PubArgs>): void;\n /**\n * A function to subscribe to events. When a subscriber function (sub) is passed,\n * it will be added to the `subs` array, and will receive notifications when the publisher calls pub.\n * Returns a function that can be used to unsubscribe from events.\n */\n sub(sub: SubFn<PubArgs>): VoidFunction;\n}\n\n/**\n * Creates a simple publish-subscribe dispatcher that stores the last published\n * arguments and allows subscription management.\n *\n * @template PubArgs Argument tuple delivered to subscribers.\n * @returns Callable publisher with subscribe and unsubscribe helpers.\n *\n * @example\n * ```ts\n * const pub = createPubSub<[string]>();\n * pub('ready');\n * ```\n *\n * @example\n * ```ts\n * const pub = createPubSub<[number]>();\n * const unsub = pub.sub((value) => console.log(value));\n * ```\n */\nexport const createPubSub = <PubArgs extends any[] = any[]>() => {\n const pubSub = ((...args: PubArgs) => {\n pubSub.lastPub = args;\n pubSub.subs.forEach((sub) => {\n sub(...args);\n });\n }) as PubSub<PubArgs>;\n pubSub.lastPub = undefined;\n\n pubSub.subs = [];\n\n pubSub.unsub = (sub: SubFn<PubArgs>) => {\n pubSub.subs = pubSub.subs.filter((it) => it !== sub);\n };\n pubSub.sub = (sub: SubFn<PubArgs>) => {\n pubSub.subs.push(sub);\n return () => pubSub.unsub(sub);\n };\n\n return pubSub;\n};\n"],"names":[],"mappings":"AAqCO,MAAM,gBAAgB,CAC3B,cACA,UAAkB,MACE;AACpB,QAAM,SAAS,CAAC,YAAoB;AAClC,OAAG,QAAQ,eAAe,OAAO,KAAM;AACvC,WAAO,GAAG;AAAA,EACZ;AAEA,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAC3C,QAAM,YAAY,MAAM,OAAO,EAAE,GAAG,OAAO;AAE3C,QAAM,KAAsB;AAE5B,KAAG,YAAY;AACf,KAAG,Y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AAAA;AAAA;AAAA;AAAA;AAAA,EAqB3E,YAAoB,QAA6C;AAA7C,SAAA,SAAA;AAAA,EAA8C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBlE,OACE,gBACG,MAGH;AACA,WAAO,KAAK,OAAO,QAAQ,aAAa;AAAA,MACtC,GAAG,KAAK,OAAO;AAAA,MACf,GAAG,KAAK,CAAC;AAAA,IAAA,CACH;AAAA,EACV;AACF;ACzCO,MAAM,eAAe,MAAqC;AAC/D,QAAM,UAAU,IAAI,SAAkB;AACpC,WAAO,UAAU;AACjB,WAAO,KAAK,QAAQ,CAAC,QAAQ;AAC3B,UAAI,GAAG,IAAI;AAAA,IACb,CAAC;AAAA,EACH;AACA,SAAO,UAAU;AAEjB,SAAO,OAAO,CAAA;AAEd,SAAO,QAAQ,CAAC,QAAwB;AACtC,WAAO,OAAO,OAAO,KAAK,OAAO,CAAC,OAAO,OAAO,GAAG;AAAA,EACrD;AACA,SAAO,MAAM,CAAC,QAAwB;AACpC,WAAO,KAAK,KAAK,GAAG;AACpB,WAAO,MAAM,OAAO,MAAM,GAAG;AAAA,EAC/B;AAEA,SAAO;AACT;"}
|
package/css.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"css.cjs","sources":["../src/css.ts"],"sourcesContent":["import { cva as cvaLib } from 'class-variance-authority';\nimport clsx, { type ClassValue } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport type { Maybe } from 'yummies/types';\n\ntype ClassProp = {\n class?: ClassValue;\n className?: ClassValue;\n};\n\ntype StringToBoolean<T> = T extends 'true' | 'false' ? boolean : T;\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"css.cjs","sources":["../src/css.ts"],"sourcesContent":["import { cva as cvaLib } from 'class-variance-authority';\nimport clsx, { type ClassValue } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport type { Maybe } from 'yummies/types';\n\ntype ClassProp = {\n class?: ClassValue;\n className?: ClassValue;\n};\n\ntype StringToBoolean<T> = T extends 'true' | 'false' ? boolean : T;\n\n/**\n * Converts a pixel value to a `rem` string.\n */\nexport const toRem = (px: number, remValue = 16) => `${px / remValue}rem`;\n\n/**\n * `classNames`/`clsx` with `tailwind-merge` support.\n */\nexport const cx = (...args: Parameters<typeof clsx>) => twMerge(clsx(...args));\n\ntype ConfigSchema = Record<string, Record<string, ClassValue>>;\ntype ConfigVariants<T extends ConfigSchema> = {\n [Variant in keyof T]?: StringToBoolean<keyof T[Variant]> | null | undefined;\n};\ntype ConfigVariantsMulti<T extends ConfigSchema> = {\n [Variant in keyof T]?:\n | StringToBoolean<keyof T[Variant]>\n | StringToBoolean<keyof T[Variant]>[]\n | undefined;\n};\ntype Config<T> = T extends ConfigSchema\n ? {\n variants?: T;\n defaultVariants?: ConfigVariants<T>;\n compoundVariants?: (T extends ConfigSchema\n ? (ConfigVariants<T> | ConfigVariantsMulti<T>) & ClassProp\n : ClassProp)[];\n }\n : never;\n\ntype Props<T> = T extends ConfigSchema\n ? ConfigVariants<T> & ClassProp\n : ClassProp;\n\n/**\n * `Class Variance Authority` with `tailwind-merge` support.\n *\n * https://cva.style/docs\n */\nexport const cva = ((...args: any[]) => {\n const schema = cvaLib(...args);\n return (...inputArgs: any[]) => twMerge(schema(...inputArgs));\n}) as any as <T>(\n base?: ClassValue,\n config?: Config<T>,\n) => (props?: Props<T>) => string;\n\nexport type { VariantProps } from 'class-variance-authority';\nexport type { ClassValue } from 'clsx';\n\n/**\n * Load CSS file by providing `url`.\n *\n * **NOTE:** If `id` is provided, it will remove the existing link element with the same `id` before creating a new one.\n */\nexport const loadCssFile = (url: string, attrubutes?: Record<string, any>) =>\n new Promise((resolve, reject) => {\n let link: Maybe<HTMLLinkElement>;\n\n if (attrubutes?.id) {\n link = document.getElementById(attrubutes.id) as HTMLLinkElement | null;\n\n if (link) {\n link.remove();\n }\n }\n\n link = document.createElement('link');\n\n const handleLoad = () => {\n resolve(undefined);\n link!.removeEventListener('load', handleLoad);\n link!.removeEventListener('error', handleError);\n };\n\n const handleError = () => {\n reject(undefined);\n link!.removeEventListener('load', handleLoad);\n link!.removeEventListener('error', handleError);\n };\n\n link.addEventListener('load', handleLoad);\n link.addEventListener('error', handleError);\n\n link.setAttribute('href', url);\n\n if (!attrubutes?.rel) {\n link.setAttribute('rel', 'stylesheet');\n }\n\n Object.entries(attrubutes || {}).forEach(([key, value]) => {\n link.setAttribute(key, value);\n });\n\n document.head.appendChild(link);\n });\n"],"names":["twMerge","cvaLib"],"mappings":";;;;;AAeO,MAAM,QAAQ,CAAC,IAAY,WAAW,OAAO,GAAG,KAAK,QAAQ;AAK7D,MAAM,KAAK,IAAI,SAAkCA,cAAAA,QAAQ,KAAK,GAAG,IAAI,CAAC;AA+BtE,MAAM,OAAO,IAAI,SAAgB;AACtC,QAAM,SAASC,2BAAO,GAAG,IAAI;AAC7B,SAAO,IAAI,cAAqBD,cAAAA,QAAQ,OAAO,GAAG,SAAS,CAAC;AAC9D;AAaO,MAAM,cAAc,CAAC,KAAa,eACvC,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC/B,MAAI;AAEJ,MAAI,YAAY,IAAI;AAClB,WAAO,SAAS,eAAe,WAAW,EAAE;AAE5C,QAAI,MAAM;AACR,WAAK,OAAA;AAAA,IACP;AAAA,EACF;AAEA,SAAO,SAAS,cAAc,MAAM;AAEpC,QAAM,aAAa,MAAM;AACvB,YAAQ,MAAS;AACjB,SAAM,oBAAoB,QAAQ,UAAU;AAC5C,SAAM,oBAAoB,SAAS,WAAW;AAAA,EAChD;AAEA,QAAM,cAAc,MAAM;AACxB,WAAO,MAAS;AAChB,SAAM,oBAAoB,QAAQ,UAAU;AAC5C,SAAM,oBAAoB,SAAS,WAAW;AAAA,EAChD;AAEA,OAAK,iBAAiB,QAAQ,UAAU;AACxC,OAAK,iBAAiB,SAAS,WAAW;AAE1C,OAAK,aAAa,QAAQ,GAAG;AAE7B,MAAI,CAAC,YAAY,KAAK;AACpB,SAAK,aAAa,OAAO,YAAY;AAAA,EACvC;AAEA,SAAO,QAAQ,cAAc,CAAA,CAAE,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACzD,SAAK,aAAa,KAAK,KAAK;AAAA,EAC9B,CAAC;AAED,WAAS,KAAK,YAAY,IAAI;AAChC,CAAC;;;;;"}
|
package/css.d.ts
CHANGED
|
@@ -8,11 +8,11 @@ type ClassProp = {
|
|
|
8
8
|
};
|
|
9
9
|
type StringToBoolean<T> = T extends 'true' | 'false' ? boolean : T;
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* Converts a pixel value to a `rem` string.
|
|
12
12
|
*/
|
|
13
13
|
declare const toRem: (px: number, remValue?: number) => string;
|
|
14
14
|
/**
|
|
15
|
-
* classNames
|
|
15
|
+
* `classNames`/`clsx` with `tailwind-merge` support.
|
|
16
16
|
*/
|
|
17
17
|
declare const cx: (...args: Parameters<typeof clsx>) => string;
|
|
18
18
|
type ConfigSchema = Record<string, Record<string, ClassValue>>;
|
|
@@ -29,7 +29,7 @@ type Config<T> = T extends ConfigSchema ? {
|
|
|
29
29
|
} : never;
|
|
30
30
|
type Props<T> = T extends ConfigSchema ? ConfigVariants<T> & ClassProp : ClassProp;
|
|
31
31
|
/**
|
|
32
|
-
* Class Variance Authority
|
|
32
|
+
* `Class Variance Authority` with `tailwind-merge` support.
|
|
33
33
|
*
|
|
34
34
|
* https://cva.style/docs
|
|
35
35
|
*/
|