@quad-education/sdk 0.1.2 → 0.1.3

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.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
99
  - **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
100
  - **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
101
  - **0.1.0** (renamed 7 Oct 2026). This was `@orca/sdk` 0.1.0, with the same contract and behaviour, renamed for Quad:
@@ -72,6 +72,47 @@ export declare const BASIC_APP: {
72
72
  manifest: Manifest;
73
73
  schema: typeof TEST_SCHEMA;
74
74
  };
75
+ /**
76
+ * A version 1 manifest (V2s D85): students are read with `dateOfBirth` required and `email` optional,
77
+ * and nothing else that varies. The core fields (studentNumber, givenName, familyName) come with the
78
+ * entity. Its scopes are exactly the tiers those fields need.
79
+ */
80
+ export declare const DATA_APP: {
81
+ manifest: Manifest;
82
+ schema: typeof TEST_SCHEMA;
83
+ };
84
+ /**
85
+ * A standalone app (V2s D84): version 1, two app-defined roles named like school roles, so the matching
86
+ * personas can preview them. The access keys are written in different cases on purpose.
87
+ */
88
+ export declare const ROLES_SCHEMA: {
89
+ readonly entry: {
90
+ readonly fields: {
91
+ readonly body: {
92
+ readonly kind: "text";
93
+ readonly tier: import("@quad-education/canonical").Tier;
94
+ };
95
+ };
96
+ readonly indexes: readonly [];
97
+ readonly subject?: "body";
98
+ readonly access?: {
99
+ readonly Staff: {
100
+ readonly read: "all";
101
+ readonly create: "own";
102
+ readonly update: "own";
103
+ readonly delete: "own";
104
+ };
105
+ readonly student: {
106
+ readonly read: "own";
107
+ readonly create: "own";
108
+ };
109
+ };
110
+ };
111
+ };
112
+ export declare const ROLES_APP: {
113
+ manifest: Manifest;
114
+ schema: typeof ROLES_SCHEMA;
115
+ };
75
116
  /**
76
117
  * D25 access control. The documented pattern: a shared record (`excursion`) is staff-only,
77
118
  * and parents work with per-student rows (`consent`) whose subject is their child.
@@ -57,6 +57,10 @@ 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',
60
64
  ],
61
65
  notifications: ['test.message', 'test.reminder'],
62
66
  },
@@ -73,6 +77,50 @@ export const BASIC_APP = {
73
77
  },
74
78
  schema: TEST_SCHEMA,
75
79
  };
80
+ /**
81
+ * A version 1 manifest (V2s D85): students are read with `dateOfBirth` required and `email` optional,
82
+ * and nothing else that varies. The core fields (studentNumber, givenName, familyName) come with the
83
+ * entity. Its scopes are exactly the tiers those fields need.
84
+ */
85
+ export const DATA_APP = {
86
+ manifest: {
87
+ ...TEST_APP.manifest,
88
+ manifestVersion: 1,
89
+ id: 'contract-data',
90
+ name: 'Declared fields app',
91
+ scopes: ['students.basic:read', 'students.contact:read'],
92
+ data: { students: { required: ['dateOfBirth'], optional: ['email'] } },
93
+ reasons: { 'students.contact:read': 'To show each student’s birthday in the contract tests.' },
94
+ notifications: ['test.message'],
95
+ },
96
+ schema: TEST_SCHEMA,
97
+ };
98
+ /**
99
+ * A standalone app (V2s D84): version 1, two app-defined roles named like school roles, so the matching
100
+ * personas can preview them. The access keys are written in different cases on purpose.
101
+ */
102
+ export const ROLES_SCHEMA = defineSchema({
103
+ entry: entity({
104
+ fields: { body: text() },
105
+ access: {
106
+ Staff: { read: 'all', create: 'own', update: 'own', delete: 'own' },
107
+ student: { read: 'own', create: 'own' },
108
+ },
109
+ }),
110
+ });
111
+ export const ROLES_APP = {
112
+ manifest: {
113
+ ...TEST_APP.manifest,
114
+ manifestVersion: 1,
115
+ id: 'contract-roles',
116
+ name: 'App roles app',
117
+ roles: ['Staff', 'Student'],
118
+ schoolRoles: [],
119
+ scopes: [],
120
+ notifications: [],
121
+ },
122
+ schema: ROLES_SCHEMA,
123
+ };
76
124
  /**
77
125
  * D25 access control. The documented pattern: a shared record (`excursion`) is staff-only,
78
126
  * and parents work with per-student rows (`consent`) whose subject is their child.
@@ -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, BASIC_APP, DATA_APP, JOBS_APP, ROLES_APP, TEST_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.3');
77
77
  });
78
78
  it('knows parents and students', async () => {
79
79
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
@@ -188,6 +188,78 @@ export function defineContractSuite(name, factory) {
188
188
  });
189
189
  });
190
190
  });
191
+ describe('app-defined roles are previewed by the persona of the same name (D84)', () => {
192
+ useApp(ROLES_APP);
193
+ it('serves the personas whose role matches an app role, ignoring case, and refuses the rest', async () => {
194
+ const staff = await env.connect(STAFF);
195
+ const student = await env.connect(STUDENT);
196
+ expect((await staff.auth.me()).role).toBe('staff');
197
+ expect((await student.auth.me()).role).toBe('student');
198
+ await expectError(env.connect(SIBLINGS_PARENT).then((p) => p.auth.me()), 'FORBIDDEN');
199
+ });
200
+ it('follows the access rules written for the app role, whatever the case of the key', async () => {
201
+ const staff = await env.connect(STAFF);
202
+ const student = await env.connect(STUDENT);
203
+ const note = await student.db.entity('entry').create({ body: 'mine' });
204
+ await staff.db.entity('entry').create({ body: 'staff note' });
205
+ // `Staff` (capitalised in the schema) gives staff all records; `student` gives a student their own.
206
+ expect((await staff.db.entity('entry').list()).items).toHaveLength(2);
207
+ expect((await student.db.entity('entry').list()).items.map((e) => e.id)).toEqual([
208
+ note.id,
209
+ ]);
210
+ await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
211
+ });
212
+ });
213
+ describe('school: declared fields (D85)', () => {
214
+ useApp(DATA_APP);
215
+ it('returns the core fields and the declared ones, and nothing else that varies', async () => {
216
+ const sdk = await env.connect(STAFF);
217
+ const expected = ds.students[0];
218
+ const student = await sdk.school.students.get(expected.id);
219
+ expect(student.givenName).toBe(expected.givenName);
220
+ expect(student.studentNumber).toBe(expected.studentNumber);
221
+ expect(student.dateOfBirth).toBe(expected.dateOfBirth);
222
+ expect(student.email).toBe(expected.email);
223
+ // yearLevel and preferredName are granted by tier but were not declared.
224
+ expect('yearLevel' in student).toBe(false);
225
+ expect('preferredName' in student).toBe(false);
226
+ for (const s of (await sdk.school.students.list({ limit: 25 })).items) {
227
+ expect('yearLevel' in s).toBe(false);
228
+ expect('preferredName' in s).toBe(false);
229
+ expect('dateOfBirth' in s).toBe(true);
230
+ }
231
+ });
232
+ it('refuses to filter or sort on a field that was not declared, so it cannot be probed', async () => {
233
+ const sdk = await env.connect(STAFF);
234
+ await expectError(sdk.school.students.list({ where: { yearLevel: 'Y9' } }), 'VALIDATION');
235
+ await expectError(sdk.school.students.list({ orderBy: { field: 'preferredName' } }), 'VALIDATION');
236
+ // Declared and core fields still work.
237
+ const name = ds.students[0].familyName;
238
+ const found = await sdk.school.students.list({ where: { familyName: name }, limit: 200 });
239
+ expect(found.items.length).toBeGreaterThan(0);
240
+ expect((await sdk.school.students.list({ where: { dateOfBirth: ds.students[0].dateOfBirth } }))
241
+ .items.length).toBeGreaterThan(0);
242
+ });
243
+ it('strips included school refs the same way', async () => {
244
+ const sdk = await env.connect(STAFF);
245
+ await sdk.db
246
+ .entity('greeting')
247
+ .create({ message: 'hi', studentId: ds.students[0].id, tone: 'warm' });
248
+ const { items } = await sdk.db.entity('greeting').list({ include: ['studentId'] });
249
+ const included = items[0].$included.studentId;
250
+ expect(included.givenName).toBe(ds.students[0].givenName);
251
+ expect('yearLevel' in included).toBe(false);
252
+ expect('dateOfBirth' in included).toBe(true);
253
+ });
254
+ });
255
+ describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
256
+ useApp(BASIC_APP);
257
+ it('keeps yearLevel and preferredName available', async () => {
258
+ const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
259
+ .items[0];
260
+ expect('yearLevel' in student).toBe(true);
261
+ });
262
+ });
191
263
  describe('school: queries and helpers', () => {
192
264
  useApp(TEST_APP);
193
265
  it('filters with where, orders and pages without gaps or repeats', async () => {
@@ -241,6 +313,53 @@ export function defineContractSuite(name, factory) {
241
313
  const student = await env.connect(STUDENT);
242
314
  await expectError(student.school.parents.children(parentId), 'NOT_FOUND');
243
315
  });
316
+ it('serves the timetable, which is derived, like any other entity (S4.1)', async () => {
317
+ const english = ds.cohorts.find((c) => c.code === 'y09-english-b');
318
+ const week = { gte: '2026-03-02', lt: '2026-03-09' };
319
+ const expected = ds.lessons
320
+ .filter((l) => l.cohortId === english.id && l.date >= week.gte && l.date < week.lt)
321
+ .map((l) => l.id);
322
+ expect(expected).toHaveLength(4);
323
+ // A published timetable: staff, students and parents all read it.
324
+ for (const who of [STAFF, STUDENT, SIBLINGS_PARENT]) {
325
+ const sdk = await env.connect(who);
326
+ const page = await sdk.school.lessons.list({
327
+ where: { cohortId: english.id, date: week },
328
+ orderBy: { field: 'startsAt' },
329
+ limit: 50,
330
+ });
331
+ expect(page.items.map((l) => l.id)).toEqual(expected);
332
+ expect(page.items[0]).toMatchObject({ cohortId: english.id });
333
+ }
334
+ });
335
+ it('pages through a day of lessons without gaps or repeats, and finds one by id', async () => {
336
+ const sdk = await env.connect(STUDENT);
337
+ const day = '2026-03-03';
338
+ const expected = ds.lessons.filter((l) => l.date === day).map((l) => l.id);
339
+ const seen = [];
340
+ let page = await sdk.school.lessons.list({ where: { date: day }, limit: 100 });
341
+ seen.push(...page.items.map((l) => l.id));
342
+ while (page.nextCursor) {
343
+ page = await sdk.school.lessons.list({
344
+ where: { date: day },
345
+ limit: 100,
346
+ cursor: page.nextCursor,
347
+ });
348
+ seen.push(...page.items.map((l) => l.id));
349
+ }
350
+ expect(seen.slice().sort()).toEqual(expected.slice().sort());
351
+ expect(new Set(seen).size).toBe(expected.length);
352
+ const one = await sdk.school.lessons.get(expected[0]);
353
+ expect(one.id).toBe(expected[0]);
354
+ await expectError(sdk.school.lessons.get('les-20260303-nope-p1'), 'NOT_FOUND');
355
+ });
356
+ it('lists the school day’s periods and rooms', async () => {
357
+ const sdk = await env.connect(STUDENT);
358
+ const periods = await listAll(sdk.school.periods, {});
359
+ expect(periods).toHaveLength(30);
360
+ const rooms = await listAll(sdk.school.rooms, {});
361
+ expect(ids(rooms)).toEqual(ids(ds.rooms));
362
+ });
244
363
  it('lists calendar events in a date range', async () => {
245
364
  const sdk = await env.connect(STAFF);
246
365
  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.3";
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.3';
@@ -99,7 +99,10 @@ export declare class Engine implements Kernel {
99
99
  private me;
100
100
  private schoolInfo;
101
101
  private entityName;
102
- /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
102
+ /**
103
+ * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
104
+ * SCOPE_NOT_GRANTED if the app has no scope for the entity.
105
+ */
103
106
  private tiers;
104
107
  private allowedFields;
105
108
  private visible;
@@ -150,4 +153,4 @@ export declare class Engine implements Kernel {
150
153
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
151
154
  private auditSensitiveRead;
152
155
  }
153
- export declare const ENGINE_SDK_VERSION = "0.1.2";
156
+ export declare const ENGINE_SDK_VERSION = "0.1.3";
@@ -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, 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";
@@ -18,6 +18,17 @@ const str = (v, what) => {
18
18
  throw new QuadError('VALIDATION', `${what} must be a non-empty string`);
19
19
  return v;
20
20
  };
21
+ /**
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).
24
+ */
25
+ class Grant extends Set {
26
+ declared;
27
+ constructor(tiers, declared) {
28
+ super(tiers);
29
+ this.declared = declared;
30
+ }
31
+ }
21
32
  /**
22
33
  * The in-browser implementation of the @quad-education/sdk contract (D15). It runs in the demo
23
34
  * shell's origin, holds the fictional school, and enforces visibility, scopes and D17 on
@@ -33,6 +44,13 @@ export class Engine {
33
44
  this.dataset = dataset;
34
45
  this.storage = storage;
35
46
  for (const entity of Object.keys(ENTITIES)) {
47
+ if (isDerived(entity)) {
48
+ // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
49
+ if (!(entity in dataset)) {
50
+ throw new Error(`the dataset has no ${entity}: it is derived, so wrap the stored dataset with withDerived() from @quad-education/fictional-school`);
51
+ }
52
+ continue;
53
+ }
36
54
  for (const record of dataset[entity]) {
37
55
  this.byId.set(record.id, { entity, record });
38
56
  }
@@ -301,7 +319,8 @@ export class Engine {
301
319
  if (!person || person.entity !== PEOPLE[principal.role]) {
302
320
  throw new QuadError('FORBIDDEN', `no ${principal.role} with id ${principal.personId}`);
303
321
  }
304
- if (!app.manifest.roles.includes(principal.role)) {
322
+ // A school persona stands in for an app role of the same name, ignoring case (V2s D84).
323
+ if (!servedRoles(app.manifest).includes(principal.role)) {
305
324
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
306
325
  }
307
326
  return { app, principal, actorId: principal.personId };
@@ -339,27 +358,33 @@ export class Engine {
339
358
  }
340
359
  return value;
341
360
  }
342
- /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
361
+ /**
362
+ * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
363
+ * SCOPE_NOT_GRANTED if the app has no scope for the entity.
364
+ */
343
365
  tiers(ctx, entity) {
344
366
  const granted = grantedTiers(ctx.app.manifest.scopes, entity);
345
367
  if (granted.size === 0) {
346
368
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
347
369
  }
348
370
  const allowed = principalTiers(ctx.principal, entity);
349
- return new Set([...granted].filter((t) => allowed.has(t)));
371
+ // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
372
+ const entry = ctx.app.manifest.data?.[entity];
373
+ const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
374
+ return new Grant([...granted].filter((t) => allowed.has(t)), declared);
350
375
  }
351
- allowedFields(entity, tiers) {
376
+ allowedFields(entity, grant) {
352
377
  const fields = new Set(Object.keys(BASE_FIELDS));
353
378
  for (const [key, def] of Object.entries(ENTITIES[entity].fields))
354
- if (tiers.has(def.tier))
379
+ if (fieldVisible(def, key, grant, grant.declared))
355
380
  fields.add(key);
356
381
  return fields;
357
382
  }
358
383
  visible(ctx, entity) {
359
384
  return visibleRecords(ctx.principal, entity, this.dataset);
360
385
  }
361
- shape(entity, tiers, records) {
362
- return records.map((r) => filterFields(entity, r, tiers));
386
+ shape(entity, grant, records) {
387
+ return records.map((r) => filterFields(entity, r, grant, grant.declared));
363
388
  }
364
389
  async schoolGet(ctx, entityValue, id) {
365
390
  const entity = this.entityName(entityValue);
@@ -368,7 +393,7 @@ export class Engine {
368
393
  if (!record)
369
394
  throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
370
395
  await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
371
- return filterFields(entity, record, tiers);
396
+ return filterFields(entity, record, tiers, tiers.declared);
372
397
  }
373
398
  async schoolList(ctx, entityValue, options) {
374
399
  const entity = this.entityName(entityValue);
@@ -380,7 +405,7 @@ export class Engine {
380
405
  cohortByCode(ctx, code) {
381
406
  const tiers = this.tiers(ctx, 'cohorts');
382
407
  const cohort = this.visible(ctx, 'cohorts').find((c) => c.code === str(code, 'code'));
383
- return cohort ? filterFields('cohorts', cohort, tiers) : null;
408
+ return cohort ? filterFields('cohorts', cohort, tiers, tiers.declared) : null;
384
409
  }
385
410
  cohortMembers(ctx, cohortId, options) {
386
411
  const tiers = this.tiers(ctx, 'cohortMemberships');
@@ -453,7 +478,12 @@ export class Engine {
453
478
  if (ctx.principal.kind === 'system')
454
479
  return 'system';
455
480
  const policy = def.access ?? DEFAULT_ACCESS;
456
- const value = policy[ctx.principal.role]?.[op];
481
+ // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
482
+ const role = ctx.principal.role;
483
+ const key = Object.hasOwn(policy, role)
484
+ ? role
485
+ : Object.keys(policy).find((k) => k.toLowerCase() === role);
486
+ const value = key === undefined ? undefined : policy[key]?.[op];
457
487
  return value === undefined ? [] : Array.isArray(value) ? value : [value];
458
488
  }
459
489
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
@@ -666,7 +696,8 @@ export class Engine {
666
696
  if (!record)
667
697
  return null;
668
698
  schoolReads.set(target, (schoolReads.get(target) ?? 0) + 1);
669
- return filterFields(target, record, this.tiers(ctx, target));
699
+ const grant = this.tiers(ctx, target);
700
+ return filterFields(target, record, grant, grant.declared);
670
701
  }
671
702
  // Included app records follow their own entity's rules (D25).
672
703
  const def = entityOf(ctx.app.schema, field.to);
@@ -765,7 +796,7 @@ export class Engine {
765
796
  const list = Array.isArray(to) ? to : [to];
766
797
  if (list.length === 0)
767
798
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
768
- const roles = ctx.app.manifest.roles;
799
+ const roles = servedRoles(ctx.app.manifest);
769
800
  const senderIsStaff = ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
770
801
  const out = new Map();
771
802
  const suppressed = new Map();
@@ -902,7 +933,7 @@ export class Engine {
902
933
  }
903
934
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
904
935
  async auditSensitiveRead(ctx, entity, tiers, count, via) {
905
- const sensitive = [...tiers].filter((t) => t === 'pastoral' || t === 'medical');
936
+ const sensitive = [...tiers].filter((t) => AUDITED_TIERS.includes(t));
906
937
  if (sensitive.length === 0 || count === 0)
907
938
  return;
908
939
  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.3",
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/schema": "^0.1.3",
51
+ "@quad-education/canonical": "^0.1.3",
52
+ "@quad-education/fictional-school": "^0.1.3"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "vitest": "^5.0.3"