@mark1russell7/algebra 0.8.6 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/build/clock-5u5mZpjL.d.ts +115 -0
- package/build/clock.d.ts +2 -2
- package/build/clock.js +203 -1
- package/build/clock.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/{run-Dol_e0Xa.d.ts → run-yLPq18NQ.d.ts} +1 -1
- package/build/run.d.ts +1 -1
- package/package.json +1 -1
- package/build/clock-BPLEBlb6.d.ts +0 -48
package/README.md
CHANGED
|
@@ -136,6 +136,34 @@ clock.after(30_000, () => cache.sweep());
|
|
|
136
136
|
await clock.advance(30_000); // the sweep runs, at 30 s exactly
|
|
137
137
|
```
|
|
138
138
|
|
|
139
|
+
### Civil time
|
|
140
|
+
|
|
141
|
+
The entry also gives civil time: the time on the wall of a time zone at an instant, and windows of local time. An instant is in milliseconds from 1970, as `Date.now()` gives. Civil time uses only `Intl.DateTimeFormat`.
|
|
142
|
+
|
|
143
|
+
| Export | What it does |
|
|
144
|
+
| --- | --- |
|
|
145
|
+
| `localTime(instant, zone)` | It gives the year, the month, the day, the hour, the minute, the second, the day of the week and the offset of the zone, or `undefined` for a bad zone. |
|
|
146
|
+
| `TimeWindow` | A window as data: `{ zone, start, end, days? }`. The start and the end are local times `HH:MM`. |
|
|
147
|
+
| `inWindow(instant, window)` | It tells if the instant is in the window. A bad window gives `false`. |
|
|
148
|
+
| `nextBoundary(instant, window)` | It gives the next instant at which the window opens or closes, as `{ at, opens }`. A timer can wait for it. It looks 9 days ahead at most. It gives `undefined` for a window with no change in that time. |
|
|
149
|
+
| `windowProblems(window)` | It gives the problems of a window: a bad zone, a bad local time or a bad day. |
|
|
150
|
+
|
|
151
|
+
These rules apply to a window:
|
|
152
|
+
|
|
153
|
+
- The start is in the window, and the end is not. An end before the start crosses midnight. An end equal to the start gives the full day.
|
|
154
|
+
- `days` are the days of the week on which the window starts, from 0 (Sunday) to 6. A window across midnight continues into the next day.
|
|
155
|
+
- The window follows the time on the wall when the clock changes. A start or an end in a gap moves to the end of the gap. A local time that occurs two times is in the window two times.
|
|
156
|
+
- An example: on 2026-10-25 in Berlin, a window from 22:00 to 02:30 closes at 00:30Z. It opens again at 01:00Z and closes at 01:30Z.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import { inWindow, nextBoundary, realClock } from "@mark1russell7/algebra/clock";
|
|
160
|
+
|
|
161
|
+
const night = { zone: "Europe/Berlin", start: "22:00", end: "07:00" };
|
|
162
|
+
inWindow(Date.now(), night); // true from 22:00 to 06:59 in Berlin, in summer time and in winter time
|
|
163
|
+
const next = nextBoundary(Date.now(), night); // { at, opens }: the next change of the window
|
|
164
|
+
if (next !== undefined) realClock.after(next.at - Date.now(), () => console.log(next.opens ? "quiet" : "loud"));
|
|
165
|
+
```
|
|
166
|
+
|
|
139
167
|
## Installation
|
|
140
168
|
|
|
141
169
|
```sh
|
|
@@ -149,7 +177,7 @@ The root entry has the machine types, the consistency checks and the algebra. It
|
|
|
149
177
|
| Entry | What it has | `zod` |
|
|
150
178
|
| --- | --- | --- |
|
|
151
179
|
| `@mark1russell7/algebra` | The machine types, the consistency checks, the algebra, `replay` and `runMachine` | No |
|
|
152
|
-
| `@mark1russell7/algebra/clock` | The clock of a runtime
|
|
180
|
+
| `@mark1russell7/algebra/clock` | The clock of a runtime, a fake clock for tests, and civil time | No |
|
|
153
181
|
| `@mark1russell7/algebra/replay` | The replay of a trace against a machine document | No |
|
|
154
182
|
| `@mark1russell7/algebra/run` | The run of a live instance of a machine document | No |
|
|
155
183
|
| `@mark1russell7/algebra/schema` | `machineSchema`, the schema of a machine document | Yes |
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This function stops a timer that `Clock.after` started. A second use does nothing. A clock of
|
|
3
|
+
* the platform also gives `unref`: after it, the timer does not keep a Node process alive.
|
|
4
|
+
*/
|
|
5
|
+
type Cancel = (() => void) & {
|
|
6
|
+
readonly unref?: (() => void) | undefined;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The
|
|
10
|
+
* runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of
|
|
11
|
+
* the runtime is then exact and repeatable.
|
|
12
|
+
*/
|
|
13
|
+
interface Clock {
|
|
14
|
+
/** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */
|
|
15
|
+
now(): number;
|
|
16
|
+
/** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */
|
|
17
|
+
after(ms: number, run: () => void): Cancel;
|
|
18
|
+
}
|
|
19
|
+
/** These options make a clock of the platform. */
|
|
20
|
+
interface PlatformClockOptions {
|
|
21
|
+
/** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */
|
|
22
|
+
readonly unref?: boolean | undefined;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
|
|
26
|
+
* that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
|
|
27
|
+
*/
|
|
28
|
+
declare const platformClock: (options?: PlatformClockOptions) => Clock;
|
|
29
|
+
/**
|
|
30
|
+
* This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node
|
|
31
|
+
* process alive, thus a timer that is not stopped cannot stop the exit of the process.
|
|
32
|
+
*/
|
|
33
|
+
declare const realClock: Clock;
|
|
34
|
+
/** A fake clock moves only when a test tells it to. */
|
|
35
|
+
interface FakeClock extends Clock {
|
|
36
|
+
/** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */
|
|
37
|
+
advance(ms: number): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.
|
|
40
|
+
* The next `advance` then starts each timer that came due during the block, late.
|
|
41
|
+
*/
|
|
42
|
+
block(ms: number): void;
|
|
43
|
+
/** This count is the number of timers that are not stopped and not called. */
|
|
44
|
+
readonly pending: number;
|
|
45
|
+
}
|
|
46
|
+
/** This function makes a fake clock. Its time starts at `start` milliseconds. */
|
|
47
|
+
declare const fakeClock: (start?: number) => FakeClock;
|
|
48
|
+
/**
|
|
49
|
+
* The wall-clock time of an instant in a time zone. An instant is a time in milliseconds from
|
|
50
|
+
* 1970-01-01T00:00:00Z, as `Date.now()` gives. It is not the monotonic time of `Clock.now()`.
|
|
51
|
+
*/
|
|
52
|
+
interface LocalTime {
|
|
53
|
+
readonly year: number;
|
|
54
|
+
/** The month, from 1 (January) to 12. */
|
|
55
|
+
readonly month: number;
|
|
56
|
+
/** The day of the month, from 1. */
|
|
57
|
+
readonly day: number;
|
|
58
|
+
/** The hour, from 0 to 23. */
|
|
59
|
+
readonly hour: number;
|
|
60
|
+
readonly minute: number;
|
|
61
|
+
readonly second: number;
|
|
62
|
+
/** The day of the week, from 0 (Sunday) to 6 (Saturday). */
|
|
63
|
+
readonly weekday: number;
|
|
64
|
+
/** The offset of the zone from UTC at the instant, in minutes. It is positive east of Greenwich. */
|
|
65
|
+
readonly offset: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A window of local time that occurs on each day, or on some days of the week. The window is
|
|
69
|
+
* data, thus a configuration can hold it.
|
|
70
|
+
*
|
|
71
|
+
* - The start is in the window, and the end is not.
|
|
72
|
+
* - An end before the start crosses midnight. An end equal to the start gives a window of a full day.
|
|
73
|
+
* - In a change of the clock, the window follows the time on the wall. A start or an end in a gap
|
|
74
|
+
* moves to the end of the gap. Thus a window with its start and its end in one gap does not open.
|
|
75
|
+
* - A local time that occurs two times is in the window two times.
|
|
76
|
+
*/
|
|
77
|
+
interface TimeWindow {
|
|
78
|
+
/** The IANA name of the time zone, for example `Europe/Berlin`. */
|
|
79
|
+
readonly zone: string;
|
|
80
|
+
/** The start, a local time `HH:MM` from `00:00` to `23:59`. */
|
|
81
|
+
readonly start: string;
|
|
82
|
+
/** The end, a local time `HH:MM` from `00:00` to `23:59`. */
|
|
83
|
+
readonly end: string;
|
|
84
|
+
/**
|
|
85
|
+
* The days of the week on which the window starts, from 0 (Sunday) to 6. When it is absent, the
|
|
86
|
+
* window starts on each day. A window across midnight continues into the next day.
|
|
87
|
+
*/
|
|
88
|
+
readonly days?: readonly number[] | undefined;
|
|
89
|
+
}
|
|
90
|
+
/** A change of a window: the instant at which it opens or closes. */
|
|
91
|
+
interface WindowBoundary {
|
|
92
|
+
readonly at: number;
|
|
93
|
+
/** True: the window opens at `at`. False: it closes. */
|
|
94
|
+
readonly opens: boolean;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* This function gives the wall-clock time of `instant` in `zone`. It gives `undefined` for a name
|
|
98
|
+
* that is not a time zone, and for an instant that is not a date.
|
|
99
|
+
*/
|
|
100
|
+
declare function localTime(instant: number, zone: string): LocalTime | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* This function tells if `instant` is in the window. It does not throw. A bad window or a bad
|
|
103
|
+
* instant gives `false`, and `windowProblems` finds the bad window.
|
|
104
|
+
*/
|
|
105
|
+
declare function inWindow(instant: number, window: TimeWindow): boolean;
|
|
106
|
+
/**
|
|
107
|
+
* This function gives the next change of the window after `instant`: the first later instant at
|
|
108
|
+
* which the window opens or closes. A timer can wait for it in closed form. It gives `undefined`
|
|
109
|
+
* for a bad window, and when the window does not change in the 9 days after `instant`. A window
|
|
110
|
+
* with no day and a full-day window on each day do not change.
|
|
111
|
+
*/
|
|
112
|
+
declare function nextBoundary(instant: number, window: TimeWindow): WindowBoundary | undefined;
|
|
113
|
+
/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */
|
|
114
|
+
declare function windowProblems(window: TimeWindow): string[];
|
|
115
|
+
export { PlatformClockOptions as a, fakeClock as c, nextBoundary as d, platformClock as f, LocalTime as i, inWindow as l, windowProblems as m, Clock as n, TimeWindow as o, realClock as p, FakeClock as r, WindowBoundary as s, Cancel as t, localTime as u };
|
package/build/clock.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as fakeClock, i as
|
|
2
|
-
export { Cancel, Clock, FakeClock, PlatformClockOptions, fakeClock, platformClock, realClock };
|
|
1
|
+
import { a as PlatformClockOptions, c as fakeClock, d as nextBoundary, f as platformClock, i as LocalTime, l as inWindow, m as windowProblems, n as Clock, o as TimeWindow, p as realClock, r as FakeClock, s as WindowBoundary, t as Cancel, u as localTime } from "./clock-5u5mZpjL.js";
|
|
2
|
+
export { Cancel, Clock, FakeClock, LocalTime, PlatformClockOptions, TimeWindow, WindowBoundary, fakeClock, inWindow, localTime, nextBoundary, platformClock, realClock, windowProblems };
|
package/build/clock.js
CHANGED
|
@@ -83,6 +83,208 @@ const fakeClock = (start = 0) => {
|
|
|
83
83
|
}
|
|
84
84
|
};
|
|
85
85
|
};
|
|
86
|
-
|
|
86
|
+
const MINUTE_MS = 6e4;
|
|
87
|
+
const DAY_MS = 864e5;
|
|
88
|
+
const WEEKDAYS = {
|
|
89
|
+
Sun: 0,
|
|
90
|
+
Mon: 1,
|
|
91
|
+
Tue: 2,
|
|
92
|
+
Wed: 3,
|
|
93
|
+
Thu: 4,
|
|
94
|
+
Fri: 5,
|
|
95
|
+
Sat: 6
|
|
96
|
+
};
|
|
97
|
+
const LOCAL_TIME = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
|
98
|
+
/**
|
|
99
|
+
* The cache has one format for each good zone name. It keeps no bad name, and it starts again at
|
|
100
|
+
* `ZONE_CACHE_MAX` names. Thus names from configuration input cannot make it grow without a limit.
|
|
101
|
+
*/
|
|
102
|
+
const ZONE_FORMATS = /* @__PURE__ */ new Map();
|
|
103
|
+
const ZONE_CACHE_MAX = 512;
|
|
104
|
+
/** The longest IANA name has 32 characters. A longer name than this limit is not a zone. */
|
|
105
|
+
const ZONE_NAME_MAX = 100;
|
|
106
|
+
const zoneFormat = (zone) => {
|
|
107
|
+
let format = ZONE_FORMATS.get(zone);
|
|
108
|
+
if (format === void 0) {
|
|
109
|
+
if (typeof zone !== "string" || zone.length > ZONE_NAME_MAX) return void 0;
|
|
110
|
+
try {
|
|
111
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
112
|
+
timeZone: zone,
|
|
113
|
+
hourCycle: "h23",
|
|
114
|
+
era: "short",
|
|
115
|
+
year: "numeric",
|
|
116
|
+
month: "numeric",
|
|
117
|
+
day: "numeric",
|
|
118
|
+
hour: "numeric",
|
|
119
|
+
minute: "numeric",
|
|
120
|
+
second: "numeric",
|
|
121
|
+
weekday: "short"
|
|
122
|
+
});
|
|
123
|
+
} catch {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (ZONE_FORMATS.size >= ZONE_CACHE_MAX) ZONE_FORMATS.clear();
|
|
127
|
+
ZONE_FORMATS.set(zone, format);
|
|
128
|
+
}
|
|
129
|
+
return format;
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* This function gives the wall-clock time of `instant` in `zone`. It gives `undefined` for a name
|
|
133
|
+
* that is not a time zone, and for an instant that is not a date.
|
|
134
|
+
*/
|
|
135
|
+
function localTime(instant, zone) {
|
|
136
|
+
const format = zoneFormat(zone);
|
|
137
|
+
if (format === void 0 || !Number.isFinite(instant)) return void 0;
|
|
138
|
+
let parts;
|
|
139
|
+
try {
|
|
140
|
+
parts = format.formatToParts(instant);
|
|
141
|
+
} catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const field = {};
|
|
145
|
+
for (const part of parts) field[part.type] = part.value;
|
|
146
|
+
const year = field["era"] === "BC" || field["era"] === "B" ? 1 - Number(field["year"]) : Number(field["year"]);
|
|
147
|
+
const month = Number(field["month"]);
|
|
148
|
+
const day = Number(field["day"]);
|
|
149
|
+
const hour = Number(field["hour"]) % 24;
|
|
150
|
+
const minute = Number(field["minute"]);
|
|
151
|
+
const second = Number(field["second"]);
|
|
152
|
+
const whole = Math.floor(instant / 1e3) * 1e3;
|
|
153
|
+
return {
|
|
154
|
+
year,
|
|
155
|
+
month,
|
|
156
|
+
day,
|
|
157
|
+
hour,
|
|
158
|
+
minute,
|
|
159
|
+
second,
|
|
160
|
+
weekday: WEEKDAYS[field["weekday"] ?? ""] ?? 0,
|
|
161
|
+
offset: (wallOf(year, month, day, hour, minute, second) - whole) / MINUTE_MS
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** The wall-clock time as an instant in UTC. `Date.UTC` reads a year from 0 to 99 as 1900 to 1999, thus this function sets the year by itself. */
|
|
165
|
+
const wallOf = (year, month, day, hour, minute, second) => {
|
|
166
|
+
const wall = /* @__PURE__ */ new Date(0);
|
|
167
|
+
wall.setUTCFullYear(year, month - 1, day);
|
|
168
|
+
wall.setUTCHours(hour, minute, second, 0);
|
|
169
|
+
return wall.getTime();
|
|
170
|
+
};
|
|
171
|
+
/** The minutes from midnight of a local time `HH:MM`. */
|
|
172
|
+
const minutesOf = (time) => {
|
|
173
|
+
const match = LOCAL_TIME.exec(time);
|
|
174
|
+
return match === null ? void 0 : Number(match[1]) * 60 + Number(match[2]);
|
|
175
|
+
};
|
|
176
|
+
const isDay = (day) => Number.isInteger(day) && day >= 0 && day <= 6;
|
|
177
|
+
const checked = (window) => {
|
|
178
|
+
const start = minutesOf(window.start);
|
|
179
|
+
const end = minutesOf(window.end);
|
|
180
|
+
if (start === void 0 || end === void 0 || zoneFormat(window.zone) === void 0) return void 0;
|
|
181
|
+
if (window.days !== void 0 && !window.days.every(isDay)) return void 0;
|
|
182
|
+
return {
|
|
183
|
+
start,
|
|
184
|
+
end,
|
|
185
|
+
days: window.days === void 0 ? void 0 : new Set(window.days)
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
const within = (window, local) => {
|
|
189
|
+
const minute = local.hour * 60 + local.minute;
|
|
190
|
+
const startsOn = (weekday) => window.days === void 0 || window.days.has(weekday);
|
|
191
|
+
if (window.start < window.end) return window.start <= minute && minute < window.end && startsOn(local.weekday);
|
|
192
|
+
return minute >= window.start && startsOn(local.weekday) || minute < window.end && startsOn((local.weekday + 6) % 7);
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* This function tells if `instant` is in the window. It does not throw. A bad window or a bad
|
|
196
|
+
* instant gives `false`, and `windowProblems` finds the bad window.
|
|
197
|
+
*/
|
|
198
|
+
function inWindow(instant, window) {
|
|
199
|
+
const valid = checked(window);
|
|
200
|
+
const local = valid === void 0 ? void 0 : localTime(instant, window.zone);
|
|
201
|
+
return valid !== void 0 && local !== void 0 && within(valid, local);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The instants at which the wall clock of the zone shows `wall`, a wall-clock time as an instant in
|
|
205
|
+
* UTC. A gap gives none, and an overlap gives two.
|
|
206
|
+
*/
|
|
207
|
+
const instantsOf = (wall, zone) => {
|
|
208
|
+
const offsets = /* @__PURE__ */ new Set();
|
|
209
|
+
for (const probe of [
|
|
210
|
+
wall - DAY_MS,
|
|
211
|
+
wall,
|
|
212
|
+
wall + DAY_MS
|
|
213
|
+
]) {
|
|
214
|
+
const local = localTime(probe, zone);
|
|
215
|
+
if (local !== void 0) offsets.add(local.offset);
|
|
216
|
+
}
|
|
217
|
+
const found = [];
|
|
218
|
+
for (const offset of offsets) {
|
|
219
|
+
const instant = wall - offset * MINUTE_MS;
|
|
220
|
+
const local = localTime(instant, zone);
|
|
221
|
+
if (local === void 0) continue;
|
|
222
|
+
if (wallOf(local.year, local.month, local.day, local.hour, local.minute, local.second) === wall && !found.includes(instant)) found.push(instant);
|
|
223
|
+
}
|
|
224
|
+
return found;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* The instants in (from, to] at which the offset of the zone changes, each one exact to the
|
|
228
|
+
* millisecond. The search reads the offset each 6 hours. No zone changes its offset two times in 6 hours.
|
|
229
|
+
*/
|
|
230
|
+
const changesOf = (from, to, zone) => {
|
|
231
|
+
const offsetAt = (instant) => localTime(instant, zone)?.offset;
|
|
232
|
+
const found = [];
|
|
233
|
+
let low = from;
|
|
234
|
+
let before = offsetAt(low);
|
|
235
|
+
while (low < to) {
|
|
236
|
+
const high = Math.min(low + DAY_MS / 4, to);
|
|
237
|
+
const after = offsetAt(high);
|
|
238
|
+
if (before !== void 0 && after !== void 0 && after !== before) {
|
|
239
|
+
let left = low;
|
|
240
|
+
let right = high;
|
|
241
|
+
while (right - left > 1) {
|
|
242
|
+
const middle = Math.floor((left + right) / 2);
|
|
243
|
+
if (offsetAt(middle) === before) left = middle;
|
|
244
|
+
else right = middle;
|
|
245
|
+
}
|
|
246
|
+
found.push(right);
|
|
247
|
+
}
|
|
248
|
+
low = high;
|
|
249
|
+
before = after;
|
|
250
|
+
}
|
|
251
|
+
return found;
|
|
252
|
+
};
|
|
253
|
+
/**
|
|
254
|
+
* This function gives the next change of the window after `instant`: the first later instant at
|
|
255
|
+
* which the window opens or closes. A timer can wait for it in closed form. It gives `undefined`
|
|
256
|
+
* for a bad window, and when the window does not change in the 9 days after `instant`. A window
|
|
257
|
+
* with no day and a full-day window on each day do not change.
|
|
258
|
+
*/
|
|
259
|
+
function nextBoundary(instant, window) {
|
|
260
|
+
const valid = checked(window);
|
|
261
|
+
const local = valid === void 0 ? void 0 : localTime(instant, window.zone);
|
|
262
|
+
if (valid === void 0 || local === void 0) return void 0;
|
|
263
|
+
const inside = within(valid, local);
|
|
264
|
+
const horizon = instant + 9 * DAY_MS;
|
|
265
|
+
const candidates = changesOf(instant, horizon, window.zone);
|
|
266
|
+
const midnight = wallOf(local.year, local.month, local.day, 0, 0, 0);
|
|
267
|
+
for (let day = -1; day <= 10; day += 1) for (const minutes of [valid.start, valid.end]) candidates.push(...instantsOf(midnight + day * DAY_MS + minutes * MINUTE_MS, window.zone));
|
|
268
|
+
candidates.sort((a, b) => a - b);
|
|
269
|
+
for (const at of candidates) {
|
|
270
|
+
if (at <= instant || at > horizon) continue;
|
|
271
|
+
const there = localTime(at, window.zone);
|
|
272
|
+
if (there !== void 0 && within(valid, there) !== inside) return {
|
|
273
|
+
at,
|
|
274
|
+
opens: !inside
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */
|
|
279
|
+
function windowProblems(window) {
|
|
280
|
+
const problems = [];
|
|
281
|
+
if (zoneFormat(window.zone) === void 0) problems.push(`"${window.zone}" is not the IANA name of a time zone.`);
|
|
282
|
+
if (minutesOf(window.start) === void 0) problems.push(`The start "${window.start}" is not a local time HH:MM from 00:00 to 23:59.`);
|
|
283
|
+
if (minutesOf(window.end) === void 0) problems.push(`The end "${window.end}" is not a local time HH:MM from 00:00 to 23:59.`);
|
|
284
|
+
for (const day of window.days ?? []) if (!isDay(day)) problems.push(`The day ${day} is not a day of the week from 0 (Sunday) to 6.`);
|
|
285
|
+
if (window.days !== void 0 && window.days.length === 0) problems.push("The window has no day, thus it does not open.");
|
|
286
|
+
return problems;
|
|
287
|
+
}
|
|
288
|
+
export { fakeClock, inWindow, localTime, nextBoundary, platformClock, realClock, windowProblems };
|
|
87
289
|
|
|
88
290
|
//# sourceMappingURL=clock.js.map
|
package/build/clock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clock.js","names":[],"sources":["../src/clock.ts"],"sourcesContent":["// @mark1russell7/algebra/clock: the clock of a runtime, and a fake clock for tests. It imports\n// nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it.\n// The service gives this clock again as @mark1russell7/service/clock.\n\n/**\n * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of\n * the platform also gives `unref`: after it, the timer does not keep a Node process alive.\n */\nexport type Cancel = (() => void) & { readonly unref?: (() => void) | undefined };\n\n/**\n * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The\n * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of\n * the runtime is then exact and repeatable.\n */\nexport interface Clock {\n /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/** These options make a clock of the platform. */\nexport interface PlatformClockOptions {\n /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */\n readonly unref?: boolean | undefined;\n}\n\n/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */\nconst monotonic = (): number => {\n const performance = (globalThis as { performance?: { now(): number } }).performance;\n return performance === undefined ? Date.now() : performance.now();\n};\n\n/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */\nconst LONGEST_DELAY = 0x7fffffff;\n\n/**\n * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel\n * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.\n */\nexport const platformClock = (options: PlatformClockOptions = {}): Clock => ({\n now: monotonic,\n after(ms, run) {\n let unrefed = options.unref === true;\n const arm = (left: number): ReturnType<typeof setTimeout> => {\n const step =\n left > LONGEST_DELAY ? setTimeout(() => (timer = arm(left - LONGEST_DELAY)), LONGEST_DELAY) : setTimeout(run, Math.max(0, left));\n if (unrefed) (step as { unref?: () => void }).unref?.();\n return step;\n };\n let timer = arm(ms);\n const unref = (): void => {\n unrefed = true;\n (timer as { unref?: () => void }).unref?.();\n };\n return Object.assign(() => clearTimeout(timer), { unref });\n },\n});\n\n/**\n * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node\n * process alive, thus a timer that is not stopped cannot stop the exit of the process.\n */\nexport const realClock: Clock = /* @__PURE__ */ platformClock({ unref: true });\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n"],"mappings":";;AA6BA,MAAM,kBAA0B;CAC9B,MAAM,cAAe,WAAmD;CACxE,OAAO,gBAAgB,KAAA,IAAY,KAAK,IAAI,IAAI,YAAY,IAAI;AAClE;;AAGA,MAAM,gBAAgB;;;;;AAMtB,MAAa,iBAAiB,UAAgC,CAAC,OAAc;CAC3E,KAAK;CACL,MAAM,IAAI,KAAK;EACb,IAAI,UAAU,QAAQ,UAAU;EAChC,MAAM,OAAO,SAAgD;GAC3D,MAAM,OACJ,OAAO,gBAAgB,iBAAkB,QAAQ,IAAI,OAAO,aAAa,GAAI,aAAa,IAAI,WAAW,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC;GACjI,IAAI,SAAS,KAAiC,Q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IAAI,CAAC,OAAO,GAAG,CAAE,MAAM,OAAO,OAAO,IAAI,CAAC;GAC7F,MAAM,OAAO;EACf;EACA,MAAM,IAAI;GACR,OAAO,KAAK,IAAI,GAAG,EAAE;EACvB;EACA,IAAI,UAAU;GACZ,OAAO,OAAO,QAAQ,UAAU,MAAM,IAAI,CAAC,CAAC;EAC9C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"clock.js","names":[],"sources":["../src/clock.ts"],"sourcesContent":["// @mark1russell7/algebra/clock: the clock of a runtime, a fake clock for tests, and civil time. It imports\n// nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it.\n// The service gives this clock again as @mark1russell7/service/clock.\n\n/**\n * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of\n * the platform also gives `unref`: after it, the timer does not keep a Node process alive.\n */\nexport type Cancel = (() => void) & { readonly unref?: (() => void) | undefined };\n\n/**\n * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The\n * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of\n * the runtime is then exact and repeatable.\n */\nexport interface Clock {\n /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/** These options make a clock of the platform. */\nexport interface PlatformClockOptions {\n /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */\n readonly unref?: boolean | undefined;\n}\n\n/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */\nconst monotonic = (): number => {\n const performance = (globalThis as { performance?: { now(): number } }).performance;\n return performance === undefined ? Date.now() : performance.now();\n};\n\n/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */\nconst LONGEST_DELAY = 0x7fffffff;\n\n/**\n * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel\n * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.\n */\nexport const platformClock = (options: PlatformClockOptions = {}): Clock => ({\n now: monotonic,\n after(ms, run) {\n let unrefed = options.unref === true;\n const arm = (left: number): ReturnType<typeof setTimeout> => {\n const step =\n left > LONGEST_DELAY ? setTimeout(() => (timer = arm(left - LONGEST_DELAY)), LONGEST_DELAY) : setTimeout(run, Math.max(0, left));\n if (unrefed) (step as { unref?: () => void }).unref?.();\n return step;\n };\n let timer = arm(ms);\n const unref = (): void => {\n unrefed = true;\n (timer as { unref?: () => void }).unref?.();\n };\n return Object.assign(() => clearTimeout(timer), { unref });\n },\n});\n\n/**\n * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node\n * process alive, thus a timer that is not stopped cannot stop the exit of the process.\n */\nexport const realClock: Clock = /* @__PURE__ */ platformClock({ unref: true });\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n// Civil time: the wall-clock time of an instant in a time zone, and windows of local time. A clock\n// gives instants, and civil time maps an instant to the time on the wall of a zone. It uses only\n// `Intl.DateTimeFormat`, thus this entry still imports nothing.\n\n/**\n * The wall-clock time of an instant in a time zone. An instant is a time in milliseconds from\n * 1970-01-01T00:00:00Z, as `Date.now()` gives. It is not the monotonic time of `Clock.now()`.\n */\nexport interface LocalTime {\n readonly year: number;\n /** The month, from 1 (January) to 12. */\n readonly month: number;\n /** The day of the month, from 1. */\n readonly day: number;\n /** The hour, from 0 to 23. */\n readonly hour: number;\n readonly minute: number;\n readonly second: number;\n /** The day of the week, from 0 (Sunday) to 6 (Saturday). */\n readonly weekday: number;\n /** The offset of the zone from UTC at the instant, in minutes. It is positive east of Greenwich. */\n readonly offset: number;\n}\n\n/**\n * A window of local time that occurs on each day, or on some days of the week. The window is\n * data, thus a configuration can hold it.\n *\n * - The start is in the window, and the end is not.\n * - An end before the start crosses midnight. An end equal to the start gives a window of a full day.\n * - In a change of the clock, the window follows the time on the wall. A start or an end in a gap\n * moves to the end of the gap. Thus a window with its start and its end in one gap does not open.\n * - A local time that occurs two times is in the window two times.\n */\nexport interface TimeWindow {\n /** The IANA name of the time zone, for example `Europe/Berlin`. */\n readonly zone: string;\n /** The start, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly start: string;\n /** The end, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly end: string;\n /**\n * The days of the week on which the window starts, from 0 (Sunday) to 6. When it is absent, the\n * window starts on each day. A window across midnight continues into the next day.\n */\n readonly days?: readonly number[] | undefined;\n}\n\n/** A change of a window: the instant at which it opens or closes. */\nexport interface WindowBoundary {\n readonly at: number;\n /** True: the window opens at `at`. False: it closes. */\n readonly opens: boolean;\n}\n\nconst MINUTE_MS = 60_000;\nconst DAY_MS = 86_400_000;\nconst WEEKDAYS: Readonly<Record<string, number>> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };\nconst LOCAL_TIME = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n\n/**\n * The cache has one format for each good zone name. It keeps no bad name, and it starts again at\n * `ZONE_CACHE_MAX` names. Thus names from configuration input cannot make it grow without a limit.\n */\nconst ZONE_FORMATS = new Map<string, Intl.DateTimeFormat>();\nconst ZONE_CACHE_MAX = 512;\n/** The longest IANA name has 32 characters. A longer name than this limit is not a zone. */\nconst ZONE_NAME_MAX = 100;\n\nconst zoneFormat = (zone: string): Intl.DateTimeFormat | undefined => {\n let format = ZONE_FORMATS.get(zone);\n if (format === undefined) {\n if (typeof zone !== \"string\" || zone.length > ZONE_NAME_MAX) return undefined;\n try {\n format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n era: \"short\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n weekday: \"short\",\n });\n } catch {\n return undefined;\n }\n if (ZONE_FORMATS.size >= ZONE_CACHE_MAX) ZONE_FORMATS.clear();\n ZONE_FORMATS.set(zone, format);\n }\n return format;\n};\n\n/**\n * This function gives the wall-clock time of `instant` in `zone`. It gives `undefined` for a name\n * that is not a time zone, and for an instant that is not a date.\n */\nexport function localTime(instant: number, zone: string): LocalTime | undefined {\n const format = zoneFormat(zone);\n if (format === undefined || !Number.isFinite(instant)) return undefined;\n let parts: Intl.DateTimeFormatPart[];\n try {\n parts = format.formatToParts(instant);\n } catch {\n // an instant out of the range of a date\n return undefined;\n }\n const field: Record<string, string> = {};\n for (const part of parts) field[part.type] = part.value;\n const before = field[\"era\"] === \"BC\" || field[\"era\"] === \"B\";\n const year = before ? 1 - Number(field[\"year\"]) : Number(field[\"year\"]);\n const month = Number(field[\"month\"]);\n const day = Number(field[\"day\"]);\n const hour = Number(field[\"hour\"]) % 24;\n const minute = Number(field[\"minute\"]);\n const second = Number(field[\"second\"]);\n const whole = Math.floor(instant / 1000) * 1000;\n return { year, month, day, hour, minute, second, weekday: WEEKDAYS[field[\"weekday\"] ?? \"\"] ?? 0, offset: (wallOf(year, month, day, hour, minute, second) - whole) / MINUTE_MS };\n}\n\n/** The wall-clock time as an instant in UTC. `Date.UTC` reads a year from 0 to 99 as 1900 to 1999, thus this function sets the year by itself. */\nconst wallOf = (year: number, month: number, day: number, hour: number, minute: number, second: number): number => {\n const wall = new Date(0);\n wall.setUTCFullYear(year, month - 1, day);\n wall.setUTCHours(hour, minute, second, 0);\n return wall.getTime();\n};\n\n/** The minutes from midnight of a local time `HH:MM`. */\nconst minutesOf = (time: string): number | undefined => {\n const match = LOCAL_TIME.exec(time);\n return match === null ? undefined : Number(match[1]) * 60 + Number(match[2]);\n};\n\ninterface CheckedWindow {\n readonly start: number;\n readonly end: number;\n readonly days: ReadonlySet<number> | undefined;\n}\n\nconst isDay = (day: number): boolean => Number.isInteger(day) && day >= 0 && day <= 6;\n\nconst checked = (window: TimeWindow): CheckedWindow | undefined => {\n const start = minutesOf(window.start);\n const end = minutesOf(window.end);\n if (start === undefined || end === undefined || zoneFormat(window.zone) === undefined) return undefined;\n if (window.days !== undefined && !window.days.every(isDay)) return undefined;\n return { start, end, days: window.days === undefined ? undefined : new Set(window.days) };\n};\n\nconst within = (window: CheckedWindow, local: LocalTime): boolean => {\n const minute = local.hour * 60 + local.minute;\n const startsOn = (weekday: number): boolean => window.days === undefined || window.days.has(weekday);\n if (window.start < window.end) return window.start <= minute && minute < window.end && startsOn(local.weekday);\n // across midnight, or a full day: the part from the start, then the part before the end on the next day\n return (minute >= window.start && startsOn(local.weekday)) || (minute < window.end && startsOn((local.weekday + 6) % 7));\n};\n\n/**\n * This function tells if `instant` is in the window. It does not throw. A bad window or a bad\n * instant gives `false`, and `windowProblems` finds the bad window.\n */\nexport function inWindow(instant: number, window: TimeWindow): boolean {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n return valid !== undefined && local !== undefined && within(valid, local);\n}\n\n/**\n * The instants at which the wall clock of the zone shows `wall`, a wall-clock time as an instant in\n * UTC. A gap gives none, and an overlap gives two.\n */\nconst instantsOf = (wall: number, zone: string): number[] => {\n const offsets = new Set<number>();\n for (const probe of [wall - DAY_MS, wall, wall + DAY_MS]) {\n const local = localTime(probe, zone);\n if (local !== undefined) offsets.add(local.offset);\n }\n const found: number[] = [];\n for (const offset of offsets) {\n const instant = wall - offset * MINUTE_MS;\n const local = localTime(instant, zone);\n if (local === undefined) continue;\n const back = wallOf(local.year, local.month, local.day, local.hour, local.minute, local.second);\n if (back === wall && !found.includes(instant)) found.push(instant);\n }\n return found;\n};\n\n/**\n * The instants in (from, to] at which the offset of the zone changes, each one exact to the\n * millisecond. The search reads the offset each 6 hours. No zone changes its offset two times in 6 hours.\n */\nconst changesOf = (from: number, to: number, zone: string): number[] => {\n const offsetAt = (instant: number): number | undefined => localTime(instant, zone)?.offset;\n const found: number[] = [];\n let low = from;\n let before = offsetAt(low);\n while (low < to) {\n const high = Math.min(low + DAY_MS / 4, to);\n const after = offsetAt(high);\n if (before !== undefined && after !== undefined && after !== before) {\n // the first instant with the new offset\n let left = low;\n let right = high;\n while (right - left > 1) {\n const middle = Math.floor((left + right) / 2);\n if (offsetAt(middle) === before) left = middle;\n else right = middle;\n }\n found.push(right);\n }\n low = high;\n before = after;\n }\n return found;\n};\n\n/**\n * This function gives the next change of the window after `instant`: the first later instant at\n * which the window opens or closes. A timer can wait for it in closed form. It gives `undefined`\n * for a bad window, and when the window does not change in the 9 days after `instant`. A window\n * with no day and a full-day window on each day do not change.\n */\nexport function nextBoundary(instant: number, window: TimeWindow): WindowBoundary | undefined {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n if (valid === undefined || local === undefined) return undefined;\n const inside = within(valid, local);\n const horizon = instant + 9 * DAY_MS;\n // The state changes only where the wall clock shows the start or the end, or where the offset changes.\n const candidates = changesOf(instant, horizon, window.zone);\n const midnight = wallOf(local.year, local.month, local.day, 0, 0, 0);\n for (let day = -1; day <= 10; day += 1) {\n for (const minutes of [valid.start, valid.end]) candidates.push(...instantsOf(midnight + day * DAY_MS + minutes * MINUTE_MS, window.zone));\n }\n candidates.sort((a, b) => a - b);\n for (const at of candidates) {\n if (at <= instant || at > horizon) continue;\n const there = localTime(at, window.zone);\n if (there !== undefined && within(valid, there) !== inside) return { at, opens: !inside };\n }\n return undefined;\n}\n\n/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */\nexport function windowProblems(window: TimeWindow): string[] {\n const problems: string[] = [];\n if (zoneFormat(window.zone) === undefined) problems.push(`\"${window.zone}\" is not the IANA name of a time zone.`);\n if (minutesOf(window.start) === undefined) problems.push(`The start \"${window.start}\" is not a local time HH:MM from 00:00 to 23:59.`);\n if (minutesOf(window.end) === undefined) problems.push(`The end \"${window.end}\" is not a local time HH:MM from 00:00 to 23:59.`);\n for (const day of window.days ?? []) {\n if (!isDay(day)) problems.push(`The day ${day} is not a day of the week from 0 (Sunday) to 6.`);\n }\n if (window.days !== undefined && window.days.length === 0) problems.push(\"The window has no day, thus it does not open.\");\n return problems;\n}\n"],"mappings":";;AA6BA,MAAM,kBAA0B;CAC9B,MAAM,cAAe,WAAmD;CACxE,OAAO,gBAAgB,KAAA,IAAY,KAAK,IAAI,IAAI,YAAY,IAAI;AAClE;;AAGA,MAAM,gBAAgB;;;;;AAMtB,MAAa,iBAAiB,UAAgC,CAAC,OAAc;CAC3E,KAAK;CACL,MAAM,IAAI,KAAK;EACb,IAAI,UAAU,QAAQ,UAAU;EAChC,MAAM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AAM,WAAW,CAAC,MAAM,OAAO,MAAM,GAAG,GAAG,WAAW,KAAK,GAAG,WAAW,WAAW,MAAM,SAAS,UAAU,WAAW,OAAO,IAAI,CAAC;CAE3I,WAAW,MAAM,GAAG,MAAM,IAAI,CAAC;CAC/B,KAAK,MAAM,MAAM,YAAY;EAC3B,IAAI,MAAM,WAAW,KAAK,SAAS;EACnC,MAAM,QAAQ,UAAU,IAAI,OAAO,IAAI;EACvC,IAAI,UAAU,KAAA,KAAa,OAAO,OAAO,KAAK,MAAM,QAAQ,OAAO;GAAE;GAAI,OAAO,CAAC;EAAO;CAC1F;AAEF;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,MAAM,WAAqB,CAAC;CAC5B,IAAI,WAAW,OAAO,IAAI,MAAM,KAAA,GAAW,SAAS,KAAK,IAAI,OAAO,KAAK,uCAAuC;CAChH,IAAI,UAAU,OAAO,KAAK,MAAM,KAAA,GAAW,SAAS,KAAK,cAAc,OAAO,MAAM,iDAAiD;CACrI,IAAI,UAAU,OAAO,GAAG,MAAM,KAAA,GAAW,SAAS,KAAK,YAAY,OAAO,IAAI,iDAAiD;CAC/H,KAAK,MAAM,OAAO,OAAO,QAAQ,CAAC,GAChC,IAAI,CAAC,MAAM,GAAG,GAAG,SAAS,KAAK,WAAW,IAAI,gDAAgD;CAEhG,IAAI,OAAO,SAAS,KAAA,KAAa,OAAO,KAAK,WAAW,GAAG,SAAS,KAAK,+CAA+C;CACxH,OAAO;AACT"}
|
package/build/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as Realization, c as Unit, d as machineProblems, f as readsFired, i as Over, l as Vantage, n as FIRED, o as Timer, r as Machine, s as TransitionDef, t as Expr, u as exprKnobs } from "./machine-yGpVFyfh.js";
|
|
2
2
|
import { i as replay, n as Replayable, r as Transition, t as ReplayOptions } from "./replay-DRTZc7Pw.js";
|
|
3
|
-
import { A as timerBand, C as parseExpr, D as recovery, E as realizationOf, M as timerUnder, N as transitionOn, O as stackedDetection, S as overValues, T as realizationKnobs, _ as detection, a as Detection, b as firings, c as KnobValues, d as Recovery, f as ScheduleOptions, g as algebraProblems, h as TimerBounds, i as Band, j as timerOf, k as synGiveUpSends, l as Manifestation, m as Situation, n as RunMachineOptions, o as Detector, p as Scheduled, r as runMachine, s as Firing, t as MachineRun, u as Node, v as errnoOf, w as probeTrain, x as modelSource, y as evaluate } from "./run-
|
|
3
|
+
import { A as timerBand, C as parseExpr, D as recovery, E as realizationOf, M as timerUnder, N as transitionOn, O as stackedDetection, S as overValues, T as realizationKnobs, _ as detection, a as Detection, b as firings, c as KnobValues, d as Recovery, f as ScheduleOptions, g as algebraProblems, h as TimerBounds, i as Band, j as timerOf, k as synGiveUpSends, l as Manifestation, m as Situation, n as RunMachineOptions, o as Detector, p as Scheduled, r as runMachine, s as Firing, t as MachineRun, u as Node, v as errnoOf, w as probeTrain, x as modelSource, y as evaluate } from "./run-yLPq18NQ.js";
|
|
4
4
|
/** This function gives one value or many values as an array. */
|
|
5
5
|
export declare const arr: <T>(value: T | readonly T[]) => readonly T[];
|
|
6
6
|
/** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as Machine, s as TransitionDef, t as Expr } from "./machine-yGpVFyfh.js";
|
|
2
|
-
import { n as Clock } from "./clock-
|
|
2
|
+
import { n as Clock } from "./clock-5u5mZpjL.js";
|
|
3
3
|
import { r as Transition } from "./replay-DRTZc7Pw.js";
|
|
4
4
|
import { Extent, Quantity, Rational, Unknown } from "@mark1russell7/quantity";
|
|
5
5
|
/**
|
package/build/run.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as RunMachineOptions, r as runMachine, t as MachineRun } from "./run-
|
|
1
|
+
import { n as RunMachineOptions, r as runMachine, t as MachineRun } from "./run-yLPq18NQ.js";
|
|
2
2
|
export { MachineRun, RunMachineOptions, runMachine };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/algebra",
|
|
4
|
-
"version": "0.8.
|
|
4
|
+
"version": "0.8.7",
|
|
5
5
|
"description": "State machines as data, and the timer algebra over them: closed forms for a machine's timers in exact rationals, detection as the first live timer, recovery after a stall, and the replay of a trace.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"state-machine",
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This function stops a timer that `Clock.after` started. A second use does nothing. A clock of
|
|
3
|
-
* the platform also gives `unref`: after it, the timer does not keep a Node process alive.
|
|
4
|
-
*/
|
|
5
|
-
type Cancel = (() => void) & {
|
|
6
|
-
readonly unref?: (() => void) | undefined;
|
|
7
|
-
};
|
|
8
|
-
/**
|
|
9
|
-
* A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The
|
|
10
|
-
* runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of
|
|
11
|
-
* the runtime is then exact and repeatable.
|
|
12
|
-
*/
|
|
13
|
-
interface Clock {
|
|
14
|
-
/** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */
|
|
15
|
-
now(): number;
|
|
16
|
-
/** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */
|
|
17
|
-
after(ms: number, run: () => void): Cancel;
|
|
18
|
-
}
|
|
19
|
-
/** These options make a clock of the platform. */
|
|
20
|
-
interface PlatformClockOptions {
|
|
21
|
-
/** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */
|
|
22
|
-
readonly unref?: boolean | undefined;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
|
|
26
|
-
* that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
|
|
27
|
-
*/
|
|
28
|
-
declare const platformClock: (options?: PlatformClockOptions) => Clock;
|
|
29
|
-
/**
|
|
30
|
-
* This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node
|
|
31
|
-
* process alive, thus a timer that is not stopped cannot stop the exit of the process.
|
|
32
|
-
*/
|
|
33
|
-
declare const realClock: Clock;
|
|
34
|
-
/** A fake clock moves only when a test tells it to. */
|
|
35
|
-
interface FakeClock extends Clock {
|
|
36
|
-
/** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */
|
|
37
|
-
advance(ms: number): Promise<void>;
|
|
38
|
-
/**
|
|
39
|
-
* This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.
|
|
40
|
-
* The next `advance` then starts each timer that came due during the block, late.
|
|
41
|
-
*/
|
|
42
|
-
block(ms: number): void;
|
|
43
|
-
/** This count is the number of timers that are not stopped and not called. */
|
|
44
|
-
readonly pending: number;
|
|
45
|
-
}
|
|
46
|
-
/** This function makes a fake clock. Its time starts at `start` milliseconds. */
|
|
47
|
-
declare const fakeClock: (start?: number) => FakeClock;
|
|
48
|
-
export { fakeClock as a, PlatformClockOptions as i, Clock as n, platformClock as o, FakeClock as r, realClock as s, Cancel as t };
|