@quad-education/sdk 0.0.0-stage → 0.1.2

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.
Files changed (69) hide show
  1. package/LICENSE.md +15 -0
  2. package/README.md +105 -2
  3. package/dist/contract-tests/apps.d.ts +332 -0
  4. package/dist/contract-tests/apps.js +261 -0
  5. package/dist/contract-tests/index.d.ts +3 -0
  6. package/dist/contract-tests/index.js +2 -0
  7. package/dist/contract-tests/suite.d.ts +57 -0
  8. package/dist/contract-tests/suite.js +1286 -0
  9. package/dist/src/client/connect.d.ts +10 -0
  10. package/dist/src/client/connect.js +12 -0
  11. package/dist/src/client/create-client.d.ts +14 -0
  12. package/dist/src/client/create-client.js +76 -0
  13. package/dist/src/client/handshake-client.d.ts +16 -0
  14. package/dist/src/client/handshake-client.js +37 -0
  15. package/dist/src/contract/errors.d.ts +8 -0
  16. package/dist/src/contract/errors.js +13 -0
  17. package/dist/src/contract/recipients.d.ts +28 -0
  18. package/dist/src/contract/recipients.js +12 -0
  19. package/dist/src/contract/types.d.ts +421 -0
  20. package/dist/src/contract/types.js +1 -0
  21. package/dist/src/engine/audit.d.ts +27 -0
  22. package/dist/src/engine/audit.js +105 -0
  23. package/dist/src/engine/cron.d.ts +17 -0
  24. package/dist/src/engine/cron.js +143 -0
  25. package/dist/src/engine/db-indexes.d.ts +11 -0
  26. package/dist/src/engine/db-indexes.js +82 -0
  27. package/dist/src/engine/engine.d.ts +153 -0
  28. package/dist/src/engine/engine.js +922 -0
  29. package/dist/src/engine/host.d.ts +39 -0
  30. package/dist/src/engine/host.js +70 -0
  31. package/dist/src/engine/in-process.d.ts +5 -0
  32. package/dist/src/engine/in-process.js +18 -0
  33. package/dist/src/engine/index.d.ts +10 -0
  34. package/dist/src/engine/index.js +8 -0
  35. package/dist/src/engine/query.d.ts +16 -0
  36. package/dist/src/engine/query.js +106 -0
  37. package/dist/src/engine/runner.d.ts +26 -0
  38. package/dist/src/engine/runner.js +260 -0
  39. package/dist/src/engine/state.d.ts +107 -0
  40. package/dist/src/engine/state.js +16 -0
  41. package/dist/src/engine/storage.d.ts +46 -0
  42. package/dist/src/engine/storage.js +86 -0
  43. package/dist/src/engine/tasks.d.ts +17 -0
  44. package/dist/src/engine/tasks.js +245 -0
  45. package/dist/src/engine/validate-input.d.ts +9 -0
  46. package/dist/src/engine/validate-input.js +76 -0
  47. package/dist/src/engine/values.d.ts +10 -0
  48. package/dist/src/engine/values.js +58 -0
  49. package/dist/src/handshake.d.ts +16 -0
  50. package/dist/src/handshake.js +9 -0
  51. package/dist/src/index.d.ts +3 -0
  52. package/dist/src/index.js +4 -0
  53. package/dist/src/jobs/define.d.ts +41 -0
  54. package/dist/src/jobs/define.js +28 -0
  55. package/dist/src/jobs/host.d.ts +13 -0
  56. package/dist/src/jobs/host.js +22 -0
  57. package/dist/src/jobs/index.d.ts +1 -0
  58. package/dist/src/jobs/index.js +2 -0
  59. package/dist/src/jobs/worker.d.ts +17 -0
  60. package/dist/src/jobs/worker.js +25 -0
  61. package/dist/src/platform-types.d.ts +19 -0
  62. package/dist/src/platform-types.js +1 -0
  63. package/dist/src/port-rpc.d.ts +42 -0
  64. package/dist/src/port-rpc.js +85 -0
  65. package/dist/src/protocol.d.ts +41 -0
  66. package/dist/src/protocol.js +45 -0
  67. package/dist/src/testing/index.d.ts +78 -0
  68. package/dist/src/testing/index.js +118 -0
  69. package/package.json +71 -3
@@ -0,0 +1,922 @@
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';
3
+ import { QuadError } from "../contract/errors.js";
4
+ import { SDK_VERSION } from "../contract/types.js";
5
+ import { clockNow } from "../protocol.js";
6
+ import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
7
+ import { checkIndexCoverage } from "./db-indexes.js";
8
+ import { runQuery } from "./query.js";
9
+ import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
10
+ import { EngineStorage, } from "./storage.js";
11
+ import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
12
+ import { entityOf, fieldOf, validateInput } from "./validate-input.js";
13
+ const SYSTEM_FIELDS = ['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
14
+ const PEOPLE = { staff: 'staff', student: 'students', parent: 'parents' };
15
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
16
+ const str = (v, what) => {
17
+ if (typeof v !== 'string' || v.length === 0)
18
+ throw new QuadError('VALIDATION', `${what} must be a non-empty string`);
19
+ return v;
20
+ };
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.
25
+ */
26
+ export class Engine {
27
+ apps = new Map();
28
+ clock = { kind: 'offset', offsetMs: 0 };
29
+ byId = new Map();
30
+ dataset;
31
+ storage;
32
+ constructor(dataset, storage) {
33
+ this.dataset = dataset;
34
+ this.storage = storage;
35
+ for (const entity of Object.keys(ENTITIES)) {
36
+ for (const record of dataset[entity]) {
37
+ this.byId.set(record.id, { entity, record });
38
+ }
39
+ }
40
+ }
41
+ static async create(options) {
42
+ const storage = await EngineStorage.open(options.indexedDB, options.dbName);
43
+ return new Engine(options.dataset, storage);
44
+ }
45
+ close() {
46
+ this.storage.close();
47
+ }
48
+ // ---- Platform-side API (shell and tests) ----
49
+ /** Load an app, resetting its store if the schema changed since last time (D12). */
50
+ async installApp({ manifest, schema }) {
51
+ const parsed = parseManifest(manifest);
52
+ if (!parsed.ok)
53
+ throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
54
+ const appId = parsed.manifest.id;
55
+ const hash = schemaHash(schema);
56
+ const meta = await this.storage.getMeta(appId);
57
+ if (meta && meta.schemaHash !== hash)
58
+ await this.storage.clearApp(appId, { schemaChangeOnly: true });
59
+ await this.storage.put('meta', [{ appId, schemaHash: hash }]);
60
+ const app = {
61
+ manifest: parsed.manifest,
62
+ schema,
63
+ records: new Map(),
64
+ keys: new Map(),
65
+ tasks: new Map(),
66
+ schedules: new Map(),
67
+ runs: new Map(),
68
+ cron: new Map(),
69
+ audit: [],
70
+ };
71
+ for (const entity of Object.keys(schema))
72
+ app.records.set(entity, new Map());
73
+ for (const r of await this.storage.getAll('records', appId)) {
74
+ app.records.get(r.entity)?.set(r.id, r.data);
75
+ }
76
+ for (const k of await this.storage.getAll('keys', appId))
77
+ app.keys.set(k.key, k.result);
78
+ for (const row of await this.storage.getAll('platform', appId)) {
79
+ if (row.kind === 'task')
80
+ app.tasks.set(row.id, row.data);
81
+ // Rows stored before run-as rules (D7) have no runAs; those were system-scheduled.
82
+ else if (row.kind === 'schedule' || row.kind === 'run') {
83
+ const data = row.data;
84
+ const withRunAs = { ...data, runAs: data.runAs ?? { kind: 'system', appId } };
85
+ if (row.kind === 'schedule')
86
+ app.schedules.set(row.id, withRunAs);
87
+ else
88
+ app.runs.set(row.id, withRunAs);
89
+ }
90
+ else if (row.kind === 'cron')
91
+ app.cron.set(row.id, row.data);
92
+ else
93
+ app.audit.push(row.data);
94
+ }
95
+ app.audit.sort((a, b) => a.seq - b.seq);
96
+ // Cron jobs no longer in the manifest stop; new ones start from now.
97
+ for (const name of app.cron.keys())
98
+ if (!app.manifest.cron.some((c) => c.name === name))
99
+ app.cron.delete(name);
100
+ this.apps.set(appId, app);
101
+ await initCron(this, app);
102
+ }
103
+ manifest(appId) {
104
+ return this.appFor(appId).manifest;
105
+ }
106
+ /** Clear an app's data and outbox (the shell's reset button). */
107
+ async resetApp(appId) {
108
+ const app = this.appFor(appId);
109
+ await this.storage.clearApp(appId);
110
+ for (const records of app.records.values())
111
+ records.clear();
112
+ app.keys.clear();
113
+ app.tasks.clear();
114
+ app.schedules.clear();
115
+ app.runs.clear();
116
+ app.cron.clear();
117
+ app.audit.length = 0;
118
+ await initCron(this, app);
119
+ }
120
+ // ---- Platform-side API for Slice B (shell and tests) ----
121
+ /** Open tasks assigned to a person: the shell's inbox (D6). */
122
+ inbox(appId, personId) {
123
+ const app = this.appFor(appId);
124
+ const ctx = { app, principal: { kind: 'system', appId }, actorId: `system:${appId}` };
125
+ return inbox(app, personId).map((t) => taskView(ctx, t));
126
+ }
127
+ /** Every audit entry, including CIO-only ones (the shell's audit viewer, D19). */
128
+ auditLog(appId) {
129
+ return this.appFor(appId).audit.map((e) => ({ ...auditView(e), visibility: e.visibility }));
130
+ }
131
+ /** Counts of everything a job can change, for run-twice tests (D20). */
132
+ async effectsSnapshot(appId) {
133
+ const app = this.appFor(appId);
134
+ const records = {};
135
+ for (const [entity, rows] of app.records) {
136
+ records[entity] = Object.fromEntries([...rows.values()].map((r) => [r.id, r.updatedAt]));
137
+ }
138
+ return {
139
+ outbox: (await this.outbox(appId)).length,
140
+ tasks: Object.fromEntries([...app.tasks.values()].map((t) => [t.id, t.status])),
141
+ schedules: Object.fromEntries([...app.schedules.values()].map((s) => [s.id, s.status])),
142
+ audit: app.audit.length,
143
+ records,
144
+ };
145
+ }
146
+ /** Runs for the job log, newest first. */
147
+ runs(appId) {
148
+ return [...this.appFor(appId).runs.values()].sort((a, b) => b.scheduledFor.localeCompare(a.scheduledFor) || a.id.localeCompare(b.id));
149
+ }
150
+ /**
151
+ * Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
152
+ * Only runs that are currently running count, so a finished run's id can't be replayed.
153
+ */
154
+ runPrincipal(appId, runId) {
155
+ const run = runId === undefined ? undefined : this.appFor(appId).runs.get(runId);
156
+ if (!run || run.status !== 'running') {
157
+ throw new QuadError('FORBIDDEN', 'calls from the jobs host must belong to a running job');
158
+ }
159
+ return run.runAs;
160
+ }
161
+ /** Start due runs; the caller executes each as its `runAs` principal and calls finishRun. */
162
+ startDueRuns(appId) {
163
+ return startDueRuns(this, this.appFor(appId));
164
+ }
165
+ finishRun(appId, runId, result) {
166
+ return finishRun(this, this.appFor(appId), runId, result);
167
+ }
168
+ releaseRun(appId, runId) {
169
+ return releaseRun(this, this.appFor(appId), runId);
170
+ }
171
+ redeliverRun(appId, runId) {
172
+ return redeliverRun(this, this.appFor(appId), runId);
173
+ }
174
+ /** Move the demo clock forward (D14). Works whether it's frozen or running. */
175
+ advanceClock(ms) {
176
+ if (!Number.isFinite(ms) || ms < 0)
177
+ throw new QuadError('VALIDATION', 'advanceClock takes a positive number of ms');
178
+ this.clock =
179
+ this.clock.kind === 'fixed'
180
+ ? { kind: 'fixed', at: this.clock.at + ms }
181
+ : { kind: 'offset', offsetMs: this.clock.offsetMs + ms };
182
+ }
183
+ // ---- Kernel (used by the Slice B modules) ----
184
+ timezone() {
185
+ return this.dataset.schools[0].timezone;
186
+ }
187
+ async persistPlatform(app, kind, items) {
188
+ await this.storage.putPlatform(app.manifest.id, kind, items);
189
+ }
190
+ async outbox(appId) {
191
+ const entries = await this.storage.getAll('outbox', appId);
192
+ return entries.sort((a, b) => a.sentAt.localeCompare(b.sentAt) || a.id.localeCompare(b.id));
193
+ }
194
+ /** Freeze the clock at an instant, or return to real time with `null` (D14). */
195
+ async setClock(iso) {
196
+ if (iso === null) {
197
+ this.clock = { kind: 'offset', offsetMs: 0 };
198
+ await this.rebaseCron();
199
+ return;
200
+ }
201
+ const at = Date.parse(iso);
202
+ if (Number.isNaN(at))
203
+ throw new QuadError('VALIDATION', `not an instant: ${iso}`);
204
+ this.clock = { kind: 'fixed', at };
205
+ await this.rebaseCron();
206
+ }
207
+ /** Carry a clock across an engine restart (tests and the shell keep the demo time). */
208
+ restoreClock(state) {
209
+ this.clock = state;
210
+ }
211
+ /** After the clock moves, cron baselines that are now in the future move back (D14). */
212
+ rebaseCron() {
213
+ return Promise.all([...this.apps.values()].map((app) => initCron(this, app))).then(() => undefined);
214
+ }
215
+ clockState() {
216
+ return this.clock;
217
+ }
218
+ nowMs() {
219
+ return clockNow(this.clock, Date.now());
220
+ }
221
+ sessionInfo(appId) {
222
+ this.appFor(appId);
223
+ return { appId, timezone: this.dataset.schools[0].timezone, clock: this.clock };
224
+ }
225
+ /** Handle one SDK call from `appId` on behalf of `principal`. */
226
+ async handle(appId, principal, method, params) {
227
+ const ctx = this.context(appId, principal);
228
+ const p = (params ?? {});
229
+ switch (method) {
230
+ case 'auth.me':
231
+ return this.me(ctx);
232
+ case 'school.info':
233
+ return this.schoolInfo();
234
+ case 'school.get':
235
+ return this.schoolGet(ctx, p.entity, p.id);
236
+ case 'school.list':
237
+ return this.schoolList(ctx, p.entity, p.options);
238
+ case 'school.cohortByCode':
239
+ return this.cohortByCode(ctx, p.code);
240
+ case 'school.cohortMembers':
241
+ return this.cohortMembers(ctx, p.cohortId, p.options);
242
+ case 'school.studentParents':
243
+ return this.studentParents(ctx, p.studentId);
244
+ case 'school.parentChildren':
245
+ return this.parentChildren(ctx, p.parentId);
246
+ case 'school.calendar':
247
+ return this.calendar(ctx, p);
248
+ case 'db.create':
249
+ return this.dbCreate(ctx, p.entity, p.input, p.options);
250
+ case 'db.update':
251
+ return this.dbUpdate(ctx, p.entity, p.id, p.patch);
252
+ case 'db.get':
253
+ return this.dbGet(ctx, p.entity, p.id);
254
+ case 'db.list':
255
+ return this.dbList(ctx, p.entity, p.options);
256
+ case 'db.delete':
257
+ return this.dbDelete(ctx, p.entity, p.id);
258
+ case 'notify.send':
259
+ return this.notify(ctx, p);
260
+ case 'tasks.assign':
261
+ return assignTask(this, ctx, p);
262
+ case 'tasks.get':
263
+ return getTask(this, ctx, p.id);
264
+ case 'tasks.list':
265
+ return listTasks(this, ctx, p);
266
+ case 'tasks.complete':
267
+ return completeTask(this, ctx, p.id, p.options);
268
+ case 'tasks.cancel':
269
+ return cancelTask(this, ctx, p.id);
270
+ case 'schedule.at':
271
+ return scheduleAt(this, ctx, p);
272
+ case 'schedule.cancel':
273
+ return scheduleCancel(this, ctx, p.id);
274
+ case 'schedule.list':
275
+ return scheduleList(ctx, p);
276
+ case 'cron.list':
277
+ return cronList(this, ctx);
278
+ case 'audit.record':
279
+ return recordAudit(this, ctx, p);
280
+ case 'audit.list':
281
+ return listAudit(this, ctx, p);
282
+ default:
283
+ throw new QuadError('VALIDATION', `unknown method ${String(method)}`);
284
+ }
285
+ }
286
+ // ---- Sessions ----
287
+ appFor(appId) {
288
+ const app = this.apps.get(appId);
289
+ if (!app)
290
+ throw new QuadError('NOT_FOUND', `app ${appId} is not installed`);
291
+ return app;
292
+ }
293
+ context(appId, principal) {
294
+ const app = this.appFor(appId);
295
+ if (principal.kind === 'system') {
296
+ if (principal.appId !== appId)
297
+ throw new QuadError('FORBIDDEN', 'system principal belongs to another app');
298
+ return { app, principal, actorId: `system:${appId}` };
299
+ }
300
+ const person = this.byId.get(principal.personId);
301
+ if (!person || person.entity !== PEOPLE[principal.role]) {
302
+ throw new QuadError('FORBIDDEN', `no ${principal.role} with id ${principal.personId}`);
303
+ }
304
+ if (!app.manifest.roles.includes(principal.role)) {
305
+ throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
306
+ }
307
+ return { app, principal, actorId: principal.personId };
308
+ }
309
+ me(ctx) {
310
+ const { principal } = ctx;
311
+ if (principal.kind === 'system')
312
+ return { kind: 'system', appId: principal.appId };
313
+ const r = this.byId.get(principal.personId).record;
314
+ return {
315
+ kind: 'user',
316
+ role: principal.role,
317
+ person: {
318
+ id: r.id,
319
+ givenName: r.givenName,
320
+ familyName: r.familyName,
321
+ displayName: `${r.givenName} ${r.familyName}`,
322
+ },
323
+ };
324
+ }
325
+ // ---- school ----
326
+ schoolInfo() {
327
+ const s = this.dataset.schools[0];
328
+ return {
329
+ id: s.id,
330
+ name: s.name,
331
+ state: s.state,
332
+ timezone: s.timezone,
333
+ yearLevelLabels: s.yearLevelLabels,
334
+ };
335
+ }
336
+ entityName(value) {
337
+ if (typeof value !== 'string' || !(value in ENTITIES) || value === 'schools') {
338
+ throw new QuadError('VALIDATION', `unknown school entity '${String(value)}'`);
339
+ }
340
+ return value;
341
+ }
342
+ /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
343
+ tiers(ctx, entity) {
344
+ const granted = grantedTiers(ctx.app.manifest.scopes, entity);
345
+ if (granted.size === 0) {
346
+ throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
347
+ }
348
+ const allowed = principalTiers(ctx.principal, entity);
349
+ return new Set([...granted].filter((t) => allowed.has(t)));
350
+ }
351
+ allowedFields(entity, tiers) {
352
+ const fields = new Set(Object.keys(BASE_FIELDS));
353
+ for (const [key, def] of Object.entries(ENTITIES[entity].fields))
354
+ if (tiers.has(def.tier))
355
+ fields.add(key);
356
+ return fields;
357
+ }
358
+ visible(ctx, entity) {
359
+ return visibleRecords(ctx.principal, entity, this.dataset);
360
+ }
361
+ shape(entity, tiers, records) {
362
+ return records.map((r) => filterFields(entity, r, tiers));
363
+ }
364
+ async schoolGet(ctx, entityValue, id) {
365
+ const entity = this.entityName(entityValue);
366
+ const tiers = this.tiers(ctx, entity);
367
+ const record = this.visible(ctx, entity).find((r) => r.id === id);
368
+ if (!record)
369
+ throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
370
+ await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
371
+ return filterFields(entity, record, tiers);
372
+ }
373
+ async schoolList(ctx, entityValue, options) {
374
+ const entity = this.entityName(entityValue);
375
+ const tiers = this.tiers(ctx, entity);
376
+ const page = runQuery(this.visible(ctx, entity), (options ?? {}), this.allowedFields(entity, tiers));
377
+ await this.auditSensitiveRead(ctx, entity, tiers, page.items.length, 'school.list');
378
+ return { items: this.shape(entity, tiers, page.items), nextCursor: page.nextCursor };
379
+ }
380
+ cohortByCode(ctx, code) {
381
+ const tiers = this.tiers(ctx, 'cohorts');
382
+ const cohort = this.visible(ctx, 'cohorts').find((c) => c.code === str(code, 'code'));
383
+ return cohort ? filterFields('cohorts', cohort, tiers) : null;
384
+ }
385
+ cohortMembers(ctx, cohortId, options) {
386
+ const tiers = this.tiers(ctx, 'cohortMemberships');
387
+ const id = str(cohortId, 'cohortId');
388
+ if (!this.visible(ctx, 'cohorts').some((c) => c.id === id))
389
+ throw new QuadError('NOT_FOUND', `no cohort ${id}`);
390
+ const memberType = isObject(options) ? options.memberType : undefined;
391
+ if (memberType !== undefined && memberType !== 'staff' && memberType !== 'student') {
392
+ throw new QuadError('VALIDATION', "memberType must be 'staff' or 'student'");
393
+ }
394
+ const members = this.visible(ctx, 'cohortMemberships').filter((m) => m.cohortId === id && (memberType === undefined || m.memberType === memberType));
395
+ return this.shape('cohortMemberships', tiers, members);
396
+ }
397
+ studentParents(ctx, studentId) {
398
+ const tiers = this.tiers(ctx, 'parents');
399
+ const id = str(studentId, 'studentId');
400
+ if (!this.visible(ctx, 'students').some((s) => s.id === id))
401
+ throw new QuadError('NOT_FOUND', `no student ${id}`);
402
+ const linked = new Set(this.dataset.parentStudentLinks.filter((l) => l.studentId === id).map((l) => l.parentId));
403
+ return this.shape('parents', tiers, this.visible(ctx, 'parents').filter((p) => linked.has(p.id)));
404
+ }
405
+ parentChildren(ctx, parentId) {
406
+ const tiers = this.tiers(ctx, 'students');
407
+ const id = str(parentId, 'parentId');
408
+ if (!this.visible(ctx, 'parents').some((p) => p.id === id))
409
+ throw new QuadError('NOT_FOUND', `no parent ${id}`);
410
+ const linked = new Set(this.dataset.parentStudentLinks.filter((l) => l.parentId === id).map((l) => l.studentId));
411
+ return this.shape('students', tiers, this.visible(ctx, 'students').filter((s) => linked.has(s.id)));
412
+ }
413
+ calendar(ctx, p) {
414
+ const tiers = this.tiers(ctx, 'calendarEvents');
415
+ const from = str(p.from, 'from');
416
+ const to = str(p.to, 'to');
417
+ if (Number.isNaN(Date.parse(from)) || Number.isNaN(Date.parse(to))) {
418
+ throw new QuadError('VALIDATION', 'from and to must be ISO dates or instants');
419
+ }
420
+ const fromMs = Date.parse(from);
421
+ const toMs = Date.parse(to);
422
+ let relevant = null;
423
+ if (p.cohortId !== undefined) {
424
+ // A cohort's events include those for its ancestors, e.g. a class sees its year's events.
425
+ relevant = new Set();
426
+ const cohorts = new Map(this.dataset.cohorts.map((c) => [c.id, c]));
427
+ let current = cohorts.get(str(p.cohortId, 'cohortId'));
428
+ if (!current)
429
+ throw new QuadError('NOT_FOUND', `no cohort ${String(p.cohortId)}`);
430
+ while (current) {
431
+ relevant.add(current.id);
432
+ current = current.parentCohortId ? cohorts.get(current.parentCohortId) : undefined;
433
+ }
434
+ }
435
+ const events = this.visible(ctx, 'calendarEvents').filter((e) => Date.parse(e.start) < toMs &&
436
+ Date.parse(e.end) > fromMs &&
437
+ (relevant === null || e.cohortIds.length === 0 || e.cohortIds.some((c) => relevant.has(c))));
438
+ return this.shape('calendarEvents', tiers, [...events].sort((a, b) => a.start.localeCompare(b.start)));
439
+ }
440
+ // ---- db (access control: D25) ----
441
+ dbEntity(ctx, value) {
442
+ const def = typeof value === 'string' ? entityOf(ctx.app.schema, value) : undefined;
443
+ if (typeof value !== 'string' || !def) {
444
+ throw new QuadError('VALIDATION', `'${String(value)}' is not an entity in this app's schema`);
445
+ }
446
+ return { name: value, def, records: ctx.app.records.get(value) };
447
+ }
448
+ nowIso() {
449
+ return new Date(this.nowMs()).toISOString();
450
+ }
451
+ /** The rules for an operation: 'system' (full access), or the role's rules (empty = denied). */
452
+ rules(ctx, def, op) {
453
+ if (ctx.principal.kind === 'system')
454
+ return 'system';
455
+ const policy = def.access ?? DEFAULT_ACCESS;
456
+ const value = policy[ctx.principal.role]?.[op];
457
+ return value === undefined ? [] : Array.isArray(value) ? value : [value];
458
+ }
459
+ /** Whether the current user may see a student, under the school's visibility policy (D4). */
460
+ seesStudent(ctx, studentId) {
461
+ if (typeof studentId !== 'string')
462
+ return false;
463
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
464
+ return ctx.students === 'all'
465
+ ? this.byId.get(studentId)?.entity === 'students'
466
+ : ctx.students.has(studentId);
467
+ }
468
+ matches(ctx, def, rules, record) {
469
+ if (rules === 'system')
470
+ return true;
471
+ return rules.some((rule) => rule === 'all' ||
472
+ (rule === 'own' && record.createdBy === ctx.actorId) ||
473
+ (rule === 'subject' &&
474
+ def.subject !== undefined &&
475
+ this.seesStudent(ctx, record[def.subject])));
476
+ }
477
+ canRead(ctx, def, record) {
478
+ return this.matches(ctx, def, this.rules(ctx, def, 'read'), record);
479
+ }
480
+ /** Fields the current role may see or write (D25 visibleTo). The system principal sees all. */
481
+ fieldVisible(ctx, def, field) {
482
+ const visibleTo = fieldOf(def, field)?.visibleTo;
483
+ return (ctx.principal.kind === 'system' ||
484
+ visibleTo === undefined ||
485
+ visibleTo.includes(ctx.principal.role));
486
+ }
487
+ /** A record as the current role receives it: hidden fields removed, not just emptied. */
488
+ shapeRecord(ctx, def, record) {
489
+ const out = {};
490
+ for (const [k, v] of Object.entries(record))
491
+ if (!fieldOf(def, k) || this.fieldVisible(ctx, def, k))
492
+ out[k] = v;
493
+ return out;
494
+ }
495
+ requireOperation(ctx, entity, def, op) {
496
+ const rules = this.rules(ctx, def, op);
497
+ if (rules !== 'system' && rules.length === 0) {
498
+ const who = ctx.principal.kind === 'user' ? ctx.principal.role : 'system';
499
+ throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
500
+ }
501
+ return rules;
502
+ }
503
+ /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
504
+ readable(ctx, entity, id) {
505
+ const record = entity.records.get(str(id, 'id'));
506
+ if (!record || !this.canRead(ctx, entity.def, record)) {
507
+ throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
508
+ }
509
+ return record;
510
+ }
511
+ /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
512
+ checkWrite(ctx, entity, values) {
513
+ for (const key of Object.keys(values)) {
514
+ if (!this.fieldVisible(ctx, entity.def, key)) {
515
+ throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
516
+ }
517
+ }
518
+ const subject = entity.def.subject;
519
+ if (subject !== undefined && subject in values && ctx.principal.kind !== 'system') {
520
+ if (!this.seesStudent(ctx, values[subject])) {
521
+ throw new QuadError('NOT_PERMITTED', `${entity.name}.${subject}: not a student you can see`);
522
+ }
523
+ }
524
+ for (const [key, value] of Object.entries(values)) {
525
+ const field = fieldOf(entity.def, key);
526
+ if (field?.kind !== 'ref' || typeof value !== 'string' || key === subject)
527
+ continue;
528
+ if (field.to.startsWith('school.')) {
529
+ const target = field.to.slice('school.'.length);
530
+ if (!this.visible(ctx, target).some((r) => r.id === value)) {
531
+ throw new QuadError('VALIDATION', `${key}: no ${target} record ${value} visible to you`);
532
+ }
533
+ }
534
+ else {
535
+ const targetDef = entityOf(ctx.app.schema, field.to);
536
+ const target = ctx.app.records.get(field.to)?.get(value);
537
+ if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
538
+ throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
539
+ }
540
+ }
541
+ }
542
+ }
543
+ async remember(ctx, key, result) {
544
+ ctx.app.keys.set(key, result);
545
+ await this.storage.put('keys', [{ appId: ctx.app.manifest.id, key, result }]);
546
+ }
547
+ idempotencyKey(options, scope) {
548
+ if (!isObject(options) || options.idempotencyKey === undefined)
549
+ return undefined;
550
+ return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
551
+ }
552
+ async persist(ctx, entity, record) {
553
+ await this.storage.put('records', [
554
+ { appId: ctx.app.manifest.id, entity, id: record.id, data: record },
555
+ ]);
556
+ }
557
+ async dbCreate(ctx, entityValue, input, options) {
558
+ const entity = this.dbEntity(ctx, entityValue);
559
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
560
+ const key = this.idempotencyKey(options, `db.create:${entity.name}`);
561
+ if (key && ctx.app.keys.has(key)) {
562
+ const existing = entity.records.get(ctx.app.keys.get(key));
563
+ if (existing && this.canRead(ctx, entity.def, existing))
564
+ return this.shapeRecord(ctx, entity.def, existing);
565
+ }
566
+ const values = validateInput(entity.name, entity.def, input, { partial: false });
567
+ for (const k of Object.keys(values))
568
+ if (values[k] === null)
569
+ delete values[k];
570
+ this.checkWrite(ctx, entity, values);
571
+ const now = this.nowIso();
572
+ const record = {
573
+ id: `${entity.name}_${crypto.randomUUID()}`,
574
+ ...values,
575
+ createdAt: now,
576
+ createdBy: ctx.actorId,
577
+ updatedAt: now,
578
+ updatedBy: ctx.actorId,
579
+ };
580
+ if (!this.matches(ctx, entity.def, rules, record)) {
581
+ throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
582
+ }
583
+ entity.records.set(record.id, record);
584
+ await this.persist(ctx, entity.name, record);
585
+ if (key)
586
+ await this.remember(ctx, key, record.id);
587
+ return this.shapeRecord(ctx, entity.def, record);
588
+ }
589
+ async dbUpdate(ctx, entityValue, id, patch) {
590
+ const entity = this.dbEntity(ctx, entityValue);
591
+ const existing = this.readable(ctx, entity, id);
592
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
593
+ if (!this.matches(ctx, entity.def, rules, existing)) {
594
+ throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
595
+ }
596
+ const values = validateInput(entity.name, entity.def, patch, { partial: true });
597
+ this.checkWrite(ctx, entity, values);
598
+ const record = { ...existing };
599
+ for (const [k, v] of Object.entries(values)) {
600
+ if (v === null)
601
+ delete record[k];
602
+ else
603
+ record[k] = v;
604
+ }
605
+ record.updatedAt = this.nowIso();
606
+ record.updatedBy = ctx.actorId;
607
+ if (!this.matches(ctx, entity.def, rules, record)) {
608
+ throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
609
+ }
610
+ entity.records.set(existing.id, record);
611
+ await this.persist(ctx, entity.name, record);
612
+ return this.shapeRecord(ctx, entity.def, record);
613
+ }
614
+ dbGet(ctx, entityValue, id) {
615
+ const entity = this.dbEntity(ctx, entityValue);
616
+ this.requireOperation(ctx, entity.name, entity.def, 'read');
617
+ return this.shapeRecord(ctx, entity.def, this.readable(ctx, entity, id));
618
+ }
619
+ async dbList(ctx, entityValue, options) {
620
+ const entity = this.dbEntity(ctx, entityValue);
621
+ this.requireOperation(ctx, entity.name, entity.def, 'read');
622
+ const { include, ...query } = (isObject(options) ? options : {});
623
+ const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
624
+ if (!includes)
625
+ throw new QuadError('VALIDATION', 'include must be an array of ref field names');
626
+ for (const f of includes) {
627
+ if (typeof f !== 'string' ||
628
+ fieldOf(entity.def, f)?.kind !== 'ref' ||
629
+ !this.fieldVisible(ctx, entity.def, f)) {
630
+ throw new QuadError('VALIDATION', `include: '${String(f)}' is not a ref field of ${entity.name}`);
631
+ }
632
+ }
633
+ // Access first, then filters and pages: results and cursors only ever cover readable records.
634
+ const readable = [...entity.records.values()].filter((r) => this.canRead(ctx, entity.def, r));
635
+ const fields = new Set([
636
+ ...SYSTEM_FIELDS,
637
+ ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
638
+ ]);
639
+ // D37: sorts and range filters need a declared index, as on the platform's data API.
640
+ checkIndexCoverage(entity.name, entity.def.indexes, query, fields);
641
+ const page = runQuery(readable, query, fields);
642
+ const items = page.items.map((r) => this.shapeRecord(ctx, entity.def, r));
643
+ if (includes.length === 0)
644
+ return { items, nextCursor: page.nextCursor };
645
+ const schoolReads = new Map();
646
+ const withIncluded = items.map((r) => ({
647
+ ...r,
648
+ $included: Object.fromEntries(includes.map((f) => [
649
+ f,
650
+ this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads),
651
+ ])),
652
+ }));
653
+ for (const [target, count] of schoolReads) {
654
+ await this.auditSensitiveRead(ctx, target, this.tiers(ctx, target), count, 'db.include');
655
+ }
656
+ return { items: withIncluded, nextCursor: page.nextCursor };
657
+ }
658
+ resolveRef(ctx, field, value, schoolReads) {
659
+ if (typeof value !== 'string' || !field.to)
660
+ return null;
661
+ if (field.to.startsWith('school.')) {
662
+ const target = field.to.slice('school.'.length);
663
+ if (grantedTiers(ctx.app.manifest.scopes, target).size === 0)
664
+ return null;
665
+ const record = this.visible(ctx, target).find((r) => r.id === value);
666
+ if (!record)
667
+ return null;
668
+ schoolReads.set(target, (schoolReads.get(target) ?? 0) + 1);
669
+ return filterFields(target, record, this.tiers(ctx, target));
670
+ }
671
+ // Included app records follow their own entity's rules (D25).
672
+ const def = entityOf(ctx.app.schema, field.to);
673
+ const record = ctx.app.records.get(field.to)?.get(value);
674
+ return def && record && this.canRead(ctx, def, record)
675
+ ? this.shapeRecord(ctx, def, record)
676
+ : null;
677
+ }
678
+ async dbDelete(ctx, entityValue, id) {
679
+ const entity = this.dbEntity(ctx, entityValue);
680
+ const existing = this.readable(ctx, entity, id);
681
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
682
+ if (!this.matches(ctx, entity.def, rules, existing)) {
683
+ throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
684
+ }
685
+ entity.records.delete(existing.id);
686
+ await this.storage.deleteRecord(ctx.app.manifest.id, entity.name, existing.id);
687
+ return null;
688
+ }
689
+ // ---- notify (D10, D17) ----
690
+ async notify(ctx, input) {
691
+ const { manifest } = ctx.app;
692
+ const type = str(input.type, 'type');
693
+ if (!manifest.notifications.includes(type)) {
694
+ throw new QuadError('UNDECLARED_TYPE', `notification type '${type}' isn't declared in app.manifest.json`);
695
+ }
696
+ const key = this.idempotencyKey(input, 'notify.send');
697
+ if (key && ctx.app.keys.has(key))
698
+ return ctx.app.keys.get(key);
699
+ const subject = str(input.subject, 'subject');
700
+ const body = str(input.body, 'body');
701
+ const channel = input.channel ?? 'inApp';
702
+ if (channel !== 'inApp' && channel !== 'email')
703
+ throw new QuadError('VALIDATION', "channel must be 'inApp' or 'email'");
704
+ if (input.link !== undefined &&
705
+ (typeof input.link !== 'string' || !input.link.startsWith('/'))) {
706
+ throw new QuadError('VALIDATION', 'link must be an app-relative path starting with /');
707
+ }
708
+ let regarding;
709
+ if (input.regarding !== undefined) {
710
+ if (!isObject(input.regarding))
711
+ throw new QuadError('VALIDATION', 'regarding must be { studentId }');
712
+ regarding = str(input.regarding.studentId, 'regarding.studentId');
713
+ if (this.byId.get(regarding)?.entity !== 'students')
714
+ throw new QuadError('VALIDATION', `no student ${regarding}`);
715
+ }
716
+ const { recipients, suppressed } = this.resolveRecipients(ctx, input.to, regarding);
717
+ const sentAt = this.nowIso();
718
+ const entries = recipients.map((r) => ({
719
+ id: `out_${crypto.randomUUID()}`,
720
+ appId: manifest.id,
721
+ type,
722
+ channel: channel,
723
+ recipientId: r.personId,
724
+ recipientRole: r.role,
725
+ subject,
726
+ body,
727
+ ...(typeof input.link === 'string' ? { link: input.link } : {}),
728
+ ...(r.regarding ? { regardingStudentId: r.regarding } : {}),
729
+ sentAt,
730
+ sentBy: ctx.actorId,
731
+ simulated: true,
732
+ }));
733
+ if (entries.length > 0)
734
+ await this.storage.put('outbox', entries);
735
+ await appendAudit(this, ctx.app, {
736
+ source: 'platform',
737
+ action: 'notification.sent',
738
+ actor: ctx.actorId,
739
+ summary: `${type} sent to ${entries.length} recipient${entries.length === 1 ? '' : 's'}`,
740
+ entity: 'notification',
741
+ visibility: 'app',
742
+ data: { type, channel: channel, recipients: entries.map((e) => e.recipientId) },
743
+ });
744
+ await this.auditSuppressed(ctx, 'notification.suppressed', type, suppressed);
745
+ const result = { recipients: recipients.map(({ personId, role }) => ({ personId, role })) };
746
+ if (key)
747
+ await this.remember(ctx, key, result);
748
+ return result;
749
+ }
750
+ roleOf(personId) {
751
+ const entity = this.byId.get(personId)?.entity;
752
+ return entity === 'staff'
753
+ ? 'staff'
754
+ : entity === 'students'
755
+ ? 'student'
756
+ : entity === 'parents'
757
+ ? 'parent'
758
+ : null;
759
+ }
760
+ /**
761
+ * Resolves recipients to people, applying the app's roles and D17. Parents are only ever
762
+ * reached about a specific student, and only through an eligible, unrestricted link.
763
+ */
764
+ resolveRecipients(ctx, to, regarding) {
765
+ const list = Array.isArray(to) ? to : [to];
766
+ if (list.length === 0)
767
+ throw new QuadError('VALIDATION', 'to must name at least one recipient');
768
+ const roles = ctx.app.manifest.roles;
769
+ const senderIsStaff = ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
770
+ const out = new Map();
771
+ const suppressed = new Map();
772
+ const suppress = (personId, studentId, purpose) => {
773
+ const reason = this.suppressionReason(personId, studentId, purpose);
774
+ // Parents who simply aren't linked to the student aren't a safeguarding event.
775
+ if (reason !== 'not-linked')
776
+ suppressed.set(`${personId}:${studentId}`, {
777
+ personId,
778
+ regardingStudentId: studentId,
779
+ reason,
780
+ });
781
+ };
782
+ const cohortMembers = (cohortId, memberType) => {
783
+ const id = str(cohortId, 'cohortId');
784
+ if (this.byId.get(id)?.entity !== 'cohorts')
785
+ throw new QuadError('VALIDATION', `no cohort ${id}`);
786
+ return this.dataset.cohortMemberships
787
+ .filter((m) => m.cohortId === id && m.memberType === memberType)
788
+ .map((m) => m.personId);
789
+ };
790
+ const add = (personId, role, about) => {
791
+ if (!roles.includes(role))
792
+ return;
793
+ if (role === 'parent') {
794
+ const studentId = about ?? regarding;
795
+ if (!studentId) {
796
+ throw new QuadError('VALIDATION', 'notifications to parents need regarding: { studentId } (D17)');
797
+ }
798
+ if (!eligibleParents(this.dataset, studentId, 'correspondence').includes(personId)) {
799
+ suppress(personId, studentId, 'correspondence');
800
+ return;
801
+ }
802
+ out.set(personId, { personId, role, regarding: studentId, purpose: 'correspondence' });
803
+ return;
804
+ }
805
+ out.set(personId, { personId, role });
806
+ };
807
+ for (const r of list) {
808
+ if (!isObject(r))
809
+ throw new QuadError('VALIDATION', 'each recipient must be an object');
810
+ const toStaffOnly = 'role' in r ? r.role === 'staff' : 'relationship' in r ? r.relationship === 'staffOf' : null;
811
+ if (!senderIsStaff) {
812
+ const personRole = 'person' in r && typeof r.person === 'string' ? this.roleOf(r.person) : null;
813
+ if (!(toStaffOnly === true || personRole === 'staff')) {
814
+ throw new QuadError('FORBIDDEN', 'students and parents can only send notifications to staff');
815
+ }
816
+ }
817
+ if ('person' in r) {
818
+ const id = str(r.person, 'person');
819
+ const role = this.roleOf(id);
820
+ if (!role)
821
+ throw new QuadError('VALIDATION', `no person ${id}`);
822
+ if (!roles.includes(role))
823
+ throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${role} users`);
824
+ add(id, role);
825
+ }
826
+ else if ('role' in r) {
827
+ if (!['staff', 'student', 'parent'].includes(r.role))
828
+ throw new QuadError('VALIDATION', `unknown role ${String(r.role)}`);
829
+ if (!roles.includes(r.role))
830
+ throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${r.role} users`);
831
+ for (const p of this.dataset[PEOPLE[r.role]])
832
+ add(p.id, r.role);
833
+ }
834
+ else if ('relationship' in r && r.relationship === 'parentsOf') {
835
+ const studentId = str(r.studentId, 'studentId');
836
+ if (this.byId.get(studentId)?.entity !== 'students')
837
+ throw new QuadError('VALIDATION', `no student ${studentId}`);
838
+ const purpose = r.purpose ?? 'correspondence';
839
+ if (purpose !== 'correspondence' && purpose !== 'consent')
840
+ throw new QuadError('VALIDATION', `unknown purpose ${String(purpose)}`);
841
+ if (!roles.includes('parent'))
842
+ continue;
843
+ const eligible = new Set(eligibleParents(this.dataset, studentId, purpose));
844
+ for (const link of this.dataset.parentStudentLinks) {
845
+ if (link.studentId !== studentId)
846
+ continue;
847
+ if (eligible.has(link.parentId)) {
848
+ out.set(link.parentId, {
849
+ personId: link.parentId,
850
+ role: 'parent',
851
+ regarding: studentId,
852
+ purpose,
853
+ });
854
+ }
855
+ else {
856
+ suppress(link.parentId, studentId, purpose);
857
+ }
858
+ }
859
+ }
860
+ else if ('relationship' in r && r.relationship === 'staffOf') {
861
+ for (const id of cohortMembers(r.cohortId, 'staff'))
862
+ add(id, 'staff');
863
+ }
864
+ else if ('relationship' in r && r.relationship === 'studentsOf') {
865
+ for (const id of cohortMembers(r.cohortId, 'student'))
866
+ add(id, 'student');
867
+ }
868
+ else {
869
+ throw new QuadError('VALIDATION', 'unknown recipient; use { person }, { role }, parentsOf, staffOf or studentsOf');
870
+ }
871
+ }
872
+ return { recipients: [...out.values()], suppressed: [...suppressed.values()] };
873
+ }
874
+ suppressionReason(parentId, studentId, purpose) {
875
+ const link = this.dataset.parentStudentLinks.find((l) => l.parentId === parentId && l.studentId === studentId);
876
+ if (!link)
877
+ return 'not-linked';
878
+ if (link.contactRestricted)
879
+ return 'restricted';
880
+ if (!link.receivesCorrespondence)
881
+ return 'no-correspondence';
882
+ return purpose === 'consent' && !link.canConsent ? 'cannot-consent' : 'no-correspondence';
883
+ }
884
+ /** D17/D19: each suppressed parent is recorded, visible only to the CIO view. */
885
+ async auditSuppressed(ctx, action, type, suppressed) {
886
+ for (const s of suppressed) {
887
+ await appendAudit(this, ctx.app, {
888
+ source: 'platform',
889
+ action,
890
+ actor: ctx.actorId,
891
+ summary: `${type} not sent to a parent (${s.reason})`,
892
+ entity: 'notification',
893
+ visibility: 'cio',
894
+ data: {
895
+ type,
896
+ recipientId: s.personId,
897
+ regardingStudentId: s.regardingStudentId,
898
+ reason: s.reason,
899
+ },
900
+ });
901
+ }
902
+ }
903
+ /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
904
+ async auditSensitiveRead(ctx, entity, tiers, count, via) {
905
+ const sensitive = [...tiers].filter((t) => t === 'pastoral' || t === 'medical');
906
+ if (sensitive.length === 0 || count === 0)
907
+ return;
908
+ const hasFields = Object.values(ENTITIES[entity].fields).some((f) => sensitive.includes(f.tier));
909
+ if (!hasFields)
910
+ return;
911
+ await appendAudit(this, ctx.app, {
912
+ source: 'platform',
913
+ action: 'school.sensitive-read',
914
+ actor: ctx.actorId,
915
+ summary: `read ${count} ${entity} record${count === 1 ? '' : 's'} with ${sensitive.join(' and ')} data`,
916
+ entity,
917
+ visibility: 'cio',
918
+ data: { entity, tiers: sensitive, recordCount: count, via },
919
+ });
920
+ }
921
+ }
922
+ export const ENGINE_SDK_VERSION = SDK_VERSION;