@tempo-kit/plugin-ticker 0.0.0-stage → 3.0.0-rc.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/dist/index.js ADDED
@@ -0,0 +1,557 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // auto-inject-version:tempo-kit/plugin/sdk
20
+ var sdk_exports = {};
21
+ __export(sdk_exports, {
22
+ definePlugin: () => definePlugin,
23
+ defineTerm: () => defineTerm
24
+ });
25
+ __reExport(sdk_exports, sdk_star);
26
+ import * as sdk_star from "tempo-kit/plugin/sdk";
27
+ import { definePlugin as originalPlugin, defineTerm as originalTerm } from "tempo-kit/plugin/sdk";
28
+ var definePlugin = (config) => originalPlugin({ ...config, version: "3.0.0-rc.0" });
29
+ var defineTerm = (config) => originalTerm({ ...config, version: "3.0.0-rc.0" });
30
+
31
+ // src/index.ts
32
+ var ACTIVE_TICKERS = /* @__PURE__ */ new Set();
33
+ var PROXY_SIGNAL = /* @__PURE__ */ Symbol.for("Tempo.ticker.cachedSignal");
34
+ var INSTANCE_KEY = /* @__PURE__ */ Symbol.for("Tempo.ticker.instance");
35
+ var Ticker = {
36
+ get active() {
37
+ const result = [];
38
+ for (const entry of ACTIVE_TICKERS) {
39
+ const t = entry.ref.deref();
40
+ if ((0, sdk_exports.isUndefined)(t) || t.info.stopped) {
41
+ ACTIVE_TICKERS.delete(entry);
42
+ } else {
43
+ const { label, next, ticks, limit, interval, rrule, cron, stopped, ntp } = t.info;
44
+ result.push({ ticker: t, label, next, ticks, limit, interval, rrule, cron, stopped, ntp });
45
+ }
46
+ }
47
+ return result;
48
+ }
49
+ };
50
+ var TickerInstance = class {
51
+ #TempoClass;
52
+ #label;
53
+ #payload = {};
54
+ #rrule;
55
+ #cron;
56
+ #next;
57
+ #until;
58
+ #limit;
59
+ #ticks = 0;
60
+ #stopped = false;
61
+ #genFirstYielded = false;
62
+ #isForward = true;
63
+ #isInstant = false;
64
+ #isShorthand = false;
65
+ #schedId;
66
+ #reactive;
67
+ #catchListeners = /* @__PURE__ */ new Set();
68
+ #stopListeners = /* @__PURE__ */ new Set();
69
+ #hasInvalidSchedule = false;
70
+ #isCatch = false;
71
+ #useNtp = false;
72
+ #isNtpCalibratedSeeded = false;
73
+ #hasExplicitFutureSeed = false;
74
+ #options;
75
+ #selfRef;
76
+ #activeEntry = void 0;
77
+ #cachedSignal = void 0;
78
+ constructor(TempoClass, arg1, arg2) {
79
+ this.#TempoClass = TempoClass;
80
+ let rawOptions = {};
81
+ let cb;
82
+ const isDateLike = (obj) => (0, sdk_exports.isObject)(obj) && ("epoch" in obj || "epochMilliseconds" in obj || "toZonedDateTimeISO" in obj || "getTime" in obj);
83
+ const isOptions = (obj) => (0, sdk_exports.isObject)(obj) && !isDateLike(obj);
84
+ switch (true) {
85
+ case (0, sdk_exports.isFunction)(arg1):
86
+ cb = arg1;
87
+ break;
88
+ case isOptions(arg1):
89
+ Object.assign(rawOptions, arg1);
90
+ if ((0, sdk_exports.isFunction)(arg2)) cb = arg2;
91
+ else if (isOptions(arg2)) Object.assign(rawOptions, arg2);
92
+ break;
93
+ default:
94
+ if ((0, sdk_exports.isNotNullish)(arg1)) {
95
+ if ((0, sdk_exports.isCronString)(arg1)) {
96
+ rawOptions.cron = arg1;
97
+ } else if ((0, sdk_exports.isRRuleString)(arg1)) {
98
+ rawOptions.rrule = arg1;
99
+ } else {
100
+ const num = Number(arg1);
101
+ if ((0, sdk_exports.isNumeric)(arg1)) rawOptions.seconds = num;
102
+ else rawOptions.seed = arg1;
103
+ }
104
+ }
105
+ if ((0, sdk_exports.isFunction)(arg2)) cb = arg2;
106
+ else if (isOptions(arg2)) Object.assign(rawOptions, arg2);
107
+ }
108
+ if ((0, sdk_exports.isNotNullish)(rawOptions.interval) && (0, sdk_exports.isNullish)(rawOptions.seconds) && (0, sdk_exports.isNullish)(rawOptions.cron) && (0, sdk_exports.isNullish)(rawOptions.rrule)) {
109
+ const intVal = rawOptions.interval;
110
+ if ((0, sdk_exports.isCronString)(intVal)) rawOptions.cron = intVal;
111
+ else if ((0, sdk_exports.isRRuleString)(intVal)) rawOptions.rrule = intVal;
112
+ else if ((0, sdk_exports.isNumeric)(intVal)) rawOptions.seconds = Number(intVal);
113
+ else rawOptions.seed = intVal;
114
+ }
115
+ const { label, limit: lmt, until: stopAt, seed: startAt, rrule: rruleOption, cron: cronOption, ntp: useNtp, ...rest } = rawOptions;
116
+ this.#options = rest;
117
+ this.#label = label;
118
+ this.#limit = lmt;
119
+ this.#useNtp = Boolean(useNtp);
120
+ this.#isNtpCalibratedSeeded = Boolean(this.#useNtp && this.#TempoClass.ntp?.isCalibrated);
121
+ if (rruleOption)
122
+ this.#rrule = (0, sdk_exports.isString)(rruleOption) ? rruleOption : rruleOption.rrule;
123
+ this.#isCatch = Boolean(rawOptions.catch ?? this.#TempoClass.config?.catch);
124
+ this.#reactive = new sdk_exports.Reactive({
125
+ tag: this.#label ?? "Ticker",
126
+ catch: this.#isCatch
127
+ });
128
+ if ((0, sdk_exports.isNotNullish)(cronOption)) {
129
+ if (!(0, sdk_exports.isCronString)(cronOption)) {
130
+ this.#hasInvalidSchedule = true;
131
+ (0, sdk_exports.logError)(new Error(`Invalid Ticker cron schedule: ${String(cronOption)}`), { ...this.#options, catch: this.#isCatch });
132
+ } else {
133
+ this.#cron = cronOption;
134
+ }
135
+ }
136
+ if (cb) this.#reactive.on("data", (t) => cb(t, () => this.stop()));
137
+ for (const [key, val] of Object.entries(rest))
138
+ if ((0, sdk_exports.isNotNullish)(val) && (key.startsWith("#") || sdk_exports.Enum.has(sdk_exports.enums.DURATIONS, key) || sdk_exports.Enum.has(sdk_exports.enums.ELEMENT, key)))
139
+ this.#payload[key] = val;
140
+ const isSeed = (0, sdk_exports.isNotNullish)(rawOptions.seed);
141
+ const isRRule = (0, sdk_exports.isNotNullish)(this.#rrule);
142
+ const isCron = (0, sdk_exports.isNotNullish)(this.#cron);
143
+ const isInterval = !(0, sdk_exports.isEmpty)(this.#payload) || (0, sdk_exports.isNotNullish)(rawOptions.seconds) && (0, sdk_exports.isNumber)(rawOptions.seconds);
144
+ if ((0, sdk_exports.isNotNullish)(arg1) && !isOptions(arg1) && !isInterval && !isSeed && !isRRule && !isCron && !cb)
145
+ (0, sdk_exports.logError)(new Error(`Invalid Ticker interval, seed, cron, or rrule: ${String(arg1)}`), { ...this.#options, catch: this.#isCatch });
146
+ this.#until = stopAt ? new this.#TempoClass(isOptions(stopAt) ? void 0 : stopAt, isOptions(stopAt) ? { ...rest, ...stopAt } : rest) : void 0;
147
+ if ((0, sdk_exports.isEmpty)(this.#payload) && !isRRule && !isCron && !this.#hasInvalidSchedule) {
148
+ if ((0, sdk_exports.isNotNullish)(startAt)) this.#limit ??= 1;
149
+ else this.#payload.seconds = 1;
150
+ }
151
+ (0, sdk_exports.normaliseFractionalDurations)(this.#payload);
152
+ if ((0, sdk_exports.isNotNullish)(startAt)) {
153
+ this.#next = new this.#TempoClass(isOptions(startAt) ? void 0 : startAt, isOptions(startAt) ? { ...rest, ...startAt } : rest);
154
+ this.#hasExplicitFutureSeed = (!isOptions(startAt) || (0, sdk_exports.isNotNullish)(startAt.epoch)) && this.#next.epoch.ms > (0, sdk_exports.instant)().epochMilliseconds;
155
+ } else if (this.#useNtp && (0, sdk_exports.isFunction)(this.#TempoClass.ntp?.now)) {
156
+ this.#next = this.#TempoClass.ntp.now(rest);
157
+ } else {
158
+ this.#next = new this.#TempoClass(void 0, rest);
159
+ }
160
+ }
161
+ /** explicitly set the proxy-self (called by factory) */
162
+ bootstrap(proxy) {
163
+ this.#selfRef = new WeakRef(proxy);
164
+ this.#activeEntry = { ref: this.#selfRef, token: /* @__PURE__ */ Object.create(null) };
165
+ if (this.#limit === 0) {
166
+ this.stop();
167
+ return proxy;
168
+ }
169
+ if (this.#hasInvalidSchedule) {
170
+ this.stop();
171
+ return proxy;
172
+ }
173
+ if (!this.#next.isValid) {
174
+ this.stop();
175
+ (0, sdk_exports.logError)(new Error(`Invalid Ticker seed: ${String(this.#next)}`), this.#next.config);
176
+ } else if (this.#until && !this.#until.isValid) {
177
+ this.stop();
178
+ (0, sdk_exports.logError)(new Error(`Invalid Ticker boundary: ${String(this.#until)}`), this.#next.config);
179
+ } else {
180
+ try {
181
+ if (this.#cron || this.#rrule) {
182
+ this.#isForward = true;
183
+ this.#isInstant = false;
184
+ ACTIVE_TICKERS.add(this.#activeEntry);
185
+ this.#runBootstrap();
186
+ } else {
187
+ const hasShorthand = Object.entries(this.#payload).some(
188
+ ([k, v]) => k.startsWith("#") && (0, sdk_exports.isString)(v) && /^[<>]/.test(v.trim())
189
+ );
190
+ const hasRelative = Object.keys(this.#payload).some((k) => !k.startsWith("#"));
191
+ if (hasShorthand && hasRelative)
192
+ throw new Error(`Ambiguous Ticker payload: cannot mix directional shorthand terms (e.g. '>') with relative durations (e.g. 'hours'). Use one or the other.`);
193
+ this.#isShorthand = hasShorthand;
194
+ const hasTermKey = Object.keys(this.#payload).some((k) => k.startsWith("#"));
195
+ const firstStep = this.#isShorthand ? this.#next.set(this.#payload) : this.#next.add(this.#payload);
196
+ if (!firstStep.isValid) throw new Error(`Invalid Ticker payload resolution for ${JSON.stringify(this.#payload)}`);
197
+ this.#isForward = this.#TempoClass.compare(firstStep, this.#next) >= 0;
198
+ this.#isInstant = firstStep.epoch.ns === this.#next.epoch.ns;
199
+ if (hasTermKey) this.#next = firstStep;
200
+ ACTIVE_TICKERS.add(this.#activeEntry);
201
+ this.#runBootstrap();
202
+ }
203
+ } catch (e) {
204
+ this.stop();
205
+ const msg = `Invalid Ticker payload resolution for ${JSON.stringify(this.#payload)}`;
206
+ (0, sdk_exports.logError)(new Error(msg), this.#next.config);
207
+ queueMicrotask(() => this.#catchListeners.forEach((l) => l(this.#next, () => this.stop())));
208
+ this.#isForward = true;
209
+ this.#isInstant = false;
210
+ }
211
+ }
212
+ return proxy;
213
+ }
214
+ #delayMs() {
215
+ const isCalibrated = this.#useNtp && Boolean(this.#TempoClass.ntp?.isCalibrated);
216
+ if (isCalibrated && !this.#isNtpCalibratedSeeded && !this.#hasExplicitFutureSeed && this.#ticks === 0 && (0, sdk_exports.isFunction)(this.#TempoClass.ntp?.now)) {
217
+ this.#next = this.#TempoClass.ntp.now(this.#options);
218
+ const hasTermKey = Object.keys(this.#payload).some((k) => k.startsWith("#"));
219
+ if (hasTermKey)
220
+ this.#next = this.#isShorthand ? this.#next.set(this.#payload) : this.#next.add(this.#payload);
221
+ this.#isNtpCalibratedSeeded = true;
222
+ }
223
+ const currentEpochMs = isCalibrated && (0, sdk_exports.isFunction)(this.#TempoClass.ntp?.now) ? this.#TempoClass.ntp.now().epoch.ms : (0, sdk_exports.instant)().epochMilliseconds;
224
+ const diff = Math.round(this.#next.epoch.ms - currentEpochMs);
225
+ if (diff > 0) return Math.min(diff, 2147483647);
226
+ if (!this.#isForward) {
227
+ const stepMs = Math.abs(Math.round(this.#next.add(this.#payload).epoch.ms - this.#next.epoch.ms));
228
+ return Math.max(20, Math.min(50, stepMs || 1e3));
229
+ }
230
+ return 0;
231
+ }
232
+ #safePulse() {
233
+ try {
234
+ return this.pulse();
235
+ } catch (e) {
236
+ const catchListeners = [...this.#catchListeners];
237
+ this.stop();
238
+ catchListeners.forEach((l) => l(this.#next, () => this.stop()));
239
+ if (!this.#isCatch)
240
+ throw e;
241
+ return this.#next;
242
+ }
243
+ }
244
+ #scheduleNext() {
245
+ if (this.#stopped || this.#isInstant) return;
246
+ this.#schedId = setTimeout(() => {
247
+ if (!this.#stopped) {
248
+ this.#safePulse();
249
+ this.#scheduleNext();
250
+ }
251
+ }, this.#delayMs());
252
+ }
253
+ #runBootstrap() {
254
+ if ((this.#reactive.state.subscribers > 0 || this.#reactive.state.queued > 0) && !this.#stopped && !this.#schedId) {
255
+ const delay = this.#delayMs();
256
+ if (delay > 0) {
257
+ this.#schedId = setTimeout(() => {
258
+ if (!this.#stopped) {
259
+ this.#safePulse();
260
+ this.#scheduleNext();
261
+ }
262
+ }, delay);
263
+ } else {
264
+ this.#safePulse();
265
+ this.#scheduleNext();
266
+ }
267
+ }
268
+ }
269
+ /**
270
+ * Advances one tick, publishes it to listeners and pending pulls, and stops at the configured limit or end.
271
+ * Returns the tick, or a Tempo constructed from null if already stopped. An invalid next tick stops the ticker
272
+ * and is returned after notifying catch listeners. Errors from advancing or notifying listeners may propagate.
273
+ */
274
+ pulse() {
275
+ if (this.#stopped) return new this.#TempoClass(null, this.#next.config);
276
+ const t = this.#next;
277
+ if (!t.isValid) {
278
+ const catchListeners = [...this.#catchListeners];
279
+ this.stop();
280
+ catchListeners.forEach((l) => l(t, () => this.stop()));
281
+ return t;
282
+ }
283
+ if (this.#cron) {
284
+ const nextMs = (0, sdk_exports.getNextCronEpoch)(this.#cron, t.epoch.ms, t.tz);
285
+ this.#next = new this.#TempoClass(nextMs, t.config);
286
+ } else if (this.#rrule) {
287
+ const nextMs = (0, sdk_exports.getNextRRuleEpoch)(this.#rrule, t.epoch.ms);
288
+ this.#next = new this.#TempoClass(nextMs, t.config);
289
+ } else {
290
+ this.#next = this.#isInstant ? t : this.#isShorthand ? t.set(this.#payload) : t.add(this.#payload);
291
+ }
292
+ this.#ticks++;
293
+ const willStop = this.#limit !== void 0 && this.#ticks >= this.#limit || (0, sdk_exports.isNotNullish)(this.#until) && (this.#isForward && this.#TempoClass.compare(t, this.#until) >= 0 || !this.#isForward && this.#TempoClass.compare(t, this.#until) <= 0);
294
+ if (this.#stopped && this.#limit === 0) return t;
295
+ this.#reactive.cast(t);
296
+ if (willStop)
297
+ this.stop();
298
+ return t;
299
+ }
300
+ on(event, cb) {
301
+ if (event === "pulse") {
302
+ this.#reactive.on("data", (t) => cb(t, () => this.stop()));
303
+ this.#runBootstrap();
304
+ } else if (event === "catch") {
305
+ this.#catchListeners.add(cb);
306
+ } else if (event === "stop") {
307
+ this.#stopListeners.add(cb);
308
+ }
309
+ return this;
310
+ }
311
+ stop(terminalValue) {
312
+ if (this.#stopped) return;
313
+ this.#stopped = true;
314
+ if (this.#activeEntry) {
315
+ ACTIVE_TICKERS.delete(this.#activeEntry);
316
+ this.#activeEntry = void 0;
317
+ }
318
+ if (this.#schedId) {
319
+ clearTimeout(this.#schedId);
320
+ this.#schedId = void 0;
321
+ }
322
+ if (terminalValue !== void 0)
323
+ this.#next = terminalValue;
324
+ this.#reactive.complete(terminalValue);
325
+ const proxy = this.#selfRef?.deref();
326
+ if (proxy && proxy[PROXY_SIGNAL]) {
327
+ proxy[PROXY_SIGNAL].dispose?.();
328
+ delete proxy[PROXY_SIGNAL];
329
+ }
330
+ if (this.#cachedSignal) {
331
+ this.#cachedSignal.dispose?.();
332
+ this.#cachedSignal = void 0;
333
+ }
334
+ const stopListeners = [...this.#stopListeners];
335
+ this.#stopListeners.clear();
336
+ this.#catchListeners.clear();
337
+ for (const l of stopListeners)
338
+ l(this.#next, () => void 0);
339
+ }
340
+ get [Symbol.toStringTag]() {
341
+ return "Tempo.Ticker";
342
+ }
343
+ get info() {
344
+ return {
345
+ label: this.#label,
346
+ next: this.#next,
347
+ ticks: this.#ticks,
348
+ limit: this.#limit,
349
+ interval: { ...this.#payload },
350
+ rrule: this.#rrule,
351
+ cron: this.#cron,
352
+ stopped: this.#stopped,
353
+ ntp: this.#useNtp
354
+ };
355
+ }
356
+ async pull() {
357
+ const res = await this.next();
358
+ return res.done ? void 0 : res.value;
359
+ }
360
+ until(notifier) {
361
+ const stream = this.#reactive.until(notifier);
362
+ this.#runBootstrap();
363
+ return stream;
364
+ }
365
+ toSignal(...args) {
366
+ const self = this;
367
+ const initial = args.length > 0 ? args[0] : this.#next;
368
+ const sig = this.#reactive.toSignal(initial);
369
+ this.#runBootstrap();
370
+ let isDisposed = false;
371
+ let activeProxy = this.#selfRef?.deref();
372
+ const accessor = function() {
373
+ return sig.apply(this, arguments);
374
+ };
375
+ const wrapper = new Proxy(accessor, {
376
+ get(_, prop) {
377
+ if (prop === INSTANCE_KEY) return activeProxy;
378
+ if (prop === "disposed") return isDisposed;
379
+ if (prop === "dispose" || prop === Symbol.dispose) {
380
+ return () => {
381
+ if (isDisposed) return;
382
+ isDisposed = true;
383
+ if (activeProxy && activeProxy[PROXY_SIGNAL] === wrapper)
384
+ delete activeProxy[PROXY_SIGNAL];
385
+ activeProxy = void 0;
386
+ if (self.#cachedSignal === wrapper)
387
+ self.#cachedSignal = void 0;
388
+ sig.dispose?.();
389
+ };
390
+ }
391
+ if (prop === "get") return () => sig.get();
392
+ return sig[prop];
393
+ },
394
+ apply(_, thisArg, argArray) {
395
+ return sig.apply(thisArg, argArray);
396
+ }
397
+ });
398
+ return wrapper;
399
+ }
400
+ get signal() {
401
+ const proxy = this.#selfRef?.deref();
402
+ if (proxy) return proxy.signal;
403
+ if (!this.#cachedSignal || this.#cachedSignal.disposed)
404
+ this.#cachedSignal = this.toSignal();
405
+ return this.#cachedSignal;
406
+ }
407
+ async next() {
408
+ if (this.#stopped || this.#isInstant) return { done: true, value: void 0 };
409
+ const promise = this.#reactive.next();
410
+ if (!this.#genFirstYielded) {
411
+ this.#genFirstYielded = true;
412
+ const delay = this.#delayMs();
413
+ if (delay > 0) {
414
+ this.#runBootstrap();
415
+ } else {
416
+ queueMicrotask(() => {
417
+ if (!this.#stopped || this.#reactive.state.queued > 0) {
418
+ this.#safePulse();
419
+ this.#scheduleNext();
420
+ }
421
+ });
422
+ }
423
+ } else {
424
+ this.#runBootstrap();
425
+ }
426
+ const res = await promise;
427
+ if (res.done) return { done: true, value: void 0 };
428
+ if (res.value && res.value.isValid) return { done: false, value: res.value };
429
+ return { done: true, value: void 0 };
430
+ }
431
+ async return() {
432
+ this.stop();
433
+ return { done: true, value: void 0 };
434
+ }
435
+ async throw(e) {
436
+ this.stop();
437
+ throw e;
438
+ }
439
+ async [Symbol.asyncDispose]() {
440
+ this.stop();
441
+ }
442
+ [Symbol.asyncIterator]() {
443
+ return this.#selfRef?.deref() ?? this;
444
+ }
445
+ [Symbol.dispose]() {
446
+ this.stop();
447
+ }
448
+ };
449
+ function createTicker(TempoClass, arg1, arg2) {
450
+ const instance = new TickerInstance(TempoClass, arg1, arg2);
451
+ const proxy = new Proxy((() => instance.stop()), {
452
+ get: (target, prop) => {
453
+ if (prop === "pulse") return instance.pulse.bind(instance);
454
+ if (prop === "pull") return instance.pull.bind(instance);
455
+ if (prop === "until") return instance.until.bind(instance);
456
+ if (prop === "on") {
457
+ return (event, cb) => {
458
+ instance.on(event, cb);
459
+ return proxy;
460
+ };
461
+ }
462
+ if (prop === "stop") return instance.stop.bind(instance);
463
+ if (prop === "signal") {
464
+ let sig = target[PROXY_SIGNAL];
465
+ if (!sig || sig.disposed) {
466
+ sig = instance.toSignal();
467
+ target[PROXY_SIGNAL] = sig;
468
+ }
469
+ return sig;
470
+ }
471
+ if (prop === PROXY_SIGNAL) return target[PROXY_SIGNAL];
472
+ if (prop === "toSignal") return instance.toSignal.bind(instance);
473
+ if (prop === "next") return instance.next.bind(instance);
474
+ if (prop === "return") return instance.return.bind(instance);
475
+ if (prop === "throw") return instance.throw.bind(instance);
476
+ if (prop === "info") return instance.info;
477
+ if (prop === Symbol.asyncIterator) return () => proxy;
478
+ if (prop === Symbol.asyncDispose) return instance[Symbol.asyncDispose].bind(instance);
479
+ if (prop === Symbol.dispose) return instance[Symbol.dispose].bind(instance);
480
+ return instance[prop];
481
+ },
482
+ deleteProperty: (target, prop) => {
483
+ if (prop === PROXY_SIGNAL) {
484
+ delete target[PROXY_SIGNAL];
485
+ return true;
486
+ }
487
+ return Reflect.deleteProperty(target, prop);
488
+ },
489
+ apply: (target) => target()
490
+ });
491
+ const instanceRef = new WeakRef(instance);
492
+ sdk_exports.Finalizer.register(proxy, () => {
493
+ instanceRef.deref()?.stop();
494
+ });
495
+ return instance.bootstrap((0, sdk_exports.cast)(proxy));
496
+ }
497
+ var tickersDescriptor = {
498
+ get: () => Ticker.active
499
+ };
500
+ var TickerPlugin = definePlugin({
501
+ name: "ticker",
502
+ install(TempoClass, options) {
503
+ const opts = options;
504
+ const installedClass = TempoClass || this;
505
+ const tickerFactory = function(arg1, arg2) {
506
+ const cls = (0, sdk_exports.hasKey)(this, "prototype") ? this : (0, sdk_exports.hasKey)(this?.constructor, "prototype") ? this.constructor : installedClass;
507
+ const defaultOpts = opts ?? cls?.config?.pluginOptions?.ticker;
508
+ if (defaultOpts && (0, sdk_exports.isObject)(defaultOpts)) {
509
+ if ((0, sdk_exports.isUndefined)(arg1))
510
+ return createTicker(cls, defaultOpts);
511
+ if ((0, sdk_exports.isFunction)(arg1) && (0, sdk_exports.isUndefined)(arg2))
512
+ return createTicker(cls, defaultOpts, arg1);
513
+ if ((0, sdk_exports.isObject)(arg1) && !(0, sdk_exports.isFunction)(arg1))
514
+ return createTicker(cls, { ...defaultOpts, ...arg1 }, arg2);
515
+ }
516
+ return createTicker(cls, arg1, arg2);
517
+ };
518
+ tickerFactory.signal = function(interval) {
519
+ const ticker = tickerFactory(interval);
520
+ const sig = ticker.signal;
521
+ const dispose = () => {
522
+ ticker.stop();
523
+ sig.dispose?.();
524
+ };
525
+ const accessor = function() {
526
+ return sig();
527
+ };
528
+ const proxy = new Proxy(accessor, {
529
+ get(_, prop) {
530
+ if (prop === "dispose" || prop === Symbol.dispose) return dispose;
531
+ if (prop === "get") return () => sig.get();
532
+ return sig[prop];
533
+ },
534
+ apply(_, thisArg, argArray) {
535
+ return sig.apply(thisArg, argArray);
536
+ }
537
+ });
538
+ const tickerRef = new WeakRef(ticker);
539
+ sdk_exports.Finalizer.register(proxy, () => {
540
+ tickerRef.deref()?.stop();
541
+ });
542
+ return proxy;
543
+ };
544
+ (0, sdk_exports.attachStatics)(installedClass, {
545
+ ticker: tickerFactory,
546
+ tickers: tickersDescriptor
547
+ });
548
+ }
549
+ });
550
+ var index_default = TickerPlugin;
551
+ var export_isCronString = sdk_exports.isCronString;
552
+ export {
553
+ Ticker,
554
+ TickerPlugin,
555
+ index_default as default,
556
+ export_isCronString as isCronString
557
+ };
@@ -0,0 +1,2 @@
1
+ export * from './index.js';
2
+ export { TickerPlugin, default } from './index.js';
@@ -0,0 +1 @@
1
+ "use strict";var Magma;((Magma||={}).plugins||={}).ticker=(()=>{var F=Object.create;var v=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var q=(c,t)=>()=>{try{return t||c((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},N=(c,t)=>{for(var i in t)v(c,i,{get:t[i],enumerable:!0})},S=(c,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of j(t))!K.call(c,n)&&n!==i&&v(c,n,{get:()=>t[n],enumerable:!(s=$(t,n))||s.enumerable});return c},k=(c,t,i)=>(S(c,t,"default"),i&&S(i,t,"default")),M=(c,t,i)=>(i=c!=null?F(B(c)):{},S(t||!c||!c.__esModule?v(i,"default",{value:c,enumerable:!0}):i,c)),U=c=>S(v({},"__esModule",{value:!0}),c);var R=q((X,A)=>{"use strict";A.exports=window.Magma.pluginSdk});var G={};N(G,{Ticker:()=>W,TickerPlugin:()=>g,default:()=>_,isCronString:()=>e.isCronString});var e={};N(e,{definePlugin:()=>O,defineTerm:()=>Y});k(e,M(R()));var w=M(R()),O=c=>(0,w.definePlugin)({...c,version:"3.0.0-rc.0"}),Y=c=>(0,w.defineTerm)({...c,version:"3.0.0-rc.0"});var b=new Set,p=Symbol.for("Tempo.ticker.cachedSignal"),Z=Symbol.for("Tempo.ticker.instance"),W={get active(){let c=[];for(let t of b){let i=t.ref.deref();if((0,e.isUndefined)(i)||i.info.stopped)b.delete(t);else{let{label:s,next:n,ticks:a,limit:o,interval:r,rrule:l,cron:m,stopped:u,ntp:d}=i.info;c.push({ticker:i,label:s,next:n,ticks:a,limit:o,interval:r,rrule:l,cron:m,stopped:u,ntp:d})}}return c}},D=class{#t;#x;#i={};#h;#l;#e;#o;#a;#b=0;#s=!1;#E=!1;#u=!0;#d=!1;#g=!1;#f;#n;#y=new Set;#I=new Set;#R=!1;#T=!1;#k=!1;#O=!1;#P=!1;#S;#p;#m=void 0;#r=void 0;constructor(t,i,s){this.#t=t;let n={},a,o=h=>(0,e.isObject)(h)&&("epoch"in h||"epochMilliseconds"in h||"toZonedDateTimeISO"in h||"getTime"in h),r=h=>(0,e.isObject)(h)&&!o(h);switch(!0){case(0,e.isFunction)(i):a=i;break;case r(i):Object.assign(n,i),(0,e.isFunction)(s)?a=s:r(s)&&Object.assign(n,s);break;default:if((0,e.isNotNullish)(i))if((0,e.isCronString)(i))n.cron=i;else if((0,e.isRRuleString)(i))n.rrule=i;else{let h=Number(i);(0,e.isNumeric)(i)?n.seconds=h:n.seed=i}(0,e.isFunction)(s)?a=s:r(s)&&Object.assign(n,s)}if((0,e.isNotNullish)(n.interval)&&(0,e.isNullish)(n.seconds)&&(0,e.isNullish)(n.cron)&&(0,e.isNullish)(n.rrule)){let h=n.interval;(0,e.isCronString)(h)?n.cron=h:(0,e.isRRuleString)(h)?n.rrule=h:(0,e.isNumeric)(h)?n.seconds=Number(h):n.seed=h}let{label:l,limit:m,until:u,seed:d,rrule:T,cron:f,ntp:I,...y}=n;this.#S=y,this.#x=l,this.#a=m,this.#k=!!I,this.#O=!!(this.#k&&this.#t.ntp?.isCalibrated),T&&(this.#h=(0,e.isString)(T)?T:T.rrule),this.#T=!!(n.catch??this.#t.config?.catch),this.#n=new e.Reactive({tag:this.#x??"Ticker",catch:this.#T}),(0,e.isNotNullish)(f)&&((0,e.isCronString)(f)?this.#l=f:(this.#R=!0,(0,e.logError)(new Error(`Invalid Ticker cron schedule: ${String(f)}`),{...this.#S,catch:this.#T}))),a&&this.#n.on("data",h=>a(h,()=>this.stop()));for(let[h,C]of Object.entries(y))(0,e.isNotNullish)(C)&&(h.startsWith("#")||e.Enum.has(e.enums.DURATIONS,h)||e.Enum.has(e.enums.ELEMENT,h))&&(this.#i[h]=C);let L=(0,e.isNotNullish)(n.seed),E=(0,e.isNotNullish)(this.#h),P=(0,e.isNotNullish)(this.#l),V=!(0,e.isEmpty)(this.#i)||(0,e.isNotNullish)(n.seconds)&&(0,e.isNumber)(n.seconds);(0,e.isNotNullish)(i)&&!r(i)&&!V&&!L&&!E&&!P&&!a&&(0,e.logError)(new Error(`Invalid Ticker interval, seed, cron, or rrule: ${String(i)}`),{...this.#S,catch:this.#T}),this.#o=u?new this.#t(r(u)?void 0:u,r(u)?{...y,...u}:y):void 0,(0,e.isEmpty)(this.#i)&&!E&&!P&&!this.#R&&((0,e.isNotNullish)(d)?this.#a??=1:this.#i.seconds=1),(0,e.normaliseFractionalDurations)(this.#i),(0,e.isNotNullish)(d)?(this.#e=new this.#t(r(d)?void 0:d,r(d)?{...y,...d}:y),this.#P=(!r(d)||(0,e.isNotNullish)(d.epoch))&&this.#e.epoch.ms>(0,e.instant)().epochMilliseconds):this.#k&&(0,e.isFunction)(this.#t.ntp?.now)?this.#e=this.#t.ntp.now(y):this.#e=new this.#t(void 0,y)}bootstrap(t){if(this.#p=new WeakRef(t),this.#m={ref:this.#p,token:Object.create(null)},this.#a===0)return this.stop(),t;if(this.#R)return this.stop(),t;if(!this.#e.isValid)this.stop(),(0,e.logError)(new Error(`Invalid Ticker seed: ${String(this.#e)}`),this.#e.config);else if(this.#o&&!this.#o.isValid)this.stop(),(0,e.logError)(new Error(`Invalid Ticker boundary: ${String(this.#o)}`),this.#e.config);else try{if(this.#l||this.#h)this.#u=!0,this.#d=!1,b.add(this.#m),this.#c();else{let i=Object.entries(this.#i).some(([o,r])=>o.startsWith("#")&&(0,e.isString)(r)&&/^[<>]/.test(r.trim())),s=Object.keys(this.#i).some(o=>!o.startsWith("#"));if(i&&s)throw new Error("Ambiguous Ticker payload: cannot mix directional shorthand terms (e.g. '>') with relative durations (e.g. 'hours'). Use one or the other.");this.#g=i;let n=Object.keys(this.#i).some(o=>o.startsWith("#")),a=this.#g?this.#e.set(this.#i):this.#e.add(this.#i);if(!a.isValid)throw new Error(`Invalid Ticker payload resolution for ${JSON.stringify(this.#i)}`);this.#u=this.#t.compare(a,this.#e)>=0,this.#d=a.epoch.ns===this.#e.epoch.ns,n&&(this.#e=a),b.add(this.#m),this.#c()}}catch{this.stop();let s=`Invalid Ticker payload resolution for ${JSON.stringify(this.#i)}`;(0,e.logError)(new Error(s),this.#e.config),queueMicrotask(()=>this.#y.forEach(n=>n(this.#e,()=>this.stop()))),this.#u=!0,this.#d=!1}return t}#D(){let t=this.#k&&!!this.#t.ntp?.isCalibrated;t&&!this.#O&&!this.#P&&this.#b===0&&(0,e.isFunction)(this.#t.ntp?.now)&&(this.#e=this.#t.ntp.now(this.#S),Object.keys(this.#i).some(a=>a.startsWith("#"))&&(this.#e=this.#g?this.#e.set(this.#i):this.#e.add(this.#i)),this.#O=!0);let i=t&&(0,e.isFunction)(this.#t.ntp?.now)?this.#t.ntp.now().epoch.ms:(0,e.instant)().epochMilliseconds,s=Math.round(this.#e.epoch.ms-i);if(s>0)return Math.min(s,2147483647);if(!this.#u){let n=Math.abs(Math.round(this.#e.add(this.#i).epoch.ms-this.#e.epoch.ms));return Math.max(20,Math.min(50,n||1e3))}return 0}#v(){try{return this.pulse()}catch(t){let i=[...this.#y];if(this.stop(),i.forEach(s=>s(this.#e,()=>this.stop())),!this.#T)throw t;return this.#e}}#w(){this.#s||this.#d||(this.#f=setTimeout(()=>{this.#s||(this.#v(),this.#w())},this.#D()))}#c(){if((this.#n.state.subscribers>0||this.#n.state.queued>0)&&!this.#s&&!this.#f){let t=this.#D();t>0?this.#f=setTimeout(()=>{this.#s||(this.#v(),this.#w())},t):(this.#v(),this.#w())}}pulse(){if(this.#s)return new this.#t(null,this.#e.config);let t=this.#e;if(!t.isValid){let s=[...this.#y];return this.stop(),s.forEach(n=>n(t,()=>this.stop())),t}if(this.#l){let s=(0,e.getNextCronEpoch)(this.#l,t.epoch.ms,t.tz);this.#e=new this.#t(s,t.config)}else if(this.#h){let s=(0,e.getNextRRuleEpoch)(this.#h,t.epoch.ms);this.#e=new this.#t(s,t.config)}else this.#e=this.#d?t:this.#g?t.set(this.#i):t.add(this.#i);this.#b++;let i=this.#a!==void 0&&this.#b>=this.#a||(0,e.isNotNullish)(this.#o)&&(this.#u&&this.#t.compare(t,this.#o)>=0||!this.#u&&this.#t.compare(t,this.#o)<=0);return this.#s&&this.#a===0||(this.#n.cast(t),i&&this.stop()),t}on(t,i){return t==="pulse"?(this.#n.on("data",s=>i(s,()=>this.stop())),this.#c()):t==="catch"?this.#y.add(i):t==="stop"&&this.#I.add(i),this}stop(t){if(this.#s)return;this.#s=!0,this.#m&&(b.delete(this.#m),this.#m=void 0),this.#f&&(clearTimeout(this.#f),this.#f=void 0),t!==void 0&&(this.#e=t),this.#n.complete(t);let i=this.#p?.deref();i&&i[p]&&(i[p].dispose?.(),delete i[p]),this.#r&&(this.#r.dispose?.(),this.#r=void 0);let s=[...this.#I];this.#I.clear(),this.#y.clear();for(let n of s)n(this.#e,()=>{})}get[Symbol.toStringTag](){return"Tempo.Ticker"}get info(){return{label:this.#x,next:this.#e,ticks:this.#b,limit:this.#a,interval:{...this.#i},rrule:this.#h,cron:this.#l,stopped:this.#s,ntp:this.#k}}async pull(){let t=await this.next();return t.done?void 0:t.value}until(t){let i=this.#n.until(t);return this.#c(),i}toSignal(...t){let i=this,s=t.length>0?t[0]:this.#e,n=this.#n.toSignal(s);this.#c();let a=!1,o=this.#p?.deref(),r=function(){return n.apply(this,arguments)},l=new Proxy(r,{get(m,u){return u===Z?o:u==="disposed"?a:u==="dispose"||u===Symbol.dispose?()=>{a||(a=!0,o&&o[p]===l&&delete o[p],o=void 0,i.#r===l&&(i.#r=void 0),n.dispose?.())}:u==="get"?()=>n.get():n[u]},apply(m,u,d){return n.apply(u,d)}});return l}get signal(){let t=this.#p?.deref();return t?t.signal:((!this.#r||this.#r.disposed)&&(this.#r=this.toSignal()),this.#r)}async next(){if(this.#s||this.#d)return{done:!0,value:void 0};let t=this.#n.next();this.#E?this.#c():(this.#E=!0,this.#D()>0?this.#c():queueMicrotask(()=>{(!this.#s||this.#n.state.queued>0)&&(this.#v(),this.#w())}));let i=await t;return i.done?{done:!0,value:void 0}:i.value&&i.value.isValid?{done:!1,value:i.value}:{done:!0,value:void 0}}async return(){return this.stop(),{done:!0,value:void 0}}async throw(t){throw this.stop(),t}async[Symbol.asyncDispose](){this.stop()}[Symbol.asyncIterator](){return this.#p?.deref()??this}[Symbol.dispose](){this.stop()}};function x(c,t,i){let s=new D(c,t,i),n=new Proxy((()=>s.stop()),{get:(o,r)=>{if(r==="pulse")return s.pulse.bind(s);if(r==="pull")return s.pull.bind(s);if(r==="until")return s.until.bind(s);if(r==="on")return(l,m)=>(s.on(l,m),n);if(r==="stop")return s.stop.bind(s);if(r==="signal"){let l=o[p];return(!l||l.disposed)&&(l=s.toSignal(),o[p]=l),l}return r===p?o[p]:r==="toSignal"?s.toSignal.bind(s):r==="next"?s.next.bind(s):r==="return"?s.return.bind(s):r==="throw"?s.throw.bind(s):r==="info"?s.info:r===Symbol.asyncIterator?()=>n:r===Symbol.asyncDispose?s[Symbol.asyncDispose].bind(s):r===Symbol.dispose?s[Symbol.dispose].bind(s):s[r]},deleteProperty:(o,r)=>r===p?(delete o[p],!0):Reflect.deleteProperty(o,r),apply:o=>o()}),a=new WeakRef(s);return e.Finalizer.register(n,()=>{a.deref()?.stop()}),s.bootstrap((0,e.cast)(n))}var z={get:()=>W.active},g=O({name:"ticker",install(c,t){let i=t,s=c||this,n=function(a,o){let r=(0,e.hasKey)(this,"prototype")?this:(0,e.hasKey)(this?.constructor,"prototype")?this.constructor:s,l=i??r?.config?.pluginOptions?.ticker;if(l&&(0,e.isObject)(l)){if((0,e.isUndefined)(a))return x(r,l);if((0,e.isFunction)(a)&&(0,e.isUndefined)(o))return x(r,l,a);if((0,e.isObject)(a)&&!(0,e.isFunction)(a))return x(r,{...l,...a},o)}return x(r,a,o)};n.signal=function(a){let o=n(a),r=o.signal,l=()=>{o.stop(),r.dispose?.()},m=function(){return r()},u=new Proxy(m,{get(T,f){return f==="dispose"||f===Symbol.dispose?l:f==="get"?()=>r.get():r[f]},apply(T,f,I){return r.apply(f,I)}}),d=new WeakRef(o);return e.Finalizer.register(u,()=>{d.deref()?.stop()}),u},(0,e.attachStatics)(s,{ticker:n,tickers:z})}}),_=g;(0,e.autoInstall)(g);return U(G);})();