@xharness/cordis-plugin-timer 0.0.0-stage → 1.3.0-alpha.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Shigma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @cordisjs/plugin-timer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Disposal-aware timer service for Cordis.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { Context } from 'cordis'
9
+ import Timer from '@cordisjs/plugin-timer'
10
+
11
+ const root = new Context()
12
+ await root.plugin(Timer)
13
+
14
+ const dispose = root.timeout(() => {
15
+ root.logger.info('done')
16
+ }, 1000)
17
+
18
+ dispose()
19
+ ```
20
+
21
+ Timer handles are registered on the current fiber, so they are cleared automatically when the plugin that created them is disposed.
22
+
23
+ ## API
24
+
25
+ | API | Description |
26
+ | --- | --- |
27
+ | `ctx.timeout(callback, delay)` | Run once and return a disposer. |
28
+ | `ctx.timeout(delay)` | Return a promise that resolves after `delay`. |
29
+ | `ctx.interval(callback, delay)` | Run repeatedly and return a disposer. |
30
+ | `ctx.interval(delay)` | Return an async iterator that yields on each interval. |
31
+ | `ctx.throttle(callback, delay, noTrailing?)` | Return a throttled function with `.dispose()`. |
32
+ | `ctx.debounce(callback, delay)` | Return a debounced function with `.dispose()`. |
33
+
34
+ `ctx.setTimeout()` and `ctx.setInterval()` are kept as deprecated aliases for `ctx.timeout()` and `ctx.interval()`.
35
+
36
+ Concurrent `next()` calls on an interval iterator complete in request order, one per tick. Returning from or throwing into the iterator settles every pending read; disposing the owning fiber rejects every pending read. Ticks without a pending read are discarded.
37
+
38
+ Throttle and debounce wrappers return `void`, regardless of the callback return type. Calling `.dispose()` or disposing the owning fiber cancels pending work and makes later calls inert. `noTrailing` suppresses delayed throttle calls while retaining leading calls until disposal.
package/lib/index.js ADDED
@@ -0,0 +1,158 @@
1
+ import { Service } from "@xharness/cordis";
2
+ //#region lib/types/index.js
3
+ /** Disposable timer helpers mixed into Cordis contexts. */
4
+ var TimerService = class extends Service {
5
+ constructor(ctx) {
6
+ super(ctx, "timer");
7
+ ctx.mixin("timer", [
8
+ "timeout",
9
+ "interval",
10
+ "throttle",
11
+ "debounce",
12
+ "setTimeout",
13
+ "setInterval"
14
+ ]);
15
+ }
16
+ /** @deprecated use `ctx.timeout()` instead */
17
+ setTimeout(callback, delay) {
18
+ return this.timeout(callback, delay);
19
+ }
20
+ /** @deprecated use `ctx.interval()` instead */
21
+ setInterval(callback, delay) {
22
+ return this.interval(callback, delay);
23
+ }
24
+ timeout(...args) {
25
+ const callback = typeof args[0] === "function" ? args.shift() : void 0;
26
+ const delay = args[0];
27
+ if (callback) {
28
+ const dispose = this.ctx.effect(() => {
29
+ const timer = setTimeout(() => {
30
+ dispose();
31
+ callback();
32
+ }, delay);
33
+ return () => clearTimeout(timer);
34
+ }, "ctx.timeout()");
35
+ return dispose;
36
+ } else {
37
+ const { promise, resolve, reject } = Promise.withResolvers();
38
+ const dispose = this.ctx.effect(() => {
39
+ const timer = setTimeout(resolve, delay);
40
+ return () => {
41
+ clearTimeout(timer);
42
+ reject(/* @__PURE__ */ new Error("Context has been disposed"));
43
+ };
44
+ }, "ctx.timeout()");
45
+ return promise.finally(dispose);
46
+ }
47
+ }
48
+ interval(...args) {
49
+ const callback = typeof args[0] === "function" ? args.shift() : void 0;
50
+ const delay = args[0];
51
+ if (callback) return this.ctx.effect(() => {
52
+ const timer = setInterval(callback, delay);
53
+ return () => clearInterval(timer);
54
+ }, "ctx.interval()");
55
+ else {
56
+ let done;
57
+ const nextTasks = [];
58
+ const dispose = this.ctx.effect(() => {
59
+ const timer = setInterval(() => {
60
+ nextTasks.shift()?.resolve({
61
+ done: false,
62
+ value: void 0
63
+ });
64
+ }, delay);
65
+ return () => {
66
+ clearInterval(timer);
67
+ if (done) return;
68
+ done = {
69
+ kind: "throw",
70
+ reason: /* @__PURE__ */ new Error("Context has been disposed")
71
+ };
72
+ for (const task of nextTasks.splice(0)) task.reject(done.reason);
73
+ };
74
+ }, "ctx.interval()");
75
+ return {
76
+ next: () => {
77
+ if (!done) {
78
+ const task = Promise.withResolvers();
79
+ nextTasks.push(task);
80
+ return task.promise;
81
+ }
82
+ if (done.kind === "return") return Promise.resolve({
83
+ done: true,
84
+ value: done.value
85
+ });
86
+ return Promise.reject(done.reason);
87
+ },
88
+ return: (value) => {
89
+ if (!done) done = {
90
+ kind: "return",
91
+ value
92
+ };
93
+ for (const task of nextTasks.splice(0)) task.resolve({
94
+ done: true,
95
+ value
96
+ });
97
+ dispose();
98
+ return Promise.resolve({
99
+ done: true,
100
+ value
101
+ });
102
+ },
103
+ throw: (reason) => {
104
+ if (!done) done = {
105
+ kind: "throw",
106
+ reason
107
+ };
108
+ for (const task of nextTasks.splice(0)) task.reject(reason);
109
+ dispose();
110
+ return Promise.resolve({
111
+ done: true,
112
+ value: void 0
113
+ });
114
+ },
115
+ [Symbol.asyncIterator]() {
116
+ return this;
117
+ }
118
+ };
119
+ }
120
+ }
121
+ _schedule(label, trigger) {
122
+ let timer;
123
+ let isDisposed = false;
124
+ const dispose = this.ctx.effect(() => () => {
125
+ isDisposed = true;
126
+ clearTimeout(timer);
127
+ timer = void 0;
128
+ }, label);
129
+ const wrapper = (...args) => {
130
+ if (isDisposed) return;
131
+ clearTimeout(timer);
132
+ timer = trigger(args);
133
+ };
134
+ wrapper.dispose = dispose;
135
+ return wrapper;
136
+ }
137
+ /** Return a throttled function whose timer is disposed with the current fiber. */
138
+ throttle(callback, delay, noTrailing) {
139
+ let lastCall = -Infinity;
140
+ const execute = (...args) => {
141
+ lastCall = Date.now();
142
+ callback(...args);
143
+ };
144
+ return this._schedule("ctx.throttle()", (args) => {
145
+ const remaining = delay - Date.now() + lastCall;
146
+ if (remaining <= 0) execute(...args);
147
+ else if (!noTrailing) return setTimeout(execute, remaining, ...args);
148
+ });
149
+ }
150
+ /** Return a debounced function whose timer is disposed with the current fiber. */
151
+ debounce(callback, delay) {
152
+ return this._schedule("ctx.debounce()", (args) => {
153
+ return setTimeout(callback, delay, ...args);
154
+ });
155
+ }
156
+ };
157
+ //#endregion
158
+ export { TimerService, TimerService as default };
@@ -0,0 +1,30 @@
1
+ import { Context, Service } from '@xharness/cordis';
2
+ declare module '@xharness/cordis' {
3
+ interface Context extends Pick<TimerService, 'interval' | 'timeout' | 'throttle' | 'debounce' | 'setTimeout' | 'setInterval'> {
4
+ timer: TimerService;
5
+ }
6
+ }
7
+ type Scheduled<F extends (...args: any[]) => any> = ((...args: Parameters<F>) => void) & {
8
+ dispose: () => void;
9
+ };
10
+ /** Disposable timer helpers mixed into Cordis contexts. */
11
+ export declare class TimerService extends Service {
12
+ constructor(ctx: Context);
13
+ /** @deprecated use `ctx.timeout()` instead */
14
+ setTimeout(callback: () => void, delay: number): () => void;
15
+ /** @deprecated use `ctx.interval()` instead */
16
+ setInterval(callback: () => void, delay: number): () => void;
17
+ /** Run a callback once, or return a promise that resolves after `delay`. */
18
+ timeout(callback: () => void, delay: number): () => void;
19
+ timeout(delay: number): Promise<void>;
20
+ /** Run a callback repeatedly, or return an async iterator of ticks. */
21
+ interval(callback: () => void, delay: number): () => void;
22
+ interval<R = any>(delay: number): AsyncIterableIterator<void, R, void>;
23
+ private _schedule;
24
+ /** Return a throttled function whose timer is disposed with the current fiber. */
25
+ throttle<F extends (...args: any[]) => any>(callback: F, delay: number, noTrailing?: boolean): Scheduled<F>;
26
+ /** Return a debounced function whose timer is disposed with the current fiber. */
27
+ debounce<F extends (...args: any[]) => any>(callback: F, delay: number): Scheduled<F>;
28
+ }
29
+ export default TimerService;
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAEnD,OAAO,QAAQ,kBAAkB,CAAC;IAChC,UAAU,OAAQ,SAAQ,IAAI,CAAC,YAAY,EAAE,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,GAAG,aAAa,CAAC;QAC3H,KAAK,EAAE,YAAY,CAAA;KACpB;CACF;AAED,KAAK,SAAS,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG;IAAE,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CAAA;AAEhH,2DAA2D;AAC3D,qBAAa,YAAa,SAAQ,OAAO;gBAC3B,GAAG,EAAE,OAAO;IAKxB,8CAA8C;IAC9C,UAAU,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,KAAK,EAAE,MAAM,SAUM,IAAI;IANxD,+CAA+C;IAC/C,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,KAAK,EAAE,MAAM,SAiCM,IAAI;IA7BzD,4EAA4E;IAC5E,OAAO,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI;IACxD,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0BrC,uEAAuE;IACvE,QAAQ,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,IAAI;IACzD,QAAQ,CAAC,CAAC,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,GAAG,qBAAqB,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC;IAoDtE,OAAO,CAAC,SAAS;IAiBjB,kFAAkF;IAClF,QAAQ,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC;IAiB3G,kFAAkF;IAClF,QAAQ,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;CAKtF;AAED,eAAe,YAAY,CAAA"}
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "timer"
4
+ }
5
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "计时服务",
4
+ "description": "为其他插件提供延时和周期执行能力。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@xharness/cordis-plugin-timer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Timer service for cordis",
4
+ "version": "1.3.0-alpha.2",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Kuner/XHarness.git",
11
+ "directory": "vendor/timer"
12
+ },
13
+ "type": "module",
14
+ "main": "lib/index.js",
15
+ "types": "lib/types/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ },
21
+ "./src/*": "./src/*",
22
+ "./package.json": "./package.json",
23
+ "./locale/*.json": "./locale/*.json"
24
+ },
25
+ "files": [
26
+ "lib/index.js",
27
+ "lib/types/**/*.d.ts",
28
+ "lib/types/**/*.d.ts.map",
29
+ "src",
30
+ "locale"
31
+ ],
32
+ "author": "Shigma <shigma10826@gmail.com>",
33
+ "license": "MIT",
34
+ "peerDependencies": {
35
+ "@xharness/cordis": "~4.2.0-alpha.2"
36
+ },
37
+ "dependencies": {
38
+ "@xharness/cosmokit": "~1.10.0-alpha.2"
39
+ }
6
40
  }
package/src/index.ts ADDED
@@ -0,0 +1,153 @@
1
+ import { Context, Service } from '@xharness/cordis'
2
+
3
+ declare module '@xharness/cordis' {
4
+ interface Context extends Pick<TimerService, 'interval' | 'timeout' | 'throttle' | 'debounce' | 'setTimeout' | 'setInterval'> {
5
+ timer: TimerService
6
+ }
7
+ }
8
+
9
+ type Scheduled<F extends (...args: any[]) => any> = ((...args: Parameters<F>) => void) & { dispose: () => void }
10
+
11
+ /** Disposable timer helpers mixed into Cordis contexts. */
12
+ export class TimerService extends Service {
13
+ constructor(ctx: Context) {
14
+ super(ctx, 'timer')
15
+ ctx.mixin('timer', ['timeout', 'interval', 'throttle', 'debounce', 'setTimeout', 'setInterval'])
16
+ }
17
+
18
+ /** @deprecated use `ctx.timeout()` instead */
19
+ setTimeout(callback: () => void, delay: number) {
20
+ return this.timeout(callback, delay)
21
+ }
22
+
23
+ /** @deprecated use `ctx.interval()` instead */
24
+ setInterval(callback: () => void, delay: number) {
25
+ return this.interval(callback, delay)
26
+ }
27
+
28
+ /** Run a callback once, or return a promise that resolves after `delay`. */
29
+ timeout(callback: () => void, delay: number): () => void
30
+ timeout(delay: number): Promise<void>
31
+ timeout(...args: any[]): any {
32
+ const callback = typeof args[0] === 'function' ? args.shift() : undefined
33
+ const delay = args[0] as number
34
+ if (callback) {
35
+ const dispose = this.ctx.effect(() => {
36
+ const timer = setTimeout(() => {
37
+ dispose()
38
+ callback()
39
+ }, delay)
40
+ return () => clearTimeout(timer)
41
+ }, 'ctx.timeout()')
42
+ return dispose
43
+ } else {
44
+ const { promise, resolve, reject } = Promise.withResolvers<void>()
45
+ const dispose = this.ctx.effect(() => {
46
+ const timer = setTimeout(resolve, delay)
47
+ return () => {
48
+ clearTimeout(timer)
49
+ reject(new Error('Context has been disposed'))
50
+ }
51
+ }, 'ctx.timeout()')
52
+ return promise.finally(dispose)
53
+ }
54
+ }
55
+
56
+ /** Run a callback repeatedly, or return an async iterator of ticks. */
57
+ interval(callback: () => void, delay: number): () => void
58
+ interval<R = any>(delay: number): AsyncIterableIterator<void, R, void>
59
+ interval(...args: any[]): any {
60
+ const callback = typeof args[0] === 'function' ? args.shift() : undefined
61
+ const delay = args[0] as number
62
+ if (callback) {
63
+ return this.ctx.effect(() => {
64
+ const timer = setInterval(callback, delay)
65
+ return () => clearInterval(timer)
66
+ }, 'ctx.interval()')
67
+ } else {
68
+ let done: { kind: 'return'; value: any } | { kind: 'throw'; reason: any } | undefined
69
+ const nextTasks: PromiseWithResolvers<IteratorResult<void>>[] = []
70
+ const dispose = this.ctx.effect(() => {
71
+ const timer = setInterval(() => {
72
+ nextTasks.shift()?.resolve({ done: false, value: undefined })
73
+ }, delay)
74
+ return () => {
75
+ clearInterval(timer)
76
+ if (done) return
77
+ done = { kind: 'throw', reason: new Error('Context has been disposed') }
78
+ for (const task of nextTasks.splice(0)) task.reject(done.reason)
79
+ }
80
+ }, 'ctx.interval()')
81
+ return {
82
+ next: () => {
83
+ if (!done) {
84
+ const task = Promise.withResolvers<IteratorResult<void>>()
85
+ nextTasks.push(task)
86
+ return task.promise
87
+ }
88
+ if (done.kind === 'return') return Promise.resolve({ done: true, value: done.value })
89
+ return Promise.reject(done.reason)
90
+ },
91
+ return: (value) => {
92
+ if (!done) done = { kind: 'return', value }
93
+ for (const task of nextTasks.splice(0)) task.resolve({ done: true, value })
94
+ dispose()
95
+ return Promise.resolve({ done: true, value })
96
+ },
97
+ throw: (reason) => {
98
+ if (!done) done = { kind: 'throw', reason }
99
+ for (const task of nextTasks.splice(0)) task.reject(reason)
100
+ dispose()
101
+ return Promise.resolve({ done: true, value: undefined })
102
+ },
103
+ [Symbol.asyncIterator]() {
104
+ return this
105
+ },
106
+ } satisfies AsyncIterableIterator<void>
107
+ }
108
+ }
109
+
110
+ private _schedule(label: string, trigger: (args: any[]) => number | NodeJS.Timeout | undefined) {
111
+ let timer: number | NodeJS.Timeout | undefined
112
+ let isDisposed = false
113
+ const dispose = this.ctx.effect(() => () => {
114
+ isDisposed = true
115
+ clearTimeout(timer)
116
+ timer = undefined
117
+ }, label)
118
+ const wrapper: any = (...args: any[]) => {
119
+ if (isDisposed) return
120
+ clearTimeout(timer)
121
+ timer = trigger(args)
122
+ }
123
+ wrapper.dispose = dispose
124
+ return wrapper
125
+ }
126
+
127
+ /** Return a throttled function whose timer is disposed with the current fiber. */
128
+ throttle<F extends (...args: any[]) => any>(callback: F, delay: number, noTrailing?: boolean): Scheduled<F> {
129
+ let lastCall = -Infinity
130
+ const execute = (...args: any[]) => {
131
+ lastCall = Date.now()
132
+ callback(...args)
133
+ }
134
+ return this._schedule('ctx.throttle()', (args) => {
135
+ const now = Date.now()
136
+ const remaining = delay - now + lastCall
137
+ if (remaining <= 0) {
138
+ execute(...args)
139
+ } else if (!noTrailing) {
140
+ return setTimeout(execute, remaining, ...args)
141
+ }
142
+ })
143
+ }
144
+
145
+ /** Return a debounced function whose timer is disposed with the current fiber. */
146
+ debounce<F extends (...args: any[]) => any>(callback: F, delay: number): Scheduled<F> {
147
+ return this._schedule('ctx.debounce()', (args) => {
148
+ return setTimeout(callback, delay, ...args)
149
+ })
150
+ }
151
+ }
152
+
153
+ export default TimerService