@ranzenjs/client 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,6 +37,7 @@ Every portal feature is an app that you open on a connection. Opening makes no r
37
37
  | `@ranzenjs/client/lessons` | Mein Unterricht | `overview()`, `course(id, { semester })`, `setHomeworkDone()`, `download()`, `downloadAll()` |
38
38
  | `@ranzenjs/client/substitutions` | Vertretungsplan | `plan({ full })` |
39
39
  | `@ranzenjs/client/profile` | Benutzerdaten | `get()` |
40
+ | `@ranzenjs/client/calendar` | Kalender | `events({ from, to })`, `categories()`, `details(id)` |
40
41
  | `@ranzenjs/client/catalog` | Start page | `list()`, `offers(app)` |
41
42
 
42
43
  Schools turn apps on and off. To find out whether an account has an app, ask
@@ -52,6 +53,31 @@ const file = await connection
52
53
  await Bun.write('blatt.pdf', new Response(file.body));
53
54
  ```
54
55
 
56
+ ### Calendar
57
+
58
+ ```ts
59
+ import { calendar } from '@ranzenjs/client/calendar';
60
+
61
+ const dates = connection.open(calendar);
62
+ const events = await dates.events({ from: '2026-10-01', to: '2026-10-31' });
63
+ const categories = await dates.categories(); // { id, name, color }, as events refer to by categoryId
64
+ ```
65
+
66
+ `events()` returns every event that overlaps the inclusive range, once per id. The portal has no
67
+ recurrence, so each event is one occurrence. Dates and times are the portal's Europe/Berlin wall
68
+ clock as written. ranzen never converts them through UTC, so `"2026-10-25"` and `"02:30"` mean
69
+ exactly what the school entered. `endDate` is inclusive and never before `startDate`. All-day
70
+ events have `startTime` and `endTime` set to `null`. Descriptions are plain text with their line
71
+ breaks. The portal sometimes encodes them twice. ranzen then turns encoded `<br />` into line
72
+ breaks and keeps any other encoded markup as visible text.
73
+
74
+ The portal ends all-day events at `23:59` of their last day. Should one end at exactly midnight of
75
+ a later day instead, ranzen reads that end as exclusive, the way calendar widgets send it: an event
76
+ from `2026-10-19 00:00:00` to `2026-10-20 00:00:00` lasts only the 19th.
77
+
78
+ `details(id)` loads the responsible person's display name and the target groups of one event. It
79
+ reports `NOT_FOUND` for an unknown id.
80
+
55
81
  ### Sessions
56
82
 
57
83
  `exportState()` returns the portal cookies, the session's cipher secret, and the account. It never
@@ -0,0 +1,13 @@
1
+ import type { SignalOption } from '../../connection.js';
2
+ import type { CalendarCategory, CalendarEvent, CalendarEventDetails, DateRange } from './types.js';
3
+ export type * from './types.js';
4
+ export interface CalendarApi {
5
+ /** Events overlapping the inclusive range, once per id, in the portal's order. */
6
+ events(range: DateRange, options?: SignalOption): Promise<CalendarEvent[]>;
7
+ /** The categories events refer to by categoryId. */
8
+ categories(options?: SignalOption): Promise<CalendarCategory[]>;
9
+ /** Who is responsible for an event and whom it addresses; NOT_FOUND for an unknown id. */
10
+ details(id: string, options?: SignalOption): Promise<CalendarEventDetails>;
11
+ }
12
+ /** "Kalender": the school's events and dates. */
13
+ export declare const calendar: import("../../app.js").App<CalendarApi>;
@@ -0,0 +1,38 @@
1
+ import { defineApp } from '../../app.js';
2
+ import { fail } from '../../errors.js';
3
+ import { isIsoDate, parseCategories, parseEventDetails, parseEvents } from './parse.js';
4
+ const PAGE = 'kalender.php';
5
+ /** "Kalender": the school's events and dates. */
6
+ export const calendar = defineApp({ id: 'calendar', page: PAGE }, (context) => ({
7
+ async events({ from, to }, { signal } = {}) {
8
+ if (!isIsoDate(from) || !isIsoDate(to)) {
9
+ throw fail('INVALID_OPTION', 'from and to must be ISO dates such as "2026-10-19".');
10
+ }
11
+ if (from > to)
12
+ throw fail('INVALID_OPTION', 'from must not be after to.');
13
+ const { text } = await context.page({
14
+ path: PAGE,
15
+ // The portal returns the events overlapping both dates, inclusive.
16
+ form: { f: 'getEvents', start: from, end: to, s: '' },
17
+ ajax: true,
18
+ signal
19
+ });
20
+ // An all-day end read as exclusive can move an event out of the range.
21
+ return parseEvents(text, context.drift).filter((event) => event.startDate <= to && event.endDate >= from);
22
+ },
23
+ async categories({ signal } = {}) {
24
+ const { text } = await context.page({ path: PAGE, signal });
25
+ return parseCategories(text, context.drift);
26
+ },
27
+ async details(id, { signal } = {}) {
28
+ if (!id.trim())
29
+ throw fail('INVALID_OPTION', 'The event id must not be empty.');
30
+ const { text } = await context.page({
31
+ path: PAGE,
32
+ form: { f: 'getEvent', id },
33
+ ajax: true,
34
+ signal
35
+ });
36
+ return parseEventDetails(text, context.drift);
37
+ }
38
+ }));
@@ -0,0 +1,7 @@
1
+ import { type DriftSink } from '../../util.js';
2
+ import type { CalendarCategory, CalendarEvent, CalendarEventDetails } from './types.js';
3
+ export declare function isIsoDate(value: unknown): value is string;
4
+ export declare function parseEvents(body: string, drift?: DriftSink): CalendarEvent[];
5
+ /** Categories from the calendar page's inline script, one object literal per line. */
6
+ export declare function parseCategories(html: string, drift?: DriftSink): CalendarCategory[];
7
+ export declare function parseEventDetails(body: string, drift?: DriftSink): CalendarEventDetails;
@@ -0,0 +1,176 @@
1
+ import { fail, layoutChanged } from '../../errors.js';
2
+ import { parseHtml, text } from '../../html.js';
3
+ import { ignoreDrift, isRecord, parseJson } from '../../util.js';
4
+ // The portal's "YYYY-MM-DD HH:MM:SS", read as wall clock.
5
+ const STAMP = /^(\d{4}-\d{2}-\d{2})[ T]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;
6
+ // Real calendar dates only; Date arithmetic in UTC never shifts a plain date.
7
+ export function isIsoDate(value) {
8
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value))
9
+ return false;
10
+ const date = new Date(`${value}T00:00:00Z`);
11
+ return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(value);
12
+ }
13
+ function addDays(date, days) {
14
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
15
+ }
16
+ export function parseEvents(body, drift = ignoreDrift) {
17
+ const data = parseJson(body, 'calendar events');
18
+ if (!Array.isArray(data))
19
+ throw layoutChanged('calendar events as a list');
20
+ const events = new Map();
21
+ for (const raw of data) {
22
+ const event = parseEvent(raw, drift);
23
+ // The same id twice is the same event; the first one wins.
24
+ if (event && !events.has(event.id))
25
+ events.set(event.id, event);
26
+ }
27
+ return [...events.values()];
28
+ }
29
+ function parseEvent(raw, drift) {
30
+ if (!isRecord(raw)) {
31
+ drift('A calendar event is not an object.');
32
+ return null;
33
+ }
34
+ const id = idOf(raw.Id);
35
+ const title = plain(raw.title);
36
+ const start = stamp(raw.Anfang);
37
+ const end = stamp(raw.Ende);
38
+ if (!id)
39
+ drift('A calendar event has no id.');
40
+ else if (!title)
41
+ drift('A calendar event has no title.');
42
+ else if (!start || !end)
43
+ drift('A calendar event has no readable start and end.');
44
+ if (!id || !title || !start || !end)
45
+ return null;
46
+ if (typeof raw.allDay !== 'boolean')
47
+ drift('A calendar event has no allDay flag.');
48
+ const allDay = raw.allDay === true;
49
+ let last = end;
50
+ // The portal ends all-day events at 23:59; an end at midnight of a later day is read as exclusive.
51
+ if (allDay && end.time === '00:00:00' && end.date > start.date) {
52
+ last = { date: addDays(end.date, -1), time: end.time };
53
+ }
54
+ if (`${last.date} ${last.time}` < `${start.date} ${start.time}`)
55
+ last = start;
56
+ const changed = raw.LetzteAenderung == null ? null : stamp(raw.LetzteAenderung);
57
+ if (raw.LetzteAenderung != null && !changed)
58
+ drift('A calendar event has an unreadable change date.');
59
+ return {
60
+ id,
61
+ title,
62
+ description: plain(raw.description, true),
63
+ location: plain(raw.Ort),
64
+ categoryId: idOf(raw.category),
65
+ group: isRecord(raw.Lerngruppe) ? plain(raw.Lerngruppe.Name) : null,
66
+ allDay,
67
+ startDate: start.date,
68
+ endDate: last.date,
69
+ startTime: allDay ? null : start.time.slice(0, 5),
70
+ endTime: allDay ? null : last.time.slice(0, 5),
71
+ updatedAt: changed && `${changed.date}T${changed.time}`,
72
+ isNew: flag(raw.Neu, drift),
73
+ isPublic: flag(raw.Oeffentlich, drift),
74
+ isPrivate: flag(raw.Privat, drift),
75
+ isSecret: flag(raw.Geheim, drift)
76
+ };
77
+ }
78
+ const CATEGORIES = /var\s+categories\s*=\s*new\s+Array\(\);([\s\S]*?)var\s+groups\s*=\s*new\s+Array\(\);/;
79
+ // A key with its single- or double-quoted value or bare number, e.g. id:'3' or "name": "Ferien".
80
+ const PROPERTY = /["']?(\w+)["']?\s*:\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"|(-?\d+))/g;
81
+ /** Categories from the calendar page's inline script, one object literal per line. */
82
+ export function parseCategories(html, drift = ignoreDrift) {
83
+ const block = CATEGORIES.exec(html)?.[1];
84
+ if (block === undefined)
85
+ throw layoutChanged('the category list on the calendar page');
86
+ const categories = new Map();
87
+ // Line by line, so a brace inside a name cannot split a literal.
88
+ for (const [literal] of block.matchAll(/\{.*\}/g)) {
89
+ const values = {};
90
+ for (const [, key = '', single, double, number] of literal.matchAll(PROPERTY)) {
91
+ values[key] = number ?? unescape(single ?? double ?? '');
92
+ }
93
+ const id = values.id?.trim();
94
+ const name = plain(values.name);
95
+ if (!id || !name) {
96
+ drift('A calendar category has no id or name.');
97
+ continue;
98
+ }
99
+ const color = values.color?.trim() || null;
100
+ const valid = color && /^#(?:[0-9a-f]{3}){1,2}$/i.test(color) ? color : null;
101
+ if (color && !valid)
102
+ drift('A calendar category has an unreadable color.');
103
+ if (!categories.has(id))
104
+ categories.set(id, { id, name, color: valid });
105
+ }
106
+ return [...categories.values()];
107
+ }
108
+ export function parseEventDetails(body, drift = ignoreDrift) {
109
+ const data = parseJson(body, 'a calendar event');
110
+ if (!isRecord(data) || Array.isArray(data))
111
+ throw layoutChanged('a calendar event as an object');
112
+ // The portal answers an unknown id with error -1, or with an empty id when it is not a number.
113
+ if (data.error === -1 || data.id === '' || data.id === null) {
114
+ throw fail('NOT_FOUND', 'The portal has no such calendar event.');
115
+ }
116
+ const id = idOf(data.id);
117
+ if (!id)
118
+ throw layoutChanged('a calendar event with an id');
119
+ const properties = isRecord(data.properties) ? data.properties : {};
120
+ if (!isRecord(data.properties))
121
+ drift('A calendar event has no properties.');
122
+ const groups = isRecord(properties.zielgruppen) ? Object.entries(properties.zielgruppen) : [];
123
+ return {
124
+ id,
125
+ responsible: plain(properties.verantwortlich),
126
+ targetGroups: groups.flatMap(([key, label]) => {
127
+ if (typeof label !== 'string')
128
+ return [];
129
+ // The -sus label carries leftover "amp;", which lanis-mobile drops the same way.
130
+ const name = plain(key === '-sus' ? label.replaceAll('amp;', '') : label);
131
+ return name ? [name] : [];
132
+ })
133
+ };
134
+ }
135
+ function stamp(value) {
136
+ const match = typeof value === 'string' ? STAMP.exec(value.trim()) : null;
137
+ if (!match || !isIsoDate(match[1]))
138
+ return null;
139
+ return { date: match[1], time: `${match[2]}:${match[3]}:${match[4] ?? '00'}` };
140
+ }
141
+ function idOf(value) {
142
+ if (typeof value !== 'string' && !(typeof value === 'number' && Number.isFinite(value))) {
143
+ return null;
144
+ }
145
+ return String(value).trim() || null;
146
+ }
147
+ // 'ja' or 'nein'; a missing flag is off (lanis-mobile reads anything but 'nein' as on).
148
+ function flag(value, drift) {
149
+ if (value !== undefined && value !== null && value !== 'ja' && value !== 'nein') {
150
+ drift('A calendar event has an unknown flag value.');
151
+ }
152
+ return value === 'ja';
153
+ }
154
+ // Values are HTML, sometimes encoded once more. Only encoded breaks such as "&lt;br /&gt;" become
155
+ // markup, so escaped text such as "a &lt;b" stays text; a second layer of entities is decoded.
156
+ function plain(value, multiline = false) {
157
+ if (typeof value !== 'string' && typeof value !== 'number')
158
+ return null;
159
+ const html = String(value).replace(/&(?:amp;)*lt;br\s*\/?&(?:amp;)*gt;/gi, '<br>');
160
+ const lines = text(parseHtml(html), multiline).split('\n');
161
+ return lines.map((line) => (ENTITY.test(line) ? decode(line) : line)).join('\n') || null;
162
+ }
163
+ const ENTITY = /&(?:[a-z][a-z\d]*|#\d+|#x[\da-f]+);/i;
164
+ // Entities only; a "<" in the text is escaped first so it cannot start a tag.
165
+ function decode(line) {
166
+ return text(parseHtml(line.replaceAll('<', '&lt;')));
167
+ }
168
+ // JavaScript string escapes such as \' and \u{...}.
169
+ function unescape(value) {
170
+ return value.replace(/\\(u\{[\da-f]{1,6}\}|u[\da-f]{4}|x[\da-f]{2}|.)/gi, (escape, code) => {
171
+ if (code.length === 1)
172
+ return { n: '\n', r: '\r', t: '\t' }[code] ?? code;
173
+ const point = parseInt(code.replace(/^[ux]\{?|\}$/g, ''), 16);
174
+ return point <= 0x10ffff ? String.fromCodePoint(point) : escape;
175
+ });
176
+ }
@@ -0,0 +1,49 @@
1
+ export interface DateRange {
2
+ /** ISO calendar date, e.g. "2026-10-01". */
3
+ from: string;
4
+ /** ISO calendar date, inclusive. */
5
+ to: string;
6
+ }
7
+ /**
8
+ * One occurrence; the portal has no recurrence. Dates and times are the portal's
9
+ * Europe/Berlin wall clock, as written, never converted through UTC.
10
+ */
11
+ export interface CalendarEvent {
12
+ id: string;
13
+ title: string;
14
+ /** Plain text, with line breaks kept. */
15
+ description: string | null;
16
+ location: string | null;
17
+ /** Refers to CalendarCategory.id. */
18
+ categoryId: string | null;
19
+ /** The course or group the event belongs to, e.g. "Q1 Mathematik". */
20
+ group: string | null;
21
+ allDay: boolean;
22
+ /** ISO calendar date, e.g. "2026-10-19". */
23
+ startDate: string;
24
+ /** ISO calendar date, inclusive; never before startDate. */
25
+ endDate: string;
26
+ /** "HH:MM"; null for all-day events. */
27
+ startTime: string | null;
28
+ endTime: string | null;
29
+ /** Last change as local portal time, e.g. "2026-10-16T11:58:40". */
30
+ updatedAt: string | null;
31
+ /** The portal's own flags: Neu, Oeffentlich, Privat and Geheim. */
32
+ isNew: boolean;
33
+ isPublic: boolean;
34
+ isPrivate: boolean;
35
+ isSecret: boolean;
36
+ }
37
+ export interface CalendarCategory {
38
+ id: string;
39
+ name: string;
40
+ /** CSS hex color, e.g. "#25599a". */
41
+ color: string | null;
42
+ }
43
+ export interface CalendarEventDetails {
44
+ id: string;
45
+ /** Display name of the person responsible; may name a person, so review it before logging. */
46
+ responsible: string | null;
47
+ /** Whom the event addresses, as the portal labels the groups. */
48
+ targetGroups: string[];
49
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ranzenjs/client",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Typed client for Schulportal Hessen (SPH, LANIS)",
5
5
  "license": "MIT",
6
6
  "author": "Suko",
@@ -42,6 +42,10 @@
42
42
  "types": "./dist/apps/catalog/index.d.ts",
43
43
  "default": "./dist/apps/catalog/index.js"
44
44
  },
45
+ "./calendar": {
46
+ "types": "./dist/apps/calendar/index.d.ts",
47
+ "default": "./dist/apps/calendar/index.js"
48
+ },
45
49
  "./kurswahl": {
46
50
  "types": "./dist/kurswahl/index.d.ts",
47
51
  "default": "./dist/kurswahl/index.js"