@streetui/scheduler 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 StreetUI contributors
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 ADDED
@@ -0,0 +1,26 @@
1
+ # @streetui/scheduler
2
+
3
+ StreetUI update scheduler — batching, microtask flushing, ordered queues
4
+
5
+ Part of [StreetUI](https://github.com/streetui/streetui) — a semantic,
6
+ signal-based UI framework with its own reactivity and keyed DOM reconciler
7
+ (no virtual DOM).
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @streetui/scheduler
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import * as pkg from '@streetui/scheduler';
19
+ ```
20
+
21
+ Both ESM (`import`) and CommonJS (`require`) entry points are shipped, with
22
+ matching TypeScript declarations.
23
+
24
+ ## License
25
+
26
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Scheduler: () => Scheduler,
24
+ flushSync: () => flushSync,
25
+ scheduleImmediate: () => scheduleImmediate,
26
+ scheduleUpdate: () => scheduleUpdate,
27
+ scheduler: () => scheduler
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/scheduler.ts
32
+ var PRIORITY_ORDER = {
33
+ immediate: 0,
34
+ normal: 1,
35
+ idle: 2
36
+ };
37
+ var Scheduler = class {
38
+ _queue = /* @__PURE__ */ new Map();
39
+ _flushScheduled = false;
40
+ _flushing = false;
41
+ _diagnostics = void 0;
42
+ /**
43
+ * Install an optional diagnostic sink for swallowed job errors. Pass
44
+ * `undefined` to restore the default `console.error` reporting. Additive and
45
+ * opt-in — the scheduler never sends anything anywhere on its own.
46
+ */
47
+ setDiagnostics(sink) {
48
+ this._diagnostics = sink;
49
+ }
50
+ /** Total jobs currently queued. */
51
+ get size() {
52
+ return this._queue.size;
53
+ }
54
+ /** True if a flush has been scheduled but not yet executed. */
55
+ get isPending() {
56
+ return this._flushScheduled;
57
+ }
58
+ /**
59
+ * Enqueue a job. If a job with the same key exists, the new one replaces it
60
+ * (allowing callers to coalesce repeated updates for the same node).
61
+ */
62
+ schedule(job) {
63
+ this._queue.set(job.key, job);
64
+ if (!this._flushScheduled && !this._flushing) {
65
+ this._flushScheduled = true;
66
+ this._scheduleMicrotask();
67
+ }
68
+ }
69
+ /** Schedule multiple jobs atomically. */
70
+ scheduleAll(jobs) {
71
+ for (const job of jobs) {
72
+ this._queue.set(job.key, job);
73
+ }
74
+ if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {
75
+ this._flushScheduled = true;
76
+ this._scheduleMicrotask();
77
+ }
78
+ }
79
+ /**
80
+ * Cancel a queued job by key. No-op if not queued.
81
+ */
82
+ cancel(key) {
83
+ this._queue.delete(key);
84
+ }
85
+ /**
86
+ * Synchronously flush all queued jobs (sorted by priority).
87
+ * Useful in tests and for immediate rendering.
88
+ */
89
+ flush() {
90
+ if (this._flushing) return;
91
+ this._flushScheduled = false;
92
+ this._flushing = true;
93
+ const jobs = Array.from(this._queue.values()).sort(
94
+ (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority]
95
+ );
96
+ this._queue.clear();
97
+ try {
98
+ for (const job of jobs) {
99
+ try {
100
+ job.fn();
101
+ } catch (err) {
102
+ if (this._diagnostics?.error) {
103
+ this._diagnostics.error(`Scheduler job "${job.key}" threw`, err);
104
+ } else {
105
+ console.error(`[Scheduler] Job "${job.key}" threw:`, err);
106
+ }
107
+ }
108
+ }
109
+ } finally {
110
+ this._flushing = false;
111
+ }
112
+ }
113
+ /** Clear all pending jobs without executing them. */
114
+ clear() {
115
+ this._queue.clear();
116
+ this._flushScheduled = false;
117
+ }
118
+ _scheduleMicrotask() {
119
+ Promise.resolve().then(() => {
120
+ if (this._flushScheduled) {
121
+ this.flush();
122
+ }
123
+ });
124
+ }
125
+ };
126
+ var scheduler = new Scheduler();
127
+ function scheduleUpdate(key, fn) {
128
+ scheduler.schedule({ key, priority: "normal", fn });
129
+ }
130
+ function scheduleImmediate(key, fn) {
131
+ scheduler.schedule({ key, priority: "immediate", fn });
132
+ }
133
+ function flushSync() {
134
+ scheduler.flush();
135
+ }
136
+ // Annotate the CommonJS export names for ESM import in node:
137
+ 0 && (module.exports = {
138
+ Scheduler,
139
+ flushSync,
140
+ scheduleImmediate,
141
+ scheduleUpdate,
142
+ scheduler
143
+ });
144
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/scheduler.ts"],"sourcesContent":["export * from './scheduler.js';\n","/**\n * StreetUI update scheduler.\n *\n * Responsibilities:\n * - Queue update callbacks\n * - Batch synchronous enqueues into a single microtask flush\n * - Guarantee ordering: higher priority jobs flush first\n * - Prevent duplicate work for the same job key\n * - Allow synchronous flush for tests\n */\n\nexport type Priority = 'immediate' | 'normal' | 'idle';\n\nconst PRIORITY_ORDER: Record<Priority, number> = {\n immediate: 0,\n normal: 1,\n idle: 2,\n};\n\nexport interface Job {\n /** Unique key — if another job with the same key is already queued, it is replaced. */\n readonly key: string;\n readonly priority: Priority;\n readonly fn: () => void;\n}\n\n/**\n * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with\n * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can\n * route swallowed scheduler-job failures through its own logger instead of the\n * default `console.error`. Kept as a local structural type so the scheduler\n * stays dependency-free; no network, no telemetry. When unset, behaviour is\n * exactly as before.\n */\nexport interface SchedulerDiagnostics {\n error?(message: string, context?: unknown): void;\n}\n\nexport class Scheduler {\n private readonly _queue: Map<string, Job> = new Map();\n private _flushScheduled = false;\n private _flushing = false;\n private _diagnostics: SchedulerDiagnostics | undefined = undefined;\n\n /**\n * Install an optional diagnostic sink for swallowed job errors. Pass\n * `undefined` to restore the default `console.error` reporting. Additive and\n * opt-in — the scheduler never sends anything anywhere on its own.\n */\n setDiagnostics(sink: SchedulerDiagnostics | undefined): void {\n this._diagnostics = sink;\n }\n\n /** Total jobs currently queued. */\n get size(): number {\n return this._queue.size;\n }\n\n /** True if a flush has been scheduled but not yet executed. */\n get isPending(): boolean {\n return this._flushScheduled;\n }\n\n /**\n * Enqueue a job. If a job with the same key exists, the new one replaces it\n * (allowing callers to coalesce repeated updates for the same node).\n */\n schedule(job: Job): void {\n this._queue.set(job.key, job);\n if (!this._flushScheduled && !this._flushing) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /** Schedule multiple jobs atomically. */\n scheduleAll(jobs: readonly Job[]): void {\n for (const job of jobs) {\n this._queue.set(job.key, job);\n }\n if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /**\n * Cancel a queued job by key. No-op if not queued.\n */\n cancel(key: string): void {\n this._queue.delete(key);\n }\n\n /**\n * Synchronously flush all queued jobs (sorted by priority).\n * Useful in tests and for immediate rendering.\n */\n flush(): void {\n if (this._flushing) return;\n this._flushScheduled = false;\n this._flushing = true;\n\n const jobs = Array.from(this._queue.values()).sort(\n (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority],\n );\n this._queue.clear();\n\n try {\n for (const job of jobs) {\n try {\n job.fn();\n } catch (err) {\n // Isolate job failures — report and continue so remaining jobs still run.\n if (this._diagnostics?.error) {\n this._diagnostics.error(`Scheduler job \"${job.key}\" threw`, err);\n } else {\n console.error(`[Scheduler] Job \"${job.key}\" threw:`, err);\n }\n }\n }\n } finally {\n this._flushing = false;\n }\n }\n\n /** Clear all pending jobs without executing them. */\n clear(): void {\n this._queue.clear();\n this._flushScheduled = false;\n }\n\n private _scheduleMicrotask(): void {\n Promise.resolve().then(() => {\n if (this._flushScheduled) {\n this.flush();\n }\n });\n }\n}\n\n/** The shared global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/** Convenience: schedule a normal-priority job. */\nexport function scheduleUpdate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'normal', fn });\n}\n\n/** Convenience: schedule an immediate-priority job. */\nexport function scheduleImmediate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'immediate', fn });\n}\n\n/** Convenience: flush the global scheduler synchronously. */\nexport function flushSync(): void {\n scheduler.flush();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,IAAM,iBAA2C;AAAA,EAC/C,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,MAAM;AACR;AAqBO,IAAM,YAAN,MAAgB;AAAA,EACJ,SAA2B,oBAAI,IAAI;AAAA,EAC5C,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,eAAiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOzD,eAAe,MAA8C;AAC3D,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,OAAe;AACjB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA,EAGA,IAAI,YAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,KAAgB;AACvB,SAAK,OAAO,IAAI,IAAI,KAAK,GAAG;AAC5B,QAAI,CAAC,KAAK,mBAAmB,CAAC,KAAK,WAAW;AAC5C,WAAK,kBAAkB;AACvB,WAAK,mBAAmB;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA,EAGA,YAAY,MAA4B;AACtC,eAAW,OAAO,MAAM;AACtB,WAAK,OAAO,IAAI,IAAI,KAAK,GAAG;AAAA,IAC9B;AACA,QAAI,CAAC,KAAK,mBAAmB,CAAC,KAAK,aAAa,KAAK,OAAO,OAAO,GAAG;AACpE,WAAK,kBAAkB;AACvB,WAAK,mBAAmB;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,KAAmB;AACxB,SAAK,OAAO,OAAO,GAAG;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAc;AACZ,QAAI,KAAK,UAAW;AACpB,SAAK,kBAAkB;AACvB,SAAK,YAAY;AAEjB,UAAM,OAAO,MAAM,KAAK,KAAK,OAAO,OAAO,CAAC,EAAE;AAAA,MAC5C,CAAC,GAAG,MAAM,eAAe,EAAE,QAAQ,IAAI,eAAe,EAAE,QAAQ;AAAA,IAClE;AACA,SAAK,OAAO,MAAM;AAElB,QAAI;AACF,iBAAW,OAAO,MAAM;AACtB,YAAI;AACF,cAAI,GAAG;AAAA,QACT,SAAS,KAAK;AAEZ,cAAI,KAAK,cAAc,OAAO;AAC5B,iBAAK,aAAa,MAAM,kBAAkB,IAAI,GAAG,WAAW,GAAG;AAAA,UACjE,OAAO;AACL,oBAAQ,MAAM,oBAAoB,IAAI,GAAG,YAAY,GAAG;AAAA,UAC1D;AAAA,QACF;AAAA,MACF;AAAA,IACF,UAAE;AACA,WAAK,YAAY;AAAA,IACnB;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAClB,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEQ,qBAA2B;AACjC,YAAQ,QAAQ,EAAE,KAAK,MAAM;AAC3B,UAAI,KAAK,iBAAiB;AACxB,aAAK,MAAM;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAGO,IAAM,YAAY,IAAI,UAAU;AAGhC,SAAS,eAAe,KAAa,IAAsB;AAChE,YAAU,SAAS,EAAE,KAAK,UAAU,UAAU,GAAG,CAAC;AACpD;AAGO,SAAS,kBAAkB,KAAa,IAAsB;AACnE,YAAU,SAAS,EAAE,KAAK,UAAU,aAAa,GAAG,CAAC;AACvD;AAGO,SAAS,YAAkB;AAChC,YAAU,MAAM;AAClB;","names":[]}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * StreetUI update scheduler.
3
+ *
4
+ * Responsibilities:
5
+ * - Queue update callbacks
6
+ * - Batch synchronous enqueues into a single microtask flush
7
+ * - Guarantee ordering: higher priority jobs flush first
8
+ * - Prevent duplicate work for the same job key
9
+ * - Allow synchronous flush for tests
10
+ */
11
+ type Priority = 'immediate' | 'normal' | 'idle';
12
+ interface Job {
13
+ /** Unique key — if another job with the same key is already queued, it is replaced. */
14
+ readonly key: string;
15
+ readonly priority: Priority;
16
+ readonly fn: () => void;
17
+ }
18
+ /**
19
+ * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with
20
+ * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can
21
+ * route swallowed scheduler-job failures through its own logger instead of the
22
+ * default `console.error`. Kept as a local structural type so the scheduler
23
+ * stays dependency-free; no network, no telemetry. When unset, behaviour is
24
+ * exactly as before.
25
+ */
26
+ interface SchedulerDiagnostics {
27
+ error?(message: string, context?: unknown): void;
28
+ }
29
+ declare class Scheduler {
30
+ private readonly _queue;
31
+ private _flushScheduled;
32
+ private _flushing;
33
+ private _diagnostics;
34
+ /**
35
+ * Install an optional diagnostic sink for swallowed job errors. Pass
36
+ * `undefined` to restore the default `console.error` reporting. Additive and
37
+ * opt-in — the scheduler never sends anything anywhere on its own.
38
+ */
39
+ setDiagnostics(sink: SchedulerDiagnostics | undefined): void;
40
+ /** Total jobs currently queued. */
41
+ get size(): number;
42
+ /** True if a flush has been scheduled but not yet executed. */
43
+ get isPending(): boolean;
44
+ /**
45
+ * Enqueue a job. If a job with the same key exists, the new one replaces it
46
+ * (allowing callers to coalesce repeated updates for the same node).
47
+ */
48
+ schedule(job: Job): void;
49
+ /** Schedule multiple jobs atomically. */
50
+ scheduleAll(jobs: readonly Job[]): void;
51
+ /**
52
+ * Cancel a queued job by key. No-op if not queued.
53
+ */
54
+ cancel(key: string): void;
55
+ /**
56
+ * Synchronously flush all queued jobs (sorted by priority).
57
+ * Useful in tests and for immediate rendering.
58
+ */
59
+ flush(): void;
60
+ /** Clear all pending jobs without executing them. */
61
+ clear(): void;
62
+ private _scheduleMicrotask;
63
+ }
64
+ /** The shared global scheduler instance. */
65
+ declare const scheduler: Scheduler;
66
+ /** Convenience: schedule a normal-priority job. */
67
+ declare function scheduleUpdate(key: string, fn: () => void): void;
68
+ /** Convenience: schedule an immediate-priority job. */
69
+ declare function scheduleImmediate(key: string, fn: () => void): void;
70
+ /** Convenience: flush the global scheduler synchronously. */
71
+ declare function flushSync(): void;
72
+
73
+ export { type Job, type Priority, Scheduler, type SchedulerDiagnostics, flushSync, scheduleImmediate, scheduleUpdate, scheduler };
@@ -0,0 +1,73 @@
1
+ /**
2
+ * StreetUI update scheduler.
3
+ *
4
+ * Responsibilities:
5
+ * - Queue update callbacks
6
+ * - Batch synchronous enqueues into a single microtask flush
7
+ * - Guarantee ordering: higher priority jobs flush first
8
+ * - Prevent duplicate work for the same job key
9
+ * - Allow synchronous flush for tests
10
+ */
11
+ type Priority = 'immediate' | 'normal' | 'idle';
12
+ interface Job {
13
+ /** Unique key — if another job with the same key is already queued, it is replaced. */
14
+ readonly key: string;
15
+ readonly priority: Priority;
16
+ readonly fn: () => void;
17
+ }
18
+ /**
19
+ * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with
20
+ * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can
21
+ * route swallowed scheduler-job failures through its own logger instead of the
22
+ * default `console.error`. Kept as a local structural type so the scheduler
23
+ * stays dependency-free; no network, no telemetry. When unset, behaviour is
24
+ * exactly as before.
25
+ */
26
+ interface SchedulerDiagnostics {
27
+ error?(message: string, context?: unknown): void;
28
+ }
29
+ declare class Scheduler {
30
+ private readonly _queue;
31
+ private _flushScheduled;
32
+ private _flushing;
33
+ private _diagnostics;
34
+ /**
35
+ * Install an optional diagnostic sink for swallowed job errors. Pass
36
+ * `undefined` to restore the default `console.error` reporting. Additive and
37
+ * opt-in — the scheduler never sends anything anywhere on its own.
38
+ */
39
+ setDiagnostics(sink: SchedulerDiagnostics | undefined): void;
40
+ /** Total jobs currently queued. */
41
+ get size(): number;
42
+ /** True if a flush has been scheduled but not yet executed. */
43
+ get isPending(): boolean;
44
+ /**
45
+ * Enqueue a job. If a job with the same key exists, the new one replaces it
46
+ * (allowing callers to coalesce repeated updates for the same node).
47
+ */
48
+ schedule(job: Job): void;
49
+ /** Schedule multiple jobs atomically. */
50
+ scheduleAll(jobs: readonly Job[]): void;
51
+ /**
52
+ * Cancel a queued job by key. No-op if not queued.
53
+ */
54
+ cancel(key: string): void;
55
+ /**
56
+ * Synchronously flush all queued jobs (sorted by priority).
57
+ * Useful in tests and for immediate rendering.
58
+ */
59
+ flush(): void;
60
+ /** Clear all pending jobs without executing them. */
61
+ clear(): void;
62
+ private _scheduleMicrotask;
63
+ }
64
+ /** The shared global scheduler instance. */
65
+ declare const scheduler: Scheduler;
66
+ /** Convenience: schedule a normal-priority job. */
67
+ declare function scheduleUpdate(key: string, fn: () => void): void;
68
+ /** Convenience: schedule an immediate-priority job. */
69
+ declare function scheduleImmediate(key: string, fn: () => void): void;
70
+ /** Convenience: flush the global scheduler synchronously. */
71
+ declare function flushSync(): void;
72
+
73
+ export { type Job, type Priority, Scheduler, type SchedulerDiagnostics, flushSync, scheduleImmediate, scheduleUpdate, scheduler };
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ // src/scheduler.ts
2
+ var PRIORITY_ORDER = {
3
+ immediate: 0,
4
+ normal: 1,
5
+ idle: 2
6
+ };
7
+ var Scheduler = class {
8
+ _queue = /* @__PURE__ */ new Map();
9
+ _flushScheduled = false;
10
+ _flushing = false;
11
+ _diagnostics = void 0;
12
+ /**
13
+ * Install an optional diagnostic sink for swallowed job errors. Pass
14
+ * `undefined` to restore the default `console.error` reporting. Additive and
15
+ * opt-in — the scheduler never sends anything anywhere on its own.
16
+ */
17
+ setDiagnostics(sink) {
18
+ this._diagnostics = sink;
19
+ }
20
+ /** Total jobs currently queued. */
21
+ get size() {
22
+ return this._queue.size;
23
+ }
24
+ /** True if a flush has been scheduled but not yet executed. */
25
+ get isPending() {
26
+ return this._flushScheduled;
27
+ }
28
+ /**
29
+ * Enqueue a job. If a job with the same key exists, the new one replaces it
30
+ * (allowing callers to coalesce repeated updates for the same node).
31
+ */
32
+ schedule(job) {
33
+ this._queue.set(job.key, job);
34
+ if (!this._flushScheduled && !this._flushing) {
35
+ this._flushScheduled = true;
36
+ this._scheduleMicrotask();
37
+ }
38
+ }
39
+ /** Schedule multiple jobs atomically. */
40
+ scheduleAll(jobs) {
41
+ for (const job of jobs) {
42
+ this._queue.set(job.key, job);
43
+ }
44
+ if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {
45
+ this._flushScheduled = true;
46
+ this._scheduleMicrotask();
47
+ }
48
+ }
49
+ /**
50
+ * Cancel a queued job by key. No-op if not queued.
51
+ */
52
+ cancel(key) {
53
+ this._queue.delete(key);
54
+ }
55
+ /**
56
+ * Synchronously flush all queued jobs (sorted by priority).
57
+ * Useful in tests and for immediate rendering.
58
+ */
59
+ flush() {
60
+ if (this._flushing) return;
61
+ this._flushScheduled = false;
62
+ this._flushing = true;
63
+ const jobs = Array.from(this._queue.values()).sort(
64
+ (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority]
65
+ );
66
+ this._queue.clear();
67
+ try {
68
+ for (const job of jobs) {
69
+ try {
70
+ job.fn();
71
+ } catch (err) {
72
+ if (this._diagnostics?.error) {
73
+ this._diagnostics.error(`Scheduler job "${job.key}" threw`, err);
74
+ } else {
75
+ console.error(`[Scheduler] Job "${job.key}" threw:`, err);
76
+ }
77
+ }
78
+ }
79
+ } finally {
80
+ this._flushing = false;
81
+ }
82
+ }
83
+ /** Clear all pending jobs without executing them. */
84
+ clear() {
85
+ this._queue.clear();
86
+ this._flushScheduled = false;
87
+ }
88
+ _scheduleMicrotask() {
89
+ Promise.resolve().then(() => {
90
+ if (this._flushScheduled) {
91
+ this.flush();
92
+ }
93
+ });
94
+ }
95
+ };
96
+ var scheduler = new Scheduler();
97
+ function scheduleUpdate(key, fn) {
98
+ scheduler.schedule({ key, priority: "normal", fn });
99
+ }
100
+ function scheduleImmediate(key, fn) {
101
+ scheduler.schedule({ key, priority: "immediate", fn });
102
+ }
103
+ function flushSync() {
104
+ scheduler.flush();
105
+ }
106
+ export {
107
+ Scheduler,
108
+ flushSync,
109
+ scheduleImmediate,
110
+ scheduleUpdate,
111
+ scheduler
112
+ };
113
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scheduler.ts"],"sourcesContent":["/**\n * StreetUI update scheduler.\n *\n * Responsibilities:\n * - Queue update callbacks\n * - Batch synchronous enqueues into a single microtask flush\n * - Guarantee ordering: higher priority jobs flush first\n * - Prevent duplicate work for the same job key\n * - Allow synchronous flush for tests\n */\n\nexport type Priority = 'immediate' | 'normal' | 'idle';\n\nconst PRIORITY_ORDER: Record<Priority, number> = {\n immediate: 0,\n normal: 1,\n idle: 2,\n};\n\nexport interface Job {\n /** Unique key — if another job with the same key is already queued, it is replaced. */\n readonly key: string;\n readonly priority: Priority;\n readonly fn: () => void;\n}\n\n/**\n * Optional error-reporting hook (v0.9 §26/§27). Structurally compatible with\n * `@streetui/core`'s `DiagnosticSink` (the `error` method) so an application can\n * route swallowed scheduler-job failures through its own logger instead of the\n * default `console.error`. Kept as a local structural type so the scheduler\n * stays dependency-free; no network, no telemetry. When unset, behaviour is\n * exactly as before.\n */\nexport interface SchedulerDiagnostics {\n error?(message: string, context?: unknown): void;\n}\n\nexport class Scheduler {\n private readonly _queue: Map<string, Job> = new Map();\n private _flushScheduled = false;\n private _flushing = false;\n private _diagnostics: SchedulerDiagnostics | undefined = undefined;\n\n /**\n * Install an optional diagnostic sink for swallowed job errors. Pass\n * `undefined` to restore the default `console.error` reporting. Additive and\n * opt-in — the scheduler never sends anything anywhere on its own.\n */\n setDiagnostics(sink: SchedulerDiagnostics | undefined): void {\n this._diagnostics = sink;\n }\n\n /** Total jobs currently queued. */\n get size(): number {\n return this._queue.size;\n }\n\n /** True if a flush has been scheduled but not yet executed. */\n get isPending(): boolean {\n return this._flushScheduled;\n }\n\n /**\n * Enqueue a job. If a job with the same key exists, the new one replaces it\n * (allowing callers to coalesce repeated updates for the same node).\n */\n schedule(job: Job): void {\n this._queue.set(job.key, job);\n if (!this._flushScheduled && !this._flushing) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /** Schedule multiple jobs atomically. */\n scheduleAll(jobs: readonly Job[]): void {\n for (const job of jobs) {\n this._queue.set(job.key, job);\n }\n if (!this._flushScheduled && !this._flushing && this._queue.size > 0) {\n this._flushScheduled = true;\n this._scheduleMicrotask();\n }\n }\n\n /**\n * Cancel a queued job by key. No-op if not queued.\n */\n cancel(key: string): void {\n this._queue.delete(key);\n }\n\n /**\n * Synchronously flush all queued jobs (sorted by priority).\n * Useful in tests and for immediate rendering.\n */\n flush(): void {\n if (this._flushing) return;\n this._flushScheduled = false;\n this._flushing = true;\n\n const jobs = Array.from(this._queue.values()).sort(\n (a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority],\n );\n this._queue.clear();\n\n try {\n for (const job of jobs) {\n try {\n job.fn();\n } catch (err) {\n // Isolate job failures — report and continue so remaining jobs still run.\n if (this._diagnostics?.error) {\n this._diagnostics.error(`Scheduler job \"${job.key}\" threw`, err);\n } else {\n console.error(`[Scheduler] Job \"${job.key}\" threw:`, err);\n }\n }\n }\n } finally {\n this._flushing = false;\n }\n }\n\n /** Clear all pending jobs without executing them. */\n clear(): void {\n this._queue.clear();\n this._flushScheduled = false;\n }\n\n private _scheduleMicrotask(): void {\n Promise.resolve().then(() => {\n if (this._flushScheduled) {\n this.flush();\n }\n });\n }\n}\n\n/** The shared global scheduler instance. */\nexport const scheduler = new Scheduler();\n\n/** Convenience: schedule a normal-priority job. */\nexport function scheduleUpdate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'normal', fn });\n}\n\n/** Convenience: schedule an immediate-priority job. */\nexport function scheduleImmediate(key: string, fn: () => void): void {\n scheduler.schedule({ key, priority: 'immediate', fn });\n}\n\n/** Convenience: flush the global scheduler synchronously. */\nexport function flushSync(): void {\n scheduler.flush();\n}\n"],"mappings":";AAaA,IAAM,iBAA2C;AAAA,EAC/C,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,MAAM;AACR;AAqBO,IAAM,YAAN,MAAgB;AAAA,EACJ,SAA2B,oBAAI,IAAI;AAAA,EAC5C,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,eAAiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOzD,eAAe,MAA8C;AAC3D,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA,EAGA,IAAI,OAAe;AACjB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA,EAGA,IAAI,YAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAS,KAAgB;AACvB,SAAK,OAAO,IAAI,IAAI,KAAK,GAAG;AAC5B,QAAI,CAAC,KAAK,mBAAmB,CAAC,KAAK,WAAW;AAC5C,WAAK,kBAAkB;AACvB,WAAK,mBAAmB;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA,EAGA,YAAY,MAA4B;AACtC,eAAW,OAAO,MAAM;AACtB,WAAK,OAAO,IAAI,IAAI,KAAK,GAAG;AAAA,IAC9B;AACA,QAAI,CAAC,KAAK,mBAAmB,CAAC,KAAK,aAAa,KAAK,OAAO,OAAO,GAAG;AACpE,WAAK,kBAAkB;AACvB,WAAK,mBAAmB;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,KAAmB;AACxB,SAAK,OAAO,OAAO,GAAG;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAc;AACZ,QAAI,KAAK,UAAW;AACpB,SAAK,kBAAkB;AACvB,SAAK,YAAY;AAEjB,UAAM,OAAO,MAAM,KAAK,KAAK,OAAO,OAAO,CAAC,EAAE;AAAA,MAC5C,CAAC,GAAG,MAAM,eAAe,EAAE,QAAQ,IAAI,eAAe,EAAE,QAAQ;AAAA,IAClE;AACA,SAAK,OAAO,MAAM;AAElB,QAAI;AACF,iBAAW,OAAO,MAAM;AACtB,YAAI;AACF,cAAI,GAAG;AAAA,QACT,SAAS,KAAK;AAEZ,cAAI,KAAK,cAAc,OAAO;AAC5B,iBAAK,aAAa,MAAM,kBAAkB,IAAI,GAAG,WAAW,GAAG;AAAA,UACjE,OAAO;AACL,oBAAQ,MAAM,oBAAoB,IAAI,GAAG,YAAY,GAAG;AAAA,UAC1D;AAAA,QACF;AAAA,MACF;AAAA,IACF,UAAE;AACA,WAAK,YAAY;AAAA,IACnB;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,OAAO,MAAM;AAClB,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEQ,qBAA2B;AACjC,YAAQ,QAAQ,EAAE,KAAK,MAAM;AAC3B,UAAI,KAAK,iBAAiB;AACxB,aAAK,MAAM;AAAA,MACb;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAGO,IAAM,YAAY,IAAI,UAAU;AAGhC,SAAS,eAAe,KAAa,IAAsB;AAChE,YAAU,SAAS,EAAE,KAAK,UAAU,UAAU,GAAG,CAAC;AACpD;AAGO,SAAS,kBAAkB,KAAa,IAAsB;AACnE,YAAU,SAAS,EAAE,KAAK,UAAU,aAAa,GAAG,CAAC;AACvD;AAGO,SAAS,YAAkB;AAChC,YAAU,MAAM;AAClB;","names":[]}
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@streetui/scheduler",
3
+ "version": "1.0.0",
4
+ "description": "StreetUI update scheduler — batching, microtask flushing, ordered queues",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ }
20
+ },
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "vitest run",
25
+ "clean": "rm -rf dist"
26
+ },
27
+ "devDependencies": {
28
+ "typescript": "*",
29
+ "tsup": "*",
30
+ "vitest": "*"
31
+ },
32
+ "license": "MIT",
33
+ "sideEffects": false,
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ]
42
+ }