@quad-education/sdk 0.3.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
@@ -95,6 +95,7 @@ The types allow `orderBy` and ranges only on indexed fields, so most mistakes ar
95
95
 
96
96
  ## Versions
97
97
 
98
+ - **0.4.0 (D103, 21 Oct 2026).** A small canonical model, and no field-level coverage anywhere an app can see it (a contract change across all the `@quad-education/*` packages, which move together). The model is 13 entities and 56 fields: the foundation (`schools`, `students`, `staff`, `parents`, `parentStudentLinks`, `cohorts`, `cohortMemberships`) and the extended ones some school systems supply (`periods`, `rooms`, `lessons`, `sessionAttendance`, `medicalAlerts`, `medicalNotes`). **Removed:** `enrolments`, `courses`, `courseEnrolments`, `subjects`, `calendarEvents` and `sdk.school.calendar`, `assignments`, `submissions`, `results`, `studentAbsences`, `attendanceSummaries`, `behaviours`, `achievements`, `learningSupportNeeds`, `medicalEvents`, `employeeAbsences`, `applicants` and `pastoralNotes`; and fields: `students.preferredName` and the seven sensitive demographic fields, `staff.positionTitle` and `phone`, a parent's title, mobile, address and language, `livesWith`, `primaryContact`, `cohorts.parentCohortId` and `subjectId`, the register's `comment` and `minutesLate`, a medical alert's `severity` and `actionPlan`, and a note's `title`, `conditionId` and `eventId`. **Added:** `students.gender`, `parents.phone`, `cohorts.subject` (text, such as "English"), the `form` cohort kind, and the capability map (`CAPABILITIES`, `capabilityOf`, `capabilitiesOf`, `entityKind` in `@quad-education/canonical`). **Changed:** apps no longer declare the fields they read, so the manifest `data` block is accepted and ignored (`manifestWarnings` says to remove it), the engine strips nothing, and `core` is gone; scopes are checked directly. Ids, references and names are required and every other field is typed optional, because a school's system may not supply it. A parent's contact flags (`receivesCorrespondence`, `canConsent`, `contactRestricted`) are optional too, and where a school's system does not supply one the parent is treated as contactable (D17 amended by D103). The `lms` backing goes, and `fieldTier`, `coreFields` and `varyingFields` with it.
98
99
  - **0.3.0 (D101, 20 Oct 2026).** Every app runs in a school, so what 0.2.0 added for apps with no school is removed (a removal across all the `@quad-education/*` packages, which move together). Gone from the main entry: the `account` and `guest` principals, `ActingAs`, the account directory and `staticDirectory`, the `account` and `guest` results of `auth.me()`, the `NOT_AVAILABLE` error code (`sdk.school` is always available: the fictional school in dev and the Sandbox, the real school in a school instance), the `{ account }` recipient, and `{ role }` taking any string (it is a school role again). Gone from `@quad-education/sdk/client`: `createHttpTransport`, `connectHttp`, the live connection (`connectLive`, `getLiveStatus`, `signIn`, `continueAsGuest`, `SignInRequired`) and the live branch of `connect()`, which now only talks to the shell. Gone from `@quad-education/sdk/engine` (platform-side only): `school: false`, `accounts`, `accountsFor`, a per-app `timezone`, `attachApp`, `hasApp`, `setAccounts` and `isStandalone`. Gone from `@quad-education/sdk/contract-tests`: the `STANDALONE_APP`, `ACCOUNT_APP` and `TEST_ACCOUNTS` fixtures and the `school` option. `@quad-education/sdk-react` loses `SignInChoices` and `SignInActions`; `@quad-education/schema` loses the manifest's `guests`, the reserved role `guest` and the SDK-version rule for guests. The `subject` rule now applies to every app. **Kept:** the `createdBy, createdAt` implicit index (a list of one's own records can be sorted), and the engine's state behind an `AppStore`, so a school instance's data API can run the same rules over DynamoDB; its `inbox`, `runs`, `auditLog`, `effectsSnapshot` and `runPrincipal` still return promises. Guest access inside a school instance is wanted, and comes back as a contract change when it is designed. Every earlier version, 0.2.0 included, is withdrawn from npm after this one is out.
99
100
  - **0.2.0** (20 Oct 2026, withdrawn). Account and guest principals, `NOT_AVAILABLE`, the manifest `guests` flag and the live connection, for apps that were to run live outside a school (V2c, D100). Removed again by D101 in 0.3.0.
100
101
  - **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.
@@ -67,29 +67,8 @@ 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: {
70
+ /** A first-aid app: it holds the medical tier, so it reads alerts and the notes about them (D103). */
71
+ export declare const MEDICAL_APP: {
93
72
  manifest: Manifest;
94
73
  schema: typeof TEST_SCHEMA;
95
74
  };
@@ -98,15 +77,6 @@ export declare const BASIC_APP: {
98
77
  manifest: Manifest;
99
78
  schema: typeof TEST_SCHEMA;
100
79
  };
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
80
  /**
111
81
  * An app (V2s D84) with version 1, two app-defined roles named like school roles, so the matching
112
82
  * personas can preview them. The access keys are written in different cases on purpose.
@@ -26,7 +26,7 @@ export const TEST_SCHEMA = defineSchema({
26
26
  const base = {
27
27
  manifestVersion: 0,
28
28
  sdk: '^0.1.0',
29
- kit: 'react-ui',
29
+ kit: 'react-shadcn',
30
30
  roles: ['staff', 'student', 'parent'],
31
31
  tasks: [],
32
32
  scheduled: [],
@@ -53,126 +53,23 @@ export const TEST_APP = {
53
53
  'cohorts.basic:read',
54
54
  'cohortMemberships.basic:read',
55
55
  'medicalAlerts.medical:read',
56
- 'pastoralNotes.pastoral:read',
57
- 'calendarEvents.basic:read',
58
- 'courses.basic:read',
59
- 'results.academic:read',
60
56
  'lessons.basic:read',
61
57
  'periods.basic:read',
62
58
  'rooms.basic:read',
63
- 'subjects.basic:read',
64
59
  'sessionAttendance.basic:read',
65
60
  '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',
79
61
  ],
80
62
  notifications: ['test.message', 'test.reminder'],
81
63
  },
82
64
  schema: TEST_SCHEMA,
83
65
  };
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 = {
66
+ /** A first-aid app: it holds the medical tier, so it reads alerts and the notes about them (D103). */
67
+ export const MEDICAL_APP = {
119
68
  manifest: {
120
69
  ...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
- ],
70
+ id: 'contract-medical',
71
+ name: 'First-aid app',
72
+ scopes: ['medicalAlerts.medical:read', 'medicalNotes.basic:read', 'medicalNotes.medical:read'],
176
73
  notifications: ['test.message'],
177
74
  },
178
75
  schema: TEST_SCHEMA,
@@ -188,24 +85,6 @@ export const BASIC_APP = {
188
85
  },
189
86
  schema: TEST_SCHEMA,
190
87
  };
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
88
  /**
210
89
  * An app (V2s D84) with version 1, two app-defined roles named like school roles, so the matching
211
90
  * personas can preview them. The access keys are written in different cases on purpose.
@@ -1,4 +1,4 @@
1
1
  export { defineContractSuite } from './suite.ts';
2
2
  export type { ContractEnv, ContractFactory, TestApp } from './suite.ts';
3
3
  export { sliceBControls } from './harness.ts';
4
- export { ACCESS_APP, AWARDS_APP, BASIC_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, TEST_APP, WELLBEING_APP, slowGate, } from './apps.ts';
4
+ export { ACCESS_APP, BASIC_APP, JOBS_APP, TEST_APP, MEDICAL_APP, slowGate } from './apps.ts';
@@ -1,3 +1,3 @@
1
1
  export { defineContractSuite } from "./suite.js";
2
2
  export { sliceBControls } from "./harness.js";
3
- export { ACCESS_APP, AWARDS_APP, BASIC_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
3
+ export { ACCESS_APP, BASIC_APP, JOBS_APP, TEST_APP, MEDICAL_APP, slowGate } from "./apps.js";
@@ -4,7 +4,7 @@ import { eligibleParents } from '@quad-education/canonical';
4
4
  import { personasFor, withDerived } from '@quad-education/fictional-school';
5
5
  import stored from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
6
  import { parentsOf, staffOf, studentsOf } from "../src/index.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";
7
+ import { ACCESS_APP, BASIC_APP, JOBS_APP, ROLES_APP, TEST_APP, MEDICAL_APP, slowGate, } from "./apps.js";
8
8
  import { expectError, ids, listAll } from "./helpers.js";
9
9
  // The fictional school is the oracle: tests compare what the SDK returns with what the
10
10
  // dataset says should be visible. They never read an implementation's storage.
@@ -52,7 +52,7 @@ export function defineContractSuite(name, factory) {
52
52
  },
53
53
  });
54
54
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
55
- expect(sdk.version).toBe('0.3.0');
55
+ expect(sdk.version).toBe('0.4.1');
56
56
  });
57
57
  it('knows parents and students', async () => {
58
58
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
@@ -69,7 +69,7 @@ export function defineContractSuite(name, factory) {
69
69
  const sdk = await env.connect(STUDENT);
70
70
  expect(ids(await listAll(sdk.school.students))).toEqual([STUDENT.personId]);
71
71
  expect((await listAll(sdk.school.parents)).length).toBe(0);
72
- expect((await listAll(sdk.school.pastoralNotes)).length).toBe(0);
72
+ expect((await listAll(sdk.school.medicalAlerts)).every((a) => a.studentId === STUDENT.personId)).toBe(true);
73
73
  });
74
74
  it('a parent sees only their own children', async () => {
75
75
  const sdk = await env.connect(SIBLINGS_PARENT);
@@ -105,9 +105,10 @@ export function defineContractSuite(name, factory) {
105
105
  expect(m.personId).toBe(studentId);
106
106
  }
107
107
  });
108
- it('staff see pastoral notes; students and parents never do', async () => {
109
- expect((await listAll((await env.connect(STAFF)).school.pastoralNotes)).length).toBe(ds.pastoralNotes.length);
110
- expect(await listAll((await env.connect(SIBLINGS_PARENT)).school.pastoralNotes)).toEqual([]);
108
+ it('staff see every medical alert; a parent sees only their own children’s', async () => {
109
+ expect((await listAll((await env.connect(STAFF)).school.medicalAlerts)).length).toBe(ds.medicalAlerts.length);
110
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
111
+ expect(ids(await listAll((await env.connect(SIBLINGS_PARENT)).school.medicalAlerts))).toEqual(ids(ds.medicalAlerts.filter((a) => kids.has(a.studentId))));
111
112
  });
112
113
  });
113
114
  describe('school: scopes and tiers (D5, D23)', () => {
@@ -127,7 +128,6 @@ export function defineContractSuite(name, factory) {
127
128
  const sdk = await env.connect(STAFF);
128
129
  await expectError(sdk.school.parents.list(), 'SCOPE_NOT_GRANTED');
129
130
  await expectError(sdk.school.medicalAlerts.get(ds.medicalAlerts[0].id), 'SCOPE_NOT_GRANTED');
130
- await expectError(sdk.school.calendar.list({ from: '2026-01-01', to: '2027-01-01' }), 'SCOPE_NOT_GRANTED');
131
131
  await expectError(sdk.school.sessionAttendance.list({ where: { date: '2026-03-03' } }), 'SCOPE_NOT_GRANTED');
132
132
  });
133
133
  it('still answers school.info', async () => {
@@ -190,51 +190,9 @@ export function defineContractSuite(name, factory) {
190
190
  await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
191
191
  });
192
192
  });
193
- describe('school: declared fields (D85)', () => {
194
- useApp(DATA_APP);
195
- it('returns the core fields and the declared ones, and nothing else that varies', async () => {
196
- const sdk = await env.connect(STAFF);
197
- const expected = ds.students[0];
198
- const student = await sdk.school.students.get(expected.id);
199
- expect(student.givenName).toBe(expected.givenName);
200
- expect(student.studentNumber).toBe(expected.studentNumber);
201
- expect(student.dateOfBirth).toBe(expected.dateOfBirth);
202
- expect(student.email).toBe(expected.email);
203
- // yearLevel and preferredName are granted by tier but were not declared.
204
- expect('yearLevel' in student).toBe(false);
205
- expect('preferredName' in student).toBe(false);
206
- for (const s of (await sdk.school.students.list({ limit: 25 })).items) {
207
- expect('yearLevel' in s).toBe(false);
208
- expect('preferredName' in s).toBe(false);
209
- expect('dateOfBirth' in s).toBe(true);
210
- }
211
- });
212
- it('refuses to filter or sort on a field that was not declared, so it cannot be probed', async () => {
213
- const sdk = await env.connect(STAFF);
214
- await expectError(sdk.school.students.list({ where: { yearLevel: 'Y9' } }), 'VALIDATION');
215
- await expectError(sdk.school.students.list({ orderBy: { field: 'preferredName' } }), 'VALIDATION');
216
- // Declared and core fields still work.
217
- const name = ds.students[0].familyName;
218
- const found = await sdk.school.students.list({ where: { familyName: name }, limit: 200 });
219
- expect(found.items.length).toBeGreaterThan(0);
220
- expect((await sdk.school.students.list({ where: { dateOfBirth: ds.students[0].dateOfBirth } }))
221
- .items.length).toBeGreaterThan(0);
222
- });
223
- it('strips included school refs the same way', async () => {
224
- const sdk = await env.connect(STAFF);
225
- await sdk.db
226
- .entity('greeting')
227
- .create({ message: 'hi', studentId: ds.students[0].id, tone: 'warm' });
228
- const { items } = await sdk.db.entity('greeting').list({ include: ['studentId'] });
229
- const included = items[0].$included.studentId;
230
- expect(included.givenName).toBe(ds.students[0].givenName);
231
- expect('yearLevel' in included).toBe(false);
232
- expect('dateOfBirth' in included).toBe(true);
233
- });
234
- });
235
- describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
193
+ describe('school: every field of the granted tiers, with no declaration (D103)', () => {
236
194
  useApp(BASIC_APP);
237
- it('keeps yearLevel and preferredName available', async () => {
195
+ it('gives yearLevel with the basic tier', async () => {
238
196
  const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
239
197
  .items[0];
240
198
  expect('yearLevel' in student).toBe(true);
@@ -371,7 +329,7 @@ export function defineContractSuite(name, factory) {
371
329
  where: { date: '2026-03-03', code: 'late' },
372
330
  });
373
331
  expect(late.length).toBeGreaterThan(0);
374
- expect(late.every((m) => m.code === 'late' && typeof m.minutesLate === 'number')).toBe(true);
332
+ expect(late.every((m) => m.code === 'late')).toBe(true);
375
333
  }, 30_000);
376
334
  it('pages through a register without gaps or repeats, and finds one mark by id', async () => {
377
335
  const staff = await env.connect(STAFF);
@@ -412,272 +370,47 @@ export function defineContractSuite(name, factory) {
412
370
  expect(new Set(parent.map((m) => m.studentId))).toEqual(new Set(kids));
413
371
  expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.sessionAttendance, day)).toEqual([]);
414
372
  });
415
- it('needs the academic scope for marks and the pastoral scope for comments, which are audited', async () => {
416
- const staff = await env.connect(STAFF);
417
- const withComments = await listAll(staff.school.sessionAttendance, {
418
- where: { studentId: ds.students[3].id },
419
- });
420
- expect(withComments.some((m) => typeof m.comment === 'string')).toBe(true);
421
- const log = await env.control.auditLog();
422
- const reads = log.filter((e) => e.action === 'school.sensitive-read' && e.entity === 'sessionAttendance');
423
- expect(reads.length).toBeGreaterThan(0);
424
- expect(reads[0].data.tiers).toEqual(['pastoral']);
425
- });
426
- it('serves absences and term summaries, each student’s own', async () => {
373
+ it('refuses medical notes to an app without the scope', async () => {
427
374
  const staff = await env.connect(STAFF);
428
- const mine = await listAll((await env.connect(STUDENT)).school.attendanceSummaries);
429
- expect(mine).toHaveLength(4);
430
- expect(mine.every((s) => s.studentId === STUDENT.personId)).toBe(true);
431
- expect(mine[0]).toMatchObject({
432
- possibleMarks: expect.any(Number),
433
- presentMarks: expect.any(Number),
434
- });
435
- const all = await listAll(staff.school.attendanceSummaries, {
436
- where: { termName: 'Term 1' },
437
- });
438
- expect(all).toHaveLength(ds.students.length);
439
- const absences = await listAll(staff.school.studentAbsences, {
440
- where: { studentId: ds.students[0].id },
441
- });
442
- expect(absences.length).toBeGreaterThan(0);
443
- // The reason is pastoral, and this app was not granted that tier.
444
- expect(absences.every((a) => a.endAt > a.startAt && !('reason' in a) && !('comment' in a))).toBe(true);
445
- const own = await listAll((await env.connect(SIBLINGS_PARENT)).school.studentAbsences);
446
- expect(new Set(own.map((a) => a.studentId))).toEqual(new Set(childrenOf(SIBLINGS_PARENT.personId)));
447
- }, 30_000);
448
- it('serves behaviour incidents and achievements, each student’s own (S4.3)', async () => {
449
- const staff = await env.connect(STAFF);
450
- const mine = ds.behaviours.find((b) => b.studentId !== STUDENT.personId);
451
- const incidents = await listAll(staff.school.behaviours, {
452
- where: { studentId: mine.studentId },
453
- });
454
- expect(incidents.length).toBeGreaterThan(0);
455
- expect(incidents.every((b) => b.studentId === mine.studentId && b.points < 0)).toBe(true);
456
- expect(incidents[0]).toMatchObject({
457
- incident: expect.any(String),
458
- date: expect.any(String),
459
- });
460
- const own = await listAll((await env.connect(STUDENT)).school.behaviours);
461
- expect(own.every((b) => b.studentId === STUDENT.personId)).toBe(true);
462
- expect(own).toHaveLength(ds.behaviours.filter((b) => b.studentId === STUDENT.personId).length);
463
- const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
464
- const family = await listAll((await env.connect(SIBLINGS_PARENT)).school.behaviours);
465
- expect(family.every((b) => kids.has(b.studentId))).toBe(true);
466
- expect(family).toHaveLength(ds.behaviours.filter((b) => kids.has(b.studentId)).length);
467
- expect(await listAll((await env.connect(RESTRICTED_PARENT)).school.behaviours)).toEqual([]);
468
- await expectError((await env.connect(STUDENT)).school.behaviours.get(mine.id), 'NOT_FOUND');
469
- const awards = await listAll((await env.connect(STUDENT)).school.achievements);
470
- expect(awards).toHaveLength(ds.achievements.filter((a) => a.studentId === STUDENT.personId).length);
471
- expect(awards.every((a) => a.points > 0 && typeof a.type === 'string')).toBe(true);
472
- const all = await listAll(staff.school.achievements, { where: { type: 'Sport' } });
473
- expect(all).toHaveLength(ds.achievements.filter((a) => a.type === 'Sport').length);
474
- }, 30_000);
475
- it('audits behaviour reads, which are pastoral, but not achievements, which are academic (S4.3, D19)', async () => {
476
- const staff = await env.connect(STAFF);
477
- await staff.school.behaviours.list({ limit: 4 });
478
- await staff.school.achievements.list({ limit: 4 });
479
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' &&
480
- ['behaviours', 'achievements'].includes(String(e.entity)));
481
- expect(reads.map((e) => [e.entity, e.data.tiers])).toEqual([['behaviours', ['pastoral']]]);
482
- });
483
- describe('an awards app with no pastoral scope', () => {
484
- useApp(AWARDS_APP);
485
- it('reads achievements but not behaviour, and leaves no pastoral audit entry', async () => {
486
- const sdk = await env.connect(STAFF);
487
- const { items } = await sdk.school.achievements.list({ limit: 5 });
488
- expect(items).toHaveLength(5);
489
- await expectError(sdk.school.behaviours.list(), 'SCOPE_NOT_GRANTED');
490
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read');
491
- expect(reads).toEqual([]);
492
- });
493
- });
494
- it('leaves the diagnosis out of learning support when only the pastoral tier is granted (S4.4)', async () => {
495
- const staff = await env.connect(STAFF);
496
- const withNeed = ds.learningSupportNeeds[0];
497
- const items = await listAll(staff.school.learningSupportNeeds, {
498
- where: { studentId: withNeed.studentId },
499
- });
500
- expect(items.length).toBeGreaterThan(0);
501
- expect(items[0]).toMatchObject({ category: expect.any(String), level: expect.any(String) });
502
- expect(items.every((n) => !('need' in n))).toBe(true);
503
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
504
- expect(reads.map((e) => e.data.tiers)).toEqual([['pastoral']]);
505
- await expectError(staff.school.medicalEvents.list(), 'SCOPE_NOT_GRANTED');
506
375
  await expectError(staff.school.medicalNotes.list(), 'SCOPE_NOT_GRANTED');
507
376
  });
508
- describe('a wellbeing app with the medical tier', () => {
509
- useApp(WELLBEING_APP);
510
- it('receives the diagnosis, and the audit records both tiers (S4.4)', async () => {
511
- const staff = await env.connect(STAFF);
512
- const withNeed = ds.learningSupportNeeds[0];
513
- const items = await listAll(staff.school.learningSupportNeeds, {
514
- where: { studentId: withNeed.studentId },
515
- });
516
- expect(items.some((n) => n.need === withNeed.need && n.category === withNeed.category)).toBe(true);
517
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'learningSupportNeeds');
518
- expect([...reads[0].data.tiers].sort()).toEqual(['medical', 'pastoral']);
519
- });
520
- it('serves medical events and the notes that link to them, each student’s own', async () => {
377
+ describe('a first-aid app with the medical tier (D103)', () => {
378
+ useApp(MEDICAL_APP);
379
+ it('reads alerts and the notes about them, and the audit records the medical tier', async () => {
521
380
  const staff = await env.connect(STAFF);
522
- const event = ds.medicalEvents.find((e) => e.followUpDate);
523
- const events = await listAll(staff.school.medicalEvents, {
524
- where: { studentId: event.studentId },
525
- });
526
- expect(events.find((e) => e.id === event.id)).toMatchObject({
527
- type: event.type,
528
- followUpDate: event.followUpDate,
381
+ const alert = ds.medicalAlerts[0];
382
+ const alerts = await listAll(staff.school.medicalAlerts, {
383
+ where: { studentId: alert.studentId },
529
384
  });
385
+ expect(alerts.some((a) => a.condition === alert.condition)).toBe(true);
530
386
  const notes = await listAll(staff.school.medicalNotes, {
531
- where: { studentId: event.studentId },
387
+ where: { studentId: alert.studentId },
532
388
  });
533
- expect(notes.some((n) => n.eventId === event.id)).toBe(true);
534
- expect(notes.every((n) => (n.conditionId === undefined) !== (n.eventId === undefined))).toBe(true);
389
+ expect(notes.length).toBeGreaterThan(0);
390
+ expect(notes.every((n) => typeof n.note === 'string')).toBe(true);
391
+ const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' &&
392
+ ['medicalAlerts', 'medicalNotes'].includes(String(e.entity)));
393
+ expect(reads.length).toBeGreaterThan(0);
394
+ expect(reads.every((e) => e.data.tiers.includes('medical'))).toBe(true);
395
+ });
396
+ it('gives a student or a parent only their own, and nothing to a restricted parent', async () => {
535
397
  const student = await env.connect(STUDENT);
398
+ const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
536
399
  for (const [entity, all] of [
537
- ['learningSupportNeeds', ds.learningSupportNeeds],
538
- ['medicalEvents', ds.medicalEvents],
400
+ ['medicalAlerts', ds.medicalAlerts],
539
401
  ['medicalNotes', ds.medicalNotes],
540
402
  ]) {
541
403
  const own = await listAll(student.school[entity]);
542
404
  expect(own, entity).toHaveLength(all.filter((r) => r.studentId === STUDENT.personId).length);
543
405
  expect(own.every((r) => r.studentId === STUDENT.personId)).toBe(true);
544
- const kids = new Set(childrenOf(SIBLINGS_PARENT.personId));
545
406
  const family = await listAll((await env.connect(SIBLINGS_PARENT)).school[entity]);
546
407
  expect(family, entity).toHaveLength(all.filter((r) => kids.has(r.studentId)).length);
547
408
  expect(await listAll((await env.connect(RESTRICTED_PARENT)).school[entity])).toEqual([]);
548
409
  }
549
- await expectError(student.school.medicalEvents.get(ds.medicalEvents.find((e) => e.studentId !== STUDENT.personId).id), 'NOT_FOUND');
550
- });
551
- });
552
- describe('demographics: the sensitive tier is staff-only (S4.5, D88)', () => {
553
- useApp(DEMOGRAPHICS_APP);
554
- const SENSITIVE = [
555
- 'firstLanguage',
556
- 'englishAsAdditionalLanguage',
557
- 'ethnicity',
558
- 'nationality',
559
- 'religion',
560
- 'birthPlace',
561
- 'freeSchoolMeals',
562
- ];
563
- const leaks = (value) => JSON.stringify(value) !== undefined &&
564
- SENSITIVE.filter((k) => JSON.stringify(value).includes(`"${k}"`));
565
- it('gives staff the fields the app asked for, lets them filter on one, and audits the read', async () => {
566
- const staff = await env.connect(STAFF);
567
- const some = ds.students.find((s) => s.religion && s.firstLanguage);
568
- const one = await staff.school.students.get(some.id);
569
- expect(one).toMatchObject({ religion: some.religion, firstLanguage: some.firstLanguage });
570
- const catholic = await listAll(staff.school.students, { where: { religion: 'Catholic' } });
571
- expect(catholic).toHaveLength(ds.students.filter((s) => s.religion === 'Catholic').length);
572
- expect(catholic.length).toBeGreaterThan(20);
573
- const eal = await listAll(staff.school.students, {
574
- where: { englishAsAdditionalLanguage: true },
575
- });
576
- expect(eal.every((s) => s.englishAsAdditionalLanguage === true)).toBe(true);
577
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'students');
578
- expect(reads.length).toBeGreaterThan(0);
579
- expect(reads.every((e) => e.data.tiers.includes('sensitive'))).toBe(true);
580
- });
581
- it('never gives a student or a parent the fields, and refuses a filter that would probe them', async () => {
582
- for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT]) {
583
- const sdk = await env.connect(who);
584
- const mine = await listAll(sdk.school.students);
585
- expect(mine.length).toBeGreaterThan(0);
586
- expect(leaks(mine), who.personId).toEqual([]);
587
- expect(leaks(await sdk.school.students.get(mine[0].id))).toEqual([]);
588
- await expectError(sdk.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
589
- await expectError(sdk.school.students.list({ orderBy: { field: 'ethnicity' } }), 'VALIDATION');
590
- }
591
- });
592
- it('does not leak them through the helpers that return students or parents', async () => {
593
- const kids = childrenOf(SIBLINGS_PARENT.personId);
594
- const parent = await env.connect(SIBLINGS_PARENT);
595
- expect(leaks(await parent.school.parents.children(SIBLINGS_PARENT.personId))).toEqual([]);
596
- expect(leaks(await parent.school.students.parents(kids[0]))).toEqual([]);
597
- const student = await env.connect(STUDENT);
598
- expect(leaks(await student.school.students.parents(STUDENT.personId))).toEqual([]);
599
- expect(leaks(await student.auth.me())).toEqual([]);
600
- const staff = await env.connect(STAFF);
601
- // Staff with the scope get them for a parent's children too: the tier is for staff.
602
- const children = await staff.school.parents.children(SIBLINGS_PARENT.personId);
603
- expect(children.some((c) => SENSITIVE.some((k) => k in c))).toBe(true);
410
+ const other = ds.medicalAlerts.find((a) => a.studentId !== STUDENT.personId);
411
+ await expectError(student.school.medicalAlerts.get(other.id), 'NOT_FOUND');
604
412
  });
605
413
  });
606
- it('never gives the fields to an app that was not granted the tier', async () => {
607
- const staff = await env.connect(STAFF);
608
- const students = await listAll(staff.school.students, { where: { yearLevel: 'Y9' } });
609
- expect(students.length).toBeGreaterThan(0);
610
- expect(JSON.stringify(students)).not.toMatch(/"(religion|ethnicity|nationality|firstLanguage|birthPlace)"/);
611
- await expectError(staff.school.students.list({ where: { religion: 'Catholic' } }), 'VALIDATION');
612
- });
613
- describe('staff absences are in the hr tier (S4.6)', () => {
614
- useApp(HR_APP);
615
- it('are read by any staff member whose app holds the tier, and audited as hr', async () => {
616
- for (const who of [STAFF, DEPUTY]) {
617
- const sdk = await env.connect(who);
618
- const all = await listAll(sdk.school.employeeAbsences);
619
- expect(all).toHaveLength(ds.employeeAbsences.length);
620
- expect(all[0]).toMatchObject({
621
- staffId: expect.any(String),
622
- absenceType: expect.any(String),
623
- workingDays: expect.any(Number),
624
- });
625
- }
626
- const sdk = await env.connect(STAFF);
627
- const sick = await listAll(sdk.school.employeeAbsences, {
628
- where: { absenceType: 'Sick leave' },
629
- });
630
- expect(sick).toHaveLength(ds.employeeAbsences.filter((a) => a.absenceType === 'Sick leave').length);
631
- expect(sick.every((a) => typeof a.illnessCategory === 'string')).toBe(true);
632
- const reads = (await env.control.auditLog()).filter((e) => e.action === 'school.sensitive-read' && e.entity === 'employeeAbsences');
633
- expect(reads.length).toBeGreaterThan(0);
634
- expect(reads.every((e) => e.data.tiers.includes('hr'))).toBe(true);
635
- });
636
- it('are never given to a student or a parent, however they ask', async () => {
637
- const one = ds.employeeAbsences[0];
638
- for (const who of [STUDENT, SIBLINGS_PARENT, SEPARATED_PARENT, RESTRICTED_PARENT]) {
639
- const sdk = await env.connect(who);
640
- expect(await listAll(sdk.school.employeeAbsences)).toEqual([]);
641
- await expectError(sdk.school.employeeAbsences.get(one.id), 'NOT_FOUND');
642
- await expectError(sdk.school.employeeAbsences.list({ where: { absenceType: 'Sick leave' } }), 'VALIDATION');
643
- }
644
- });
645
- });
646
- it('refuses staff absences to an app that was not granted the tier', async () => {
647
- const staff = await env.connect(STAFF);
648
- await expectError(staff.school.employeeAbsences.list(), 'SCOPE_NOT_GRANTED');
649
- });
650
- it('serves admissions applicants to staff only, in the contact tier (S4.6)', async () => {
651
- const staff = await env.connect(STAFF);
652
- const all = await listAll(staff.school.applicants);
653
- expect(all).toHaveLength(ds.applicants.length);
654
- expect(all[0]).toMatchObject({
655
- givenName: expect.any(String),
656
- email: expect.any(String),
657
- status: expect.any(String),
658
- });
659
- const offered = await listAll(staff.school.applicants, { where: { status: 'offered' } });
660
- expect(offered).toHaveLength(ds.applicants.filter((a) => a.status === 'offered').length);
661
- const sibling = ds.applicants.find((a) => a.siblingId);
662
- expect((await staff.school.applicants.get(sibling.id)).siblingId).toBe(sibling.siblingId);
663
- for (const who of [STUDENT, SIBLINGS_PARENT, RESTRICTED_PARENT]) {
664
- const sdk = await env.connect(who);
665
- expect(await listAll(sdk.school.applicants)).toEqual([]);
666
- await expectError(sdk.school.applicants.get(sibling.id), 'NOT_FOUND');
667
- }
668
- });
669
- it('lists calendar events in a date range', async () => {
670
- const sdk = await env.connect(STAFF);
671
- const from = '2026-03-01T00:00:00Z';
672
- const to = '2026-04-01T00:00:00Z';
673
- const events = await sdk.school.calendar.list({ from, to });
674
- const expected = ds.calendarEvents.filter((e) => e.start < to && e.end > from);
675
- expect(ids(events)).toEqual(ids(expected));
676
- const y7 = await sdk.school.cohorts.byCode('y07');
677
- const forY7 = await sdk.school.calendar.list({ from, to, cohortId: y7.id });
678
- expect(forY7.every((e) => e.cohortIds.length === 0 || e.cohortIds.includes(y7.id))).toBe(true);
679
- expect(forY7.some((e) => e.title === 'Year 7 camp')).toBe(true);
680
- });
681
414
  });
682
415
  describe('db', () => {
683
416
  useApp(TEST_APP);
@@ -1209,7 +942,7 @@ export function defineContractSuite(name, factory) {
1209
942
  await sdk.tasks.assign({ ...approval, assignee: staffOf(team.id), mode: 'any' });
1210
943
  const deputies = new Set(teamMembers('deputy-principal'));
1211
944
  for (const s of ds.staff) {
1212
- expect((await env.control.inbox(s.id)).length, s.positionTitle).toBe(deputies.has(s.id) ? 1 : 0);
945
+ expect((await env.control.inbox(s.id)).length, s.id).toBe(deputies.has(s.id) ? 1 : 0);
1213
946
  }
1214
947
  });
1215
948
  it('permission slips never reach a restricted or non-consenting parent (D17)', async () => {
@@ -1596,7 +1329,7 @@ export function defineContractSuite(name, factory) {
1596
1329
  await env.control.runDueJobs();
1597
1330
  await staff.school.students.list({ limit: 5 }); // basic: no sensitive-read entry
1598
1331
  await staff.school.medicalAlerts.list({ limit: 3 });
1599
- await staff.school.pastoralNotes.get(ds.pastoralNotes[0].id);
1332
+ await staff.school.medicalAlerts.get(ds.medicalAlerts[0].id);
1600
1333
  const log = await env.control.auditLog();
1601
1334
  const actions = log.map((e) => e.action);
1602
1335
  for (const a of [
@@ -1612,7 +1345,7 @@ export function defineContractSuite(name, factory) {
1612
1345
  const reads = log.filter((e) => e.action === 'school.sensitive-read');
1613
1346
  expect(reads.map((e) => [e.entity, e.data.recordCount, e.visibility])).toEqual([
1614
1347
  ['medicalAlerts', 3, 'cio'],
1615
- ['pastoralNotes', 1, 'cio'],
1348
+ ['medicalAlerts', 1, 'cio'],
1616
1349
  ]);
1617
1350
  const suppressed = log.find((e) => e.action === 'notification.suppressed');
1618
1351
  expect(suppressed).toMatchObject({
@@ -12,9 +12,6 @@ export function createSdkClient(transport, session, context) {
12
12
  const nowMs = () => transport.nowMs();
13
13
  const school = {
14
14
  info: () => call('school.info'),
15
- calendar: {
16
- list: (options) => call('school.calendar', options),
17
- },
18
15
  };
19
16
  for (const entity of ENTITY_NAMES) {
20
17
  if (entity === 'schools')
@@ -1,7 +1,7 @@
1
- import type { CanonicalRecord, ContactPurpose, Entities, EntityName, RecordWithFields, RecordWithTiers, Role, TiersFor } from '@quad-education/canonical';
1
+ import type { CanonicalRecord, ContactPurpose, Entities, EntityName, 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.3.0";
4
+ export declare const SDK_VERSION = "0.4.1";
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.
@@ -31,7 +31,6 @@ type Field<T, K extends string, Fallback> = T extends {
31
31
  export type CurrentApp = {
32
32
  roles: Field<QuadApp, 'roles', Role> & string;
33
33
  scopes: Field<QuadApp, 'scopes', never> & string;
34
- data: Field<QuadApp, 'data', undefined>;
35
34
  notifications: Field<QuadApp, 'notifications', never> & string;
36
35
  tasks: Field<QuadApp, 'tasks', never> & string;
37
36
  scheduled: Field<QuadApp, 'scheduled', never> & string;
@@ -85,22 +84,11 @@ export type Me = {
85
84
  export type AuthApi = {
86
85
  me(): Promise<Me>;
87
86
  };
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
87
  /**
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).
88
+ * A school record as this app sees it: the fields of the tiers its scopes grant (D23). Fields beyond ids, references
89
+ * and names are typed optional, because a school's system may not supply them (D103).
100
90
  */
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>>;
91
+ export type SchoolRecord<A extends AppConfig, N extends EntityName> = RecordWithTiers<Entities[N], TiersFor<A['scopes'], N>>;
104
92
  export type Collection<R> = {
105
93
  /** A record the current user can see; NOT_FOUND otherwise. */
106
94
  get(id: string): Promise<R>;
@@ -139,16 +127,7 @@ export type SchoolApi<A extends AppConfig> = {
139
127
  info(): Promise<SchoolInfo>;
140
128
  } & {
141
129
  readonly [N in Readable<A>]: Collection<SchoolRecord<A, N>> & Helpers<A, N>;
142
- } & ('calendarEvents' extends Readable<A> ? {
143
- readonly calendar: {
144
- /** Events overlapping [from, to); with `cohortId`, that cohort's events plus whole-school ones. */
145
- list(options: {
146
- from: string;
147
- to: string;
148
- cohortId?: string;
149
- }): Promise<readonly SchoolRecord<A, 'calendarEvents'>[]>;
150
- };
151
- } : unknown);
130
+ };
152
131
  type Simplify<T> = {
153
132
  [K in keyof T]: T[K];
154
133
  };
@@ -1 +1 @@
1
- export const SDK_VERSION = '0.3.0';
1
+ export const SDK_VERSION = '0.4.1';
@@ -57,7 +57,7 @@ export declare class Engine implements Kernel {
57
57
  [k: string]: import("../index.ts").TaskStatus;
58
58
  };
59
59
  schedules: {
60
- [k: string]: "pending" | "done" | "cancelled";
60
+ [k: string]: "done" | "cancelled" | "pending";
61
61
  };
62
62
  audit: number;
63
63
  records: Record<string, Record<string, string>>;
@@ -98,8 +98,7 @@ export declare class Engine implements Kernel {
98
98
  private schoolInfo;
99
99
  private entityName;
100
100
  /**
101
- * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
102
- * SCOPE_NOT_GRANTED if the app has no scope for the entity.
101
+ * Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has no scope for the entity.
103
102
  */
104
103
  private tiers;
105
104
  private allowedFields;
@@ -118,7 +117,6 @@ export declare class Engine implements Kernel {
118
117
  private cohortMembers;
119
118
  private studentParents;
120
119
  private parentChildren;
121
- private calendar;
122
120
  private dbEntity;
123
121
  nowIso(): string;
124
122
  /** The rules for an operation: 'system' (full access), or the role's rules (empty = denied). */
@@ -157,4 +155,4 @@ export declare class Engine implements Kernel {
157
155
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
158
156
  private auditSensitiveRead;
159
157
  }
160
- export declare const ENGINE_SDK_VERSION = "0.3.0";
158
+ export declare const ENGINE_SDK_VERSION = "0.4.1";
@@ -19,16 +19,8 @@ const str = (v, what) => {
19
19
  throw new QuadError('VALIDATION', `${what} must be a non-empty string`);
20
20
  return v;
21
21
  };
22
- /**
23
- * What an app may read of one entity: the tiers granted to it and allowed to the principal (D23), plus
24
- * the varying fields its version 1 manifest declared (null for version 0, which has no declaration).
25
- */
22
+ /** What an app may read of one entity: the tiers granted to it and allowed to the principal (D23). */
26
23
  class Grant extends Set {
27
- declared;
28
- constructor(tiers, declared) {
29
- super(tiers);
30
- this.declared = declared;
31
- }
32
24
  }
33
25
  export class Engine {
34
26
  apps = new Map();
@@ -220,8 +212,6 @@ export class Engine {
220
212
  return this.studentParents(ctx, p.studentId);
221
213
  case 'school.parentChildren':
222
214
  return this.parentChildren(ctx, p.parentId);
223
- case 'school.calendar':
224
- return this.calendar(ctx, p);
225
215
  case 'db.create':
226
216
  return this.dbCreate(ctx, p.entity, p.input, p.options);
227
217
  case 'db.update':
@@ -318,8 +308,7 @@ export class Engine {
318
308
  return value;
319
309
  }
320
310
  /**
321
- * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
322
- * SCOPE_NOT_GRANTED if the app has no scope for the entity.
311
+ * Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has no scope for the entity.
323
312
  */
324
313
  tiers(ctx, entity) {
325
314
  const granted = grantedTiers(ctx.app.manifest.scopes, entity);
@@ -327,15 +316,12 @@ export class Engine {
327
316
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
328
317
  }
329
318
  const allowed = principalTiers(ctx.principal, entity);
330
- // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
331
- const entry = ctx.app.manifest.data?.[entity];
332
- const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
333
- return new Grant([...granted].filter((t) => allowed.has(t)), declared);
319
+ return new Grant([...granted].filter((t) => allowed.has(t)));
334
320
  }
335
321
  allowedFields(entity, grant) {
336
322
  const fields = new Set(Object.keys(BASE_FIELDS));
337
323
  for (const [key, def] of Object.entries(ENTITIES[entity].fields))
338
- if (fieldVisible(def, key, grant, grant.declared))
324
+ if (fieldVisible(def, grant))
339
325
  fields.add(key);
340
326
  return fields;
341
327
  }
@@ -363,7 +349,7 @@ export class Engine {
363
349
  return visibleRecords(ctx.principal, entity, this.dataset, made.rows);
364
350
  }
365
351
  shape(entity, grant, records) {
366
- return records.map((r) => filterFields(entity, r, grant, grant.declared));
352
+ return records.map((r) => filterFields(entity, r, grant));
367
353
  }
368
354
  async schoolGet(ctx, entityValue, id) {
369
355
  const entity = this.entityName(entityValue);
@@ -372,7 +358,7 @@ export class Engine {
372
358
  if (!record)
373
359
  throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
374
360
  await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
375
- return filterFields(entity, record, tiers, tiers.declared);
361
+ return filterFields(entity, record, tiers);
376
362
  }
377
363
  async schoolList(ctx, entityValue, options) {
378
364
  const entity = this.entityName(entityValue);
@@ -384,7 +370,7 @@ export class Engine {
384
370
  cohortByCode(ctx, code) {
385
371
  const tiers = this.tiers(ctx, 'cohorts');
386
372
  const cohort = this.visible(ctx, 'cohorts').find((c) => c.code === str(code, 'code'));
387
- return cohort ? filterFields('cohorts', cohort, tiers, tiers.declared) : null;
373
+ return cohort ? filterFields('cohorts', cohort, tiers) : null;
388
374
  }
389
375
  cohortMembers(ctx, cohortId, options) {
390
376
  const tiers = this.tiers(ctx, 'cohortMemberships');
@@ -414,33 +400,6 @@ export class Engine {
414
400
  const linked = new Set(this.dataset.parentStudentLinks.filter((l) => l.parentId === id).map((l) => l.studentId));
415
401
  return this.shape('students', tiers, this.visible(ctx, 'students').filter((s) => linked.has(s.id)));
416
402
  }
417
- calendar(ctx, p) {
418
- const tiers = this.tiers(ctx, 'calendarEvents');
419
- const from = str(p.from, 'from');
420
- const to = str(p.to, 'to');
421
- if (Number.isNaN(Date.parse(from)) || Number.isNaN(Date.parse(to))) {
422
- throw new QuadError('VALIDATION', 'from and to must be ISO dates or instants');
423
- }
424
- const fromMs = Date.parse(from);
425
- const toMs = Date.parse(to);
426
- let relevant = null;
427
- if (p.cohortId !== undefined) {
428
- // A cohort's events include those for its ancestors, e.g. a class sees its year's events.
429
- relevant = new Set();
430
- const cohorts = new Map(this.dataset.cohorts.map((c) => [c.id, c]));
431
- let current = cohorts.get(str(p.cohortId, 'cohortId'));
432
- if (!current)
433
- throw new QuadError('NOT_FOUND', `no cohort ${String(p.cohortId)}`);
434
- while (current) {
435
- relevant.add(current.id);
436
- current = current.parentCohortId ? cohorts.get(current.parentCohortId) : undefined;
437
- }
438
- }
439
- const events = this.visible(ctx, 'calendarEvents').filter((e) => Date.parse(e.start) < toMs &&
440
- Date.parse(e.end) > fromMs &&
441
- (relevant === null || e.cohortIds.length === 0 || e.cohortIds.some((c) => relevant.has(c))));
442
- return this.shape('calendarEvents', tiers, [...events].sort((a, b) => a.start.localeCompare(b.start)));
443
- }
444
403
  // ---- db (access control: D25) ----
445
404
  dbEntity(ctx, value) {
446
405
  const def = typeof value === 'string' ? entityOf(ctx.app.schema, value) : undefined;
@@ -677,7 +636,7 @@ export class Engine {
677
636
  return null;
678
637
  schoolReads.set(target, (schoolReads.get(target) ?? 0) + 1);
679
638
  const grant = this.tiers(ctx, target);
680
- return filterFields(target, record, grant, grant.declared);
639
+ return filterFields(target, record, grant);
681
640
  }
682
641
  // Included app records follow their own entity's rules (D25).
683
642
  const def = entityOf(ctx.app.schema, field.to);
@@ -1,5 +1,5 @@
1
1
  import { QuadError, type QuadErrorCode } from './contract/errors.ts';
2
- export declare const METHODS: readonly ["auth.me", "school.info", "school.get", "school.list", "school.cohortByCode", "school.cohortMembers", "school.studentParents", "school.parentChildren", "school.calendar", "db.create", "db.update", "db.get", "db.list", "db.delete", "notify.send", "tasks.assign", "tasks.get", "tasks.list", "tasks.complete", "tasks.cancel", "schedule.at", "schedule.cancel", "schedule.list", "cron.list", "audit.record", "audit.list"];
2
+ export declare const METHODS: readonly ["auth.me", "school.info", "school.get", "school.list", "school.cohortByCode", "school.cohortMembers", "school.studentParents", "school.parentChildren", "db.create", "db.update", "db.get", "db.list", "db.delete", "notify.send", "tasks.assign", "tasks.get", "tasks.list", "tasks.complete", "tasks.cancel", "schedule.at", "schedule.cancel", "schedule.list", "cron.list", "audit.record", "audit.list"];
3
3
  export type Method = (typeof METHODS)[number];
4
4
  export type SerializedError = {
5
5
  code: QuadErrorCode;
@@ -10,7 +10,6 @@ export const METHODS = [
10
10
  'school.cohortMembers',
11
11
  'school.studentParents',
12
12
  'school.parentChildren',
13
- 'school.calendar',
14
13
  'db.create',
15
14
  'db.update',
16
15
  'db.get',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quad-education/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
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.3.0",
51
- "@quad-education/fictional-school": "^0.3.0",
52
- "@quad-education/schema": "^0.3.0"
50
+ "@quad-education/canonical": "^0.4.1",
51
+ "@quad-education/fictional-school": "^0.4.1",
52
+ "@quad-education/schema": "^0.4.1"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "vitest": "^5.0.3"