@cmtlyt/lingshu-toolkit 0.5.0 → 0.6.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/README.md +10 -0
- package/dist/665.js +1 -0
- package/dist/893.js +1 -0
- package/dist/react/index.js +1 -205
- package/dist/react/use-boolean/index.d.ts +2 -1
- package/dist/react/use-boolean/index.js +1 -16
- package/dist/react/use-controllable-value/index.d.ts +3 -3
- package/dist/react/use-controllable-value/index.js +1 -32
- package/dist/react/use-counter/index.d.ts +2 -2
- package/dist/react/use-counter/index.js +1 -49
- package/dist/react/use-force-update/index.d.ts +2 -1
- package/dist/react/use-force-update/index.js +1 -6
- package/dist/react/use-mount/index.d.ts +2 -1
- package/dist/react/use-mount/index.js +1 -16
- package/dist/react/use-ref-state/index.d.ts +3 -2
- package/dist/react/use-ref-state/index.js +1 -33
- package/dist/react/use-storage/index.d.ts +2 -1
- package/dist/react/use-storage/index.js +1 -15
- package/dist/react/use-title/index.d.ts +2 -2
- package/dist/react/use-title/index.js +1 -24
- package/dist/react/use-toggle/index.d.ts +4 -4
- package/dist/react/use-toggle/index.js +1 -26
- package/dist/react/use-valid-data/index.d.ts +5 -4
- package/dist/react/use-valid-data/index.js +1 -14
- package/dist/shared/allx/index.d.ts +2 -1
- package/dist/shared/allx/index.js +1 -44
- package/dist/shared/allx/types.d.ts +6 -0
- package/dist/shared/allx/utils.d.ts +9 -7
- package/dist/shared/allx/utils.js +1 -94
- package/dist/shared/animation/index.d.ts +3 -2
- package/dist/shared/animation/index.js +1 -77
- package/dist/shared/animation/types.d.ts +8 -0
- package/dist/shared/animation/utils.d.ts +3 -10
- package/dist/shared/animation/utils.js +1 -134
- package/dist/shared/api-controller/create-api.js +1 -79
- package/dist/shared/api-controller/index.js +1 -3
- package/dist/shared/api-controller/request.js +1 -66
- package/dist/shared/api-controller/types.d.ts +26 -27
- package/dist/shared/api-controller/utils.d.ts +6 -15
- package/dist/shared/api-controller/utils.js +1 -96
- package/dist/shared/condition-merge/index.d.ts +6 -6
- package/dist/shared/condition-merge/index.js +1 -30
- package/dist/shared/create-storage-handler/index.d.ts +4 -3
- package/dist/shared/create-storage-handler/index.js +1 -68
- package/dist/shared/data-handler/index.d.ts +4 -3
- package/dist/shared/data-handler/index.js +1 -77
- package/dist/shared/data-handler/tools.d.ts +6 -23
- package/dist/shared/data-handler/tools.js +1 -48
- package/dist/shared/data-handler/types.d.ts +20 -2
- package/dist/shared/data-mixed-manager/constants.js +1 -9
- package/dist/shared/data-mixed-manager/index.js +1 -226
- package/dist/shared/data-mixed-manager/types.d.ts +1 -2
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.js +1 -957
- package/dist/shared/logger/index.d.ts +2 -2
- package/dist/shared/logger/index.js +1 -10
- package/dist/shared/priority-queue/index.d.ts +45 -0
- package/dist/shared/priority-queue/index.js +1 -0
- package/dist/shared/priority-queue/types.d.ts +10 -0
- package/dist/shared/priority-queue/types.js +0 -0
- package/dist/shared/priority-queue/utils.d.ts +7 -0
- package/dist/shared/priority-queue/utils.js +1 -0
- package/dist/shared/throw-error/index.d.ts +4 -3
- package/dist/shared/throw-error/index.js +1 -10
- package/dist/shared/try-call/index.d.ts +3 -3
- package/dist/shared/try-call/index.js +1 -59
- package/dist/shared/types/index.js +1 -2
- package/dist/shared/types/pack.d.ts +2 -2
- package/dist/shared/types/pack.js +1 -1
- package/dist/shared/utils/base.d.ts +1 -1
- package/dist/shared/utils/base.js +1 -6
- package/dist/shared/utils/index.js +1 -2
- package/dist/shared/utils/verify.d.ts +1 -1
- package/dist/shared/utils/verify.js +1 -67
- package/dist/shared/with-resolvers/index.d.ts +5 -3
- package/dist/shared/with-resolvers/index.js +1 -15
- package/dist/vue/index.js +1 -29
- package/dist/vue/use-title/index.d.ts +2 -2
- package/dist/vue/use-title/index.js +1 -29
- package/package.json +26 -26
- package/dist/247.js +0 -66
- package/dist/707.js +0 -142
- package/dist/react/use-boolean/index.test.d.ts +0 -1
- package/dist/react/use-controllable-value/index.test.d.ts +0 -1
- package/dist/react/use-counter/index.test.d.ts +0 -1
- package/dist/react/use-force-update/index.test.d.ts +0 -1
- package/dist/react/use-mount/index.test.d.ts +0 -1
- package/dist/react/use-ref-state/index.test.d.ts +0 -1
- package/dist/react/use-storage/index.test.d.ts +0 -1
- package/dist/react/use-title/index.test.d.ts +0 -1
- package/dist/react/use-toggle/index.test.d.ts +0 -1
- package/dist/react/use-valid-data/index.test.d.ts +0 -1
- package/dist/shared/allx/__test__/allsettled.test.d.ts +0 -1
- package/dist/shared/allx/__test__/basic.test.d.ts +0 -1
- package/dist/shared/allx/__test__/circular-dependency.test.d.ts +0 -1
- package/dist/shared/allx/__test__/dependency.test.d.ts +0 -1
- package/dist/shared/allx/__test__/edge-cases.test.d.ts +0 -1
- package/dist/shared/allx/__test__/error-handling.test.d.ts +0 -1
- package/dist/shared/allx/__test__/execution-order.test.d.ts +0 -1
- package/dist/shared/allx/__test__/falsy-values.test.d.ts +0 -1
- package/dist/shared/allx/__test__/performance.test.d.ts +0 -1
- package/dist/shared/allx/__test__/type-checking.test.d.ts +0 -1
- package/dist/shared/allx/__test__/use-cases.test.d.ts +0 -1
- package/dist/shared/animation/__test__/animation-pause-resume.test.d.ts +0 -1
- package/dist/shared/animation/__test__/animation.test.d.ts +0 -1
- package/dist/shared/animation/__test__/step-animation.test.d.ts +0 -1
- package/dist/shared/animation/__test__/utils.test.d.ts +0 -1
- package/dist/shared/api-controller/__test__/index.browser.test.d.ts +0 -1
- package/dist/shared/api-controller/__test__/index.node.test.d.ts +0 -1
- package/dist/shared/condition-merge/index.test-d.js +0 -108
- package/dist/shared/condition-merge/index.test.d.ts +0 -1
- package/dist/shared/create-storage-handler/index.browser.test.d.ts +0 -1
- package/dist/shared/create-storage-handler/index.test.d.ts +0 -1
- package/dist/shared/data-handler/index.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/basic.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/build-options.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/constructor-options.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/data-management.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/edge-cases.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/events.browser.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/events.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/fixed-slots.test.d.ts +0 -1
- package/dist/shared/data-mixed-manager/__test__/insert-mode.test.d.ts +0 -1
- package/dist/shared/throw-error/index.test.d.ts +0 -1
- package/dist/shared/try-call/index.test.d.ts +0 -1
- package/dist/shared/utils/__test__/base.test.d.ts +0 -1
- package/dist/shared/utils/__test__/verify.test.d.ts +0 -1
- package/dist/shared/with-resolvers/index.test.d.ts +0 -1
- package/dist/test/utils.d.ts +0 -13
- package/dist/vue/use-title/index.test.d.ts +0 -1
|
@@ -1,44 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { isFunction, isPromiseLike } from "../utils/verify.js";
|
|
3
|
-
import { withResolvers } from "../with-resolvers/index.js";
|
|
4
|
-
import { createDepProxy, getValueFormatFunc } from "./utils.js";
|
|
5
|
-
const validInfo = $dt({
|
|
6
|
-
allSettled: $t.boolean(false)
|
|
7
|
-
});
|
|
8
|
-
async function allx(tasks, options) {
|
|
9
|
-
const validOptions = dataHandler(options || {}, validInfo, {
|
|
10
|
-
unwrap: true
|
|
11
|
-
});
|
|
12
|
-
const { allSettled } = validOptions;
|
|
13
|
-
const results = {};
|
|
14
|
-
const depCtrl = createDepProxy(tasks, results, validOptions);
|
|
15
|
-
const valueFormat = getValueFormatFunc(options);
|
|
16
|
-
const promises = [];
|
|
17
|
-
depCtrl.taskNameSet.forEach(async (taskName)=>{
|
|
18
|
-
const taskFn = tasks[taskName];
|
|
19
|
-
const context = {
|
|
20
|
-
$: depCtrl.createContextFor(taskName)
|
|
21
|
-
};
|
|
22
|
-
const taskResolvers = withResolvers();
|
|
23
|
-
taskResolvers.promise.then((value)=>{
|
|
24
|
-
results[taskName] = valueFormat(value, 'fulfilled');
|
|
25
|
-
depCtrl.resolveDepFor(taskName, value);
|
|
26
|
-
return value;
|
|
27
|
-
}, (error)=>{
|
|
28
|
-
if (allSettled) results[taskName] = valueFormat(error, 'rejected');
|
|
29
|
-
depCtrl.rejectDepFor(taskName, error);
|
|
30
|
-
});
|
|
31
|
-
promises.push(taskResolvers.promise);
|
|
32
|
-
if (isPromiseLike(taskFn)) return void await taskFn.then(taskResolvers.resolve, taskResolvers.reject);
|
|
33
|
-
if (!isFunction(taskFn)) return void taskResolvers.resolve(taskFn);
|
|
34
|
-
try {
|
|
35
|
-
const result = await taskFn.call(context);
|
|
36
|
-
taskResolvers.resolve(result);
|
|
37
|
-
} catch (error) {
|
|
38
|
-
taskResolvers.reject(error);
|
|
39
|
-
}
|
|
40
|
-
});
|
|
41
|
-
if (allSettled) return Promise.allSettled(promises).then(()=>results);
|
|
42
|
-
return Promise.all(promises).then(()=>results);
|
|
43
|
-
}
|
|
44
|
-
export { allx };
|
|
1
|
+
import{$dt as e,$t as r,dataHandler as t}from"../data-handler/index.js";import{isFunction as o,isPromiseLike as l}from"../utils/verify.js";import{withResolvers as i}from"../with-resolvers/index.js";import{createDepProxy as a,getValueFormatFunc as s}from"./utils.js";let n=e({allSettled:r.boolean(!1)});async function m(e,r){let m=t(r||{},n,{unwrap:!0}),{allSettled:c}=m,f={},p=a(e,f,m),d=s(r),h=[];return(p.taskNameSet.forEach(async r=>{let t=e[r],a={$:p.createContextFor(r)},s=i();if(s.promise.then(e=>(f[r]=d(e,"fulfilled"),p.resolveDepFor(r,e),e),e=>{c&&(f[r]=d(e,"rejected")),p.rejectDepFor(r,e)}),h.push(s.promise),l(t))return void await t.then(s.resolve,s.reject);if(!o(t))return void s.resolve(t);try{let e=await t.call(a);s.resolve(e)}catch(e){s.reject(e)}}),c)?Promise.allSettled(h).then(()=>f):Promise.all(h).then(()=>f)}export{m as allx};
|
|
@@ -11,3 +11,9 @@ export interface AllxContext<M extends Record<PropertyKey, AnyFunc>> {
|
|
|
11
11
|
export type AllxResult<M extends Record<PropertyKey, AnyFunc>, O extends AllxOptions = AllxOptions> = {
|
|
12
12
|
[P in keyof M]: O['allSettled'] extends true ? PromiseSettledResult<Awaited<ReturnType<M[P]>>> : AllxTaskValue<M[P]>;
|
|
13
13
|
};
|
|
14
|
+
export interface DepProxyResult {
|
|
15
|
+
taskNameSet: Set<PropertyKey>;
|
|
16
|
+
createContextFor: (currentTask: PropertyKey) => any;
|
|
17
|
+
resolveDepFor: (depName: PropertyKey, value: any) => void;
|
|
18
|
+
rejectDepFor: (depName: PropertyKey, error: any) => void;
|
|
19
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { AnyFunc } from '../types/base';
|
|
2
|
-
import type { AllxOptions } from './types';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
import type { AllxOptions, DepProxyResult } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* BFS 算法处理 waitingForGraph 的依赖关系
|
|
5
|
+
*/
|
|
6
|
+
export declare function detectCycle(from: PropertyKey, to: PropertyKey, waitingForGraph: Map<PropertyKey, Set<PropertyKey>>): boolean;
|
|
7
|
+
export declare function getCached(results: Record<PropertyKey, any>, depName: PropertyKey, allSettled: boolean): Promise<any> | undefined;
|
|
8
|
+
export declare function createDepResolver(waitingFor: Map<PropertyKey, Set<PropertyKey>>, resolverMap: Map<PropertyKey, PromiseWithResolvers<any>>, currentTask: PropertyKey, depName: PropertyKey): Promise<any>;
|
|
9
|
+
export declare function cleanWaitingForGraph(waitingForGraph: Map<PropertyKey, Set<PropertyKey>>, depName: PropertyKey): void;
|
|
10
|
+
export declare function createDepProxy(tasks: Record<PropertyKey, AnyFunc>, results: Record<PropertyKey, any>, options: Required<AllxOptions>): DepProxyResult;
|
|
9
11
|
export declare function getValueFormatFunc(options?: AllxOptions): (value: any, _type?: PromiseSettledResult<any>["status"]) => any;
|
|
@@ -1,94 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { withResolvers } from "../with-resolvers/index.js";
|
|
3
|
-
function detectCycle(from, to, waitingForGraph) {
|
|
4
|
-
const visited = new Set();
|
|
5
|
-
const queue = [
|
|
6
|
-
to
|
|
7
|
-
];
|
|
8
|
-
let head = 0;
|
|
9
|
-
while(head < queue.length){
|
|
10
|
-
const node = queue[head++];
|
|
11
|
-
if (node === from) return true;
|
|
12
|
-
if (visited.has(node)) continue;
|
|
13
|
-
visited.add(node);
|
|
14
|
-
const deps = waitingForGraph.get(node);
|
|
15
|
-
if (deps) {
|
|
16
|
-
const depsIter = deps.values();
|
|
17
|
-
for(let dep = depsIter.next(); !dep.done; dep = depsIter.next())queue.push(dep.value);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return false;
|
|
21
|
-
}
|
|
22
|
-
function getCached(results, depName, allSettled) {
|
|
23
|
-
if (Reflect.getOwnPropertyDescriptor(results, depName)) {
|
|
24
|
-
const cached = results[depName];
|
|
25
|
-
if (allSettled) return 'rejected' === cached.status ? Promise.reject(cached.reason) : Promise.resolve(cached.value);
|
|
26
|
-
return Promise.resolve(cached);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
function createDepResolver(waitingFor, resolverMap, currentTask, depName) {
|
|
30
|
-
waitingFor.set(currentTask, (waitingFor.get(currentTask) || new Set()).add(depName));
|
|
31
|
-
const depResolvers = resolverMap.get(depName) || withResolvers();
|
|
32
|
-
resolverMap.set(depName, depResolvers);
|
|
33
|
-
return depResolvers.promise.then((value)=>{
|
|
34
|
-
waitingFor.get(currentTask)?.delete(depName);
|
|
35
|
-
return value;
|
|
36
|
-
}, (error)=>{
|
|
37
|
-
waitingFor.get(currentTask)?.delete(depName);
|
|
38
|
-
throw error;
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
function cleanWaitingForGraph(waitingForGraph, depName) {
|
|
42
|
-
waitingForGraph.forEach((deps, task)=>{
|
|
43
|
-
deps.delete(depName);
|
|
44
|
-
if (0 === deps.size) waitingForGraph.delete(task);
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
function createDepProxy(tasks, results, options) {
|
|
48
|
-
const resolverMap = new Map();
|
|
49
|
-
const taskNameSet = new Set(Reflect.ownKeys(tasks));
|
|
50
|
-
const waitingForGraph = new Map();
|
|
51
|
-
const resolveDepFor = (depName, value)=>{
|
|
52
|
-
const resolver = resolverMap.get(depName);
|
|
53
|
-
if (resolver) {
|
|
54
|
-
resolver.resolve(value);
|
|
55
|
-
resolverMap.delete(depName);
|
|
56
|
-
}
|
|
57
|
-
cleanWaitingForGraph(waitingForGraph, depName);
|
|
58
|
-
};
|
|
59
|
-
const rejectDepFor = (depName, error)=>{
|
|
60
|
-
const resolver = resolverMap.get(depName);
|
|
61
|
-
if (resolver) {
|
|
62
|
-
resolver.reject(error);
|
|
63
|
-
resolverMap.delete(depName);
|
|
64
|
-
}
|
|
65
|
-
cleanWaitingForGraph(waitingForGraph, depName);
|
|
66
|
-
};
|
|
67
|
-
const createContextFor = (currentTask)=>new Proxy({}, {
|
|
68
|
-
get (_, depName) {
|
|
69
|
-
if (!taskNameSet.has(depName)) return Promise.reject(createError('allx', `Unknown task "${String(depName)}"`));
|
|
70
|
-
const cached = getCached(results, depName, options.allSettled);
|
|
71
|
-
if (cached) return cached;
|
|
72
|
-
if (detectCycle(currentTask, depName, waitingForGraph)) return Promise.reject(createError('allx', `Circular dependency detected: "${String(currentTask)}" -> "${String(depName)}"`));
|
|
73
|
-
return createDepResolver(waitingForGraph, resolverMap, currentTask, depName);
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
return {
|
|
77
|
-
taskNameSet,
|
|
78
|
-
createContextFor,
|
|
79
|
-
resolveDepFor,
|
|
80
|
-
rejectDepFor
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
function getValueFormatFunc(options) {
|
|
84
|
-
if (!options) return (value, _type = 'fulfilled')=>value;
|
|
85
|
-
if (options.allSettled) return (value, status = 'fulfilled')=>'fulfilled' === status ? {
|
|
86
|
-
status,
|
|
87
|
-
value
|
|
88
|
-
} : {
|
|
89
|
-
status,
|
|
90
|
-
reason: value
|
|
91
|
-
};
|
|
92
|
-
return (value, _type = 'fulfilled')=>value;
|
|
93
|
-
}
|
|
94
|
-
export { createDepProxy, getValueFormatFunc };
|
|
1
|
+
import{createError as e}from"../throw-error/index.js";import{isNullOrUndef as t}from"../utils/verify.js";import{withResolvers as r}from"../with-resolvers/index.js";function l(e,t,r){let l=new Set,n=[t],o=0;for(;o<n.length;){let t=n[o++];if(t===e)return!0;if(l.has(t))continue;l.add(t);let i=r.get(t);if(i){let e=i.values();for(let t=e.next();!t.done;t=e.next())n.push(t.value)}}return!1}function n(e,t,r){if(Reflect.getOwnPropertyDescriptor(e,t)){let l=e[t];return r?"rejected"===l.status?Promise.reject(l.reason):Promise.resolve(l.value):Promise.resolve(l)}}function o(e,t,l,n){e.set(l,(e.get(l)||new Set).add(n));let o=t.get(n)||r();return t.set(n,o),o.promise.then(t=>(e.get(l)?.delete(n),t),t=>{throw e.get(l)?.delete(n),t})}function i(e,t){e.forEach((r,l)=>{r.delete(t),0===r.size&&e.delete(l)})}function s(r,s,a){let c=new Map,f=new Set(Reflect.ownKeys(r)),u=new Map;return{taskNameSet:f,createContextFor:r=>new Proxy({},{get(i,d){if(!f.has(d))return Promise.reject(e("allx",`Unknown task "${String(d)}"`));let g=n(s,d,a.allSettled);return t(g)?l(r,d,u)?Promise.reject(e("allx",`Circular dependency detected: "${String(r)}" -> "${String(d)}"`)):o(u,c,r,d):g}}),resolveDepFor:(e,t)=>{let r=c.get(e);r&&(r.resolve(t),c.delete(e)),i(u,e)},rejectDepFor:(e,t)=>{let r=c.get(e);r&&(r.reject(t),c.delete(e)),i(u,e)}}}function a(e){return e?e.allSettled?(e,t="fulfilled")=>"fulfilled"===t?{status:t,value:e}:{status:t,reason:e}:(e,t="fulfilled")=>e:(e,t="fulfilled")=>e}export{i as cleanWaitingForGraph,s as createDepProxy,o as createDepResolver,l as detectCycle,n as getCached,a as getValueFormatFunc};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { AnimationBaseOptions, AnimationOptions, AnimationResult } from './types';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
declare function stepAnimation<T>(from: T, to: T, step: number, options?: AnimationBaseOptions<T>): Generator<T>;
|
|
3
|
+
declare function animation<T>(from: T, to: T, duration: number, options?: AnimationOptions<T>): AnimationResult;
|
|
4
|
+
export { animation, stepAnimation };
|
|
@@ -1,77 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { throwError } from "../throw-error/index.js";
|
|
3
|
-
import { identity, noop } from "../utils/base.js";
|
|
4
|
-
import { createNextTick, createRunningControllerSignal, getNextValueHandler, matchValid } from "./utils.js";
|
|
5
|
-
const validInfo = $dt({
|
|
6
|
-
autoStart: $t.boolean(true),
|
|
7
|
-
easing: $t["function"](()=>identity),
|
|
8
|
-
onStart: $t["function"](()=>noop),
|
|
9
|
-
onStop: $t["function"](()=>noop),
|
|
10
|
-
onClear: $t["function"](()=>noop),
|
|
11
|
-
onUpdate: $t["function"](()=>noop),
|
|
12
|
-
onComplete: $t["function"](()=>noop),
|
|
13
|
-
formatterValue: $t["function"](()=>identity),
|
|
14
|
-
formatter: $t["function"](()=>identity),
|
|
15
|
-
parser: $t["function"](()=>identity)
|
|
16
|
-
});
|
|
17
|
-
function* stepAnimation(from, to, step, options = {}) {
|
|
18
|
-
if (!Number.isInteger(step) || step <= 0) throwError('stepAnimation', 'step must be a positive integer', RangeError);
|
|
19
|
-
const validOptions = dataHandler(options, validInfo, {
|
|
20
|
-
unwrap: true
|
|
21
|
-
});
|
|
22
|
-
const { parser: valueParser = identity, formatterValue = identity, formatter } = validOptions;
|
|
23
|
-
const [validFrom, validTo] = matchValid(from, to, valueParser);
|
|
24
|
-
const getNextValue = getNextValueHandler(validFrom, validTo, formatterValue);
|
|
25
|
-
for(let i = 0; i <= step; i++){
|
|
26
|
-
const value = formatter(getNextValue(i / step));
|
|
27
|
-
yield value;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
function animation(from, to, duration, options = {}) {
|
|
31
|
-
if (duration <= 0 || !Number.isInteger(duration)) throwError('animation', 'duration must be a positive integer', RangeError);
|
|
32
|
-
const validOptions = dataHandler(options, validInfo, {
|
|
33
|
-
unwrap: true
|
|
34
|
-
});
|
|
35
|
-
const [validFrom, validTo] = matchValid(from, to, validOptions.parser);
|
|
36
|
-
const { autoStart, easing, onComplete, onUpdate, formatterValue, formatter } = validOptions;
|
|
37
|
-
const _getNextValue = getNextValueHandler(validFrom, validTo, formatterValue);
|
|
38
|
-
const getNextValue = (...args)=>formatter(_getNextValue(...args));
|
|
39
|
-
let startTime = 0;
|
|
40
|
-
let hasStarted = false;
|
|
41
|
-
const rcSignal = createRunningControllerSignal(()=>{
|
|
42
|
-
const now = performance.now();
|
|
43
|
-
startTime += now;
|
|
44
|
-
const stopFlag = nextTick(tick);
|
|
45
|
-
if (stopFlag) {
|
|
46
|
-
startTime -= performance.now();
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
if (!hasStarted) {
|
|
50
|
-
onUpdate(getNextValue(0));
|
|
51
|
-
hasStarted = true;
|
|
52
|
-
}
|
|
53
|
-
}, validOptions);
|
|
54
|
-
const { resolvers } = rcSignal;
|
|
55
|
-
const nextTick = createNextTick(resolvers, rcSignal);
|
|
56
|
-
const tick = ()=>{
|
|
57
|
-
const elapsed = performance.now() - startTime;
|
|
58
|
-
const progress = easing(Math.min(elapsed / duration, 1));
|
|
59
|
-
const value = getNextValue(progress);
|
|
60
|
-
onUpdate(value);
|
|
61
|
-
if (elapsed < duration) {
|
|
62
|
-
const stopFlag = nextTick(tick);
|
|
63
|
-
if (stopFlag) startTime = -elapsed;
|
|
64
|
-
} else {
|
|
65
|
-
onComplete();
|
|
66
|
-
resolvers.resolve(false);
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
if (false !== autoStart) rcSignal.start();
|
|
70
|
-
return {
|
|
71
|
-
promise: resolvers.promise,
|
|
72
|
-
stop: rcSignal.stop,
|
|
73
|
-
start: rcSignal.start,
|
|
74
|
-
clear: rcSignal.clear
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
export { animation, stepAnimation };
|
|
1
|
+
import{$dt as t,$t as r,dataHandler as e}from"../data-handler/index.js";import{throwError as n}from"../throw-error/index.js";import{identity as o,noop as i}from"../utils/base.js";import{createNextTick as a,createRunningControllerSignal as s,getNextValueHandler as m,matchValid as p}from"./utils.js";let u=t({autoStart:r.boolean(!0),easing:r.function(()=>o),onStart:r.function(()=>i),onStop:r.function(()=>i),onClear:r.function(()=>i),onUpdate:r.function(()=>i),onComplete:r.function(()=>i),formatterValue:r.function(()=>o),formatter:r.function(()=>o),parser:r.function(()=>o)});function*f(t,r,i,a={}){(!Number.isInteger(i)||i<=0)&&n("stepAnimation","step must be a positive integer",RangeError);let{parser:s=o,formatterValue:l=o,formatter:c}=e(a,u,{unwrap:!0}),[d,g]=p(t,r,s),b=m(d,g,l);for(let t=0;t<=i;t++){let r=c(b(t/i));yield r}}function l(t,r,o,i={}){(o<=0||!Number.isInteger(o))&&n("animation","duration must be a positive integer",RangeError);let f=e(i,u,{unwrap:!0}),[c,d]=p(t,r,f.parser),{autoStart:g,easing:b,onComplete:w,onUpdate:j,formatterValue:h,formatter:v}=f,x=m(c,d,h),S=(...t)=>v(x(...t)),A=0,C=!1,E=s(()=>{let t=performance.now();if(A+=t,N(R)){A-=performance.now();return}C||(j(S(0)),C=!0)},f),{resolvers:I}=E,N=a(I,E),R=()=>{let t=performance.now()-A;j(S(b(Math.min(t/o,1)))),t<o?N(R)&&(A=-t):(w(),I.resolve(!1))};return!1!==g&&E.start(),{promise:I.promise,stop:E.stop,start:E.start,clear:E.clear}}export{l as animation,f as stepAnimation};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Resolver } from '../with-resolvers';
|
|
1
2
|
export type FormatterValue = (value: number) => any;
|
|
2
3
|
export type Formatter<T> = (value: T) => any;
|
|
3
4
|
export interface AnimationBaseOptions<T> {
|
|
@@ -22,3 +23,10 @@ export interface AnimationCtrl {
|
|
|
22
23
|
export type AnimationResult = AnimationCtrl & {
|
|
23
24
|
promise: Promise<boolean>;
|
|
24
25
|
};
|
|
26
|
+
export interface RCSignal {
|
|
27
|
+
stopSignal: boolean;
|
|
28
|
+
resolvers: Resolver<boolean>;
|
|
29
|
+
stop: () => void;
|
|
30
|
+
start: () => void;
|
|
31
|
+
clear: () => void;
|
|
32
|
+
}
|
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { type Resolver } from '../with-resolvers';
|
|
2
|
-
import type { AnimationOptions, FormatterValue } from './types';
|
|
2
|
+
import type { AnimationOptions, FormatterValue, RCSignal } from './types';
|
|
3
3
|
export declare function getNextValueHandler<T>(from: T, to: T, valueFormatter: FormatterValue): (progress: number) => any;
|
|
4
|
-
export declare function matchValid(from: any, to: any, valueParser: (value: any) => number):
|
|
4
|
+
export declare function matchValid(from: any, to: any, valueParser: (value: any) => number): [any, any];
|
|
5
5
|
export declare function createNextTick(resolvers: Resolver<any>, rcSignal: RCSignal): (callback: (...args: any[]) => void) => boolean;
|
|
6
6
|
export declare function tryRun(callback: () => any, resolvers: Resolver<any>, customErrorHandler?: (err: any) => void): Promise<void>;
|
|
7
|
-
export declare function createRunningControllerSignal(startFn: () => void, options: Required<AnimationOptions<any>>):
|
|
8
|
-
stopSignal: boolean;
|
|
9
|
-
resolvers: Resolver<boolean>;
|
|
10
|
-
stop: () => void;
|
|
11
|
-
start: () => void;
|
|
12
|
-
clear: () => void;
|
|
13
|
-
};
|
|
14
|
-
export type RCSignal = Omit<ReturnType<typeof createRunningControllerSignal>, 'resolvers'>;
|
|
7
|
+
export declare function createRunningControllerSignal(startFn: () => void, options: Required<AnimationOptions<any>>): RCSignal;
|
|
@@ -1,134 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { getType } from "../utils/base.js";
|
|
3
|
-
import { withResolvers } from "../with-resolvers/index.js";
|
|
4
|
-
function getNextValueHandler(from, to, valueFormatter) {
|
|
5
|
-
const type = getType(from);
|
|
6
|
-
const context = {
|
|
7
|
-
progress: 0,
|
|
8
|
-
valueFormatter
|
|
9
|
-
};
|
|
10
|
-
const baseNextValue = (_from, _to)=>{
|
|
11
|
-
const { valueFormatter: formatter, progress } = context;
|
|
12
|
-
if ('number' !== getType(_from)) return _from;
|
|
13
|
-
return formatter(_from + (_to - _from) * progress);
|
|
14
|
-
};
|
|
15
|
-
const arrayHandler = (_from, _to)=>{
|
|
16
|
-
const result = Array.from(_from, (item, idx)=>{
|
|
17
|
-
if (Array.isArray(item)) return arrayHandler(item, _to[idx]);
|
|
18
|
-
if ('object' === getType(item)) return objectHandler(item, _to[idx]);
|
|
19
|
-
return baseNextValue(item, _to[idx]);
|
|
20
|
-
});
|
|
21
|
-
return result;
|
|
22
|
-
};
|
|
23
|
-
const objectHandler = (_from, _to)=>{
|
|
24
|
-
const result = {};
|
|
25
|
-
const keys = Reflect.ownKeys(_from);
|
|
26
|
-
for(let i = 0; i < keys.length; i++){
|
|
27
|
-
const key = keys[i];
|
|
28
|
-
const fromValue = _from[key];
|
|
29
|
-
const toValue = _to[key];
|
|
30
|
-
if (Array.isArray(_from[key])) result[key] = arrayHandler(fromValue, toValue);
|
|
31
|
-
else if ('object' === getType(fromValue)) result[key] = objectHandler(fromValue, toValue);
|
|
32
|
-
else result[key] = baseNextValue(fromValue, toValue);
|
|
33
|
-
}
|
|
34
|
-
return result;
|
|
35
|
-
};
|
|
36
|
-
let nextValueHandler = baseNextValue;
|
|
37
|
-
if ('array' === type) nextValueHandler = arrayHandler;
|
|
38
|
-
else if ('object' === type) nextValueHandler = objectHandler;
|
|
39
|
-
return (progress)=>{
|
|
40
|
-
context.progress = progress;
|
|
41
|
-
return nextValueHandler(from, to);
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
function matchValid(from, to, valueParser) {
|
|
45
|
-
const fromType = getType(from);
|
|
46
|
-
const toType = getType(to);
|
|
47
|
-
if (fromType !== toType) throwType('animation/stepAnimation', 'from and to must be the same type');
|
|
48
|
-
if ('array' === fromType) {
|
|
49
|
-
if (from.length !== to.length) throwType('animation/stepAnimation', 'from and to must be the same length');
|
|
50
|
-
const result = [
|
|
51
|
-
Array.from({
|
|
52
|
-
length: from.length
|
|
53
|
-
}),
|
|
54
|
-
Array.from({
|
|
55
|
-
length: to.length
|
|
56
|
-
})
|
|
57
|
-
];
|
|
58
|
-
for(let i = 0; i < from.length; i++){
|
|
59
|
-
const [fromItem, toItem] = matchValid(from[i], to[i], valueParser);
|
|
60
|
-
result[0][i] = fromItem;
|
|
61
|
-
result[1][i] = toItem;
|
|
62
|
-
}
|
|
63
|
-
return result;
|
|
64
|
-
}
|
|
65
|
-
if ('object' === fromType) {
|
|
66
|
-
const toKeys = Reflect.ownKeys(to);
|
|
67
|
-
const fromKeys = new Set(Reflect.ownKeys(from));
|
|
68
|
-
const result = [
|
|
69
|
-
{},
|
|
70
|
-
{}
|
|
71
|
-
];
|
|
72
|
-
for(let i = 0; i < toKeys.length; i++){
|
|
73
|
-
const key = toKeys[i];
|
|
74
|
-
if (!fromKeys.has(key)) throwType('animation/stepAnimation', `from does not have this key: ${String(key)}`);
|
|
75
|
-
const [fromItem, toItem] = matchValid(from[key], to[key], valueParser);
|
|
76
|
-
result[0][key] = fromItem;
|
|
77
|
-
result[1][key] = toItem;
|
|
78
|
-
}
|
|
79
|
-
return result;
|
|
80
|
-
}
|
|
81
|
-
if ('number' !== fromType) return [
|
|
82
|
-
valueParser(from),
|
|
83
|
-
valueParser(to)
|
|
84
|
-
];
|
|
85
|
-
return [
|
|
86
|
-
from,
|
|
87
|
-
to
|
|
88
|
-
];
|
|
89
|
-
}
|
|
90
|
-
function createNextTick(resolvers, rcSignal) {
|
|
91
|
-
const nextTick = (()=>{
|
|
92
|
-
if ('function' == typeof globalThis.requestAnimationFrame) return globalThis.requestAnimationFrame;
|
|
93
|
-
return (callback)=>setTimeout(callback, 16);
|
|
94
|
-
})();
|
|
95
|
-
return (callback)=>{
|
|
96
|
-
if (rcSignal.stopSignal) return true;
|
|
97
|
-
nextTick(()=>tryRun(callback, resolvers, (error)=>{
|
|
98
|
-
rcSignal.stop();
|
|
99
|
-
resolvers.reject(error);
|
|
100
|
-
}));
|
|
101
|
-
return false;
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
async function tryRun(callback, resolvers, customErrorHandler) {
|
|
105
|
-
return new Promise((resolve, reject)=>{
|
|
106
|
-
const result = callback();
|
|
107
|
-
if (result && 'function' == typeof result.then) return result.then(resolve, reject);
|
|
108
|
-
resolve();
|
|
109
|
-
}).catch(customErrorHandler || resolvers.reject);
|
|
110
|
-
}
|
|
111
|
-
function createRunningControllerSignal(startFn, options) {
|
|
112
|
-
const { onStart, onStop, onClear } = options;
|
|
113
|
-
const resolvers = withResolvers();
|
|
114
|
-
const ctrl = {
|
|
115
|
-
stopSignal: true,
|
|
116
|
-
resolvers,
|
|
117
|
-
stop: ()=>{
|
|
118
|
-
ctrl.stopSignal = true;
|
|
119
|
-
onStop();
|
|
120
|
-
},
|
|
121
|
-
start: ()=>{
|
|
122
|
-
ctrl.stopSignal = false;
|
|
123
|
-
onStart();
|
|
124
|
-
startFn();
|
|
125
|
-
},
|
|
126
|
-
clear: ()=>{
|
|
127
|
-
ctrl.stopSignal = true;
|
|
128
|
-
onClear();
|
|
129
|
-
resolvers.resolve(true);
|
|
130
|
-
}
|
|
131
|
-
};
|
|
132
|
-
return ctrl;
|
|
133
|
-
}
|
|
134
|
-
export { createNextTick, createRunningControllerSignal, getNextValueHandler, matchValid, tryRun };
|
|
1
|
+
import{throwType as t}from"../throw-error/index.js";import{getType as e}from"../utils/base.js";import{isPromiseLike as r}from"../utils/verify.js";import{withResolvers as n}from"../with-resolvers/index.js";function o(t,r,n){let o=e(t),i={progress:0,valueFormatter:n},a=(t,r)=>{let{valueFormatter:n,progress:o}=i;return"number"!==e(t)?t:n(t+(r-t)*o)},l=(t,r)=>Array.from(t,(t,n)=>Array.isArray(t)?l(t,r[n]):"object"===e(t)?s(t,r[n]):a(t,r[n])),s=(t,r)=>{let n={},o=Reflect.ownKeys(t);for(let i=0;i<o.length;i++){let m=o[i],u=t[m],f=r[m];Array.isArray(t[m])?n[m]=l(u,f):"object"===e(u)?n[m]=s(u,f):n[m]=a(u,f)}return n},m=a;return"array"===o?m=l:"object"===o&&(m=s),e=>(i.progress=e,m(t,r))}function i(r,n,o){let a=e(r);if(a!==e(n)&&t("animation/stepAnimation","from and to must be the same type"),"array"===a){r.length!==n.length&&t("animation/stepAnimation","from and to must be the same length");let e=[Array.from({length:r.length}),Array.from({length:n.length})];for(let t=0;t<r.length;t++){let[a,l]=i(r[t],n[t],o);e[0][t]=a,e[1][t]=l}return e}if("object"===a){let e=Reflect.ownKeys(n),a=new Set(Reflect.ownKeys(r)),l=[{},{}];for(let s=0;s<e.length;s++){let m=e[s];a.has(m)||t("animation/stepAnimation",`from does not have this key: ${String(m)}`);let[u,f]=i(r[m],n[m],o);l[0][m]=u,l[1][m]=f}return l}return"number"!==a?[o(r),o(n)]:[r,n]}function a(t,e){let r="function"==typeof globalThis.requestAnimationFrame?globalThis.requestAnimationFrame:t=>setTimeout(t,16);return n=>!!e.stopSignal||(r(()=>l(n,t,r=>{e.stop(),t.reject(r)})),!1)}async function l(t,e,n){return new Promise((e,n)=>{let o=t();if(r(o))return o.then(e,n);e()}).catch(n??e.reject)}function s(t,e){let{onStart:r,onStop:o,onClear:i}=e,a=n(),l={stopSignal:!0,resolvers:a,stop:()=>{l.stopSignal=!0,o()},start:()=>{l.stopSignal=!1,r(),t()},clear:()=>{l.stopSignal=!0,i(),a.resolve(!0)}};return l}export{a as createNextTick,s as createRunningControllerSignal,o as getNextValueHandler,i as matchValid,l as tryRun};
|
|
@@ -1,79 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { throwType } from "../throw-error/index.js";
|
|
3
|
-
import { isString, isTrue } from "../utils/verify.js";
|
|
4
|
-
import { request } from "./request.js";
|
|
5
|
-
import { apiNamesCheck, createInstance, getInstanceMemberOrApi, instanceMemberGetter, isAbsUrl } from "./utils.js";
|
|
6
|
-
const FROM_DEFINE = Symbol('fromDefine');
|
|
7
|
-
function createApiWithMap(apiMap, defaultConfig) {
|
|
8
|
-
const fromDefine = apiMap[FROM_DEFINE];
|
|
9
|
-
delete apiMap[FROM_DEFINE];
|
|
10
|
-
const proxyCache = Object.create(null);
|
|
11
|
-
const realDefaultConfig = defaultConfig || {};
|
|
12
|
-
if (!isTrue(fromDefine)) apiNamesCheck(apiMap);
|
|
13
|
-
const instanceObj = createInstance(apiMap, realDefaultConfig, defaultConfig);
|
|
14
|
-
const proxy = new Proxy(apiMap, {
|
|
15
|
-
get (target, prop, receiver) {
|
|
16
|
-
if (Reflect.getOwnPropertyDescriptor(proxyCache, prop)) return proxyCache[prop];
|
|
17
|
-
const { instanceMember, api, isCustom = false } = getInstanceMemberOrApi(target, prop, receiver, instanceObj) || {};
|
|
18
|
-
if (instanceMember) return instanceMember;
|
|
19
|
-
if (!api) return;
|
|
20
|
-
let result = null;
|
|
21
|
-
result = isString(api.url) ? createApi({
|
|
22
|
-
...api,
|
|
23
|
-
[FROM_DEFINE]: fromDefine
|
|
24
|
-
}, realDefaultConfig, isCustom) : createApiWithMap({
|
|
25
|
-
...api,
|
|
26
|
-
[FROM_DEFINE]: fromDefine
|
|
27
|
-
}, realDefaultConfig);
|
|
28
|
-
proxyCache[prop] = result;
|
|
29
|
-
return result;
|
|
30
|
-
}
|
|
31
|
-
});
|
|
32
|
-
return proxy;
|
|
33
|
-
}
|
|
34
|
-
function createApi(api, defaultConfig, custom) {
|
|
35
|
-
const fromDefine = api[FROM_DEFINE];
|
|
36
|
-
delete api[FROM_DEFINE];
|
|
37
|
-
const realDefaultConfig = defaultConfig || {};
|
|
38
|
-
if (!isString(api.url)) throwType('apiController.createApi', '入参应为 APIConfig 对象');
|
|
39
|
-
if (api.url.includes('/:')) {
|
|
40
|
-
if (!isTrue(fromDefine)) logger.warn('apiController.createApi', 'url 中存在 params 参数, 使用 defineApi 或 defineApiMap 定义 API 或 API map 来获取更好的类型提示');
|
|
41
|
-
if (!isTrue(custom)) throwType('apiController.createApi', 'url 中存在 params 参数, 不支持普通请求, 转为自定义请求');
|
|
42
|
-
}
|
|
43
|
-
let handler = null;
|
|
44
|
-
handler = isTrue(custom) ? (data, config)=>request({
|
|
45
|
-
...realDefaultConfig,
|
|
46
|
-
...api,
|
|
47
|
-
...config,
|
|
48
|
-
url: api.url,
|
|
49
|
-
data,
|
|
50
|
-
oriUrl: api.url
|
|
51
|
-
}) : (data)=>request({
|
|
52
|
-
...realDefaultConfig,
|
|
53
|
-
...api,
|
|
54
|
-
data,
|
|
55
|
-
oriUrl: api.url
|
|
56
|
-
});
|
|
57
|
-
const instanceObj = createInstance(api, realDefaultConfig, defaultConfig);
|
|
58
|
-
if (!isAbsUrl(api.url)) instanceObj.$updateBaseUrl(realDefaultConfig.baseUrl);
|
|
59
|
-
return new Proxy(handler, {
|
|
60
|
-
get (target, prop, receiver) {
|
|
61
|
-
if (Reflect.getOwnPropertyDescriptor(instanceObj, prop)) return instanceMemberGetter(prop, instanceObj);
|
|
62
|
-
return Reflect.get(target, prop, receiver);
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
function defineApi(_api) {
|
|
67
|
-
return {
|
|
68
|
-
..._api,
|
|
69
|
-
[FROM_DEFINE]: true
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
function defineApiMap(_apiMap) {
|
|
73
|
-
apiNamesCheck(_apiMap);
|
|
74
|
-
return {
|
|
75
|
-
..._apiMap,
|
|
76
|
-
[FROM_DEFINE]: true
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
export { createApi, createApiWithMap, defineApi, defineApiMap };
|
|
1
|
+
import{logger as e}from"../logger/index.js";import{throwType as r}from"../throw-error/index.js";import{isString as t,isTrue as l}from"../utils/verify.js";import{request as i}from"./request.js";import{apiNamesCheck as n,createInstance as o,getInstanceMemberOrApi as u,instanceMemberGetter as p,isAbsUrl as f}from"./utils.js";let a=Symbol("fromDefine");function c(e,r){let i=e[a];delete e[a];let p=Object.create(null),f=r||{};l(i)||n(e);let s=o(e,f,r);return new Proxy(e,{get(e,r,l){if(Reflect.getOwnPropertyDescriptor(p,r))return p[r];let{instanceMember:n,api:o,isCustom:A=!1}=u(e,r,l,s)||{};if(n)return n;if(!o)return;let d=null;return d=t(o.url)?m({...o,[a]:i},f,A):c({...o,[a]:i},f),p[r]=d,d}})}function m(n,u,c){let m=n[a];delete n[a];let s=u||{};t(n.url)||r("apiController.createApi","入参应为 APIConfig 对象"),n.url.includes("/:")&&(l(m)||e.warn("apiController.createApi","url 中存在 params 参数, 使用 defineApi 或 defineApiMap 定义 API 或 API map 来获取更好的类型提示"),l(c)||r("apiController.createApi","url 中存在 params 参数, 不支持普通请求, 转为自定义请求"));let A=null;A=l(c)?(e,r)=>i({...s,...n,...r,url:n.url,data:e,oriUrl:n.url}):e=>i({...s,...n,data:e,oriUrl:n.url});let d=o(n,s,u);return f(n.url)||d.$updateBaseUrl(s.baseUrl),new Proxy(A,{get:(e,r,t)=>Reflect.getOwnPropertyDescriptor(d,r)?p(r,d):Reflect.get(e,r,t)})}function s(e){return{...e,[a]:!0}}function A(e){return n(e),{...e,[a]:!0}}export{m as createApi,c as createApiWithMap,s as defineApi,A as defineApiMap};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { request } from "./request.js";
|
|
3
|
-
export { createApi, createApiWithMap, defineApi, defineApiMap, request };
|
|
1
|
+
export{createApi,createApiWithMap,defineApi,defineApiMap}from"./create-api.js";export{request}from"./request.js";
|
|
@@ -1,66 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { tryCall } from "../try-call/index.js";
|
|
3
|
-
import { isFunction, isNullOrUndef } from "../utils/verify.js";
|
|
4
|
-
import { getBody, targetUrlParser, urlParamsParser } from "./utils.js";
|
|
5
|
-
async function baseRequest(config, getResponse) {
|
|
6
|
-
const { baseUrl, url, method: _method, parser, data, tdto, tvo, onResponse, ...rest } = config;
|
|
7
|
-
const targetUrl = targetUrlParser(url, baseUrl);
|
|
8
|
-
const method = _method?.toUpperCase();
|
|
9
|
-
const requestInfo = tryCall(()=>{
|
|
10
|
-
if (isNullOrUndef(method) || 'GET' === method || 'HEAD' === method) {
|
|
11
|
-
const queryKeys = Object.keys(data || {});
|
|
12
|
-
for(let i = 0; i < queryKeys.length; ++i)targetUrl.searchParams.append(queryKeys[i], data[queryKeys[i]]);
|
|
13
|
-
return new Request(targetUrl, {
|
|
14
|
-
...rest,
|
|
15
|
-
method
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
const body = getBody(data, tdto);
|
|
19
|
-
return new Request(targetUrl, {
|
|
20
|
-
...rest,
|
|
21
|
-
method,
|
|
22
|
-
body
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
const responseInfo = await getResponse(requestInfo);
|
|
26
|
-
const resResult = await tryCall(()=>{
|
|
27
|
-
if (onResponse) return onResponse(responseInfo, config);
|
|
28
|
-
if (!parser) return responseInfo.json();
|
|
29
|
-
if ('stream' === parser) return responseInfo.body;
|
|
30
|
-
const responseHandler = responseInfo[parser];
|
|
31
|
-
if (isFunction(responseHandler)) return Reflect.apply(responseHandler, responseInfo, []);
|
|
32
|
-
throwType('apiController.responseParser', 'Invalid parser');
|
|
33
|
-
});
|
|
34
|
-
return tvo ? tvo(resResult) : resResult;
|
|
35
|
-
}
|
|
36
|
-
async function mockRequest(config) {
|
|
37
|
-
const { onRequest, ...rest } = config;
|
|
38
|
-
return baseRequest(config, async (requestInfo)=>{
|
|
39
|
-
const reqResult = await (onRequest && onRequest(requestInfo, config));
|
|
40
|
-
const responseBody = getBody(reqResult);
|
|
41
|
-
return new Response(responseBody, {
|
|
42
|
-
...rest
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
async function networkRequest(config) {
|
|
47
|
-
return baseRequest(config, fetch);
|
|
48
|
-
}
|
|
49
|
-
function request(config) {
|
|
50
|
-
const url = urlParamsParser(config.url, config.params);
|
|
51
|
-
const { requestMode, requestModeMap } = config;
|
|
52
|
-
const customRequest = (requestModeMap || {})[requestMode || ''];
|
|
53
|
-
if (customRequest) return customRequest({
|
|
54
|
-
...config,
|
|
55
|
-
url
|
|
56
|
-
});
|
|
57
|
-
if ('mock' === requestMode) return mockRequest({
|
|
58
|
-
...config,
|
|
59
|
-
url
|
|
60
|
-
});
|
|
61
|
-
return networkRequest({
|
|
62
|
-
...config,
|
|
63
|
-
url
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
export { request };
|
|
1
|
+
import{throwType as e}from"../throw-error/index.js";import{tryCall as r}from"../try-call/index.js";import{isFunction as t,isNullOrUndef as n}from"../utils/verify.js";import{getBody as s,targetUrlParser as o,urlParamsParser as a}from"./utils.js";async function i(a,i){let{baseUrl:u,url:l,method:f,parser:p,data:c,tdto:m,tvo:y,onResponse:w,...d}=a,j=o(l,u),h=f?.toUpperCase(),R=r(()=>{if(n(h)||"GET"===h||"HEAD"===h){let e=Object.keys(c||{});for(let r=0;r<e.length;++r)j.searchParams.append(e[r],c[e[r]]);return new Request(j,{...d,method:h})}let e=s(c,m);return new Request(j,{...d,method:h,body:e})}),q=await i(R),x=await r(()=>{if(w)return w(q,a);if(!p)return q.json();if("stream"===p)return q.body;let r=q[p];if(t(r))return Reflect.apply(r,q,[]);e("apiController.responseParser","Invalid parser")});return y?y(x):x}async function u(e){let{onRequest:r,...t}=e;return i(e,async n=>new Response(s(await (r&&r(n,e))),{...t}))}async function l(e){return i(e,fetch)}function f(e){let r=a(e.url,e.params),{requestMode:t,requestModeMap:n}=e,s=(n||{})[t||""];return s?s({...e,url:r}):"mock"===t?u({...e,url:r}):l({...e,url:r})}export{f as request};
|