@quad-education/sdk 0.1.2 → 0.1.4

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
@@ -95,6 +95,8 @@ The types allow `orderBy` and ranges only on indexed fields, so most mistakes ar
95
95
 
96
96
  ## Versions
97
97
 
98
+ - **0.1.4** (19 Oct 2026). The same SDK calls. The canonical model grows to what V2s S4 builds, which is what an app's `sdk.school.<entity>` and its types come from, so **0.1.3 cannot use any of it**: the attendance register (`sessionAttendance`, which must be filtered by student or date; `studentAbsences`, `attendanceSummaries`), behaviour and achievements, learning support, medical events and notes, staff absences and admissions applicants, and the demographic fields on `students`. It also adds two sensitivity tiers, `sensitive` and `hr`, which are staff-only (a student or parent never receives them), audited, and need manifest version 1 and a reason. A version 1 manifest still needs 0.1.3 or newer.
99
+ - **0.1.3** (18 Oct 2026). The same SDK calls, plus what V2s needs to run: manifest version 1 (`data`, `reasons`, `roles` and `schoolRoles`), declared-field types and stripping for school data, the new school entities (`periods`, `rooms`, `subjects`, `lessons`, with `lessons` generated on demand) and the test toolkit that understands all of it. **A version 1 manifest needs 0.1.3 or newer**: the test toolkit in 0.1.2 only reads version 0 manifests and fails every test with `invalid manifest: manifestVersion: expected 0`. The starter templates ask for `^0.1.3`.
98
100
  - **0.1.2** (9 Oct 2026). The same contract as 0.1.1, and the first version to stay on npm. All the `@quad-education/*` packages were published on 9 Oct 2026 (0.1.0, and 0.1.1 for this one), then unpublished the same day to move the npm org to a new owner, and npm never allows an unpublished version again; every package is now 0.1.2. `SDK_VERSION` (`sdk.version`) now matches the package version; it had stayed at 0.1.0 through 0.1.1.
99
101
  - **0.1.1** (8 Oct 2026). Contract change: `sdk.db` list `orderBy` and range filters need a declared index (or `id`/`createdAt`), and both the types and the engine enforce it (D37). The schema DSL keeps `indexes` as literal types, and `DbListOptions` gains `DbWhere`, `DbOrderBy` and `IndexedField`. The packages also moved from `@quad/*` to `@quad-education/*`, because the `@quad` npm scope belongs to someone else (D41); only the import paths change, and the version stays 0.1.1 because nothing was published under the old name. Before the first publish, the engine also stopped treating names inherited from `Object.prototype` (`constructor`, `toString`) as entities or fields; they now fail with `VALIDATION`, as any unknown name does.
100
102
  - **0.1.0** (renamed 7 Oct 2026). This was `@orca/sdk` 0.1.0, with the same contract and behaviour, renamed for Quad:
@@ -67,11 +67,78 @@ export declare const TEST_APP: {
67
67
  manifest: Manifest;
68
68
  schema: typeof TEST_SCHEMA;
69
69
  };
70
+ /**
71
+ * A demographics app (S4.5): version 1, because a staff-only tier needs a reason. It asks for the seven sensitive
72
+ * fields of a student and nothing else that varies.
73
+ */
74
+ export declare const DEMOGRAPHICS_APP: {
75
+ manifest: Manifest;
76
+ schema: typeof TEST_SCHEMA;
77
+ };
78
+ /** An awards app: achievements are academic, so it needs no pastoral scope and is not in the pastoral audit (S4.3). */
79
+ export declare const AWARDS_APP: {
80
+ manifest: Manifest;
81
+ schema: typeof TEST_SCHEMA;
82
+ };
83
+ /**
84
+ * A staff leave app (S4.6): version 1, because a staff-only tier needs a reason. It asks for the staff reference and the
85
+ * `hr` fields of an absence.
86
+ */
87
+ export declare const HR_APP: {
88
+ manifest: Manifest;
89
+ schema: typeof TEST_SCHEMA;
90
+ };
91
+ /** A first-aid and learning support app: it holds the medical tier too, so it receives diagnoses (S4.4). */
92
+ export declare const WELLBEING_APP: {
93
+ manifest: Manifest;
94
+ schema: typeof TEST_SCHEMA;
95
+ };
70
96
  /** A test app with only `students.basic:read`. */
71
97
  export declare const BASIC_APP: {
72
98
  manifest: Manifest;
73
99
  schema: typeof TEST_SCHEMA;
74
100
  };
101
+ /**
102
+ * A version 1 manifest (V2s D85): students are read with `dateOfBirth` required and `email` optional,
103
+ * and nothing else that varies. The core fields (studentNumber, givenName, familyName) come with the
104
+ * entity. Its scopes are exactly the tiers those fields need.
105
+ */
106
+ export declare const DATA_APP: {
107
+ manifest: Manifest;
108
+ schema: typeof TEST_SCHEMA;
109
+ };
110
+ /**
111
+ * A standalone app (V2s D84): version 1, two app-defined roles named like school roles, so the matching
112
+ * personas can preview them. The access keys are written in different cases on purpose.
113
+ */
114
+ export declare const ROLES_SCHEMA: {
115
+ readonly entry: {
116
+ readonly fields: {
117
+ readonly body: {
118
+ readonly kind: "text";
119
+ readonly tier: import("@quad-education/canonical").Tier;
120
+ };
121
+ };
122
+ readonly indexes: readonly [];
123
+ readonly subject?: "body";
124
+ readonly access?: {
125
+ readonly Staff: {
126
+ readonly read: "all";
127
+ readonly create: "own";
128
+ readonly update: "own";
129
+ readonly delete: "own";
130
+ };
131
+ readonly student: {
132
+ readonly read: "own";
133
+ readonly create: "own";
134
+ };
135
+ };
136
+ };
137
+ };
138
+ export declare const ROLES_APP: {
139
+ manifest: Manifest;
140
+ schema: typeof ROLES_SCHEMA;
141
+ };
75
142
  /**
76
143
  * D25 access control. The documented pattern: a shared record (`excursion`) is staff-only,
77
144
  * and parents work with per-student rows (`consent`) whose subject is their child.
@@ -57,11 +57,126 @@ export const TEST_APP = {
57
57
  'calendarEvents.basic:read',
58
58
  'courses.basic:read',
59
59
  'results.academic:read',
60
+ 'lessons.basic:read',
61
+ 'periods.basic:read',
62
+ 'rooms.basic:read',
63
+ 'subjects.basic:read',
64
+ 'sessionAttendance.basic:read',
65
+ 'sessionAttendance.academic:read',
66
+ 'sessionAttendance.pastoral:read',
67
+ 'studentAbsences.basic:read',
68
+ 'studentAbsences.academic:read',
69
+ 'attendanceSummaries.basic:read',
70
+ 'attendanceSummaries.academic:read',
71
+ 'behaviours.basic:read',
72
+ 'behaviours.pastoral:read',
73
+ 'achievements.basic:read',
74
+ 'achievements.academic:read',
75
+ 'learningSupportNeeds.basic:read',
76
+ 'learningSupportNeeds.pastoral:read',
77
+ 'applicants.basic:read',
78
+ 'applicants.contact:read',
60
79
  ],
61
80
  notifications: ['test.message', 'test.reminder'],
62
81
  },
63
82
  schema: TEST_SCHEMA,
64
83
  };
84
+ /**
85
+ * A demographics app (S4.5): version 1, because a staff-only tier needs a reason. It asks for the seven sensitive
86
+ * fields of a student and nothing else that varies.
87
+ */
88
+ export const DEMOGRAPHICS_APP = {
89
+ manifest: {
90
+ ...TEST_APP.manifest,
91
+ manifestVersion: 1,
92
+ id: 'contract-demographics',
93
+ name: 'Demographics app',
94
+ scopes: ['parents.basic:read', 'students.basic:read', 'students.sensitive:read'],
95
+ data: {
96
+ parents: { required: [], optional: ['title'] },
97
+ students: {
98
+ required: [],
99
+ optional: [
100
+ 'firstLanguage',
101
+ 'englishAsAdditionalLanguage',
102
+ 'ethnicity',
103
+ 'nationality',
104
+ 'religion',
105
+ 'birthPlace',
106
+ 'freeSchoolMeals',
107
+ ],
108
+ },
109
+ },
110
+ reasons: {
111
+ 'students.sensitive:read': 'To plan language support and cultural events with families’ agreement.',
112
+ },
113
+ notifications: ['test.message'],
114
+ },
115
+ schema: TEST_SCHEMA,
116
+ };
117
+ /** An awards app: achievements are academic, so it needs no pastoral scope and is not in the pastoral audit (S4.3). */
118
+ export const AWARDS_APP = {
119
+ manifest: {
120
+ ...TEST_APP.manifest,
121
+ id: 'contract-awards',
122
+ name: 'Awards app',
123
+ scopes: ['achievements.basic:read', 'achievements.academic:read'],
124
+ notifications: ['test.message'],
125
+ },
126
+ schema: TEST_SCHEMA,
127
+ };
128
+ /**
129
+ * A staff leave app (S4.6): version 1, because a staff-only tier needs a reason. It asks for the staff reference and the
130
+ * `hr` fields of an absence.
131
+ */
132
+ export const HR_APP = {
133
+ manifest: {
134
+ ...TEST_APP.manifest,
135
+ manifestVersion: 1,
136
+ id: 'contract-hr',
137
+ name: 'Staff leave app',
138
+ scopes: ['employeeAbsences.basic:read', 'employeeAbsences.hr:read'],
139
+ data: {
140
+ employeeAbsences: {
141
+ required: [],
142
+ optional: [
143
+ 'staffId',
144
+ 'startAt',
145
+ 'endAt',
146
+ 'absenceType',
147
+ 'illnessCategory',
148
+ 'workingDays',
149
+ 'hours',
150
+ 'note',
151
+ ],
152
+ },
153
+ },
154
+ reasons: {
155
+ 'employeeAbsences.hr:read': 'To roster relief staff and report on leave taken across the year.',
156
+ },
157
+ notifications: ['test.message'],
158
+ },
159
+ schema: TEST_SCHEMA,
160
+ };
161
+ /** A first-aid and learning support app: it holds the medical tier too, so it receives diagnoses (S4.4). */
162
+ export const WELLBEING_APP = {
163
+ manifest: {
164
+ ...TEST_APP.manifest,
165
+ id: 'contract-wellbeing',
166
+ name: 'Wellbeing app',
167
+ scopes: [
168
+ 'learningSupportNeeds.basic:read',
169
+ 'learningSupportNeeds.pastoral:read',
170
+ 'learningSupportNeeds.medical:read',
171
+ 'medicalEvents.basic:read',
172
+ 'medicalEvents.medical:read',
173
+ 'medicalNotes.basic:read',
174
+ 'medicalNotes.medical:read',
175
+ ],
176
+ notifications: ['test.message'],
177
+ },
178
+ schema: TEST_SCHEMA,
179
+ };
65
180
  /** A test app with only `students.basic:read`. */
66
181
  export const BASIC_APP = {
67
182
  manifest: {
@@ -73,6 +188,50 @@ export const BASIC_APP = {
73
188
  },
74
189
  schema: TEST_SCHEMA,
75
190
  };
191
+ /**
192
+ * A version 1 manifest (V2s D85): students are read with `dateOfBirth` required and `email` optional,
193
+ * and nothing else that varies. The core fields (studentNumber, givenName, familyName) come with the
194
+ * entity. Its scopes are exactly the tiers those fields need.
195
+ */
196
+ export const DATA_APP = {
197
+ manifest: {
198
+ ...TEST_APP.manifest,
199
+ manifestVersion: 1,
200
+ id: 'contract-data',
201
+ name: 'Declared fields app',
202
+ scopes: ['students.basic:read', 'students.contact:read'],
203
+ data: { students: { required: ['dateOfBirth'], optional: ['email'] } },
204
+ reasons: { 'students.contact:read': 'To show each student’s birthday in the contract tests.' },
205
+ notifications: ['test.message'],
206
+ },
207
+ schema: TEST_SCHEMA,
208
+ };
209
+ /**
210
+ * A standalone app (V2s D84): version 1, two app-defined roles named like school roles, so the matching
211
+ * personas can preview them. The access keys are written in different cases on purpose.
212
+ */
213
+ export const ROLES_SCHEMA = defineSchema({
214
+ entry: entity({
215
+ fields: { body: text() },
216
+ access: {
217
+ Staff: { read: 'all', create: 'own', update: 'own', delete: 'own' },
218
+ student: { read: 'own', create: 'own' },
219
+ },
220
+ }),
221
+ });
222
+ export const ROLES_APP = {
223
+ manifest: {
224
+ ...TEST_APP.manifest,
225
+ manifestVersion: 1,
226
+ id: 'contract-roles',
227
+ name: 'App roles app',
228
+ roles: ['Staff', 'Student'],
229
+ schoolRoles: [],
230
+ scopes: [],
231
+ notifications: [],
232
+ },
233
+ schema: ROLES_SCHEMA,
234
+ };
76
235
  /**
77
236
  * D25 access control. The documented pattern: a shared record (`excursion`) is staff-only,
78
237
  * and parents work with per-student rows (`consent`) whose subject is their child.
@@ -1,3 +1,3 @@
1
1
  export { defineContractSuite } from './suite.ts';
2
2
  export type { ContractEnv, ContractFactory, TestApp } from './suite.ts';
3
- export { ACCESS_APP, BASIC_APP, JOBS_APP, TEST_APP, slowGate } from './apps.ts';
3
+ export { ACCESS_APP, AWARDS_APP, BASIC_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, TEST_APP, WELLBEING_APP, slowGate, } from './apps.ts';
@@ -1,2 +1,2 @@
1
1
  export { defineContractSuite } from "./suite.js";
2
- export { ACCESS_APP, BASIC_APP, JOBS_APP, TEST_APP, slowGate } from "./apps.js";
2
+ export { ACCESS_APP, AWARDS_APP, BASIC_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
@@ -1,13 +1,13 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
2
  import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
3
  import { eligibleParents } from '@quad-education/canonical';
4
- import { personasFor } from '@quad-education/fictional-school';
5
- import dataset from '@quad-education/fictional-school/dataset' with { type: 'json' };
4
+ import { personasFor, withDerived } from '@quad-education/fictional-school';
5
+ import stored from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
6
  import { isQuadError, parentsOf, staffOf, studentsOf } from "../src/index.js";
7
- import { ACCESS_APP, BASIC_APP, JOBS_APP, TEST_APP, slowGate } from "./apps.js";
7
+ import { ACCESS_APP, AWARDS_APP, BASIC_APP, DATA_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, ROLES_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
8
8
  // The fictional school is the oracle: tests compare what the SDK returns with what the
9
9
  // dataset says should be visible. They never read an implementation's storage.
10
- const ds = dataset;
10
+ const ds = withDerived(stored);
11
11
  const personas = personasFor(ds);
12
12
  const persona = (key) => {
13
13
  const p = personas.find((x) => x.key === key);
@@ -73,7 +73,7 @@ export function defineContractSuite(name, factory) {
73
73
  },
74
74
  });
75
75
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
76
- expect(sdk.version).toBe('0.1.2');
76
+ expect(sdk.version).toBe('0.1.4');
77
77
  });
78
78
  it('knows parents and students', async () => {
79
79
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
@@ -149,6 +149,7 @@ export function defineContractSuite(name, factory) {
149
149
  await expectError(sdk.school.parents.list(), 'SCOPE_NOT_GRANTED');
150
150
  await expectError(sdk.school.medicalAlerts.get(ds.medicalAlerts[0].id), 'SCOPE_NOT_GRANTED');
151
151
  await expectError(sdk.school.calendar.list({ from: '2026-01-01', to: '2027-01-01' }), 'SCOPE_NOT_GRANTED');
152
+ await expectError(sdk.school.sessionAttendance.list({ where: { date: '2026-03-03' } }), 'SCOPE_NOT_GRANTED');
152
153
  });
153
154
  it('still answers school.info', async () => {
154
155
  const info = await (await env.connect(STUDENT)).school.info();
@@ -188,6 +189,78 @@ export function defineContractSuite(name, factory) {
188
189
  });
189
190
  });
190
191
  });
192
+ describe('app-defined roles are previewed by the persona of the same name (D84)', () => {
193
+ useApp(ROLES_APP);
194
+ it('serves the personas whose role matches an app role, ignoring case, and refuses the rest', async () => {
195
+ const staff = await env.connect(STAFF);
196
+ const student = await env.connect(STUDENT);
197
+ expect((await staff.auth.me()).role).toBe('staff');
198
+ expect((await student.auth.me()).role).toBe('student');
199
+ await expectError(env.connect(SIBLINGS_PARENT).then((p) => p.auth.me()), 'FORBIDDEN');
200
+ });
201
+ it('follows the access rules written for the app role, whatever the case of the key', async () => {
202
+ const staff = await env.connect(STAFF);
203
+ const student = await env.connect(STUDENT);
204
+ const note = await student.db.entity('entry').create({ body: 'mine' });
205
+ await staff.db.entity('entry').create({ body: 'staff note' });
206
+ // `Staff` (capitalised in the schema) gives staff all records; `student` gives a student their own.
207
+ expect((await staff.db.entity('entry').list()).items).toHaveLength(2);
208
+ expect((await student.db.entity('entry').list()).items.map((e) => e.id)).toEqual([
209
+ note.id,
210
+ ]);
211
+ await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
212
+ });
213
+ });
214
+ describe('school: declared fields (D85)', () => {
215
+ useApp(DATA_APP);
216
+ it('returns the core fields and the declared ones, and nothing else that varies', async () => {
217
+ const sdk = await env.connect(STAFF);
218
+ const expected = ds.students[0];
219
+ const student = await sdk.school.students.get(expected.id);
220
+ expect(student.givenName).toBe(expected.givenName);
221
+ expect(student.studentNumber).toBe(expected.studentNumber);
222
+ expect(student.dateOfBirth).toBe(expected.dateOfBirth);
223
+ expect(student.email).toBe(expected.email);
224
+ // yearLevel and preferredName are granted by tier but were not declared.
225
+ expect('yearLevel' in student).toBe(false);
226
+ expect('preferredName' in student).toBe(false);
227
+ for (const s of (await sdk.school.students.list({ limit: 25 })).items) {
228
+ expect('yearLevel' in s).toBe(false);
229
+ expect('preferredName' in s).toBe(false);
230
+ expect('dateOfBirth' in s).toBe(true);
231
+ }
232
+ });
233
+ it('refuses to filter or sort on a field that was not declared, so it cannot be probed', async () => {
234
+ const sdk = await env.connect(STAFF);
235
+ await expectError(sdk.school.students.list({ where: { yearLevel: 'Y9' } }), 'VALIDATION');
236
+ await expectError(sdk.school.students.list({ orderBy: { field: 'preferredName' } }), 'VALIDATION');
237
+ // Declared and core fields still work.
238
+ const name = ds.students[0].familyName;
239
+ const found = await sdk.school.students.list({ where: { familyName: name }, limit: 200 });
240
+ expect(found.items.length).toBeGreaterThan(0);
241
+ expect((await sdk.school.students.list({ where: { dateOfBirth: ds.students[0].dateOfBirth } }))
242
+ .items.length).toBeGreaterThan(0);
243
+ });
244
+ it('strips included school refs the same way', async () => {
245
+ const sdk = await env.connect(STAFF);
246
+ await sdk.db
247
+ .entity('greeting')
248
+ .create({ message: 'hi', studentId: ds.students[0].id, tone: 'warm' });
249
+ const { items } = await sdk.db.entity('greeting').list({ include: ['studentId'] });
250
+ const included = items[0].$included.studentId;
251
+ expect(included.givenName).toBe(ds.students[0].givenName);
252
+ expect('yearLevel' in included).toBe(false);
253
+ expect('dateOfBirth' in included).toBe(true);
254
+ });
255
+ });
256
+ describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
257
+ useApp(BASIC_APP);
258
+ it('keeps yearLevel and preferredName available', async () => {
259
+ const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
260
+ .items[0];
261
+ expect('yearLevel' in student).toBe(true);
262
+ });
263
+ });
191
264
  describe('school: queries and helpers', () => {
192
265
  useApp(TEST_APP);
193
266
  it('filters with where, orders and pages without gaps or repeats', async () => {
@@ -241,6 +314,379 @@ export function defineContractSuite(name, factory) {
241
314
  const student = await env.connect(STUDENT);
242
315
  await expectError(student.school.parents.children(parentId), 'NOT_FOUND');
243
316
  });
317
+ it('serves the timetable, which is derived, like any other entity (S4.1)', async () => {
318
+ const english = ds.cohorts.find((c) => c.code === 'y09-english-b');
319
+ const week = { gte: '2026-03-02', lt: '2026-03-09' };
320
+ const expected = ds.lessons
321
+ .filter((l) => l.cohortId === english.id && l.date >= week.gte && l.date < week.lt)
322
+ .map((l) => l.id);
323
+ expect(expected).toHaveLength(4);
324
+ // A published timetable: staff, students and parents all read it.
325
+ for (const who of [STAFF, STUDENT, SIBLINGS_PARENT]) {
326
+ const sdk = await env.connect(who);
327
+ const page = await sdk.school.lessons.list({
328
+ where: { cohortId: english.id, date: week },
329
+ orderBy: { field: 'startsAt' },
330
+ limit: 50,
331
+ });
332
+ expect(page.items.map((l) => l.id)).toEqual(expected);
333
+ expect(page.items[0]).toMatchObject({ cohortId: english.id });
334
+ }
335
+ }, 30_000);
336
+ it('pages through a day of lessons without gaps or repeats, and finds one by id', async () => {
337
+ const sdk = await env.connect(STUDENT);
338
+ const day = '2026-03-03';
339
+ const expected = ds.lessons.filter((l) => l.date === day).map((l) => l.id);
340
+ const seen = [];
341
+ let page = await sdk.school.lessons.list({ where: { date: day }, limit: 100 });
342
+ seen.push(...page.items.map((l) => l.id));
343
+ while (page.nextCursor) {
344
+ page = await sdk.school.lessons.list({
345
+ where: { date: day },
346
+ limit: 100,
347
+ cursor: page.nextCursor,
348
+ });
349
+ seen.push(...page.items.map((l) => l.id));
350
+ }
351
+ expect(seen.slice().sort()).toEqual(expected.slice().sort());
352
+ expect(new Set(seen).size).toBe(expected.length);
353
+ const one = await sdk.school.lessons.get(expected[0]);
354
+ expect(one.id).toBe(expected[0]);
355
+ await expectError(sdk.school.lessons.get('les-20260303-nope-p1'), 'NOT_FOUND');
356
+ }, 30_000);
357
+ it('lists the school day’s periods and rooms', async () => {
358
+ const sdk = await env.connect(STUDENT);
359
+ const periods = await listAll(sdk.school.periods, {});
360
+ expect(periods).toHaveLength(30);
361
+ const rooms = await listAll(sdk.school.rooms, {});
362
+ expect(ids(rooms)).toEqual(ids(ds.rooms));
363
+ });
364
+ it('serves the register for the slice asked for, and says what to add otherwise (S4.2)', async () => {
365
+ const staff = await env.connect(STAFF);
366
+ const student = ds.students[10];
367
+ const week = { gte: '2026-03-02', lte: '2026-03-06' };
368
+ const page = await staff.school.sessionAttendance.list({
369
+ where: { studentId: student.id, date: week },
370
+ orderBy: { field: 'date' },
371
+ limit: 50,
372
+ });
373
+ expect(page.items).toHaveLength(10);
374
+ expect(page.items.every((m) => m.studentId === student.id && m.date >= week.gte && m.date <= week.lte)).toBe(true);
375
+ expect(page.items.map((m) => m.date)).toEqual([...page.items.map((m) => m.date)].sort());
376
+ expect(page.items[0]).toMatchObject({
377
+ source: 'simulated',
378
+ session: expect.stringMatching(/^(am|pm)$/),
379
+ code: expect.any(String),
380
+ });
381
+ const noFilter = await expectError(staff.school.sessionAttendance.list({ where: { code: 'late' } }), 'VALIDATION');
382
+ expect(noFilter.message).toMatch(/studentId/);
383
+ await expectError(staff.school.sessionAttendance.list(), 'VALIDATION');
384
+ const wide = await expectError(staff.school.sessionAttendance.list({
385
+ where: { date: { gte: '2026-02-02', lte: '2026-06-30' } },
386
+ }), 'VALIDATION');
387
+ expect(wide.message).toMatch(/narrow by/);
388
+ // A school day is fine, and other filters narrow it further.
389
+ const day = await listAll(staff.school.sessionAttendance, { where: { date: '2026-03-03' } });
390
+ expect(day).toHaveLength(ds.students.length * 2);
391
+ const late = await listAll(staff.school.sessionAttendance, {
392
+ where: { date: '2026-03-03', code: 'late' },
393
+ });
394
+ expect(late.length).toBeGreaterThan(0);
395
+ expect(late.every((m) => m.code === 'late' && typeof m.minutesLate === 'number')).toBe(true);
396
+ }, 30_000);
397
+ it('pages through a register without gaps or repeats, and finds one mark by id', async () => {
398
+ const staff = await env.connect(STAFF);
399
+ const where = {
400
+ studentId: ds.students[20].id,
401
+ date: { gte: '2026-02-02', lte: '2026-04-02' },
402
+ };
403
+ const seen = [];
404
+ let page = await staff.school.sessionAttendance.list({ where, limit: 37 });
405
+ seen.push(...page.items);
406
+ while (page.nextCursor) {
407
+ page = await staff.school.sessionAttendance.list({
408
+ where,
409
+ limit: 37,
410
+ cursor: page.nextCursor,
411
+ });
412
+ seen.push(...page.items);
413
+ }
414
+ expect(new Set(seen.map((m) => m.id)).size).toBe(seen.length);
415
+ expect(seen.length).toBeGreaterThan(80);
416
+ const one = await staff.school.sessionAttendance.get(seen[5].id);
417
+ expect(one).toEqual(seen[5]);
418
+ await expectError(staff.school.sessionAttendance.get('att-stu-nope-20260302-am'), 'NOT_FOUND');
419
+ });
420
+ it('shows a student or parent only their own children, however they ask (D4, D17)', async () => {
421
+ const day = { where: { date: '2026-03-04' } };
422
+ const student = await listAll((await env.connect(STUDENT)).school.sessionAttendance, day);
423
+ expect(new Set(student.map((m) => m.studentId))).toEqual(new Set([STUDENT.personId]));
424
+ expect(student).toHaveLength(2);
425
+ const other = ds.students.find((s) => s.id !== STUDENT.personId);
426
+ const asked = await listAll((await env.connect(STUDENT)).school.sessionAttendance, {
427
+ where: { studentId: other.id, date: '2026-03-04' },
428
+ });
429
+ expect(asked).toEqual([]);
430
+ await expectError((await env.connect(STUDENT)).school.sessionAttendance.get(`att-${other.id}-20260304-am`), 'NOT_FOUND');
431
+ const kids = childrenOf(SIBLINGS_PARENT.personId);
432
+ const parent = await listAll((await env.connect(SIBLINGS_PARENT)).school.sessionAttendance, day);
433
+ expect(new Set(parent.map((m) => m.studentId))).toEqual(new Set(kids));
434
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.sessionAttendance, day)).toEqual([]);
435
+ });
436
+ it('needs the academic scope for marks and the pastoral scope for comments, which are audited', async () => {
437
+ const staff = await env.connect(STAFF);
438
+ const withComments = await listAll(staff.school.sessionAttendance, {
439
+ where: { studentId: ds.students[3].id },
440
+ });
441
+ expect(withComments.some((m) => typeof m.comment === 'string')).toBe(true);
442
+ const log = await env.control.auditLog();
443
+ const reads = log.filter((e) => e.action === 'school.sensitive-read' && e.entity === 'sessionAttendance');
444
+ expect(reads.length).toBeGreaterThan(0);
445
+ expect(reads[0].data.tiers).toEqual(['pastoral']);
446
+ });
447
+ it('serves absences and term summaries, each student’s own', async () => {
448
+ const staff = await env.connect(STAFF);
449
+ const mine = await listAll((await env.connect(STUDENT)).school.attendanceSummaries);
450
+ expect(mine).toHaveLength(4);
451
+ expect(mine.every((s) => s.studentId === STUDENT.personId)).toBe(true);
452
+ expect(mine[0]).toMatchObject({
453
+ possibleMarks: expect.any(Number),
454
+ presentMarks: expect.any(Number),
455
+ });
456
+ const all = await listAll(staff.school.attendanceSummaries, {
457
+ where: { termName: 'Term 1' },
458
+ });
459
+ expect(all).toHaveLength(ds.students.length);
460
+ const absences = await listAll(staff.school.studentAbsences, {
461
+ where: { studentId: ds.students[0].id },
462
+ });
463
+ expect(absences.length).toBeGreaterThan(0);
464
+ // The reason is pastoral, and this app was not granted that tier.
465
+ expect(absences.every((a) => a.endAt > a.startAt && !('reason' in a) && !('comment' in a))).toBe(true);
466
+ const own = await listAll((await env.connect(SIBLINGS_PARENT)).school.studentAbsences);
467
+ expect(new Set(own.map((a) => a.studentId))).toEqual(new Set(childrenOf(SIBLINGS_PARENT.personId)));
468
+ }, 30_000);
469
+ it('serves behaviour incidents and achievements, each student’s own (S4.3)', async () => {
470
+ const staff = await env.connect(STAFF);
471
+ const mine = ds.behaviours.find((b) => b.studentId !== STUDENT.personId);
472
+ const incidents = await listAll(staff.school.behaviours, {
473
+ where: { studentId: mine.studentId },
474
+ });
475
+ expect(incidents.length).toBeGreaterThan(0);
476
+ expect(incidents.every((b) => b.studentId === mine.studentId && b.points < 0)).toBe(true);
477
+ expect(incidents[0]).toMatchObject({
478
+ incident: expect.any(String),
479
+ date: expect.any(String),
480
+ });
481
+ const own = await listAll((await env.connect(STUDENT)).school.behaviours);
482
+ expect(own.every((b) => b.studentId === STUDENT.personId)).toBe(true);
483
+ expect(own).toHaveLength(ds.behaviours.filter((b) => b.studentId === STUDENT.personId).length);
484
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
485
+ const family = await listAll((await env.connect(SIBLINGS_PARENT)).school.behaviours);
486
+ expect(family.every((b) => kids.has(b.studentId))).toBe(true);
487
+ expect(family).toHaveLength(ds.behaviours.filter((b) => kids.has(b.studentId)).length);
488
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.behaviours)).toEqual([]);
489
+ await expectError((await env.connect(STUDENT)).school.behaviours.get(mine.id), 'NOT_FOUND');
490
+ const awards = await listAll((await env.connect(STUDENT)).school.achievements);
491
+ expect(awards).toHaveLength(ds.achievements.filter((a) => a.studentId === STUDENT.personId).length);
492
+ expect(awards.every((a) => a.points > 0 && typeof a.type === 'string')).toBe(true);
493
+ const all = await listAll(staff.school.achievements, { where: { type: 'Sport' } });
494
+ expect(all).toHaveLength(ds.achievements.filter((a) => a.type === 'Sport').length);
495
+ }, 30_000);
496
+ it('audits behaviour reads, which are pastoral, but not achievements, which are academic (S4.3, D19)', async () => {
497
+ const staff = await env.connect(STAFF);
498
+ await staff.school.behaviours.list({ limit: 4 });
499
+ await staff.school.achievements.list({ limit: 4 });
500
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' &&
501
+ ['behaviours', 'achievements'].includes(String(e.entity)));
502
+ expect(reads.map((e) => [e.entity, e.data.tiers])).toEqual([['behaviours', ['pastoral']]]);
503
+ });
504
+ describe('an awards app with no pastoral scope', () => {
505
+ useApp(AWARDS_APP);
506
+ it('reads achievements but not behaviour, and leaves no pastoral audit entry', async () => {
507
+ const sdk = await env.connect(STAFF);
508
+ const { items } = await sdk.school.achievements.list({ limit: 5 });
509
+ expect(items).toHaveLength(5);
510
+ await expectError(sdk.school.behaviours.list(), 'SCOPE_NOT_GRANTED');
511
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read');
512
+ expect(reads).toEqual([]);
513
+ });
514
+ });
515
+ it('leaves the diagnosis out of learning support when only the pastoral tier is granted (S4.4)', async () => {
516
+ const staff = await env.connect(STAFF);
517
+ const withNeed = ds.learningSupportNeeds[0];
518
+ const items = await listAll(staff.school.learningSupportNeeds, {
519
+ where: { studentId: withNeed.studentId },
520
+ });
521
+ expect(items.length).toBeGreaterThan(0);
522
+ expect(items[0]).toMatchObject({ category: expect.any(String), level: expect.any(String) });
523
+ expect(items.every((n) => !('need' in n))).toBe(true);
524
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
525
+ expect(reads.map((e) => e.data.tiers)).toEqual([['pastoral']]);
526
+ await expectError(staff.school.medicalEvents.list(), 'SCOPE_NOT_GRANTED');
527
+ await expectError(staff.school.medicalNotes.list(), 'SCOPE_NOT_GRANTED');
528
+ });
529
+ describe('a wellbeing app with the medical tier', () => {
530
+ useApp(WELLBEING_APP);
531
+ it('receives the diagnosis, and the audit records both tiers (S4.4)', async () => {
532
+ const staff = await env.connect(STAFF);
533
+ const withNeed = ds.learningSupportNeeds[0];
534
+ const items = await listAll(staff.school.learningSupportNeeds, {
535
+ where: { studentId: withNeed.studentId },
536
+ });
537
+ expect(items.some((n) => n.need === withNeed.need && n.category === withNeed.category)).toBe(true);
538
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
539
+ expect([...reads[0].data.tiers].sort()).toEqual(['medical', 'pastoral']);
540
+ });
541
+ it('serves medical events and the notes that link to them, each student’s own', async () => {
542
+ const staff = await env.connect(STAFF);
543
+ const event = ds.medicalEvents.find((e) => e.followUpDate);
544
+ const events = await listAll(staff.school.medicalEvents, {
545
+ where: { studentId: event.studentId },
546
+ });
547
+ expect(events.find((e) => e.id === event.id)).toMatchObject({
548
+ type: event.type,
549
+ followUpDate: event.followUpDate,
550
+ });
551
+ const notes = await listAll(staff.school.medicalNotes, {
552
+ where: { studentId: event.studentId },
553
+ });
554
+ expect(notes.some((n) => n.eventId === event.id)).toBe(true);
555
+ expect(notes.every((n) => (n.conditionId === undefined) !== (n.eventId === undefined))).toBe(true);
556
+ const student = await env.connect(STUDENT);
557
+ for (const [entity, all] of [
558
+ ['learningSupportNeeds', ds.learningSupportNeeds],
559
+ ['medicalEvents', ds.medicalEvents],
560
+ ['medicalNotes', ds.medicalNotes],
561
+ ]) {
562
+ const own = await listAll(student.school[entity]);
563
+ expect(own, entity).toHaveLength(all.filter((r) => r.studentId === STUDENT.personId).length);
564
+ expect(own.every((r) => r.studentId === STUDENT.personId)).toBe(true);
565
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
566
+ const family = await listAll((await env.connect(SIBLINGS_PARENT)).school[entity]);
567
+ expect(family, entity).toHaveLength(all.filter((r) => kids.has(r.studentId)).length);
568
+ expect(await listAll((await env.connect(RESTRICTED_PARENT)).school[entity])).toEqual([]);
569
+ }
570
+ await expectError(student.school.medicalEvents.get(ds.medicalEvents.find((e) => e.studentId !== STUDENT.personId).id), 'NOT_FOUND');
571
+ });
572
+ });
573
+ describe('demographics: the sensitive tier is staff-only (S4.5, D88)', () => {
574
+ useApp(DEMOGRAPHICS_APP);
575
+ const SENSITIVE = [
576
+ 'firstLanguage',
577
+ 'englishAsAdditionalLanguage',
578
+ 'ethnicity',
579
+ 'nationality',
580
+ 'religion',
581
+ 'birthPlace',
582
+ 'freeSchoolMeals',
583
+ ];
584
+ const leaks = (value) => JSON.stringify(value) !== undefined &&
585
+ SENSITIVE.filter((k) => JSON.stringify(value).includes(`"${k}"`));
586
+ it('gives staff the fields the app asked for, lets them filter on one, and audits the read', async () => {
587
+ const staff = await env.connect(STAFF);
588
+ const some = ds.students.find((s) => s.religion && s.firstLanguage);
589
+ const one = await staff.school.students.get(some.id);
590
+ expect(one).toMatchObject({ religion: some.religion, firstLanguage: some.firstLanguage });
591
+ const catholic = await listAll(staff.school.students, { where: { religion: 'Catholic' } });
592
+ expect(catholic).toHaveLength(ds.students.filter((s) => s.religion === 'Catholic').length);
593
+ expect(catholic.length).toBeGreaterThan(20);
594
+ const eal = await listAll(staff.school.students, {
595
+ where: { englishAsAdditionalLanguage: true },
596
+ });
597
+ expect(eal.every((s) => s.englishAsAdditionalLanguage === true)).toBe(true);
598
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'students');
599
+ expect(reads.length).toBeGreaterThan(0);
600
+ expect(reads.every((e) => e.data.tiers.includes('sensitive'))).toBe(true);
601
+ });
602
+ it('never gives a student or a parent the fields, and refuses a filter that would probe them', async () => {
603
+ for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT]) {
604
+ const sdk = await env.connect(who);
605
+ const mine = await listAll(sdk.school.students);
606
+ expect(mine.length).toBeGreaterThan(0);
607
+ expect(leaks(mine), who.personId).toEqual([]);
608
+ expect(leaks(await sdk.school.students.get(mine[0].id))).toEqual([]);
609
+ await expectError(sdk.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
610
+ await expectError(sdk.school.students.list({ orderBy: { field: 'ethnicity' } }), 'VALIDATION');
611
+ }
612
+ });
613
+ it('does not leak them through the helpers that return students or parents', async () => {
614
+ const kids = childrenOf(SIBLINGS_PARENT.personId);
615
+ const parent = await env.connect(SIBLINGS_PARENT);
616
+ expect(leaks(await parent.school.parents.children(SIBLINGS_PARENT.personId))).toEqual([]);
617
+ expect(leaks(await parent.school.students.parents(kids[0]))).toEqual([]);
618
+ const student = await env.connect(STUDENT);
619
+ expect(leaks(await student.school.students.parents(STUDENT.personId))).toEqual([]);
620
+ expect(leaks(await student.auth.me())).toEqual([]);
621
+ const staff = await env.connect(STAFF);
622
+ // Staff with the scope get them for a parent's children too: the tier is for staff.
623
+ const children = await staff.school.parents.children(SIBLINGS_PARENT.personId);
624
+ expect(children.some((c) => SENSITIVE.some((k) => k in c))).toBe(true);
625
+ });
626
+ });
627
+ it('never gives the fields to an app that was not granted the tier', async () => {
628
+ const staff = await env.connect(STAFF);
629
+ const students = await listAll(staff.school.students, { where: { yearLevel: 'Y9' } });
630
+ expect(students.length).toBeGreaterThan(0);
631
+ expect(JSON.stringify(students)).not.toMatch(/"(religion|ethnicity|nationality|firstLanguage|birthPlace)"/);
632
+ await expectError(staff.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
633
+ });
634
+ describe('staff absences are in the hr tier (S4.6)', () => {
635
+ useApp(HR_APP);
636
+ it('are read by any staff member whose app holds the tier, and audited as hr', async () => {
637
+ for (const who of [STAFF, DEPUTY]) {
638
+ const sdk = await env.connect(who);
639
+ const all = await listAll(sdk.school.employeeAbsences);
640
+ expect(all).toHaveLength(ds.employeeAbsences.length);
641
+ expect(all[0]).toMatchObject({
642
+ staffId: expect.any(String),
643
+ absenceType: expect.any(String),
644
+ workingDays: expect.any(Number),
645
+ });
646
+ }
647
+ const sdk = await env.connect(STAFF);
648
+ const sick = await listAll(sdk.school.employeeAbsences, {
649
+ where: { absenceType: 'Sick leave' },
650
+ });
651
+ expect(sick).toHaveLength(ds.employeeAbsences.filter((a) => a.absenceType === 'Sick leave').length);
652
+ expect(sick.every((a) => typeof a.illnessCategory === 'string')).toBe(true);
653
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'employeeAbsences');
654
+ expect(reads.length).toBeGreaterThan(0);
655
+ expect(reads.every((e) => e.data.tiers.includes('hr'))).toBe(true);
656
+ });
657
+ it('are never given to a student or a parent, however they ask', async () => {
658
+ const one = ds.employeeAbsences[0];
659
+ for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT, RESTRICTED_PARENT]) {
660
+ const sdk = await env.connect(who);
661
+ expect(await listAll(sdk.school.employeeAbsences)).toEqual([]);
662
+ await expectError(sdk.school.employeeAbsences.get(one.id), 'NOT_FOUND');
663
+ await expectError(sdk.school.employeeAbsences.list({ where: { absenceType: 'Sick leave' } }), 'VALIDATION');
664
+ }
665
+ });
666
+ });
667
+ it('refuses staff absences to an app that was not granted the tier', async () => {
668
+ const staff = await env.connect(STAFF);
669
+ await expectError(staff.school.employeeAbsences.list(), 'SCOPE_NOT_GRANTED');
670
+ });
671
+ it('serves admissions applicants to staff only, in the contact tier (S4.6)', async () => {
672
+ const staff = await env.connect(STAFF);
673
+ const all = await listAll(staff.school.applicants);
674
+ expect(all).toHaveLength(ds.applicants.length);
675
+ expect(all[0]).toMatchObject({
676
+ givenName: expect.any(String),
677
+ email: expect.any(String),
678
+ status: expect.any(String),
679
+ });
680
+ const offered = await listAll(staff.school.applicants, { where: { status: 'offered' } });
681
+ expect(offered).toHaveLength(ds.applicants.filter((a) => a.status === 'offered').length);
682
+ const sibling = ds.applicants.find((a) => a.siblingId);
683
+ expect((await staff.school.applicants.get(sibling.id)).siblingId).toBe(sibling.siblingId);
684
+ for (const who of [STUDENT, SIBLINGS_PARENT, RESTRICTED_PARENT]) {
685
+ const sdk = await env.connect(who);
686
+ expect(await listAll(sdk.school.applicants)).toEqual([]);
687
+ await expectError(sdk.school.applicants.get(sibling.id), 'NOT_FOUND');
688
+ }
689
+ });
244
690
  it('lists calendar events in a date range', async () => {
245
691
  const sdk = await env.connect(STAFF);
246
692
  const from = '2026-03-01T00:00:00Z';
@@ -1,7 +1,7 @@
1
- import type { CanonicalRecord, ContactPurpose, Entities, EntityName, RecordWithTiers, Role, TiersFor } from '@quad-education/canonical';
1
+ import type { CanonicalRecord, ContactPurpose, Entities, EntityName, RecordWithFields, RecordWithTiers, Role, TiersFor } from '@quad-education/canonical';
2
2
  import type { AppEntityDef, AppInput, AppSchema, FieldValue, SystemFields } from '@quad-education/schema';
3
3
  import type { Recipient } from './recipients.ts';
4
- export declare const SDK_VERSION = "0.1.2";
4
+ export declare const SDK_VERSION = "0.1.4";
5
5
  /**
6
6
  * Describes the current app to the type system. `quad gen` augments it from
7
7
  * app.manifest.json and schema/ (D23); without that, nothing is readable.
@@ -13,6 +13,11 @@ export type AppConfig = {
13
13
  /** The roles the app serves (D2). Fields hidden from any of them are optional (D25). */
14
14
  roles: string;
15
15
  scopes: string;
16
+ /** The varying fields a version 1 manifest declares, per entity (V2s D85). Absent for version 0. */
17
+ data?: Record<string, {
18
+ required: string;
19
+ optional: string;
20
+ }> | undefined;
16
21
  notifications: string;
17
22
  tasks: string;
18
23
  /** Jobs that `schedule.at` may name (the manifest's `scheduled` list, D7). */
@@ -26,6 +31,7 @@ type Field<T, K extends string, Fallback> = T extends {
26
31
  export type CurrentApp = {
27
32
  roles: Field<QuadApp, 'roles', Role> & string;
28
33
  scopes: Field<QuadApp, 'scopes', never> & string;
34
+ data: Field<QuadApp, 'data', undefined>;
29
35
  notifications: Field<QuadApp, 'notifications', never> & string;
30
36
  tasks: Field<QuadApp, 'tasks', never> & string;
31
37
  scheduled: Field<QuadApp, 'scheduled', never> & string;
@@ -79,7 +85,22 @@ export type Me = {
79
85
  export type AuthApi = {
80
86
  me(): Promise<Me>;
81
87
  };
82
- export type SchoolRecord<A extends AppConfig, N extends EntityName> = RecordWithTiers<Entities[N], TiersFor<A['scopes'], N>>;
88
+ /** What an app declared for one entity: required and optional field names (V2s D85). */
89
+ type DeclaredFor<A, N extends string, K extends 'required' | 'optional'> = A extends {
90
+ data: infer D;
91
+ } ? D extends {
92
+ [P in N]: {
93
+ [Q in K]: infer F extends string;
94
+ };
95
+ } ? F : never : never;
96
+ /**
97
+ * A school record as this app sees it. A version 1 manifest (with `data`) gets the core fields and the
98
+ * fields it declared, optional ones typed `?`; a version 0 manifest gets every field of its granted
99
+ * tiers (D23).
100
+ */
101
+ export type SchoolRecord<A extends AppConfig, N extends EntityName> = A extends {
102
+ data: infer D;
103
+ } ? [D] extends [undefined] ? RecordWithTiers<Entities[N], TiersFor<A['scopes'], N>> : RecordWithFields<Entities[N], TiersFor<A['scopes'], N>, DeclaredFor<A, N, 'required'>, DeclaredFor<A, N, 'optional'>> : RecordWithTiers<Entities[N], TiersFor<A['scopes'], N>>;
83
104
  export type Collection<R> = {
84
105
  /** A record the current user can see; NOT_FOUND otherwise. */
85
106
  get(id: string): Promise<R>;
@@ -1 +1 @@
1
- export const SDK_VERSION = '0.1.2';
1
+ export const SDK_VERSION = '0.1.4';
@@ -11,11 +11,6 @@ export type EngineOptions = {
11
11
  /** IndexedDB database name; defaults to `quad-engine`. */
12
12
  dbName?: string;
13
13
  };
14
- /**
15
- * The in-browser implementation of the @quad-education/sdk contract (D15). It runs in the demo
16
- * shell's origin, holds the fictional school, and enforces visibility, scopes and D17 on
17
- * every call. Apps reach it only through a transport.
18
- */
19
14
  export declare class Engine implements Kernel {
20
15
  private readonly apps;
21
16
  private clock;
@@ -99,10 +94,20 @@ export declare class Engine implements Kernel {
99
94
  private me;
100
95
  private schoolInfo;
101
96
  private entityName;
102
- /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
97
+ /**
98
+ * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
99
+ * SCOPE_NOT_GRANTED if the app has no scope for the entity.
100
+ */
103
101
  private tiers;
104
102
  private allowedFields;
105
103
  private visible;
104
+ /**
105
+ * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
106
+ * dataset makes only the slice the where clause names, for only the students the reader may see, and
107
+ * visibility, fields and the rest of the where clause apply to that slice as to any other. A dataset with no
108
+ * way to select (one wrapped with a custom registry) falls back to building everything.
109
+ */
110
+ private visibleFor;
106
111
  private shape;
107
112
  private schoolGet;
108
113
  private schoolList;
@@ -150,4 +155,4 @@ export declare class Engine implements Kernel {
150
155
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
151
156
  private auditSensitiveRead;
152
157
  }
153
- export declare const ENGINE_SDK_VERSION = "0.1.2";
158
+ export declare const ENGINE_SDK_VERSION = "0.1.4";
@@ -1,5 +1,5 @@
1
- import { BASE_FIELDS, ENTITIES, eligibleParents, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
- import { DEFAULT_ACCESS, parseManifest, schemaHash, } from '@quad-education/schema';
1
+ import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
+ import { DEFAULT_ACCESS, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
3
3
  import { QuadError } from "../contract/errors.js";
4
4
  import { SDK_VERSION } from "../contract/types.js";
5
5
  import { clockNow } from "../protocol.js";
@@ -19,10 +19,16 @@ const str = (v, what) => {
19
19
  return v;
20
20
  };
21
21
  /**
22
- * The in-browser implementation of the @quad-education/sdk contract (D15). It runs in the demo
23
- * shell's origin, holds the fictional school, and enforces visibility, scopes and D17 on
24
- * every call. Apps reach it only through a transport.
22
+ * What an app may read of one entity: the tiers granted to it and allowed to the principal (D23), plus
23
+ * the varying fields its version 1 manifest declared (null for version 0, which has no declaration).
25
24
  */
25
+ class Grant extends Set {
26
+ declared;
27
+ constructor(tiers, declared) {
28
+ super(tiers);
29
+ this.declared = declared;
30
+ }
31
+ }
26
32
  export class Engine {
27
33
  apps = new Map();
28
34
  clock = { kind: 'offset', offsetMs: 0 };
@@ -33,6 +39,13 @@ export class Engine {
33
39
  this.dataset = dataset;
34
40
  this.storage = storage;
35
41
  for (const entity of Object.keys(ENTITIES)) {
42
+ if (isDerived(entity)) {
43
+ // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
44
+ if (!(entity in dataset)) {
45
+ throw new Error(`the dataset has no ${entity}: it is derived, so wrap the stored dataset with withDerived() from @quad-education/fictional-school`);
46
+ }
47
+ continue;
48
+ }
36
49
  for (const record of dataset[entity]) {
37
50
  this.byId.set(record.id, { entity, record });
38
51
  }
@@ -301,7 +314,8 @@ export class Engine {
301
314
  if (!person || person.entity !== PEOPLE[principal.role]) {
302
315
  throw new QuadError('FORBIDDEN', `no ${principal.role} with id ${principal.personId}`);
303
316
  }
304
- if (!app.manifest.roles.includes(principal.role)) {
317
+ // A school persona stands in for an app role of the same name, ignoring case (V2s D84).
318
+ if (!servedRoles(app.manifest).includes(principal.role)) {
305
319
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
306
320
  }
307
321
  return { app, principal, actorId: principal.personId };
@@ -339,48 +353,74 @@ export class Engine {
339
353
  }
340
354
  return value;
341
355
  }
342
- /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
356
+ /**
357
+ * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
358
+ * SCOPE_NOT_GRANTED if the app has no scope for the entity.
359
+ */
343
360
  tiers(ctx, entity) {
344
361
  const granted = grantedTiers(ctx.app.manifest.scopes, entity);
345
362
  if (granted.size === 0) {
346
363
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
347
364
  }
348
365
  const allowed = principalTiers(ctx.principal, entity);
349
- return new Set([...granted].filter((t) => allowed.has(t)));
366
+ // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
367
+ const entry = ctx.app.manifest.data?.[entity];
368
+ const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
369
+ return new Grant([...granted].filter((t) => allowed.has(t)), declared);
350
370
  }
351
- allowedFields(entity, tiers) {
371
+ allowedFields(entity, grant) {
352
372
  const fields = new Set(Object.keys(BASE_FIELDS));
353
373
  for (const [key, def] of Object.entries(ENTITIES[entity].fields))
354
- if (tiers.has(def.tier))
374
+ if (fieldVisible(def, key, grant, grant.declared))
355
375
  fields.add(key);
356
376
  return fields;
357
377
  }
358
378
  visible(ctx, entity) {
359
379
  return visibleRecords(ctx.principal, entity, this.dataset);
360
380
  }
361
- shape(entity, tiers, records) {
362
- return records.map((r) => filterFields(entity, r, tiers));
381
+ /**
382
+ * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
383
+ * dataset makes only the slice the where clause names, for only the students the reader may see, and
384
+ * visibility, fields and the rest of the where clause apply to that slice as to any other. A dataset with no
385
+ * way to select (one wrapped with a custom registry) falls back to building everything.
386
+ */
387
+ visibleFor(ctx, entity, where) {
388
+ const select = isWindowed(entity)
389
+ ? this.dataset.select
390
+ : undefined;
391
+ if (typeof select !== 'function')
392
+ return this.visible(ctx, entity);
393
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
394
+ const made = select.call(this.dataset, entity, { where, students: ctx.students });
395
+ if (made === null)
396
+ return this.visible(ctx, entity);
397
+ if (!made.ok)
398
+ throw new QuadError('VALIDATION', made.message);
399
+ return visibleRecords(ctx.principal, entity, this.dataset, made.rows);
400
+ }
401
+ shape(entity, grant, records) {
402
+ return records.map((r) => filterFields(entity, r, grant, grant.declared));
363
403
  }
364
404
  async schoolGet(ctx, entityValue, id) {
365
405
  const entity = this.entityName(entityValue);
366
406
  const tiers = this.tiers(ctx, entity);
367
- const record = this.visible(ctx, entity).find((r) => r.id === id);
407
+ const record = this.visibleFor(ctx, entity, { id }).find((r) => r.id === id);
368
408
  if (!record)
369
409
  throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
370
410
  await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
371
- return filterFields(entity, record, tiers);
411
+ return filterFields(entity, record, tiers, tiers.declared);
372
412
  }
373
413
  async schoolList(ctx, entityValue, options) {
374
414
  const entity = this.entityName(entityValue);
375
415
  const tiers = this.tiers(ctx, entity);
376
- const page = runQuery(this.visible(ctx, entity), (options ?? {}), this.allowedFields(entity, tiers));
416
+ const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers));
377
417
  await this.auditSensitiveRead(ctx, entity, tiers, page.items.length, 'school.list');
378
418
  return { items: this.shape(entity, tiers, page.items), nextCursor: page.nextCursor };
379
419
  }
380
420
  cohortByCode(ctx, code) {
381
421
  const tiers = this.tiers(ctx, 'cohorts');
382
422
  const cohort = this.visible(ctx, 'cohorts').find((c) => c.code === str(code, 'code'));
383
- return cohort ? filterFields('cohorts', cohort, tiers) : null;
423
+ return cohort ? filterFields('cohorts', cohort, tiers, tiers.declared) : null;
384
424
  }
385
425
  cohortMembers(ctx, cohortId, options) {
386
426
  const tiers = this.tiers(ctx, 'cohortMemberships');
@@ -453,7 +493,12 @@ export class Engine {
453
493
  if (ctx.principal.kind === 'system')
454
494
  return 'system';
455
495
  const policy = def.access ?? DEFAULT_ACCESS;
456
- const value = policy[ctx.principal.role]?.[op];
496
+ // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
497
+ const role = ctx.principal.role;
498
+ const key = Object.hasOwn(policy, role)
499
+ ? role
500
+ : Object.keys(policy).find((k) => k.toLowerCase() === role);
501
+ const value = key === undefined ? undefined : policy[key]?.[op];
457
502
  return value === undefined ? [] : Array.isArray(value) ? value : [value];
458
503
  }
459
504
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
@@ -666,7 +711,8 @@ export class Engine {
666
711
  if (!record)
667
712
  return null;
668
713
  schoolReads.set(target, (schoolReads.get(target) ?? 0) + 1);
669
- return filterFields(target, record, this.tiers(ctx, target));
714
+ const grant = this.tiers(ctx, target);
715
+ return filterFields(target, record, grant, grant.declared);
670
716
  }
671
717
  // Included app records follow their own entity's rules (D25).
672
718
  const def = entityOf(ctx.app.schema, field.to);
@@ -765,7 +811,7 @@ export class Engine {
765
811
  const list = Array.isArray(to) ? to : [to];
766
812
  if (list.length === 0)
767
813
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
768
- const roles = ctx.app.manifest.roles;
814
+ const roles = servedRoles(ctx.app.manifest);
769
815
  const senderIsStaff = ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
770
816
  const out = new Map();
771
817
  const suppressed = new Map();
@@ -902,7 +948,7 @@ export class Engine {
902
948
  }
903
949
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
904
950
  async auditSensitiveRead(ctx, entity, tiers, count, via) {
905
- const sensitive = [...tiers].filter((t) => t === 'pastoral' || t === 'medical');
951
+ const sensitive = [...tiers].filter((t) => AUDITED_TIERS.includes(t));
906
952
  if (sensitive.length === 0 || count === 0)
907
953
  return;
908
954
  const hasFields = Object.values(ENTITIES[entity].fields).some((f) => sensitive.includes(f.tier));
@@ -23,6 +23,9 @@ export function hostApp(options) {
23
23
  reject(e.origin, 'message from a window that is not one of the app’s frames');
24
24
  return;
25
25
  }
26
+ // A preview's app file (D69) is the shell's to handle, not the session's.
27
+ if (e.data?.type === 'quad:app-file')
28
+ return;
26
29
  if (!isReady(e.data)) {
27
30
  reject(e.origin, 'unexpected window message (RPC must use the session port)');
28
31
  return;
@@ -1,7 +1,7 @@
1
1
  // @quad-education/sdk/testing: a test kit for app code. It runs the in-browser engine in memory
2
2
  // (fake IndexedDB) with the fictional school, so app tests need no browser or shell.
3
3
  import 'fake-indexeddb/auto';
4
- import { personasFor } from '@quad-education/fictional-school';
4
+ import { personasFor, withDerived } from '@quad-education/fictional-school';
5
5
  import fictionalSchool from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
6
  import { connectInProcess } from "../engine/in-process.js";
7
7
  import { Engine } from "../engine/engine.js";
@@ -9,7 +9,7 @@ import { executeRun } from "../jobs/define.js";
9
9
  let instance = 0;
10
10
  /** A fresh in-memory platform with your app installed. */
11
11
  export async function createTestPlatform(app) {
12
- const dataset = fictionalSchool;
12
+ const dataset = withDerived(fictionalSchool);
13
13
  const engine = await Engine.create({ dataset, indexedDB, dbName: `quad-test-${++instance}` });
14
14
  if (app.now)
15
15
  await engine.setClock(app.now);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quad-education/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "The @quad-education/sdk contract, its in-browser engine, transports and contract tests",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -47,9 +47,9 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "fake-indexeddb": "^6.2.5",
50
- "@quad-education/canonical": "^0.1.2",
51
- "@quad-education/fictional-school": "^0.1.2",
52
- "@quad-education/schema": "^0.1.2"
50
+ "@quad-education/canonical": "^0.1.4",
51
+ "@quad-education/fictional-school": "^0.1.4",
52
+ "@quad-education/schema": "^0.1.4"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "vitest": "^5.0.3"