@cmtlyt/lingshu-toolkit 0.1.1 → 0.3.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.
Files changed (76) hide show
  1. package/README.md +2 -0
  2. package/dist/607.js +288 -108
  3. package/dist/707.js +136 -0
  4. package/dist/react/index.d.ts +7 -0
  5. package/dist/react/index.js +129 -8
  6. package/dist/react/use-boolean/index.d.ts +6 -0
  7. package/dist/react/use-boolean/index.js +16 -0
  8. package/dist/react/use-boolean/index.test.d.ts +1 -0
  9. package/dist/react/use-controllable-value/index.js +1 -2
  10. package/dist/react/use-counter/index.js +2 -2
  11. package/dist/react/use-force-update/index.d.ts +1 -0
  12. package/dist/react/use-force-update/index.js +6 -0
  13. package/dist/react/use-force-update/index.test.d.ts +1 -0
  14. package/dist/react/use-mount/index.d.ts +1 -0
  15. package/dist/react/use-mount/index.js +16 -0
  16. package/dist/react/use-mount/index.test.d.ts +1 -0
  17. package/dist/react/use-ref-state/index.d.ts +8 -0
  18. package/dist/react/use-ref-state/index.js +35 -0
  19. package/dist/react/use-ref-state/index.test.d.ts +1 -0
  20. package/dist/react/use-storage/index.d.ts +2 -0
  21. package/dist/react/use-storage/index.js +15 -0
  22. package/dist/react/use-storage/index.test.d.ts +1 -0
  23. package/dist/react/use-title/index.d.ts +6 -0
  24. package/dist/react/use-title/index.js +24 -0
  25. package/dist/react/use-title/index.test.d.ts +1 -0
  26. package/dist/react/use-toggle/index.d.ts +10 -0
  27. package/dist/react/use-toggle/index.js +26 -0
  28. package/dist/react/use-toggle/index.test.d.ts +1 -0
  29. package/dist/react/use-valid-data/index.d.ts +4 -2
  30. package/dist/react/use-valid-data/index.js +5 -2
  31. package/dist/shared/animation/__test__/animation-pause-resume.test.d.ts +1 -0
  32. package/dist/shared/animation/__test__/animation.test.d.ts +1 -0
  33. package/dist/shared/animation/__test__/step-animation.test.d.ts +1 -0
  34. package/dist/shared/animation/__test__/utils.test.d.ts +1 -0
  35. package/dist/shared/animation/index.d.ts +3 -0
  36. package/dist/shared/animation/index.js +71 -0
  37. package/dist/shared/animation/types.d.ts +22 -0
  38. package/dist/shared/animation/types.js +0 -0
  39. package/dist/shared/animation/utils.d.ts +16 -0
  40. package/dist/shared/animation/utils.js +138 -0
  41. package/dist/shared/condition-merge/index.d.ts +31 -0
  42. package/dist/shared/condition-merge/index.js +30 -0
  43. package/dist/shared/condition-merge/index.test-d.d.ts +1 -0
  44. package/dist/shared/condition-merge/index.test-d.js +108 -0
  45. package/dist/shared/condition-merge/index.test.d.ts +1 -0
  46. package/dist/shared/create-storage-handler/index.browser.test.d.ts +1 -0
  47. package/dist/shared/create-storage-handler/index.d.ts +10 -0
  48. package/dist/shared/create-storage-handler/index.js +68 -0
  49. package/dist/shared/create-storage-handler/index.test.d.ts +1 -0
  50. package/dist/shared/data-handler/index.d.ts +7 -2
  51. package/dist/shared/data-handler/index.js +4 -4
  52. package/dist/shared/data-handler/tools.d.ts +36 -12
  53. package/dist/shared/data-handler/tools.js +8 -2
  54. package/dist/shared/data-handler/types.d.ts +3 -2
  55. package/dist/shared/index.d.ts +5 -0
  56. package/dist/shared/index.js +2 -1
  57. package/dist/shared/logger/index.d.ts +5 -1
  58. package/dist/shared/logger/index.js +2 -2
  59. package/dist/shared/throw-error/index.d.ts +2 -2
  60. package/dist/shared/throw-error/index.js +4 -4
  61. package/dist/shared/types/base.d.ts +8 -0
  62. package/dist/shared/types/base.js +0 -0
  63. package/dist/shared/types/index.d.ts +2 -2
  64. package/dist/shared/types/index.js +2 -0
  65. package/dist/shared/types/pack.d.ts +9 -0
  66. package/dist/shared/types/pack.js +1 -0
  67. package/dist/shared/with-resolvers/index.d.ts +6 -0
  68. package/dist/shared/with-resolvers/index.js +15 -0
  69. package/dist/shared/with-resolvers/index.test.d.ts +1 -0
  70. package/dist/test/utils.d.ts +13 -0
  71. package/dist/vue/index.d.ts +1 -0
  72. package/dist/vue/index.js +29 -0
  73. package/dist/vue/use-title/index.d.ts +6 -0
  74. package/dist/vue/use-title/index.js +29 -0
  75. package/dist/vue/use-title/index.test.d.ts +1 -0
  76. package/package.json +16 -4
@@ -0,0 +1,138 @@
1
+ import { throwType } from "../throw-error/index.js";
2
+ import { withResolvers } from "../with-resolvers/index.js";
3
+ const noop = ()=>void 0;
4
+ const identity = (_v)=>_v;
5
+ function getType(_v) {
6
+ return Object.prototype.toString.call(_v).slice(8, -1).toLowerCase();
7
+ }
8
+ function getNextValueHandler(from, to, valueFormatter) {
9
+ const type = getType(from);
10
+ const context = {
11
+ progress: 0,
12
+ valueFormatter
13
+ };
14
+ const baseNextValue = (_from, _to)=>{
15
+ const { valueFormatter: formatter, progress } = context;
16
+ if ('number' !== getType(_from)) return _from;
17
+ return formatter(_from + (_to - _from) * progress);
18
+ };
19
+ const arrayHandler = (_from, _to)=>{
20
+ const result = Array.from(_from, (item, idx)=>{
21
+ if (Array.isArray(item)) return arrayHandler(item, _to[idx]);
22
+ if ('object' === getType(item)) return objectHandler(item, _to[idx]);
23
+ return baseNextValue(item, _to[idx]);
24
+ });
25
+ return result;
26
+ };
27
+ const objectHandler = (_from, _to)=>{
28
+ const result = {};
29
+ const keys = Reflect.ownKeys(_from);
30
+ for(let i = 0; i < keys.length; i++){
31
+ const key = keys[i];
32
+ const fromValue = _from[key];
33
+ const toValue = _to[key];
34
+ if (Array.isArray(_from[key])) result[key] = arrayHandler(fromValue, toValue);
35
+ else if ('object' === getType(fromValue)) result[key] = objectHandler(fromValue, toValue);
36
+ else result[key] = baseNextValue(fromValue, toValue);
37
+ }
38
+ return result;
39
+ };
40
+ let nextValueHandler = baseNextValue;
41
+ if ('array' === type) nextValueHandler = arrayHandler;
42
+ else if ('object' === type) nextValueHandler = objectHandler;
43
+ return (progress)=>{
44
+ context.progress = progress;
45
+ return nextValueHandler(from, to);
46
+ };
47
+ }
48
+ function matchValid(from, to, valueParser) {
49
+ const fromType = getType(from);
50
+ const toType = getType(to);
51
+ if (fromType !== toType) throwType('animation/stepAnimation', 'from and to must be the same type');
52
+ if ('array' === fromType) {
53
+ if (from.length !== to.length) throwType('animation/stepAnimation', 'from and to must be the same length');
54
+ const result = [
55
+ Array.from({
56
+ length: from.length
57
+ }),
58
+ Array.from({
59
+ length: to.length
60
+ })
61
+ ];
62
+ for(let i = 0; i < from.length; i++){
63
+ const [fromItem, toItem] = matchValid(from[i], to[i], valueParser);
64
+ result[0][i] = fromItem;
65
+ result[1][i] = toItem;
66
+ }
67
+ return result;
68
+ }
69
+ if ('object' === fromType) {
70
+ const toKeys = Reflect.ownKeys(to);
71
+ const fromKeys = new Set(Reflect.ownKeys(from));
72
+ const result = [
73
+ {},
74
+ {}
75
+ ];
76
+ for(let i = 0; i < toKeys.length; i++){
77
+ const key = toKeys[i];
78
+ if (!fromKeys.has(key)) throwType('animation/stepAnimation', `from does not have this key: ${String(key)}`);
79
+ const [fromItem, toItem] = matchValid(from[key], to[key], valueParser);
80
+ result[0][key] = fromItem;
81
+ result[1][key] = toItem;
82
+ }
83
+ return result;
84
+ }
85
+ if ('number' !== fromType) return [
86
+ valueParser(from),
87
+ valueParser(to)
88
+ ];
89
+ return [
90
+ from,
91
+ to
92
+ ];
93
+ }
94
+ function createNextTick(resolvers, rcSignal) {
95
+ const nextTick = (()=>{
96
+ if ('function' == typeof globalThis.requestAnimationFrame) return globalThis.requestAnimationFrame;
97
+ return (callback)=>setTimeout(callback, 16);
98
+ })();
99
+ return (callback)=>{
100
+ if (rcSignal.stopSignal) return true;
101
+ nextTick(()=>tryRun(callback, resolvers, (error)=>{
102
+ rcSignal.stop();
103
+ resolvers.reject(error);
104
+ }));
105
+ return false;
106
+ };
107
+ }
108
+ async function tryRun(callback, resolvers, customErrorHandler) {
109
+ return new Promise((resolve, reject)=>{
110
+ const result = callback();
111
+ if (result && 'function' == typeof result.then) return result.then(resolve, reject);
112
+ resolve();
113
+ }).catch(customErrorHandler || resolvers.reject);
114
+ }
115
+ function createRunningControllerSignal(startFn, options) {
116
+ const { onStart, onStop, onClear } = options;
117
+ const resolvers = withResolvers();
118
+ const ctrl = {
119
+ stopSignal: true,
120
+ resolvers,
121
+ stop: ()=>{
122
+ ctrl.stopSignal = true;
123
+ onStop();
124
+ },
125
+ start: ()=>{
126
+ ctrl.stopSignal = false;
127
+ onStart();
128
+ startFn();
129
+ },
130
+ clear: ()=>{
131
+ ctrl.stopSignal = true;
132
+ onClear();
133
+ resolvers.resolve(true);
134
+ }
135
+ };
136
+ return ctrl;
137
+ }
138
+ export { createNextTick, createRunningControllerSignal, getNextValueHandler, identity, matchValid, noop, tryRun };
@@ -0,0 +1,31 @@
1
+ import type { IsPrimitive, Printify, UnionToIntersection } from '../types';
2
+ type AssertValue = Record<PropertyKey, any> | any[];
3
+ type ConditionArrayItem = [boolean, AssertValue, AssertValue?];
4
+ type ConditionObjItem = {
5
+ condition: boolean;
6
+ value: AssertValue;
7
+ fullback?: AssertValue;
8
+ };
9
+ type ConditionItem = ConditionObjItem | ConditionArrayItem;
10
+ type GetDefaultValue<V> = IsPrimitive<V> extends true ? never : Record<never, any>;
11
+ type ParseDefaultValue<V, D> = FormatValue<unknown extends D ? (V extends any[] ? [] : GetDefaultValue<V>) : D extends undefined | null ? GetDefaultValue<V> : D>;
12
+ type ParseArrayCondition<T extends [any, any, any?]> = T extends [infer Flag, infer Value, (infer DefaultValue)?] ? boolean extends Flag ? FormatValue<Value> | ParseDefaultValue<Value, DefaultValue> : Flag extends true ? FormatValue<Value> & Record<PropertyKey, any> : ParseDefaultValue<Value, DefaultValue> & Record<PropertyKey, any> : never;
13
+ type ParseObjCondition<T extends ConditionObjItem> = T extends {
14
+ condition: infer Flag extends boolean;
15
+ value: infer Value;
16
+ fullback?: infer DefaultValue;
17
+ } ? ParseArrayCondition<[Flag, Value, DefaultValue]> : never;
18
+ type FormatValue<V> = [V] extends [never] ? never : V extends any[] ? V : {
19
+ [K in keyof V as V[K] extends undefined ? never : K]: V[K];
20
+ };
21
+ type BuildConditionValue<T> = [T];
22
+ type ParseConditionValue<T extends ConditionItem> = UnionToIntersection<T extends infer IT ? BuildConditionValue<Printify<IT extends ConditionArrayItem ? ParseArrayCondition<IT> : IT extends ConditionObjItem ? ParseObjCondition<IT> : never>> : never>;
23
+ type MergedResult<T extends ConditionItem[]> = T extends [
24
+ infer First extends ConditionItem,
25
+ ...infer Last extends [ConditionItem, ...ConditionItem[]]
26
+ ] ? ParseConditionValue<First> & MergedResult<Last> : ParseConditionValue<T[0]>;
27
+ type CMInput = ConditionItem[];
28
+ type FormatResult<T extends any[]> = T[0] & Record<PropertyKey, any>;
29
+ export declare function conditionMerge<T extends CMInput>(...input: T): FormatResult<MergedResult<T>>;
30
+ export declare function conditionMerge<T extends CMInput>(input: T): FormatResult<MergedResult<T>>;
31
+ export {};
@@ -0,0 +1,30 @@
1
+ import { throwType } from "../throw-error/index.js";
2
+ function getEmpty(_v) {
3
+ return Array.isArray(_v) ? [] : {};
4
+ }
5
+ function valueCheck(_v) {
6
+ return Array.isArray(_v) || 'object' == typeof _v;
7
+ }
8
+ function conditionMerge(...input) {
9
+ const conditionItems = (input.length > 1 ? input : input[0]).map((item)=>{
10
+ let result = null;
11
+ if (Array.isArray(item)) {
12
+ const [condition, value, fullback] = item;
13
+ result = {
14
+ condition,
15
+ value,
16
+ fullback
17
+ };
18
+ } else if (Object.getOwnPropertyDescriptor(item, 'condition')) result = item;
19
+ else throwType('conditionMerge', 'input must be an ConditionItem');
20
+ const validValue = valueCheck(result.value);
21
+ const validFullback = void 0 === result.fullback || valueCheck(result.fullback);
22
+ if (!(validValue && validFullback)) throwType('conditionMerge', 'value and fullback must be an array or object');
23
+ return result;
24
+ });
25
+ const result = getEmpty(conditionItems[0].value);
26
+ const mergeFn = Array.isArray(result) ? (a1, a2)=>Reflect.apply(Array.prototype.splice.bind(a1, a1.length, 0), null, a2) : Object.assign;
27
+ for(let i = 0, item = conditionItems[i]; i < conditionItems.length; item = conditionItems[++i])mergeFn(result, item.condition ? item.value : item.fullback || getEmpty(item.value));
28
+ return result;
29
+ }
30
+ export { conditionMerge };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,108 @@
1
+ import { describe, expectTypeOf, test } from "vitest";
2
+ import { conditionMerge } from "./index.js";
3
+ describe('conditionMerge 类型测试', ()=>{
4
+ test(': 混合布尔类型', ()=>{
5
+ const t1 = conditionMerge([
6
+ {
7
+ condition: true,
8
+ value: {
9
+ num: 1
10
+ }
11
+ },
12
+ {
13
+ condition: Math.random() > 0.5,
14
+ value: {
15
+ num: 3,
16
+ str: '3'
17
+ },
18
+ fullback: {
19
+ str: '4'
20
+ }
21
+ }
22
+ ]);
23
+ expectTypeOf(t1).pick().toEqualTypeOf();
24
+ expectTypeOf(t1).pick().toEqualTypeOf();
25
+ expectTypeOf(conditionMerge({
26
+ condition: true,
27
+ value: {
28
+ num: 1
29
+ }
30
+ }, {
31
+ condition: Math.random() > 0.5,
32
+ value: {
33
+ num: 3,
34
+ str: '3'
35
+ },
36
+ fullback: {
37
+ str: '4'
38
+ }
39
+ })).toEqualTypeOf(t1);
40
+ const t3 = conditionMerge([
41
+ {
42
+ condition: true,
43
+ value: {
44
+ num: 1
45
+ }
46
+ },
47
+ {
48
+ condition: false,
49
+ value: {
50
+ num: 1
51
+ },
52
+ fullback: {
53
+ bool: true
54
+ }
55
+ },
56
+ {
57
+ condition: Math.random() > 0.5,
58
+ value: {
59
+ num: 3,
60
+ str: '3'
61
+ },
62
+ fullback: {
63
+ str: '4'
64
+ }
65
+ }
66
+ ]);
67
+ expectTypeOf(t3).pick().toEqualTypeOf();
68
+ expectTypeOf(t3).pick().toEqualTypeOf();
69
+ expectTypeOf(t3).pick().toEqualTypeOf();
70
+ });
71
+ test('类型测试: 纯 boolean 类型测试', ()=>{
72
+ const t1 = conditionMerge([
73
+ {
74
+ condition: Math.random() > 0.1,
75
+ value: {
76
+ num: 1
77
+ }
78
+ },
79
+ {
80
+ condition: Math.random() > 0.5,
81
+ value: {
82
+ num: 3,
83
+ str: '3'
84
+ },
85
+ fullback: {
86
+ str: '4'
87
+ }
88
+ }
89
+ ]);
90
+ expectTypeOf(t1).pick().toEqualTypeOf();
91
+ expectTypeOf(t1).pick().toEqualTypeOf();
92
+ expectTypeOf(conditionMerge({
93
+ condition: Math.random() > 0.1,
94
+ value: {
95
+ num: 1
96
+ }
97
+ }, {
98
+ condition: Math.random() > 0.5,
99
+ value: {
100
+ num: 3,
101
+ str: '3'
102
+ },
103
+ fullback: {
104
+ str: '4'
105
+ }
106
+ })).toEqualTypeOf(t1);
107
+ });
108
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ export interface CreateStorageOptions {
2
+ storageType: 'local' | 'session' | 'memory';
3
+ autoSaveInterval: number;
4
+ }
5
+ export interface StorageHandler<T extends Record<string, any>> {
6
+ get: <K extends keyof T | (string & {})>(key?: K) => string extends K ? T : T[K & keyof T];
7
+ set: <K extends keyof T | (string & {})>(value: string extends K ? T : T[K & keyof T], key?: K) => void;
8
+ clear: () => void;
9
+ }
10
+ export declare function createStorageHandler<T extends Record<string, any>>(storageKey: string, initialData?: T, options?: Partial<CreateStorageOptions>): StorageHandler<T>;
@@ -0,0 +1,68 @@
1
+ import { $dt, $t, dataHandler } from "../data-handler/index.js";
2
+ import { logger } from "../logger/index.js";
3
+ import { throwError } from "../throw-error/index.js";
4
+ const validInfo = $dt({
5
+ storageKey: 'validString',
6
+ storageType: $t["enum"]([
7
+ 'local',
8
+ 'session',
9
+ 'memory'
10
+ ], 'local'),
11
+ autoSaveInterval: $t.number(0)
12
+ });
13
+ const memoryStorage = {
14
+ data: {},
15
+ getItem (key) {
16
+ return this.data[key];
17
+ },
18
+ setItem (key, value) {
19
+ this.data[key] = value;
20
+ },
21
+ removeItem (key) {
22
+ delete this.data[key];
23
+ }
24
+ };
25
+ function getStorage(storageType) {
26
+ try {
27
+ if ('memory' === storageType) return memoryStorage;
28
+ return 'local' === storageType ? localStorage : sessionStorage;
29
+ } catch {
30
+ logger.warn('createStorage', 'Failed to access localStorage or sessionStorage, using memoryStorage instead.');
31
+ return memoryStorage;
32
+ }
33
+ }
34
+ const CLEAR_FLAG = Symbol('cleared');
35
+ function createStorageHandler(storageKey, initialData, options = {}) {
36
+ const { storageKey: validStorageKey, storageType, autoSaveInterval } = dataHandler({
37
+ storageKey,
38
+ ...options
39
+ }, validInfo, {
40
+ unwrap: true
41
+ });
42
+ const storage = getStorage(storageType);
43
+ const storageData = storage.getItem(validStorageKey);
44
+ const context = {
45
+ data: storageData ? JSON.parse(storageData) : initialData || {}
46
+ };
47
+ return {
48
+ get (key) {
49
+ if (context.data === CLEAR_FLAG) throwError('createStorageHandler', 'Storage has been cleared.');
50
+ if (null == key) return context.data;
51
+ return context.data[key];
52
+ },
53
+ set (value, key) {
54
+ if (context.data === CLEAR_FLAG) throwError('createStorageHandler', 'Storage has been cleared.');
55
+ if (null == key) context.data = value;
56
+ else context.data[key] = value;
57
+ if (autoSaveInterval > 0) setTimeout(()=>{
58
+ storage.setItem(validStorageKey, JSON.stringify(context.data));
59
+ }, autoSaveInterval);
60
+ else storage.setItem(validStorageKey, JSON.stringify(context.data));
61
+ },
62
+ clear () {
63
+ context.data = CLEAR_FLAG;
64
+ storage.removeItem(validStorageKey);
65
+ }
66
+ };
67
+ }
68
+ export { createStorageHandler };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,11 @@
1
+ import type { Equal, Printify } from '../types';
2
+ import type { Transform2Type } from './tools';
1
3
  import type { DataHandlerOptions, Handler } from './types';
2
- export declare function dataHandler<M extends Record<PropertyKey, any>, O extends DataHandlerOptions<M> = DataHandlerOptions<M>>(data: M & Partial<O['defaultValue']>, handler: Handler<M>, options?: O): {
3
- result: M & O['defaultValue'];
4
+ type MergeResult<BaseResult extends Record<PropertyKey, any>, HandlerResult extends Handler<any>> = Printify<HandlerResult extends (...args: any[]) => any ? BaseResult : BaseResult & {
5
+ [K in keyof HandlerResult]: Equal<HandlerResult[K], any> extends true ? Required<BaseResult>[K] : HandlerResult[K];
6
+ }>;
7
+ export declare function dataHandler<M extends Record<PropertyKey, any>, H extends Handler<M> = Handler<M>, O extends DataHandlerOptions<M> = DataHandlerOptions<M>>(data: M & Partial<O['defaultValue']>, handler: H, options?: O): O['unwrap'] extends true ? MergeResult<M & O['defaultValue'], Transform2Type<H>> : {
8
+ result: MergeResult<M & O['defaultValue'], Transform2Type<H>>;
4
9
  errors: string[];
5
10
  };
6
11
  export * from './tools';
@@ -47,7 +47,7 @@ function handleProcess(data, keys, handleFn, getActions, actionHandlers) {
47
47
  function errorProcess(errors, errorHandler, strict) {
48
48
  if (!errors.length) return;
49
49
  if (errorHandler) errorHandler(errors);
50
- else if (strict) throwType(errors.join('\n'));
50
+ else if (strict) throwType('dataHandler', errors.join('\n'));
51
51
  }
52
52
  function filterData(data, ctx, defaultValue = {}) {
53
53
  ctx.handledErrorKeys.forEach((key)=>{
@@ -55,8 +55,8 @@ function filterData(data, ctx, defaultValue = {}) {
55
55
  });
56
56
  }
57
57
  function dataHandler(data, handler, options) {
58
- if (!handler) throwType('handler is required');
59
- const { strict = false, errorHandler, defaultValue } = options || {};
58
+ if (!handler) throwType('dataHandler', 'handler is required');
59
+ const { strict = false, errorHandler, defaultValue, unwrap = false } = options || {};
60
60
  const handlerIsFunction = 'function' == typeof handler;
61
61
  const handleFn = handlerIsFunction ? handler : (value, key, ...args)=>handler[key](value, ...args);
62
62
  const tempData = {
@@ -69,7 +69,7 @@ function dataHandler(data, handler, options) {
69
69
  errorProcess(ctx.errors, errorHandler, strict);
70
70
  transformApply(tempData, ctx.transforms);
71
71
  filterData(tempData, ctx, defaultValue);
72
- return {
72
+ return unwrap ? tempData : {
73
73
  result: tempData,
74
74
  errors: ctx.errors
75
75
  };
@@ -1,18 +1,42 @@
1
1
  import type { Handler } from './types';
2
2
  type TypeHandler = NonNullable<Exclude<Handler<any>, (...args: any[]) => any>[string]>;
3
- type Fullback = ((_v: any) => any) | (any & {});
3
+ type TypeHandlerParams = Parameters<TypeHandler> extends [any, ...infer Rest] ? Rest : never;
4
+ type ParseType<T extends string> = T extends keyof TypeMap ? TypeMap[T] : any;
5
+ type TypeHandlerInfo<T extends string> = (value: ParseType<T>, ...args: TypeHandlerParams) => ReturnType<TypeHandler>;
6
+ interface TypeMap {
7
+ notNullable: any & {};
8
+ string: string;
9
+ validString: string;
10
+ number: number;
11
+ validNumber: number;
12
+ boolean: boolean;
13
+ object: Record<PropertyKey, any>;
14
+ array: any[];
15
+ function: (...args: any[]) => any;
16
+ symbol: symbol;
17
+ enum: any & {};
18
+ }
4
19
  export declare const $t: {
5
- notNullable: (fullback?: Fullback) => TypeHandler;
6
- string: (fullback?: Fullback) => TypeHandler;
7
- validString: (fullback?: Fullback) => TypeHandler;
8
- number: (fullback?: Fullback) => TypeHandler;
9
- validNumber: (fullback?: Fullback) => TypeHandler;
10
- boolean: (fullback?: Fullback) => TypeHandler;
11
- object: (fullback?: Fullback) => TypeHandler;
12
- array: (fullback?: Fullback) => TypeHandler;
13
- function: (fullback?: Fullback) => TypeHandler;
14
- symbol: (fullback?: Fullback) => TypeHandler;
20
+ notNullable: (fullback?: any) => TypeHandlerInfo<"notNullable">;
21
+ string: (fullback?: string | ((_v: any) => string) | undefined) => TypeHandlerInfo<"string">;
22
+ validString: (fullback?: string | ((_v: any) => string) | undefined) => TypeHandlerInfo<"validString">;
23
+ number: (fullback?: number | ((_v: any) => number) | undefined) => TypeHandlerInfo<"number">;
24
+ validNumber: (fullback?: number | ((_v: any) => number) | undefined) => TypeHandlerInfo<"validNumber">;
25
+ boolean: (fullback?: boolean | ((_v: any) => boolean) | undefined) => TypeHandlerInfo<"boolean">;
26
+ object: (fullback?: Record<PropertyKey, any> | ((_v: any) => Record<PropertyKey, any>) | undefined) => TypeHandlerInfo<"object">;
27
+ array: (fullback?: any[] | ((_v: any) => any[]) | undefined) => TypeHandlerInfo<"array">;
28
+ function: (fullback?: ((_v: any) => (...args: any[]) => any) | undefined) => TypeHandlerInfo<"function">;
29
+ symbol: (fullback?: symbol | ((_v: any) => symbol) | undefined) => TypeHandlerInfo<"symbol">;
30
+ enum: <T>(list: T[], fullback?: T) => TypeHandlerInfo<"enum">;
15
31
  };
16
- export declare function defineTransform<T extends Record<PropertyKey, any>>(dataInfo: Partial<Record<keyof T, keyof typeof $t | TypeHandler>>): Record<PropertyKey, (value: any, action: import("./types").Actions, option: any) => false | (any & {})>;
32
+ type TransformMap = typeof $t;
33
+ type TransformKey = Exclude<keyof TransformMap, 'enum'>;
34
+ type DataTransformResult<D extends Record<PropertyKey, TransformKey | TypeHandler | undefined>> = {
35
+ [K in keyof D]: D[K] extends TransformKey ? TransformMap[D[K]] : D[K];
36
+ };
37
+ export type Transform2Type<R extends DataTransformResult<any>> = {
38
+ [K in keyof R]: R[K] extends TypeHandlerInfo<infer T> ? ParseType<T> & {} : any & {};
39
+ };
40
+ export declare function defineTransform<T extends Record<PropertyKey, any>, D extends Partial<Record<keyof T, TransformKey | TypeHandler>> = Partial<Record<keyof T, TransformKey | TypeHandler>>>(dataInfo: D): DataTransformResult<D>;
17
41
  export declare const $dt: typeof defineTransform;
18
42
  export {};
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../logger/index.js";
2
+ import { throwType } from "../throw-error/index.js";
2
3
  function getType(_v) {
3
4
  return Object.prototype.toString.call(_v).slice(8, -1).toLowerCase();
4
5
  }
@@ -21,7 +22,12 @@ const $t = {
21
22
  object: typeHandler('object'),
22
23
  array: typeHandler('array'),
23
24
  function: typeHandler('function'),
24
- symbol: typeHandler('symbol')
25
+ symbol: typeHandler('symbol'),
26
+ enum: (list, fullback)=>{
27
+ if (!Array.isArray(list)) throwType('$t.enum', 'list must be an array');
28
+ const set = new Set(list);
29
+ return typeHandler('enum', (_v)=>set.has(_v))(fullback);
30
+ }
25
31
  };
26
32
  function defineTransform(dataInfo) {
27
33
  const verifyInfo = {};
@@ -33,7 +39,7 @@ function defineTransform(dataInfo) {
33
39
  }
34
40
  const handler = $t[item];
35
41
  if (!handler) {
36
- logger.warn(`${item} is not a valid type`);
42
+ logger.warn('defineTransform', `${item} is not a valid type`);
37
43
  continue;
38
44
  }
39
45
  verifyInfo[key] = handler();
@@ -8,8 +8,8 @@ export interface Actions {
8
8
  transform: <T>(value: T) => T;
9
9
  }
10
10
  export type Handler<M extends Record<PropertyKey, any>> = Partial<{
11
- [K in keyof M]: (value: M[K], action: Actions, option: M) => false | (any & {});
12
- }> | (<K extends keyof M>(value: M[K], key: K, action: Actions, option: M) => false | (any & {}));
11
+ [K in keyof M]: (value: any, action: Actions, option: M) => false | (any & {});
12
+ }> | (<K extends keyof M>(value: any, key: K, action: Actions, option: M) => false | (any & {}));
13
13
  export interface ActionContext {
14
14
  errors: string[];
15
15
  transforms: [PropertyKey, any][];
@@ -23,4 +23,5 @@ export interface DataHandlerOptions<M extends Record<PropertyKey, any>> {
23
23
  strict?: boolean;
24
24
  errorHandler?: (error: ActionContext['errors']) => void;
25
25
  defaultValue?: M;
26
+ unwrap?: boolean;
26
27
  }
@@ -1,2 +1,7 @@
1
+ export * from './animation';
2
+ export * from './condition-merge';
3
+ export * from './create-storage-handler';
1
4
  export * from './data-handler';
2
5
  export * from './throw-error';
6
+ export * from './types';
7
+ export * from './with-resolvers';
@@ -1 +1,2 @@
1
- export { $dt, $t, dataHandler, defineTransform, throwError, throwType } from "../607.js";
1
+ export { $dt, $t, dataHandler, defineTransform, throwError, throwType } from "../707.js";
2
+ export { animation, conditionMerge, createStorageHandler, stepAnimation, withResolvers } from "../607.js";
@@ -1 +1,5 @@
1
- export declare const logger: Console;
1
+ type Logger = {
2
+ [K in keyof Omit<Console, 'table'> as Console[K] extends (...args: any[]) => any ? K : never]: Console[K] extends (...args: [any, ...infer AS]) => infer R ? (fnName: string, ...args: AS) => R : never;
3
+ };
4
+ export declare const logger: Logger;
5
+ export {};
@@ -1,8 +1,8 @@
1
1
  const logger = new Proxy(console, {
2
2
  get (target, prop, receiver) {
3
3
  const oldLog = Reflect.get(target, prop, receiver).bind(console);
4
- return (...args)=>{
5
- oldLog('[@cmtlyt/lingshu-toolkit]:', ...args);
4
+ return (fnName, ...args)=>{
5
+ oldLog(`[@cmtlyt/lingshu-toolkit#${fnName}]:`, ...args);
6
6
  };
7
7
  }
8
8
  });
@@ -1,2 +1,2 @@
1
- export declare function throwError(message: string, ErrorClass?: ErrorConstructor): never;
2
- export declare function throwType(message: string): never;
1
+ export declare function throwError(fnName: string, message: string, ErrorClass?: ErrorConstructor): never;
2
+ export declare function throwType(fnName: string, message: string): never;
@@ -1,7 +1,7 @@
1
- function throwError(message, ErrorClass = Error) {
2
- throw new ErrorClass(`[@cmtlyt/lingshu-toolkit]: ${message}`);
1
+ function throwError(fnName, message, ErrorClass = Error) {
2
+ throw new ErrorClass(`[@cmtlyt/lingshu-toolkit#${fnName}]: ${message}`);
3
3
  }
4
- function throwType(message) {
5
- throwError(message, TypeError);
4
+ function throwType(fnName, message) {
5
+ throwError(fnName, message, TypeError);
6
6
  }
7
7
  export { throwError, throwType };
@@ -0,0 +1,8 @@
1
+ export type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
2
+ export type NonUnion<T> = Equal<[T] extends [never] ? never : T[], T extends any ? T[] : never>;
3
+ export type UnionToIntersection<U> = [U] extends [never] ? never : (U extends any ? (_v: U) => void : never) extends (_v: infer I) => void ? I : never;
4
+ export type IsPrimitive<T> = T extends number | string | boolean | symbol | bigint | null | undefined ? true : false;
5
+ export type IsBasicType<T> = T extends number | string | boolean | symbol | bigint ? true : false;
6
+ export type Printify<T> = T extends any[] ? T : [T] extends [never] ? T : {
7
+ [K in keyof T]: T[K];
8
+ };
File without changes
@@ -1,2 +1,2 @@
1
- export type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
2
- export type NotUnion<T> = Equal<[T] extends [never] ? never : T[], T extends any ? T[] : never>;
1
+ export * from './base';
2
+ export * from './pack';
@@ -0,0 +1,2 @@
1
+ export * from "./base.js";
2
+ export * from "./pack.js";
@@ -0,0 +1,9 @@
1
+ declare const __PACK__: unique symbol;
2
+ export type Pack<T> = {
3
+ [__PACK__]: T;
4
+ };
5
+ export type Unpack<T extends Pack<any>> = T extends Pack<infer U> ? U : never;
6
+ export type SafeUnpack<T extends Pack<any>> = T extends Pack<infer U> ? U : T;
7
+ export type IsPack<T> = Pack<any> extends T ? true : false;
8
+ export type HasPack<T> = (T extends any[] ? HasPack<T[number]> : IsPack<T>) extends false ? false : true;
9
+ export {};
@@ -0,0 +1 @@
1
+ Symbol('__PACK__');
@@ -0,0 +1,6 @@
1
+ export type Resolver<T> = {
2
+ promise: Promise<T>;
3
+ resolve: (value: T | PromiseLike<T>) => void;
4
+ reject: (reason?: any) => void;
5
+ };
6
+ export declare function withResolvers<T>(): Resolver<T>;