@connextar/house 0.27.0 → 0.28.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.
@@ -0,0 +1,387 @@
1
+ import * as z from "zod";
2
+
3
+ /**
4
+ * The rules of a day / week / month calendar, with no markup and no database in them.
5
+ *
6
+ * Which view is showing and which day it is anchored on (`parseCalendarQuery`, `calendarQuery`), what that view covers
7
+ * (`visibleRange`, `visibleDays`, `visibleWindow`), how ‹ › and the quick ranges move it (`stepAnchor`,
8
+ * `QUICK_RANGES`), what the date button and heading say (`rangeLabel`, `rangeHeading`), and how a day's timed items
9
+ * are laid out and moved (`gridSlots`, `layoutDay`, `movedTimes`). Built from quickie's planner and AltEd's port of it.
10
+ *
11
+ * Days are calendar days as `yyyy-MM-dd` keys and times are wall-clock minutes past midnight in a named time zone, so a
12
+ * 10:00 lesson sits at 10:00 all year. Day arithmetic is done on the keys themselves — never on a local `Date` — so the
13
+ * server's zone and the browser's can't move a day. Weeks start on Monday (en-GB).
14
+ */
15
+
16
+ export const CALENDAR_VIEW_NAMES = ["day", "week", "month"] as const;
17
+ export type CalendarView = (typeof CALENDAR_VIEW_NAMES)[number];
18
+
19
+ export const CALENDAR_VIEWS: readonly { value: CalendarView; label: string }[] = [
20
+ { value: "day", label: "Day" },
21
+ { value: "week", label: "Week" },
22
+ { value: "month", label: "Month" },
23
+ ];
24
+
25
+ /** A view's name, for a request body or a stored setting. */
26
+ export const calendarViewSchema = z.enum(CALENDAR_VIEW_NAMES);
27
+
28
+ export function isCalendarView(value: unknown): value is CalendarView {
29
+ return typeof value === "string" && (CALENDAR_VIEW_NAMES as readonly string[]).includes(value);
30
+ }
31
+
32
+ // ---------------------------------------------------------------------------------------------------------------------
33
+ // Day keys
34
+
35
+ const KEY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
36
+ const DAY_MS = 86_400_000;
37
+ const MONTHS = [
38
+ "January",
39
+ "February",
40
+ "March",
41
+ "April",
42
+ "May",
43
+ "June",
44
+ "July",
45
+ "August",
46
+ "September",
47
+ "October",
48
+ "November",
49
+ "December",
50
+ ];
51
+ const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
52
+
53
+ function utcOf(key: string): number {
54
+ const [, y, m, d] = KEY_PATTERN.exec(key) ?? [];
55
+ return Date.UTC(Number(y), Number(m) - 1, Number(d));
56
+ }
57
+
58
+ function keyOf(utc: number): string {
59
+ return new Date(utc).toISOString().slice(0, 10);
60
+ }
61
+
62
+ /** Whether `value` is a real day key between the years 1900 and 2200 — not "2026-02-30". */
63
+ export function isDayKey(value: unknown): value is string {
64
+ if (typeof value !== "string" || !KEY_PATTERN.test(value)) return false;
65
+ const year = Number(value.slice(0, 4));
66
+ return year > 1900 && year < 2200 && keyOf(utcOf(value)) === value;
67
+ }
68
+
69
+ export function addDays(key: string, days: number): string {
70
+ return keyOf(utcOf(key) + days * DAY_MS);
71
+ }
72
+
73
+ /** The same day `months` on, or the month's last day when it hasn't got one (31 January + 1 → 28 February). */
74
+ export function addMonths(key: string, months: number): string {
75
+ const date = new Date(utcOf(key));
76
+ const target = date.getUTCMonth() + months;
77
+ const last = new Date(Date.UTC(date.getUTCFullYear(), target + 1, 0)).getUTCDate();
78
+ return keyOf(Date.UTC(date.getUTCFullYear(), target, Math.min(date.getUTCDate(), last)));
79
+ }
80
+
81
+ /** 0 for Sunday to 6 for Saturday, as `Date.getDay`. */
82
+ export function weekdayOf(key: string): number {
83
+ return new Date(utcOf(key)).getUTCDay();
84
+ }
85
+
86
+ /** The Monday of the day's week. */
87
+ export function startOfWeek(key: string): string {
88
+ return addDays(key, -((weekdayOf(key) + 6) % 7));
89
+ }
90
+
91
+ export function startOfMonth(key: string): string {
92
+ return `${key.slice(0, 7)}-01`;
93
+ }
94
+
95
+ export function endOfMonth(key: string): string {
96
+ return addDays(addMonths(startOfMonth(key), 1), -1);
97
+ }
98
+
99
+ /** The day keys from `start` to `end`, both included. */
100
+ export function daysBetween(start: string, end: string): string[] {
101
+ const days: string[] = [];
102
+ for (let d = start; d <= end; d = addDays(d, 1)) days.push(d);
103
+ return days;
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------------------------------------------------
107
+ // Time zones
108
+
109
+ function zoneParts(instant: Date, timeZone: string): Record<string, string> {
110
+ return Object.fromEntries(
111
+ new Intl.DateTimeFormat("en-CA", {
112
+ timeZone,
113
+ hourCycle: "h23",
114
+ year: "numeric",
115
+ month: "2-digit",
116
+ day: "2-digit",
117
+ hour: "2-digit",
118
+ minute: "2-digit",
119
+ second: "2-digit",
120
+ })
121
+ .formatToParts(instant)
122
+ .map((part) => [part.type, part.value]),
123
+ );
124
+ }
125
+
126
+ function offsetMinutes(instant: Date, timeZone: string): number {
127
+ const p = zoneParts(instant, timeZone);
128
+ const asUtc = Date.UTC(
129
+ Number(p.year),
130
+ Number(p.month) - 1,
131
+ Number(p.day),
132
+ Number(p.hour),
133
+ Number(p.minute),
134
+ Number(p.second),
135
+ );
136
+ return Math.round((asUtc - Math.floor(instant.getTime() / 1000) * 1000) / 60_000);
137
+ }
138
+
139
+ /**
140
+ * The instant `day` at `minutes` past midnight happens in `timeZone`. Worked out twice, so a time on the day the clocks
141
+ * change lands right too.
142
+ */
143
+ export function zonedInstant(day: string, minutes: number, timeZone: string): Date {
144
+ const wallClockAsUtc = utcOf(day) + minutes * 60_000;
145
+ const first = wallClockAsUtc - offsetMinutes(new Date(wallClockAsUtc), timeZone) * 60_000;
146
+ return new Date(wallClockAsUtc - offsetMinutes(new Date(first), timeZone) * 60_000);
147
+ }
148
+
149
+ /** Where an instant falls on the calendar in `timeZone`: its day and minutes past midnight. */
150
+ export function placeOf(instant: string | Date, timeZone: string): { day: string; minutes: number } {
151
+ const p = zoneParts(typeof instant === "string" ? new Date(instant) : instant, timeZone);
152
+ return { day: `${p.year}-${p.month}-${p.day}`, minutes: Number(p.hour) * 60 + Number(p.minute) };
153
+ }
154
+
155
+ /** Today in `timeZone`, as a day key. */
156
+ export function todayIn(timeZone: string, now: Date = new Date()): string {
157
+ return placeOf(now, timeZone).day;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------------------------------------------------
161
+ // The address
162
+
163
+ type QueryInput = URLSearchParams | Record<string, string | string[] | undefined>;
164
+
165
+ function first(query: QueryInput, name: string): string | undefined {
166
+ if (query instanceof URLSearchParams) return query.get(name) ?? undefined;
167
+ const value = query[name];
168
+ return Array.isArray(value) ? value[0] : value;
169
+ }
170
+
171
+ /**
172
+ * The view and anchor day from `?view=&date=` — a request's search params or a page's `searchParams`. Anything
173
+ * unreadable is the default view (the app's, or the reader's remembered one) and today.
174
+ */
175
+ export function parseCalendarQuery(
176
+ query: QueryInput,
177
+ todayKey: string,
178
+ defaultView: CalendarView = "month",
179
+ ): { view: CalendarView; anchor: string } {
180
+ const view = first(query, "view");
181
+ const date = first(query, "date");
182
+ return { view: isCalendarView(view) ? view : defaultView, anchor: isDayKey(date) ? date : todayKey };
183
+ }
184
+
185
+ /** The query string for a view and day, `view=week&date=2026-11-23`, to put after the calendar's path and a `?`. */
186
+ export function calendarQuery(view: CalendarView, anchor: string): string {
187
+ return new URLSearchParams({ view, date: anchor }).toString();
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------------------------------------------------
191
+ // What a view covers
192
+
193
+ /** The first and last day a view shows: the day, its Monday–Sunday week, or the whole weeks around its month. */
194
+ export function visibleRange(view: CalendarView, anchor: string): { start: string; end: string } {
195
+ if (view === "day") return { start: anchor, end: anchor };
196
+ if (view === "week") return { start: startOfWeek(anchor), end: addDays(startOfWeek(anchor), 6) };
197
+ return { start: startOfWeek(startOfMonth(anchor)), end: addDays(startOfWeek(endOfMonth(anchor)), 6) };
198
+ }
199
+
200
+ /** Every day a view shows, in order; with `weekdaysOnly`, the week and month views leave out Saturday and Sunday. */
201
+ export function visibleDays(view: CalendarView, anchor: string, weekdaysOnly = false): string[] {
202
+ const { start, end } = visibleRange(view, anchor);
203
+ const days = daysBetween(start, end);
204
+ return view !== "day" && weekdaysOnly ? days.filter((d) => ![0, 6].includes(weekdayOf(d))) : days;
205
+ }
206
+
207
+ /**
208
+ * The instants a view covers, `[from, to)`: midnight of its first day to midnight after its last, in `timeZone`. Read
209
+ * only what falls in it — and for a repeating item, every time it happens in it.
210
+ */
211
+ export function visibleWindow(view: CalendarView, anchor: string, timeZone: string): { from: Date; to: Date } {
212
+ const { start, end } = visibleRange(view, anchor);
213
+ return { from: zonedInstant(start, 0, timeZone), to: zonedInstant(addDays(end, 1), 0, timeZone) };
214
+ }
215
+
216
+ /** The anchor one step back or on: a day, a week, or the first of the month before or after. */
217
+ export function stepAnchor(view: CalendarView, anchor: string, by: 1 | -1): string {
218
+ if (view === "day") return addDays(anchor, by);
219
+ if (view === "week") return addDays(anchor, 7 * by);
220
+ return startOfMonth(addMonths(startOfMonth(anchor), by));
221
+ }
222
+
223
+ export interface QuickRange {
224
+ key: string;
225
+ label: string;
226
+ view: CalendarView;
227
+ anchor: (todayKey: string) => string;
228
+ }
229
+
230
+ /** The ranges a date button offers beside its months. */
231
+ export const QUICK_RANGES: readonly QuickRange[] = [
232
+ { key: "today", label: "Today", view: "day", anchor: (t) => t },
233
+ { key: "tomorrow", label: "Tomorrow", view: "day", anchor: (t) => addDays(t, 1) },
234
+ { key: "yesterday", label: "Yesterday", view: "day", anchor: (t) => addDays(t, -1) },
235
+ { key: "this-week", label: "This week", view: "week", anchor: (t) => startOfWeek(t) },
236
+ { key: "next-week", label: "Next week", view: "week", anchor: (t) => startOfWeek(addDays(t, 7)) },
237
+ { key: "last-week", label: "Last week", view: "week", anchor: (t) => startOfWeek(addDays(t, -7)) },
238
+ { key: "this-month", label: "This month", view: "month", anchor: (t) => startOfMonth(t) },
239
+ { key: "next-month", label: "Next month", view: "month", anchor: (t) => addMonths(startOfMonth(t), 1) },
240
+ { key: "last-month", label: "Last month", view: "month", anchor: (t) => addMonths(startOfMonth(t), -1) },
241
+ ];
242
+
243
+ /** The quick range a view and anchor are, if any ("This week"), so the button can say so. */
244
+ export function matchingQuickRange(view: CalendarView, anchor: string, todayKey: string): QuickRange | null {
245
+ const shown = visibleRange(view, anchor);
246
+ return (
247
+ QUICK_RANGES.find((range) => {
248
+ if (range.view !== view) return false;
249
+ const theirs = visibleRange(range.view, range.anchor(todayKey));
250
+ return theirs.start === shown.start && theirs.end === shown.end;
251
+ }) ?? null
252
+ );
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------------------------------------------------
256
+ // Words
257
+
258
+ const pad = (n: number) => String(n).padStart(2, "0");
259
+
260
+ function parts(key: string) {
261
+ const date = new Date(utcOf(key));
262
+ return { y: date.getUTCFullYear(), m: date.getUTCMonth(), d: date.getUTCDate(), w: date.getUTCDay() };
263
+ }
264
+
265
+ /** "12/11/2026". */
266
+ export function shortDate(key: string): string {
267
+ const { y, m, d } = parts(key);
268
+ return `${pad(d)}/${pad(m + 1)}/${y}`;
269
+ }
270
+
271
+ /** "Thursday 12 November 2026". */
272
+ export function longDate(key: string): string {
273
+ const { y, m, d, w } = parts(key);
274
+ return `${WEEKDAYS[w]} ${d} ${MONTHS[m]} ${y}`;
275
+ }
276
+
277
+ /** "November 2026". */
278
+ export function monthTitle(key: string): string {
279
+ const { y, m } = parts(key);
280
+ return `${MONTHS[m]} ${y}`;
281
+ }
282
+
283
+ /** "Mon", "Tue"… for a day key; `long` gives "Monday". */
284
+ export function weekdayName(key: string, long = false): string {
285
+ const name = WEEKDAYS[weekdayOf(key)] ?? "";
286
+ return long ? name : name.slice(0, 3);
287
+ }
288
+
289
+ /**
290
+ * What the date button says: the quick range's name when it is one ("Last week"), otherwise the dates —
291
+ * "Thu 12/11/2026", "02/11/2026 – 08/11/2026" or "November 2026".
292
+ */
293
+ export function rangeLabel(view: CalendarView, anchor: string, todayKey: string): string {
294
+ const quick = matchingQuickRange(view, anchor, todayKey);
295
+ if (quick) return quick.label;
296
+ if (view === "day") return `${weekdayName(anchor)} ${shortDate(anchor)}`;
297
+ if (view === "month") return monthTitle(anchor);
298
+ const { start, end } = visibleRange("week", anchor);
299
+ return `${shortDate(start)} – ${shortDate(end)}`;
300
+ }
301
+
302
+ /** The heading over the grid: "Thursday 12 November 2026", "2 – 8 Nov 2026", "30 Nov – 6 Dec 2026", "November 2026". */
303
+ export function rangeHeading(view: CalendarView, anchor: string): string {
304
+ if (view === "day") return longDate(anchor);
305
+ if (view === "month") return monthTitle(anchor);
306
+ const { start, end } = visibleRange("week", anchor);
307
+ const s = parts(start);
308
+ const e = parts(end);
309
+ const mon = (m: number) => (MONTHS[m] ?? "").slice(0, 3);
310
+ if (s.y !== e.y) return `${s.d} ${mon(s.m)} ${s.y} – ${e.d} ${mon(e.m)} ${e.y}`;
311
+ return s.m === e.m ? `${s.d} – ${e.d} ${mon(e.m)} ${e.y}` : `${s.d} ${mon(s.m)} – ${e.d} ${mon(e.m)} ${e.y}`;
312
+ }
313
+
314
+ /** Minutes past midnight as `HH:mm`. */
315
+ export function hhmm(minutes: number): string {
316
+ return `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------------------------------------------------
320
+ // The day and week grids
321
+
322
+ export interface GridHours {
323
+ /** The first hour the grid shows, 0–23. */
324
+ startHour: number;
325
+ /** The hour it ends at, 1–24, after `startHour`. */
326
+ endHour: number;
327
+ slotMinutes: 30 | 60;
328
+ }
329
+
330
+ /**
331
+ * The rows of a day or week grid, as minutes past midnight: every slot from the first hour to the last, widened to the
332
+ * hour to take in anything timed outside them.
333
+ */
334
+ export function gridSlots(hours: GridHours, spans: readonly { start: number; end: number }[]): number[] {
335
+ const earliest = Math.min(hours.startHour * 60, ...spans.map((s) => Math.floor(s.start / 60) * 60));
336
+ const latest = Math.max(hours.endHour * 60, ...spans.map((s) => Math.ceil(s.end / 60) * 60));
337
+ const slots: number[] = [];
338
+ for (let m = Math.max(0, earliest); m < Math.min(24 * 60, latest); m += hours.slotMinutes) slots.push(m);
339
+ return slots;
340
+ }
341
+
342
+ /**
343
+ * Each timed item's place in its day: its lane among the ones it overlaps, and how many lanes that cluster of
344
+ * overlapping items has — so two lessons at 15:00 sit side by side at half width each.
345
+ */
346
+ export function layoutDay<T extends { start: number; end: number }>(
347
+ items: readonly T[],
348
+ ): (T & { lane: number; lanes: number })[] {
349
+ const sorted = [...items].sort((a, b) => a.start - b.start || b.end - a.end);
350
+ const placed: (T & { lane: number; lanes: number })[] = [];
351
+ let cluster: (T & { lane: number; lanes: number })[] = [];
352
+ let clusterEnd = -1;
353
+ let laneEnds: number[] = [];
354
+ const close = () => {
355
+ for (const p of cluster) p.lanes = laneEnds.length;
356
+ cluster = [];
357
+ laneEnds = [];
358
+ };
359
+ for (const item of sorted) {
360
+ if (item.start >= clusterEnd) close();
361
+ let lane = laneEnds.findIndex((end) => end <= item.start);
362
+ if (lane < 0) lane = laneEnds.push(item.end) - 1;
363
+ else laneEnds[lane] = item.end;
364
+ const p = { ...item, lane, lanes: 1 };
365
+ cluster.push(p);
366
+ placed.push(p);
367
+ clusterEnd = Math.max(clusterEnd, item.end);
368
+ }
369
+ close();
370
+ return placed;
371
+ }
372
+
373
+ /**
374
+ * An item's new times when it's dropped on `day` at `minutes` past midnight in `timeZone` — or, with `minutes` null (a
375
+ * month cell), at its own time of day — keeping its length. ISO strings in, ISO strings out.
376
+ */
377
+ export function movedTimes(
378
+ item: { startTime: string; endTime: string },
379
+ day: string,
380
+ minutes: number | null,
381
+ timeZone: string,
382
+ ): { startTime: string; endTime: string } {
383
+ const start = new Date(item.startTime);
384
+ const length = new Date(item.endTime).getTime() - start.getTime();
385
+ const next = zonedInstant(day, minutes ?? placeOf(start, timeZone).minutes, timeZone);
386
+ return { startTime: next.toISOString(), endTime: new Date(next.getTime() + length).toISOString() };
387
+ }
@@ -5,7 +5,12 @@ import type { MessageStream } from "@anthropic-ai/sdk/lib/MessageStream";
5
5
  import OpenAI from "openai";
6
6
 
7
7
  import { PROVIDER_LABELS, type AiProviderName, type ResolvedAi } from "../../ai/config.js";
8
- import { AiServiceError, OPENAI_MIN_OUTPUT_TOKENS, type AiCallResult } from "../../ai/provider.js";
8
+ import {
9
+ AiServiceError,
10
+ OPENAI_MIN_OUTPUT_TOKENS,
11
+ openAiReasoningEffortFor,
12
+ type AiCallResult,
13
+ } from "../../ai/provider.js";
9
14
  import { TransferLineStream } from "./transfer-line.js";
10
15
 
11
16
  /**
@@ -74,7 +79,10 @@ export interface DialogModel {
74
79
  /** The resolved provider, key and model, how long a reply may run, and the app's tools. */
75
80
  export interface DialogModelOptions extends ResolvedAi {
76
81
  maxTokens?: number;
77
- /** How hard an OpenAI reasoning model thinks before it speaks. Sent only when set. */
82
+ /**
83
+ * How hard an OpenAI reasoning model thinks before it speaks. Sent only when set, and only
84
+ * to a model that reasons; a level the model refuses is mapped (`openAiReasoningEffortFor`).
85
+ */
78
86
  reasoningEffort?: OpenAI.ReasoningEffort;
79
87
  /** How hard a current Claude model thinks before it speaks. Sent only when set. */
80
88
  anthropicEffort?: Anthropic.OutputConfig["effort"];
@@ -271,6 +279,12 @@ function createAnthropicModel(opts: DialogModelOptions): DialogModel {
271
279
  };
272
280
  }
273
281
 
282
+ /** The `reasoning` field for the model, or nothing: see `openAiReasoningEffortFor`. */
283
+ function reasoningFor(opts: DialogModelOptions) {
284
+ const effort = openAiReasoningEffortFor(opts.model, opts.reasoningEffort);
285
+ return effort ? { reasoning: { effort } } : {};
286
+ }
287
+
274
288
  function createOpenAiModel(opts: DialogModelOptions): DialogModel {
275
289
  const client = new OpenAI({ apiKey: opts.apiKey });
276
290
  const toolsFor = memo((team) => openAiTools(opts.tools(team)));
@@ -288,7 +302,7 @@ function createOpenAiModel(opts: DialogModelOptions): DialogModel {
288
302
  input: toResponsesInput(messages),
289
303
  tools: toolsFor(team ?? "open"),
290
304
  max_output_tokens: Math.max(opts.maxTokens ?? DEFAULT_MAX_TOKENS, OPENAI_MIN_OUTPUT_TOKENS),
291
- ...(opts.reasoningEffort ? { reasoning: { effort: opts.reasoningEffort } } : {}),
305
+ ...reasoningFor(opts),
292
306
  // A call's words are personal data: OpenAI keeps none of it for us.
293
307
  store: false,
294
308
  },