@bitakit/scheduler 0.0.0-stage → 0.2.1

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/AGENTS.md ADDED
@@ -0,0 +1,141 @@
1
+ # @bitakit/scheduler consumer guide
2
+
3
+ This guide is for using the package. Changes to the package follow the repository root rules.
4
+
5
+ ## Composition and ownership
6
+
7
+ Install the optional package in the runtime that owns scheduled work. It has no React or UI
8
+ imports. Discovery's package metadata installs its zero-argument default plugin factory;
9
+ manual hosts use the named `schedulerPlugin` with `createRuntime`. The plugin ID is `scheduler`,
10
+ the service ID is `scheduler-engine`, and the shared contract is `scheduler`:
11
+
12
+ ```ts
13
+ import { getService } from '@bitakit/core';
14
+ import { scheduler } from '@bitakit/scheduler';
15
+ const jobs = getService(services, scheduler);
16
+ await jobs.run('reports.weekly', { audience: 'team' });
17
+ ```
18
+
19
+ No server generator exists yet. Use explicit server composition as in `examples/server/main.ts`.
20
+ Never import `@bitakit/scheduler/server` into browser code. Install the scheduler once per
21
+ runtime; installing it on both server and browser executes two independent sets of jobs.
22
+
23
+ ## Tasks and default schedules
24
+
25
+ A feature declares executable code with `defineTask({ input?, requires?, execute })` in
26
+ `contributions/tasks/weekly.ts`. The execute context contains `services`, plugin-owned `config`,
27
+ `events`, `settings`, parsed `input` and `signal`. `input` accepts Core's Zod/Standard Schema
28
+ contract; `requires` checks available services at registration and each execution. Domain
29
+ permissions belong in the task or the called business service and must be checked on every run.
30
+ UI Actions are callers, not task definitions. Never load executable code from a schedule source.
31
+
32
+ Use `defineSchedule({ task, cron, input?, timezone?, paused? })` or `{ task, at, ... }` in
33
+ `contributions/schedules/weekly.ts`. `at` is an ISO datetime with an explicit UTC offset.
34
+ [Croner](https://croner.56k.guru/usage/configuration/) validates cron patterns and IANA timezones. Croner 11 supports Node >=18 and browsers;
35
+ the repository and example runner use Node 24. No custom cron syntax or parser is added.
36
+
37
+ IDs derive from plugin + file: `reports.weekly` in two separate namespaces. Folder, dotted
38
+ (`contributions/tasks.weekly.ts`) and record (`contributions/tasks.ts` exporting `{ weekly }`)
39
+ forms are equivalent. Generated `TaskMap` checks task string arguments and inputs;
40
+ `ScheduleMap` supplies known schedule IDs. Schedule APIs also accept runtime source IDs.
41
+ Registration IDs must be unique ignoring case in this new package; source snapshots also reject
42
+ case-only duplicate schedule IDs. Lookups and external task references ignore case. Existing
43
+ Core names retain their exact spellings and exact-match precedence.
44
+
45
+ Manual composition uses `registerTask(id, definition, context?)`, returning an async cleanup
46
+ function. Pass the feature's context for ownership, rather than the scheduler's context, when
47
+ emitting that feature's events. Discovery installers supply that context automatically.
48
+ A host may also call `createScheduler(context)` directly, then await `start()`/`stop()`; use the
49
+ ordinary plugin when Core service interception and runtime ownership are needed.
50
+
51
+ ## Schedule sources
52
+
53
+ `registerSource({ id, priority?, load, subscribe? })` is the one source contract. `load()` returns
54
+ an entire `Promise<readonly Schedule[]>`; each schedule adds `id` to the fields above.
55
+ `subscribe(onChange)` optionally returns a synchronous unsubscribe function. Notifications
56
+ request serialized reloads; they do not carry deltas. No separate adapter registry exists.
57
+
58
+ The returned handle has `ready`, `reload()`, `dispose()` and `[Symbol.asyncDispose]()`. Register
59
+ in a normal service's `onStart`, immediately own disposal with `onStop`, then await `ready`.
60
+ Initial errors reject `ready`/startup; later errors reject explicit reload and report through
61
+ the scheduler's local error handler (console by default), with a sanitized `failed` source
62
+ flag in the store. Invalid snapshots retain the previous valid snapshot. Unsubscribe and revoke
63
+ happen before waiting for an in-flight load; an old load cannot restore a removed source.
64
+ Loads must settle: the source contract does not forcibly cancel provider I/O.
65
+
66
+ Higher priority wins. Defaults use -100; sources default to 0; `registerSchedule` uses 100.
67
+ Equal priority sorts source IDs by case-folded code-point order, with the last source winning.
68
+ Schedule IDs are case-insensitive. Removing an override restores its lower-priority default.
69
+ Unchanged effective definitions keep their Croner instance, including completed one-shot state.
70
+ `pause(scheduleId)`/`resume(scheduleId)` are runtime overrides retained through source refresh.
71
+ Removed schedules stop their timers; already-running calls finish normally unless their task
72
+ or the entire scheduler is disposed. No ongoing run is silently restarted by a reload.
73
+
74
+ Built-ins:
75
+
76
+ - `dataSource({ id, load, subscribe?, priority? })` accepts an ordinary data callback.
77
+ - `urlSource({ id, url, format?: 'json' | 'yaml', fetch?, subscribe?, priority? })` fetches at
78
+ registration and reload, with `cache: 'no-store'`. Supply authenticated fetch as needed.
79
+ - `fileSource({ id, path, format?, watch?, priority? })` from `@bitakit/scheduler/server` reads
80
+ at runtime and watches the containing directory for atomic replacement. `watch: false`
81
+ means explicit reload. File watcher errors remain observable through a failed reload.
82
+
83
+ JSON/YAML documents are arrays, not code or build imports. Use JSON-compatible task input.
84
+ `parseSchedules` and `parseScheduleDocument` expose the same Zod/YAML parsing used by sources.
85
+ A DB/CMS adapter is an ordinary authorized server service, for example:
86
+
87
+ ```ts
88
+ const registration = jobs.registerSource({
89
+ id: 'tenant-db',
90
+ priority: 20,
91
+ load: async () => parseSchedules(await database.readAuthorizedSchedules()),
92
+ subscribe: (reload) => database.subscribeToScheduleChanges(reload),
93
+ });
94
+ onStop(() => registration.dispose());
95
+ await registration.ready;
96
+ ```
97
+
98
+ `database` here is the host's existing provider, not an included CMS/DB integration. Access
99
+ control and trusted tenant selection belong to that provider. Browser clients use data/URL
100
+ sources and must not receive server credentials.
101
+
102
+ ## Execution, observation and cleanup
103
+
104
+ `run(taskId, input?, { schedule? }?)` executes and returns the task result. `schedule` is
105
+ correlation metadata, never proof of authorization. `reload(sourceId?)`, `unregisterSource(id)`,
106
+ `registerSchedule(schedule, { priority? }?)`, `pause`, `resume` and `list` manage schedules.
107
+ `state` is Core's observable service store: running count, schedule status/next run, and source
108
+ failure flags. It excludes task input/results and raw errors. No history/database is maintained.
109
+
110
+ Croner protects each schedule from overlapping itself. Manual runs and different schedules
111
+ may overlap. Every automatic callback re-enters the decorated public `scheduler.run` service,
112
+ so existing Core service interceptors see automatic, manual and event-triggered calls once.
113
+ Use `defineInterceptor({ service: 'scheduler', method: 'run', before, after, onError })` as in
114
+ `examples/audit/plugin.ts`. Service interceptors are already cross-plugin; unlike Action
115
+ interceptors they do not accept a `scope: 'global'` option. `callId` correlates phases within
116
+ one runtime, `startedAt` is epoch milliseconds, and `durationMs` measures through settlement.
117
+ Observers may call their own DB/file logging service. Hooks do not block execution and do not
118
+ promise durable logging. Interceptors are trusted code and see arguments/results; redact there.
119
+
120
+ Existing events `scheduler.started`, `scheduler.completed`, `scheduler.failed` contain only
121
+ `task`, optional `schedule` and a runtime-local `runId`. Failed validation emits `failed` without
122
+ `started`. These events use Core's bus and normal listener ownership. `runId` and interceptor
123
+ `callId` are separate local correlation domains. Event-triggered tasks call `jobs.run` and await
124
+ or handle its promise. A task may emit only its own feature's declared events.
125
+
126
+ The plugin gates execution on Core runtime readiness; timers do not run during incomplete startup.
127
+ Task removal aborts and drains its jobs. Runtime stop stops timers, revokes/unsubscribes all
128
+ sources, aborts jobs and awaits their settlement; it is idempotent. Tasks must cooperate with
129
+ AbortSignal. Never await scheduler/task/runtime cleanup from one of its own running tasks:
130
+ that would wait for itself. Source errors do not erase valid schedules; task failures reject
131
+ manual calls and are reported for automatic runs. There is no persistence, missed-run catch-up,
132
+ exactly-once, distributed locking, leader election, or execution while a browser tab is closed.
133
+
134
+ ## Verification
135
+
136
+ From the repository: build Core, then `npm run test --workspace @bitakit/scheduler`;
137
+ `tsc -p packages/scheduler/examples/tsconfig.json`; run the server example with `--once`.
138
+ Tests cover source precedence, invalid/stale snapshots, cleanup, feature ownership, input
139
+ validation, timer execution and one public interceptor trace per run. Test a real installed
140
+ consumer's generated type maps when changing contribution metadata. Keep this guide and the
141
+ reference page aligned with shipped behavior; `CLAUDE.md` only imports this file.
package/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @bitakit/scheduler
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
+ UI-free, in-process scheduling for BitaKit. Tasks are executable feature code; schedules and
4
+ sources are data. Croner owns cron/date/timezone scheduling in Node and browsers.
5
+
6
+ Read [AGENTS.md](./AGENTS.md) for the complete package contract, source lifecycle, discovery,
7
+ manual server composition and tracing. Runnable examples live in `examples/`; after building,
8
+ run `node packages/scheduler/examples/server/main.ts --once` from the repository root.
9
+
10
+ Source responsibilities: `define.ts` declares tasks/schedules; `discovered.ts` adapts the shared
11
+ contribution expansion; `engine.ts` owns execution and reconciliation; `sources.ts` reads data
12
+ and URLs; `server/index.ts` reads/watches Node files; `plugin.ts` binds Core lifecycle/events.
13
+
14
+ This is not a durable queue: no persistence, exactly-once, leader election or closed-tab guarantee.
15
+ Install the plugin in the runtime that owns the work; server and browser runtimes are independent.
package/discovery.mjs ADDED
@@ -0,0 +1,12 @@
1
+ export default function discovery() {
2
+ return ['tasks', 'schedules'].map((directory) => ({
3
+ name: `scheduler.${directory}`,
4
+ directory,
5
+ from: '@bitakit/scheduler',
6
+ normalize: directory === 'tasks' ? 'discoverTasks' : 'discoverSchedules',
7
+ types: {
8
+ entry: directory === 'tasks' ? 'TaskEntry' : 'ScheduleEntry',
9
+ map: directory === 'tasks' ? 'TaskMap' : 'ScheduleMap',
10
+ },
11
+ }));
12
+ }
@@ -0,0 +1,9 @@
1
+ import type { InputSchema } from '@bitakit/core';
2
+ import type { ScheduleOptions, TaskDefinition } from './types.js';
3
+ export declare function defineTask<I, R>(definition: Omit<TaskDefinition<I, R>, 'kind'> & {
4
+ input: InputSchema<I>;
5
+ }): TaskDefinition<I, R>;
6
+ export declare function defineTask<I = unknown, R = unknown>(definition: Omit<TaskDefinition<I, R>, 'kind'>): TaskDefinition<I, R>;
7
+ export declare function defineSchedule<const T extends ScheduleOptions>(definition: T): T & {
8
+ readonly kind: 'schedule';
9
+ };
package/dist/define.js ADDED
@@ -0,0 +1,6 @@
1
+ export function defineTask(definition) {
2
+ return { ...definition, kind: 'task' };
3
+ }
4
+ export function defineSchedule(definition) {
5
+ return { ...definition, kind: 'schedule' };
6
+ }
@@ -0,0 +1,20 @@
1
+ import { type DiscoveredFile } from '@bitakit/core';
2
+ import type { TaskDefinition, Schedule } from './types.js';
3
+ export type DiscoveredTask = {
4
+ id: string;
5
+ definition: TaskDefinition<any, any>;
6
+ };
7
+ export declare function discoverTasks(files: readonly DiscoveredFile[], module?: string): DiscoveredTask[];
8
+ export declare function discoverSchedules(files: readonly DiscoveredFile[], module?: string): Schedule[];
9
+ type Join<A extends string, B extends string> = A extends '' ? B : B extends '' ? A : `${A}.${B}`;
10
+ type Intersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
11
+ type Entries<V, P extends string, Kind extends string> = [V] extends [{
12
+ kind: Kind;
13
+ }] ? {
14
+ [K in P]: V;
15
+ } : V extends object ? Intersection<{
16
+ [K in Extract<keyof V, string>]: Entries<V[K], Join<P, K>, Kind>;
17
+ }[Extract<keyof V, string>]> : {};
18
+ export type TaskEntry<F, Module extends string> = F extends DiscoveredFile<infer V, infer P> ? Entries<V, Join<Module, P>, 'task'> : {};
19
+ export type ScheduleEntry<F, Module extends string> = F extends DiscoveredFile<infer V, infer P> ? Entries<V, Join<Module, P>, 'schedule'> : {};
20
+ export {};
@@ -0,0 +1,14 @@
1
+ import { expandContributions } from '@bitakit/core';
2
+ const kind = (value, expected) => !!value && typeof value === 'object' && 'kind' in value && value.kind === expected;
3
+ export function discoverTasks(files, module = '') {
4
+ return expandContributions(files, (value) => kind(value, 'task')).map(({ value, path }) => ({
5
+ id: [module, ...path].filter(Boolean).join('.'),
6
+ definition: value,
7
+ }));
8
+ }
9
+ export function discoverSchedules(files, module = '') {
10
+ return expandContributions(files, (value) => kind(value, 'schedule')).map(({ value, path }) => {
11
+ const { kind: _kind, ...schedule } = value;
12
+ return { ...schedule, id: [module, ...path].filter(Boolean).join('.') };
13
+ });
14
+ }
@@ -0,0 +1,18 @@
1
+ import type { Scheduler, SchedulerContext } from './types.js';
2
+ /** In-process scheduler. The host must await stop; tasks must cooperate with their AbortSignal. */
3
+ export declare function createScheduler(context: SchedulerContext, options?: {
4
+ /** Manual engines are ready by default; the plugin binds this to Core lifecycle state. */
5
+ initiallyReady?: boolean;
6
+ /** Runtime integration re-enters the decorated public service method for automatic jobs. */
7
+ dispatch?: (task: string, input: unknown, options: {
8
+ schedule: string;
9
+ }) => Promise<unknown>;
10
+ onError?: (error: unknown, origin: {
11
+ source?: string;
12
+ task?: string;
13
+ }) => void;
14
+ }): Scheduler & {
15
+ start(): Promise<void>;
16
+ stop(): Promise<void>;
17
+ setReady(ready: boolean): void;
18
+ };
package/dist/engine.js ADDED
@@ -0,0 +1,377 @@
1
+ import equal from 'fast-deep-equal';
2
+ import { Cron } from 'croner';
3
+ import { getService, serviceKey, validate } from '@bitakit/core';
4
+ import { parseSchedules } from './sources.js';
5
+ const key = (id) => id.toLowerCase();
6
+ /** In-process scheduler. The host must await stop; tasks must cooperate with their AbortSignal. */
7
+ export function createScheduler(context, options = {}) {
8
+ const tasks = new Map();
9
+ const sources = new Map();
10
+ const timers = new Map();
11
+ const runs = new Set();
12
+ const paused = new Map();
13
+ const state = context.store({ running: 0, schedules: [], sources: [] });
14
+ let ready = options.initiallyReady ?? true;
15
+ let nextRunId = 0;
16
+ let started = false, stopped = false;
17
+ let stopping;
18
+ let mutation = Promise.resolve();
19
+ const assertOpen = () => {
20
+ if (stopped)
21
+ throw new Error('Scheduler is stopped.');
22
+ };
23
+ const report = (error, origin) => {
24
+ try {
25
+ (options.onError ??
26
+ ((error, origin) => console.error('Scheduler operation failed.', origin, error)))(error, origin);
27
+ }
28
+ catch (failure) {
29
+ console.error('Scheduler error reporter failed.', failure);
30
+ }
31
+ };
32
+ const publish = () => state.set({
33
+ running: runs.size,
34
+ schedules: [...timers.values()].map(({ schedule, source, cron }) => Object.freeze({
35
+ id: schedule.id,
36
+ task: schedule.task,
37
+ source,
38
+ paused: !started || !ready || (paused.get(key(schedule.id)) ?? schedule.paused ?? false),
39
+ nextRun: cron.nextRun()?.toISOString() ?? null,
40
+ })),
41
+ sources: [...sources.values()].map(({ source, failed }) => ({ id: source.id, failed })),
42
+ });
43
+ const serial = (work) => {
44
+ const result = mutation.then(work);
45
+ mutation = result.then(() => { }, () => { });
46
+ return result;
47
+ };
48
+ const makeTimer = (schedule, source) => new Cron(schedule.cron ?? new Date(schedule.at), {
49
+ paused: true,
50
+ timezone: schedule.timezone,
51
+ protect: true,
52
+ catch: (error) => report(error, { task: schedule.task }),
53
+ }, async () => {
54
+ try {
55
+ await (options.dispatch ?? execute)(schedule.task, schedule.input, {
56
+ schedule: schedule.id,
57
+ });
58
+ }
59
+ catch {
60
+ /* execute reports the failure once and emits a sanitized event. */
61
+ }
62
+ finally {
63
+ publish();
64
+ }
65
+ });
66
+ const reconcile = () => {
67
+ if (stopped)
68
+ return;
69
+ const desired = new Map();
70
+ const sorted = [...sources.values()]
71
+ .filter((entry) => entry.active)
72
+ .sort((a, b) => (a.source.priority ?? 0) - (b.source.priority ?? 0) ||
73
+ (key(a.source.id) < key(b.source.id) ? -1 : key(a.source.id) > key(b.source.id) ? 1 : 0));
74
+ for (const entry of sorted)
75
+ for (const schedule of entry.snapshot)
76
+ desired.set(key(schedule.id), { schedule, source: entry.source.id });
77
+ // Preflight every replacement before changing any active timer.
78
+ const replacements = new Map();
79
+ try {
80
+ for (const [id, next] of desired) {
81
+ if (!tasks.has(key(next.schedule.task)))
82
+ continue;
83
+ const existing = timers.get(id);
84
+ if (existing && equal(existing.schedule, next.schedule)) {
85
+ existing.source = next.source;
86
+ continue;
87
+ }
88
+ replacements.set(id, { ...next, cron: makeTimer(next.schedule, next.source) });
89
+ }
90
+ }
91
+ catch (error) {
92
+ for (const value of replacements.values())
93
+ value.cron.stop();
94
+ throw error;
95
+ }
96
+ for (const [id, timer] of timers) {
97
+ if (!desired.has(id) || !tasks.has(key(timer.schedule.task)) || replacements.has(id)) {
98
+ timer.cron.stop();
99
+ timers.delete(id);
100
+ if (!desired.has(id))
101
+ paused.delete(id);
102
+ }
103
+ }
104
+ for (const id of paused.keys())
105
+ if (!desired.has(id))
106
+ paused.delete(id);
107
+ for (const [id, timer] of replacements)
108
+ timers.set(id, timer);
109
+ for (const [id, timer] of timers) {
110
+ if (started && ready && !(paused.get(id) ?? timer.schedule.paused ?? false))
111
+ timer.cron.resume();
112
+ else
113
+ timer.cron.pause();
114
+ }
115
+ publish();
116
+ };
117
+ const checkSnapshot = async (value) => {
118
+ const snapshot = parseSchedules(value);
119
+ const seen = new Set();
120
+ for (const schedule of snapshot) {
121
+ const id = key(schedule.id);
122
+ if (seen.has(id))
123
+ throw new Error(`Duplicate schedule "${schedule.id}" in source snapshot.`);
124
+ seen.add(id);
125
+ const task = tasks.get(key(schedule.task));
126
+ if (!task)
127
+ throw new Error(`Unknown task "${schedule.task}" in schedule "${schedule.id}".`);
128
+ if (task.definition.input)
129
+ await validate(task.definition.input, schedule.input);
130
+ const probe = makeTimer(schedule, 'validation');
131
+ probe.stop();
132
+ }
133
+ return snapshot;
134
+ };
135
+ const notify = (name, task, runId, schedule) => {
136
+ context.events.emit(`scheduler.${name}`, { task, runId, ...(schedule ? { schedule } : {}) });
137
+ };
138
+ async function execute(id, input, runOptions) {
139
+ assertOpen();
140
+ if (!ready)
141
+ throw new Error('Scheduler runtime is not ready.');
142
+ const runId = ++nextRunId;
143
+ const schedule = runOptions?.schedule;
144
+ const task = tasks.get(key(id));
145
+ if (!task?.active)
146
+ throw new Error(`Unknown task "${id}".`);
147
+ const controller = new AbortController();
148
+ // Track before invoking user code, including asynchronous validation.
149
+ const run = { task, controller, promise: Promise.resolve() };
150
+ runs.add(run);
151
+ run.promise = Promise.resolve().then(async () => {
152
+ try {
153
+ const checked = task.definition.input
154
+ ? await validate(task.definition.input, input)
155
+ : input;
156
+ controller.signal.throwIfAborted();
157
+ for (const name of task.definition.requires ?? [])
158
+ getService(task.context.services, serviceKey(name));
159
+ notify('started', id, runId, schedule);
160
+ const result = await task.definition.execute({
161
+ ...task.context,
162
+ input: checked,
163
+ signal: controller.signal,
164
+ });
165
+ notify('completed', id, runId, schedule);
166
+ return result;
167
+ }
168
+ catch (error) {
169
+ notify('failed', id, runId, schedule);
170
+ report(error, { task: id });
171
+ throw error;
172
+ }
173
+ finally {
174
+ runs.delete(run);
175
+ publish();
176
+ }
177
+ });
178
+ publish();
179
+ return run.promise;
180
+ }
181
+ const reloadEntry = (entry) => {
182
+ const result = entry.queue.then(async () => {
183
+ if (!entry.active || stopped)
184
+ return;
185
+ try {
186
+ const snapshot = await checkSnapshot(await entry.source.load());
187
+ await serial(() => {
188
+ if (!entry.active || stopped)
189
+ return;
190
+ const previous = entry.snapshot;
191
+ entry.snapshot = snapshot;
192
+ try {
193
+ reconcile();
194
+ }
195
+ catch (error) {
196
+ entry.snapshot = previous;
197
+ throw error;
198
+ }
199
+ entry.failed = false;
200
+ publish();
201
+ });
202
+ }
203
+ catch (error) {
204
+ if (entry.active && !stopped) {
205
+ entry.failed = true;
206
+ publish();
207
+ report(error, { source: entry.source.id });
208
+ }
209
+ throw error;
210
+ }
211
+ });
212
+ entry.queue = result.catch(() => { });
213
+ return result;
214
+ };
215
+ const registerSource = (source) => {
216
+ assertOpen();
217
+ const id = key(source.id);
218
+ if (!id || sources.has(id))
219
+ throw new Error(`Duplicate or empty source ID "${source.id}".`);
220
+ if (!Number.isFinite(source.priority ?? 0))
221
+ throw new Error(`Invalid source priority for "${source.id}".`);
222
+ let completion;
223
+ const entry = {
224
+ source,
225
+ active: true,
226
+ failed: false,
227
+ snapshot: [],
228
+ queue: Promise.resolve(),
229
+ handle: undefined,
230
+ };
231
+ const dispose = () => {
232
+ if (completion)
233
+ return completion;
234
+ entry.active = false;
235
+ sources.delete(id);
236
+ // Revoke before awaiting I/O; old loads can never resurrect a registration.
237
+ let error;
238
+ try {
239
+ entry.unsubscribe?.();
240
+ }
241
+ catch (failure) {
242
+ error = failure;
243
+ }
244
+ reconcile();
245
+ completion = entry.queue.then(() => {
246
+ if (error)
247
+ throw error;
248
+ });
249
+ return completion;
250
+ };
251
+ sources.set(id, entry);
252
+ try {
253
+ entry.unsubscribe = source.subscribe?.(() => {
254
+ void reloadEntry(entry).catch(() => { });
255
+ });
256
+ }
257
+ catch (error) {
258
+ entry.active = false;
259
+ sources.delete(id);
260
+ throw error;
261
+ }
262
+ const ready = reloadEntry(entry);
263
+ // The caller/startup still receives rejection; unawaited registration has an error reporter.
264
+ void ready.catch(() => { });
265
+ entry.handle = {
266
+ ready,
267
+ reload: () => reloadEntry(entry),
268
+ dispose,
269
+ [Symbol.asyncDispose]: dispose,
270
+ };
271
+ publish();
272
+ return entry.handle;
273
+ };
274
+ return {
275
+ state,
276
+ setReady(value) {
277
+ ready = value;
278
+ reconcile();
279
+ },
280
+ registerTask(id, definition, taskContext = context) {
281
+ assertOpen();
282
+ if (!id || tasks.has(key(id)))
283
+ throw new Error(`Duplicate or empty task ID "${id}".`);
284
+ for (const name of definition.requires ?? [])
285
+ getService(taskContext.services, serviceKey(name));
286
+ const task = { definition, context: taskContext, active: true };
287
+ tasks.set(key(id), task);
288
+ reconcile();
289
+ let disposed;
290
+ return () => {
291
+ if (disposed)
292
+ return disposed;
293
+ task.active = false;
294
+ tasks.delete(key(id));
295
+ reconcile();
296
+ const pending = [...runs].filter((run) => run.task === task);
297
+ for (const run of pending)
298
+ run.controller.abort();
299
+ disposed = Promise.allSettled(pending.map((run) => run.promise)).then(() => { });
300
+ return disposed;
301
+ };
302
+ },
303
+ registerSource,
304
+ async reload(id) {
305
+ assertOpen();
306
+ if (id !== undefined) {
307
+ const entry = sources.get(key(id));
308
+ if (!entry)
309
+ throw new Error(`Unknown source "${id}".`);
310
+ await reloadEntry(entry);
311
+ }
312
+ else
313
+ await Promise.all([...sources.values()].map(reloadEntry));
314
+ },
315
+ async unregisterSource(id) {
316
+ await sources.get(key(id))?.handle.dispose();
317
+ },
318
+ registerSchedule(schedule, options) {
319
+ return registerSource({
320
+ id: `manual:${schedule.id}`,
321
+ priority: options?.priority ?? 100,
322
+ load: async () => [schedule],
323
+ });
324
+ },
325
+ run: execute,
326
+ pause(id) {
327
+ assertOpen();
328
+ if (!timers.has(key(id)))
329
+ throw new Error(`Unknown schedule "${id}".`);
330
+ paused.set(key(id), true);
331
+ timers.get(key(id)).cron.pause();
332
+ publish();
333
+ },
334
+ resume(id) {
335
+ assertOpen();
336
+ if (!timers.has(key(id)))
337
+ throw new Error(`Unknown schedule "${id}".`);
338
+ paused.set(key(id), false);
339
+ if (started && ready)
340
+ timers.get(key(id)).cron.resume();
341
+ publish();
342
+ },
343
+ list: () => state.get().schedules,
344
+ async start() {
345
+ assertOpen();
346
+ await Promise.all([...sources.values()].map((entry) => entry.handle.ready));
347
+ assertOpen();
348
+ started = true;
349
+ reconcile();
350
+ },
351
+ stop() {
352
+ if (stopping)
353
+ return stopping;
354
+ stopped = true;
355
+ started = false;
356
+ for (const timer of timers.values())
357
+ timer.cron.stop();
358
+ timers.clear();
359
+ const handles = [...sources.values()].map((entry) => entry.handle);
360
+ for (const run of runs)
361
+ run.controller.abort();
362
+ stopping = Promise.allSettled([
363
+ ...handles.map((handle) => handle.dispose()),
364
+ ...[...runs].map((run) => run.promise),
365
+ ]).then((results) => {
366
+ publish();
367
+ const errors = results
368
+ .slice(0, handles.length)
369
+ .filter((result) => result.status === 'rejected')
370
+ .map((result) => result.reason);
371
+ if (errors.length)
372
+ throw new AggregateError(errors, 'Scheduler source cleanup failed.');
373
+ });
374
+ return stopping;
375
+ },
376
+ };
377
+ }
@@ -0,0 +1,7 @@
1
+ export { defineTask, defineSchedule } from './define.js';
2
+ export { scheduler, schedulerPlugin } from './plugin.js';
3
+ export { createScheduler } from './engine.js';
4
+ export { discoverTasks, discoverSchedules } from './discovered.js';
5
+ export type { TaskEntry, ScheduleEntry, DiscoveredTask } from './discovered.js';
6
+ export { dataSource, urlSource, parseSchedules, parseScheduleDocument, scheduleSchema, } from './sources.js';
7
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { defineTask, defineSchedule } from './define.js';
2
+ export { scheduler, schedulerPlugin } from './plugin.js';
3
+ export { createScheduler } from './engine.js';
4
+ export { discoverTasks, discoverSchedules } from './discovered.js';
5
+ export { dataSource, urlSource, parseSchedules, parseScheduleDocument, scheduleSchema, } from './sources.js';
@@ -0,0 +1,89 @@
1
+ import { type ContributionContext } from '@bitakit/core';
2
+ import type { DiscoveredTask } from './discovered.js';
3
+ import type { Schedule, Scheduler } from './types.js';
4
+ export declare const scheduler: import("@bitakit/core").ServiceKey<Scheduler, "scheduler">;
5
+ /** No platform is started implicitly: install in exactly the runtime that owns these jobs. */
6
+ export declare const schedulerPlugin: {
7
+ readonly id: "scheduler";
8
+ readonly services: readonly [import("@bitakit/core").ServiceOptions & {
9
+ readonly kind: "service";
10
+ create(context: import("@bitakit/core").ServiceContext): Scheduler & {
11
+ start(): Promise<void>;
12
+ stop(): Promise<void>;
13
+ setReady(ready: boolean): void;
14
+ };
15
+ } & {
16
+ readonly id: "scheduler-engine";
17
+ readonly provides: import("@bitakit/core").ServiceKey<Scheduler, "scheduler">;
18
+ }];
19
+ readonly setup: ({ scope, services }: {
20
+ scope: import("@bitakit/core").PluginScope;
21
+ services: import("@bitakit/core").Services;
22
+ }) => () => void;
23
+ readonly events: import("@bitakit/core").EventsDefinition<{
24
+ readonly started: import("@bitakit/core").EventSpec<Readonly<{
25
+ task: string;
26
+ schedule?: string;
27
+ runId: number;
28
+ }>, false>;
29
+ readonly completed: import("@bitakit/core").EventSpec<Readonly<{
30
+ task: string;
31
+ schedule?: string;
32
+ runId: number;
33
+ }>, false>;
34
+ readonly failed: import("@bitakit/core").EventSpec<Readonly<{
35
+ task: string;
36
+ schedule?: string;
37
+ runId: number;
38
+ }>, false>;
39
+ }>;
40
+ readonly installs: {
41
+ readonly 'scheduler.tasks': (values: readonly DiscoveredTask[], context: ContributionContext) => () => Promise<void>;
42
+ readonly 'scheduler.schedules': (values: readonly Schedule[], context: ContributionContext) => () => Promise<void>;
43
+ };
44
+ };
45
+ export default function plugin(): {
46
+ readonly id: "scheduler";
47
+ readonly services: readonly [import("@bitakit/core").ServiceOptions & {
48
+ readonly kind: "service";
49
+ create(context: import("@bitakit/core").ServiceContext): Scheduler & {
50
+ start(): Promise<void>;
51
+ stop(): Promise<void>;
52
+ setReady(ready: boolean): void;
53
+ };
54
+ } & {
55
+ readonly id: "scheduler-engine";
56
+ readonly provides: import("@bitakit/core").ServiceKey<Scheduler, "scheduler">;
57
+ }];
58
+ readonly setup: ({ scope, services }: {
59
+ scope: import("@bitakit/core").PluginScope;
60
+ services: import("@bitakit/core").Services;
61
+ }) => () => void;
62
+ readonly events: import("@bitakit/core").EventsDefinition<{
63
+ readonly started: import("@bitakit/core").EventSpec<Readonly<{
64
+ task: string;
65
+ schedule?: string;
66
+ runId: number;
67
+ }>, false>;
68
+ readonly completed: import("@bitakit/core").EventSpec<Readonly<{
69
+ task: string;
70
+ schedule?: string;
71
+ runId: number;
72
+ }>, false>;
73
+ readonly failed: import("@bitakit/core").EventSpec<Readonly<{
74
+ task: string;
75
+ schedule?: string;
76
+ runId: number;
77
+ }>, false>;
78
+ }>;
79
+ readonly installs: {
80
+ readonly 'scheduler.tasks': (values: readonly DiscoveredTask[], context: ContributionContext) => () => Promise<void>;
81
+ readonly 'scheduler.schedules': (values: readonly Schedule[], context: ContributionContext) => () => Promise<void>;
82
+ };
83
+ };
84
+ declare module '@bitakit/core' {
85
+ interface ContributionMap {
86
+ 'scheduler.tasks': DiscoveredTask;
87
+ 'scheduler.schedules': Schedule;
88
+ }
89
+ }
package/dist/plugin.js ADDED
@@ -0,0 +1,63 @@
1
+ import { defineContract, defineEvents, definePlugin, defineService, event, getService, scopeLifecycle, serviceKey, } from '@bitakit/core';
2
+ import { createScheduler } from './engine.js';
3
+ export const scheduler = defineContract('scheduler').of();
4
+ const schedulerService = defineService((context) => {
5
+ const engine = createScheduler(context, {
6
+ initiallyReady: false,
7
+ dispatch: (id, input, options) => getService(context.services, scheduler).run(id, input, options),
8
+ });
9
+ context.onStart(() => engine.start());
10
+ context.onStop(() => engine.stop());
11
+ return engine;
12
+ }, { id: 'scheduler-engine', provides: scheduler });
13
+ /** No platform is started implicitly: install in exactly the runtime that owns these jobs. */
14
+ export const schedulerPlugin = definePlugin({
15
+ id: 'scheduler',
16
+ services: [schedulerService],
17
+ setup({ scope, services }) {
18
+ const engine = getService(services, serviceKey('scheduler-engine'));
19
+ return scopeLifecycle(scope).watch((snapshot) => engine.setReady(snapshot.phase === 'ready'));
20
+ },
21
+ events: defineEvents({
22
+ started: event(),
23
+ completed: event(),
24
+ failed: event(),
25
+ }),
26
+ installs: {
27
+ 'scheduler.tasks': (values, context) => {
28
+ const service = getService(context.services, scheduler);
29
+ if (!context.config || !context.events || !context.settings)
30
+ throw new Error('Task contributions require a Core runtime that supplies the contributing owner context.');
31
+ const owner = {
32
+ services: context.services,
33
+ config: context.config,
34
+ events: context.events,
35
+ settings: context.settings,
36
+ };
37
+ const releases = [];
38
+ try {
39
+ for (const { id, definition } of values)
40
+ releases.push(service.registerTask(id, definition, owner));
41
+ }
42
+ catch (error) {
43
+ for (const release of releases)
44
+ void release();
45
+ throw error;
46
+ }
47
+ return async () => {
48
+ await Promise.all(releases.reverse().map((release) => release()));
49
+ };
50
+ },
51
+ 'scheduler.schedules': (values, context) => {
52
+ const registration = getService(context.services, scheduler).registerSource({
53
+ id: `defaults:${context.module}`,
54
+ priority: -100,
55
+ load: async () => values,
56
+ });
57
+ return () => registration.dispose();
58
+ },
59
+ },
60
+ });
61
+ export default function plugin() {
62
+ return schedulerPlugin;
63
+ }
@@ -0,0 +1,9 @@
1
+ import type { ScheduleSource } from '../types.js';
2
+ /** Node-only runtime file source. Watches the directory so atomic file replacement is observed. */
3
+ export declare function fileSource(options: {
4
+ id: string;
5
+ path: string;
6
+ priority?: number;
7
+ format?: 'json' | 'yaml';
8
+ watch?: boolean;
9
+ }): ScheduleSource;
@@ -0,0 +1,33 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { watch } from 'node:fs';
3
+ import { dirname, basename, extname } from 'node:path';
4
+ import { parseScheduleDocument } from '../sources.js';
5
+ /** Node-only runtime file source. Watches the directory so atomic file replacement is observed. */
6
+ export function fileSource(options) {
7
+ let watcherError;
8
+ return {
9
+ id: options.id,
10
+ priority: options.priority,
11
+ async load() {
12
+ if (watcherError)
13
+ throw watcherError;
14
+ return parseScheduleDocument(await readFile(options.path, 'utf8'), options.format ?? (extname(options.path).toLowerCase() === '.json' ? 'json' : 'yaml'));
15
+ },
16
+ ...(options.watch === false
17
+ ? {}
18
+ : {
19
+ subscribe(onChange) {
20
+ const watcher = watch(dirname(options.path), (_event, name) => {
21
+ if (name === null || name.toString() === basename(options.path))
22
+ onChange();
23
+ });
24
+ // A watcher error requests a reload; the source reports any read failure normally.
25
+ watcher.on('error', (error) => {
26
+ watcherError = error;
27
+ onChange();
28
+ });
29
+ return () => watcher.close();
30
+ },
31
+ }),
32
+ };
33
+ }
@@ -0,0 +1,31 @@
1
+ import { z } from 'zod';
2
+ import type { Schedule, ScheduleSource } from './types.js';
3
+ /** External sources contain data only; Croner validates cron/date/timezone semantics. */
4
+ export declare const scheduleSchema: z.ZodUnion<readonly [z.ZodObject<{
5
+ cron: z.ZodString;
6
+ id: z.ZodString;
7
+ task: z.ZodString;
8
+ input: z.ZodOptional<z.ZodJSONSchema>;
9
+ timezone: z.ZodOptional<z.ZodString>;
10
+ paused: z.ZodOptional<z.ZodBoolean>;
11
+ }, z.core.$strict>, z.ZodObject<{
12
+ at: z.ZodISODateTime;
13
+ id: z.ZodString;
14
+ task: z.ZodString;
15
+ input: z.ZodOptional<z.ZodJSONSchema>;
16
+ timezone: z.ZodOptional<z.ZodString>;
17
+ paused: z.ZodOptional<z.ZodBoolean>;
18
+ }, z.core.$strict>]>;
19
+ export declare function parseSchedules(data: unknown): Schedule[];
20
+ export declare function parseScheduleDocument(text: string, format: 'json' | 'yaml'): Schedule[];
21
+ /** A callback may read a DB or CMS using its ordinary server-side authorization. */
22
+ export declare function dataSource(source: ScheduleSource): ScheduleSource;
23
+ /** Fetches a complete data snapshot on registration, explicit reload or subscribed changes. */
24
+ export declare function urlSource(options: {
25
+ id: string;
26
+ url: string | URL;
27
+ priority?: number;
28
+ format?: 'json' | 'yaml';
29
+ fetch?: typeof globalThis.fetch;
30
+ subscribe?: ScheduleSource['subscribe'];
31
+ }): ScheduleSource;
@@ -0,0 +1,40 @@
1
+ import { parse } from 'yaml';
2
+ import { z } from 'zod';
3
+ const common = {
4
+ id: z.string().min(1),
5
+ task: z.string().min(1),
6
+ input: z.json().optional(),
7
+ timezone: z.string().optional(),
8
+ paused: z.boolean().optional(),
9
+ };
10
+ /** External sources contain data only; Croner validates cron/date/timezone semantics. */
11
+ export const scheduleSchema = z.union([
12
+ z.strictObject({ ...common, cron: z.string().min(1) }),
13
+ z.strictObject({ ...common, at: z.iso.datetime({ offset: true }) }),
14
+ ]);
15
+ export function parseSchedules(data) {
16
+ return z.array(scheduleSchema).parse(data);
17
+ }
18
+ export function parseScheduleDocument(text, format) {
19
+ return parseSchedules(format === 'yaml' ? parse(text) : JSON.parse(text));
20
+ }
21
+ /** A callback may read a DB or CMS using its ordinary server-side authorization. */
22
+ export function dataSource(source) {
23
+ return source;
24
+ }
25
+ /** Fetches a complete data snapshot on registration, explicit reload or subscribed changes. */
26
+ export function urlSource(options) {
27
+ return {
28
+ id: options.id,
29
+ priority: options.priority,
30
+ subscribe: options.subscribe,
31
+ async load() {
32
+ const response = await (options.fetch ?? globalThis.fetch)(options.url, {
33
+ cache: 'no-store',
34
+ });
35
+ if (!response.ok)
36
+ throw new Error(`Schedule source "${options.id}" returned HTTP ${response.status}.`);
37
+ return parseScheduleDocument(await response.text(), options.format ?? 'json');
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,95 @@
1
+ import type { ContributionInstallerContext as ContributionContext, GeneratedName, CheckedName, NamedValue, InputSchema, ServiceContext, Store } from '@bitakit/core';
2
+ /** Discovery augments this map with task definitions. */
3
+ export interface TaskMap {
4
+ }
5
+ export interface ScheduleMap {
6
+ }
7
+ export type TaskId = GeneratedName<Extract<keyof TaskMap, string>>;
8
+ /** Sources may add IDs at runtime; discovery supplies suggestions, not a closed set. */
9
+ export type ScheduleId = Extract<keyof ScheduleMap, string> | (string & {});
10
+ export type TaskContext<Input = unknown> = Pick<ContributionContext, 'services' | 'config' | 'events' | 'settings'> & {
11
+ input: Input;
12
+ signal: AbortSignal;
13
+ };
14
+ export type TaskDefinition<Input = unknown, Result = unknown> = {
15
+ readonly kind: 'task';
16
+ input?: InputSchema<Input>;
17
+ requires?: readonly string[];
18
+ /** Domain authorization belongs here or in the called service and runs on every invocation. */
19
+ execute(context: TaskContext<Input>): Result | Promise<Result>;
20
+ };
21
+ export type TaskInput<Id extends string> = NamedValue<TaskMap, Id> extends TaskDefinition<infer I, any> ? I : unknown;
22
+ export type TaskResult<Id extends string> = NamedValue<TaskMap, Id> extends TaskDefinition<any, infer R> ? Awaited<R> : unknown;
23
+ export type Schedule = {
24
+ id: string;
25
+ task: string;
26
+ input?: unknown;
27
+ timezone?: string;
28
+ paused?: boolean;
29
+ } & ({
30
+ cron: string;
31
+ at?: never;
32
+ } | {
33
+ at: string;
34
+ cron?: never;
35
+ });
36
+ export type ScheduleOptions = Omit<Extract<Schedule, {
37
+ cron: string;
38
+ }>, 'id'> | Omit<Extract<Schedule, {
39
+ at: string;
40
+ }>, 'id'>;
41
+ export type ScheduleDefinition = ScheduleOptions & {
42
+ readonly kind: 'schedule';
43
+ };
44
+ export type ScheduleSource = {
45
+ id: string;
46
+ /** Higher wins; equal priorities use case-folded source ID ascending (last wins). */
47
+ priority?: number;
48
+ load(): Promise<readonly Schedule[]>;
49
+ subscribe?(onChange: () => void): () => void;
50
+ };
51
+ export type SourceRegistration = {
52
+ ready: Promise<void>;
53
+ reload(): Promise<void>;
54
+ /** Immediately revokes the source, then awaits pending loads and restores lower priorities. */
55
+ dispose(): Promise<void>;
56
+ [Symbol.asyncDispose](): Promise<void>;
57
+ };
58
+ export type ScheduleStatus = Readonly<{
59
+ id: string;
60
+ task: string;
61
+ source: string;
62
+ paused: boolean;
63
+ nextRun: string | null;
64
+ }>;
65
+ export type SchedulerState = Readonly<{
66
+ running: number;
67
+ schedules: readonly ScheduleStatus[];
68
+ sources: readonly {
69
+ id: string;
70
+ failed: boolean;
71
+ }[];
72
+ }>;
73
+ export type SchedulerNotice = Readonly<{
74
+ task: string;
75
+ schedule?: string;
76
+ runId: number;
77
+ }>;
78
+ export type RunOptions = {
79
+ schedule?: string;
80
+ };
81
+ export interface Scheduler {
82
+ readonly state: Store<SchedulerState>;
83
+ registerTask<Input, Result>(id: string, task: TaskDefinition<Input, Result>, context?: Pick<ContributionContext, 'services' | 'config' | 'events' | 'settings'>): () => Promise<void>;
84
+ registerSource(source: ScheduleSource): SourceRegistration;
85
+ reload(id?: string): Promise<void>;
86
+ unregisterSource(id: string): Promise<void>;
87
+ registerSchedule(schedule: Schedule, options?: {
88
+ priority?: number;
89
+ }): SourceRegistration;
90
+ run<const Id extends string>(id: Id & CheckedName<Id, Extract<keyof TaskMap, string>>, input?: TaskInput<Id>, options?: RunOptions): Promise<TaskResult<Id>>;
91
+ pause(id: ScheduleId): void;
92
+ resume(id: ScheduleId): void;
93
+ list(): readonly ScheduleStatus[];
94
+ }
95
+ export type SchedulerContext = Pick<ServiceContext, 'services' | 'config' | 'events' | 'settings' | 'store'>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ # Audit example plugin
2
+
3
+ `plugin.ts` observes the existing scheduler service's `run` method. It logs call ID, task ID,
4
+ optional schedule ID and elapsed milliseconds; never task inputs, results or raw errors.
5
+ Service interceptors already observe across plugins and have no Action-style scope option.
6
+ Logging is observational, not awaited or durable. A production consumer may replace console
7
+ calls with its own authorized DB/file service and must handle that service's failures.
8
+ Verify that the scheduler tests report one trace per automatic or manual invocation.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,16 @@
1
+ import { defineInterceptor, definePlugin } from '@bitakit/core';
2
+
3
+ export default definePlugin({
4
+ id: 'audit',
5
+ interceptors: [
6
+ defineInterceptor({
7
+ service: 'scheduler',
8
+ method: 'run',
9
+ before: ({ callId, args }) => {
10
+ console.info('Task started', { callId, task: args[0], schedule: args[2]?.schedule });
11
+ },
12
+ after: ({ callId, durationMs }) => console.info('Task completed', { callId, durationMs }),
13
+ onError: ({ callId, durationMs }) => console.error('Task failed', { callId, durationMs }),
14
+ }),
15
+ ],
16
+ });
@@ -0,0 +1,8 @@
1
+ # File schedules example plugin
2
+
3
+ `server/plugin.ts` declares `file-schedules.source`, requiring the shared scheduler contract.
4
+ Its lifecycle owns source `host-file` at priority 10, using `BITAKIT_SCHEDULE_FILE` or the adjacent
5
+ YAML fixture. This is Node-only code, never browser discovery input. Changes to the YAML are
6
+ read at runtime; removing the override restores the reports default. Always register cleanup
7
+ before awaiting the initial load. This example adds no persistence, tenant policy or new adapter
8
+ registry. Verify through `examples/server/main.ts --once` and the file source tests.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,29 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { definePlugin, defineService, getService } from '@bitakit/core';
3
+ import { scheduler } from '@bitakit/scheduler';
4
+ import { fileSource } from '@bitakit/scheduler/server';
5
+
6
+ export default definePlugin({
7
+ id: 'file-schedules',
8
+ services: {
9
+ source: defineService(
10
+ ({ services, onStart, onStop }) => {
11
+ onStart(async () => {
12
+ const registration = getService(services, scheduler).registerSource(
13
+ fileSource({
14
+ id: 'host-file',
15
+ priority: 10,
16
+ path:
17
+ process.env.BITAKIT_SCHEDULE_FILE ??
18
+ fileURLToPath(new URL('./schedules.yaml', import.meta.url)),
19
+ }),
20
+ );
21
+ onStop(() => registration.dispose());
22
+ await registration.ready;
23
+ });
24
+ return {};
25
+ },
26
+ { requires: [scheduler] },
27
+ ),
28
+ },
29
+ });
@@ -0,0 +1,6 @@
1
+ - id: REPORTS.WEEKLY
2
+ task: Reports.Weekly
3
+ cron: '0 10 * * MON'
4
+ timezone: Europe/Berlin
5
+ input:
6
+ audience: team
@@ -0,0 +1,8 @@
1
+ # Reports example plugin
2
+
3
+ Declares `reports.weekly` as both a task and a default schedule in separate namespaces.
4
+ The task accepts `{ audience: string }` and returns an example result; it sends no real mail.
5
+ The default runs Mondays at 09:00 Europe/Berlin. Keep executable code in `contributions/tasks`
6
+ and schedule data in `contributions/schedules`. Domain authorization belongs in real business
7
+ services. See the scheduler package guide for runtime ownership and source overrides.
8
+ Verify with the package tests and `examples/server/main.ts --once`.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,8 @@
1
+ import { defineSchedule } from '@bitakit/scheduler';
2
+
3
+ export default defineSchedule({
4
+ task: 'reports.weekly',
5
+ cron: '0 9 * * MON',
6
+ timezone: 'Europe/Berlin',
7
+ input: { audience: 'team' },
8
+ });
@@ -0,0 +1,11 @@
1
+ import { defineTask } from '@bitakit/scheduler';
2
+ import { z } from 'zod';
3
+
4
+ export default defineTask({
5
+ input: z.object({ audience: z.string() }),
6
+ execute: async ({ input, signal }) => {
7
+ signal.throwIfAborted();
8
+ // Replace this example result with an authorized business service call.
9
+ return { delivered: input.audience };
10
+ },
11
+ });
@@ -0,0 +1,43 @@
1
+ import { createRuntime, definePlugin, discoveredFile, getService } from '@bitakit/core';
2
+ import { schedulerPlugin, scheduler, discoverTasks, discoverSchedules } from '@bitakit/scheduler';
3
+ import task from '../reports/contributions/tasks/weekly.ts';
4
+ import schedule from '../reports/contributions/schedules/weekly.ts';
5
+ import fileSchedules from '../file-schedules/server/plugin.ts';
6
+ import audit from '../audit/plugin.ts';
7
+
8
+ // Server discovery is not generated yet: compose the same declarations explicitly.
9
+ const reports = definePlugin({
10
+ id: 'reports',
11
+ contributions: {
12
+ 'scheduler.tasks': discoverTasks(
13
+ [discoveredFile(task, 'weekly', 'reports/contributions/tasks/weekly.ts')],
14
+ 'reports',
15
+ ),
16
+ 'scheduler.schedules': discoverSchedules(
17
+ [discoveredFile(schedule, 'weekly', 'reports/contributions/schedules/weekly.ts')],
18
+ 'reports',
19
+ ),
20
+ },
21
+ });
22
+ const runtime = createRuntime({ plugins: [schedulerPlugin, reports, fileSchedules, audit] });
23
+ const stop = runtime.mount();
24
+ try {
25
+ await runtime.ready;
26
+ if (process.argv.includes('--once')) {
27
+ await getService(runtime.services, scheduler).run('reports.weekly', { audience: 'team' });
28
+ await stop();
29
+ } else {
30
+ const shutdown = () => {
31
+ void stop().catch((error) => {
32
+ console.error(error);
33
+ process.exitCode = 1;
34
+ });
35
+ };
36
+ process.once('SIGINT', shutdown);
37
+ process.once('SIGTERM', shutdown);
38
+ console.info('Scheduler ready. Edit the YAML file or send SIGINT to stop.');
39
+ }
40
+ } catch (error) {
41
+ await stop();
42
+ throw error;
43
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "allowImportingTsExtensions": true,
9
+ "skipLibCheck": true
10
+ },
11
+ "include": ["**/*.ts"]
12
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@bitakit/scheduler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "files": [
7
+ "dist",
8
+ "README.md",
9
+ "AGENTS.md",
10
+ "CLAUDE.md",
11
+ "discovery.mjs",
12
+ "examples"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./plugin": {
20
+ "types": "./dist/plugin.d.ts",
21
+ "default": "./dist/plugin.js"
22
+ },
23
+ "./server": {
24
+ "types": "./dist/server/index.d.ts",
25
+ "default": "./dist/server/index.js"
26
+ },
27
+ "./discovery": "./discovery.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "test": "npm run build && node --test tests/*.test.mjs",
33
+ "prepack": "npm run build"
34
+ },
35
+ "dependencies": {
36
+ "@bitakit/core": "^0.2.9",
37
+ "croner": "^11.0.0",
38
+ "fast-deep-equal": "^3.1.3",
39
+ "yaml": "^2.9.1",
40
+ "zod": "^4.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^24.0.0",
44
+ "typescript": "^5.9.3",
45
+ "@bitakit/discovery": "^0.2.6",
46
+ "jiti": "^2.7.0"
47
+ },
48
+ "description": "UI-free in-process task scheduling and runtime schedule sources for BitaKit.",
49
+ "license": "MIT",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/mvavesal/bitakit.git",
53
+ "directory": "packages/scheduler"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "keywords": [
59
+ "bitakit",
60
+ "scheduler",
61
+ "cron"
62
+ ],
63
+ "bitakit": {
64
+ "plugin": "./plugin",
65
+ "discovery": "./discovery"
66
+ }
67
+ }