@quad-education/sdk 0.8.0 → 0.9.0

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 (57) hide show
  1. package/README.md +1 -0
  2. package/dist/contract-tests/apps.d.ts +430 -0
  3. package/dist/contract-tests/apps.js +143 -1
  4. package/dist/contract-tests/harness.d.ts +1 -1
  5. package/dist/contract-tests/harness.js +4 -0
  6. package/dist/contract-tests/lists-and-files.d.ts +19 -0
  7. package/dist/contract-tests/lists-and-files.js +279 -0
  8. package/dist/contract-tests/live.d.ts +3 -0
  9. package/dist/contract-tests/live.js +156 -0
  10. package/dist/contract-tests/notifications.d.ts +3 -0
  11. package/dist/contract-tests/notifications.js +218 -0
  12. package/dist/contract-tests/search-and-totals.d.ts +13 -0
  13. package/dist/contract-tests/search-and-totals.js +226 -0
  14. package/dist/contract-tests/suite.d.ts +5 -0
  15. package/dist/contract-tests/suite.js +27 -1
  16. package/dist/contract-tests/writes.d.ts +3 -0
  17. package/dist/contract-tests/writes.js +265 -0
  18. package/dist/src/base64.d.ts +3 -0
  19. package/dist/src/base64.js +52 -0
  20. package/dist/src/client/connect.d.ts +1 -0
  21. package/dist/src/client/connect.js +1 -0
  22. package/dist/src/client/create-client.js +39 -5
  23. package/dist/src/client/save-file.d.ts +16 -0
  24. package/dist/src/client/save-file.js +28 -0
  25. package/dist/src/client/watch.d.ts +20 -0
  26. package/dist/src/client/watch.js +175 -0
  27. package/dist/src/contract/errors.d.ts +1 -1
  28. package/dist/src/contract/types.d.ts +214 -10
  29. package/dist/src/contract/types.js +4 -1
  30. package/dist/src/engine/engine.d.ts +68 -1
  31. package/dist/src/engine/engine.js +508 -57
  32. package/dist/src/engine/files.d.ts +25 -0
  33. package/dist/src/engine/files.js +88 -0
  34. package/dist/src/engine/index.d.ts +1 -1
  35. package/dist/src/engine/memory-store.d.ts +33 -3
  36. package/dist/src/engine/memory-store.js +116 -8
  37. package/dist/src/engine/notify-content.d.ts +9 -0
  38. package/dist/src/engine/notify-content.js +88 -0
  39. package/dist/src/engine/query.d.ts +14 -2
  40. package/dist/src/engine/query.js +45 -13
  41. package/dist/src/engine/search.d.ts +8 -0
  42. package/dist/src/engine/search.js +32 -0
  43. package/dist/src/engine/storage.d.ts +46 -1
  44. package/dist/src/engine/storage.js +46 -3
  45. package/dist/src/engine/store.d.ts +39 -2
  46. package/dist/src/engine/summary.d.ts +25 -0
  47. package/dist/src/engine/summary.js +107 -0
  48. package/dist/src/engine/validate-input.d.ts +7 -1
  49. package/dist/src/engine/validate-input.js +28 -1
  50. package/dist/src/engine/working-copy.d.ts +30 -0
  51. package/dist/src/engine/working-copy.js +91 -0
  52. package/dist/src/platform-types.d.ts +11 -1
  53. package/dist/src/protocol.d.ts +1 -1
  54. package/dist/src/protocol.js +9 -0
  55. package/dist/src/testing/index.d.ts +2 -0
  56. package/dist/src/testing/index.js +9 -1
  57. package/package.json +4 -4
@@ -1,16 +1,21 @@
1
- import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
- import { DEFAULT_ACCESS, listedField, parseListed, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
1
+ import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, STAFF_ONLY_TIERS, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
+ import { DEFAULT_ACCESS, MAX_BATCH_OPERATIONS, MAX_UNIQUE_TEXT, listedField, parseListed, 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";
6
6
  import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
7
7
  import { checkIndexCoverage } from "./db-indexes.js";
8
- import { runQuery } from "./query.js";
8
+ import { filterRows, runQuery } from "./query.js";
9
9
  import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
10
10
  import { isStaffOrSystem, } from "./state.js";
11
+ import { MAX_APP_FILE_BYTES, UNATTACHED_MS, acceptProblem, checkUpload, fileId, fileInfo, filesNamed, schemaKeepsFiles, } from "./files.js";
12
+ import { toBase64 } from "../base64.js";
13
+ import { MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, checkContent, plainText } from "./notify-content.js";
14
+ import { TOTALS, checkSummarySize, queryOptions, summarise, summaryPlan } from "./summary.js";
11
15
  import { MemoryStore } from "./memory-store.js";
16
+ import { WorkingCopy } from "./working-copy.js";
12
17
  import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
13
- import { entityOf, fieldOf, validateInput } from "./validate-input.js";
18
+ import { entityOf, fieldOf, heldBy, validateInput, valuesOf } from "./validate-input.js";
14
19
  const SYSTEM_FIELDS = ['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
15
20
  const PEOPLE = { staff: 'staff', student: 'students', parent: 'parents' };
16
21
  const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -67,7 +72,9 @@ export class Engine {
67
72
  }
68
73
  static async create(options) {
69
74
  const store = options.store ??
70
- (options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
75
+ (options.indexedDB
76
+ ? await MemoryStore.open(options.indexedDB, options.dbName, options.channel)
77
+ : undefined);
71
78
  if (!store)
72
79
  throw new Error('an engine needs a store or an IndexedDB factory');
73
80
  return new Engine(options.dataset, store);
@@ -158,7 +165,8 @@ export class Engine {
158
165
  }
159
166
  /** Counts of everything a job can change, for run-twice tests (D20). */
160
167
  async effectsSnapshot(appId) {
161
- const [records, tasks, schedules, audit, outbox] = await Promise.all([
168
+ const [files, records, tasks, schedules, audit, outbox] = await Promise.all([
169
+ this.store.allFiles(appId),
162
170
  this.store.recordStamps(appId),
163
171
  this.store.allPlatform(appId, 'task'),
164
172
  this.store.allPlatform(appId, 'schedule'),
@@ -171,6 +179,7 @@ export class Engine {
171
179
  schedules: Object.fromEntries(schedules.map((s) => [s.id, s.status])),
172
180
  audit: audit.length,
173
181
  records,
182
+ files: files.map((f) => f.id),
174
183
  };
175
184
  }
176
185
  /** Runs for the job log, newest first. */
@@ -258,7 +267,8 @@ export class Engine {
258
267
  async handle(appId, principal, method, params) {
259
268
  const ctx = this.context(appId, principal);
260
269
  const p = (params ?? {});
261
- if (method.startsWith('db.'))
270
+ // Files follow a record's access rules, and a notification may attach one (D148, D152).
271
+ if (method.startsWith('db.') || method.startsWith('files.') || method === 'notify.send')
262
272
  await this.resolveGrants(ctx);
263
273
  switch (method) {
264
274
  case 'auth.me':
@@ -280,15 +290,23 @@ export class Engine {
280
290
  case 'school.parentChildren':
281
291
  return this.parentChildren(ctx, p.parentId);
282
292
  case 'db.create':
283
- return this.dbCreate(ctx, p.entity, p.input, p.options);
293
+ return this.single(ctx, (w) => this.dbCreate(ctx, w, p.entity, p.input, p.options));
284
294
  case 'db.update':
285
- return this.dbUpdate(ctx, p.entity, p.id, p.patch);
295
+ return this.single(ctx, (w) => this.dbUpdate(ctx, w, p.entity, p.id, p.patch, p.options));
296
+ case 'db.batch':
297
+ return this.dbBatch(ctx, p.ops, p.options);
298
+ case 'db.changes':
299
+ return this.dbChanges(ctx, p.entities);
286
300
  case 'db.get':
287
301
  return this.dbGet(ctx, p.entity, p.id);
288
302
  case 'db.list':
289
303
  return this.dbList(ctx, p.entity, p.options);
304
+ case 'db.count':
305
+ return this.dbCount(ctx, p.entity, p.options);
306
+ case 'db.summarise':
307
+ return this.dbSummarise(ctx, p.entity, p.options);
290
308
  case 'db.delete':
291
- return this.dbDelete(ctx, p.entity, p.id);
309
+ return this.single(ctx, (w) => this.dbDelete(ctx, w, p.entity, p.id, p.options));
292
310
  case 'notify.send':
293
311
  return this.notify(ctx, p);
294
312
  case 'tasks.assign':
@@ -313,6 +331,12 @@ export class Engine {
313
331
  return recordAudit(this, ctx, p);
314
332
  case 'audit.list':
315
333
  return listAudit(this, ctx, p);
334
+ case 'files.upload':
335
+ return this.filesUpload(ctx, p);
336
+ case 'files.info':
337
+ return fileInfo(await this.readableFile(ctx, fileId(p)));
338
+ case 'files.read':
339
+ return this.filesRead(ctx, fileId(p));
316
340
  default:
317
341
  throw new QuadError('VALIDATION', `unknown method ${String(method)}`);
318
342
  }
@@ -437,7 +461,11 @@ export class Engine {
437
461
  async schoolList(ctx, entityValue, options) {
438
462
  const entity = this.entityName(entityValue);
439
463
  const tiers = this.tiers(ctx, entity);
440
- const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers));
464
+ const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers), undefined,
465
+ // D153: a search looks in the text the app has been granted, among the records the person may see.
466
+ Object.entries(ENTITIES[entity].fields)
467
+ .filter(([, def]) => (def.type === 'string' || def.type === 'stringList') && fieldVisible(def, tiers))
468
+ .map(([name]) => name));
441
469
  await this.auditSensitiveRead(ctx, entity, tiers, page.items.length, 'school.list');
442
470
  return { items: this.shape(entity, tiers, page.items), nextCursor: page.nextCursor };
443
471
  }
@@ -591,15 +619,17 @@ export class Engine {
591
619
  return rules;
592
620
  }
593
621
  /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
594
- async readable(ctx, entity, id) {
595
- const record = await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
622
+ async readable(ctx, entity, id, w) {
623
+ const record = w
624
+ ? await w.getRecord(entity.name, str(id, 'id'))
625
+ : await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
596
626
  if (!record || !this.canRead(ctx, entity.def, record)) {
597
627
  throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
598
628
  }
599
629
  return record;
600
630
  }
601
631
  /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
602
- async checkWrite(ctx, entity, values) {
632
+ async checkWrite(ctx, entity, values, w) {
603
633
  for (const key of Object.keys(values)) {
604
634
  if (!this.fieldVisible(ctx, entity.def, key)) {
605
635
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
@@ -613,19 +643,27 @@ export class Engine {
613
643
  }
614
644
  for (const [key, value] of Object.entries(values)) {
615
645
  const field = fieldOf(entity.def, key);
616
- if (field?.kind !== 'ref' || typeof value !== 'string' || key === subject)
646
+ if (!field || key === subject)
617
647
  continue;
618
- if (field.to.startsWith('school.')) {
619
- const target = field.to.slice('school.'.length);
620
- if (!this.visible(ctx, target).some((r) => r.id === value)) {
621
- throw new QuadError('VALIDATION', `${key}: no ${target} record ${value} visible to you`);
648
+ const held = heldBy(field);
649
+ if (held.kind !== 'ref')
650
+ continue;
651
+ // Every link is checked, whether the field holds one or a list of them (D147).
652
+ for (const item of valuesOf(field, value)) {
653
+ if (typeof item !== 'string')
654
+ continue;
655
+ if (held.to.startsWith('school.')) {
656
+ const target = held.to.slice('school.'.length);
657
+ if (!this.visible(ctx, target).some((r) => r.id === item)) {
658
+ throw new QuadError('VALIDATION', `${key}: no ${target} record ${item} visible to you`);
659
+ }
622
660
  }
623
- }
624
- else {
625
- const targetDef = entityOf(ctx.app.schema, field.to);
626
- const target = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
627
- if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
628
- throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
661
+ else {
662
+ const targetDef = entityOf(ctx.app.schema, held.to);
663
+ const target = await w.getRecord(held.to, item);
664
+ if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
665
+ throw new QuadError('VALIDATION', `${key}: no ${held.to} record ${item}`);
666
+ }
629
667
  }
630
668
  }
631
669
  }
@@ -638,13 +676,134 @@ export class Engine {
638
676
  return undefined;
639
677
  return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
640
678
  }
641
- async dbCreate(ctx, entityValue, input, options) {
679
+ // ---- db writes (D149, D150, ADR 0040) ----
680
+ writeQueues = new Map();
681
+ /**
682
+ * Writes to one app run one after another, so a check and the write that follows it are never interleaved with
683
+ * another call's: of two bookings for the last slot started together, one sees the other.
684
+ */
685
+ queued(appId, write) {
686
+ const run = (this.writeQueues.get(appId) ?? Promise.resolve()).then(write, write);
687
+ this.writeQueues.set(appId, run.catch(() => undefined));
688
+ return run;
689
+ }
690
+ /** One create, update or delete: a working copy of its own, committed when it has passed every check. */
691
+ single(ctx, write) {
692
+ return this.queued(ctx.app.manifest.id, async () => {
693
+ const w = new WorkingCopy(this.store, ctx.app.manifest.id);
694
+ const result = await write(w);
695
+ await w.commit();
696
+ return result;
697
+ });
698
+ }
699
+ /** Up to 25 writes, all stored or none (D150). Each is checked as it is on its own. */
700
+ dbBatch(ctx, opsValue, options) {
701
+ if (!Array.isArray(opsValue) || opsValue.length < 1 || opsValue.length > MAX_BATCH_OPERATIONS)
702
+ throw new QuadError('VALIDATION', `db.batch takes a list of 1 to ${MAX_BATCH_OPERATIONS} operations`);
703
+ const ops = opsValue.map((op, i) => {
704
+ const kinds = isObject(op)
705
+ ? ['create', 'update', 'delete'].filter((k) => k in op)
706
+ : [];
707
+ if (!isObject(op) || kinds.length !== 1)
708
+ throw new QuadError('VALIDATION', `operation ${i + 1}: write it as { create: 'entity', input }, { update: 'entity', id, patch } or { delete: 'entity', id }`, { index: i });
709
+ return { kind: kinds[0], op };
710
+ });
711
+ const key = this.idempotencyKey(options, 'db.batch');
712
+ return this.queued(ctx.app.manifest.id, async () => {
713
+ const appId = ctx.app.manifest.id;
714
+ const remembered = key ? await this.store.getKey(appId, key) : undefined;
715
+ if (Array.isArray(remembered)) {
716
+ // The batch was written before: its records as they stand now, for whoever asks again.
717
+ const again = [];
718
+ for (const item of remembered) {
719
+ const def = item ? entityOf(ctx.app.schema, item.entity) : undefined;
720
+ const record = item && def ? await this.store.getRecord(appId, item.entity, item.id) : null;
721
+ again.push(record && def && this.canRead(ctx, def, record)
722
+ ? this.shapeRecord(ctx, def, record)
723
+ : null);
724
+ }
725
+ return again;
726
+ }
727
+ const w = new WorkingCopy(this.store, appId);
728
+ const results = [];
729
+ const written = [];
730
+ for (const [index, { kind, op }] of ops.entries()) {
731
+ try {
732
+ const result = kind === 'create'
733
+ ? await this.dbCreate(ctx, w, op.create, op.input, op)
734
+ : kind === 'update'
735
+ ? await this.dbUpdate(ctx, w, op.update, op.id, op.patch, op)
736
+ : await this.dbDelete(ctx, w, op.delete, op.id, op);
737
+ results.push(result);
738
+ written.push(result ? { entity: op[kind], id: result.id } : null);
739
+ }
740
+ catch (e) {
741
+ if (!(e instanceof QuadError))
742
+ throw e;
743
+ throw new QuadError(e.code, `operation ${index + 1}: ${e.message}`, {
744
+ ...(isObject(e.details) ? e.details : {}),
745
+ index,
746
+ });
747
+ }
748
+ }
749
+ if (key)
750
+ w.putKey(key, written);
751
+ await w.commit();
752
+ return results;
753
+ });
754
+ }
755
+ /** D149: no other record of the entity holds the same values for any of its unique rules. */
756
+ async checkUnique(w, entity, record) {
757
+ const rules = entity.def.unique ?? [];
758
+ if (rules.length === 0)
759
+ return;
760
+ let others;
761
+ for (const fields of rules) {
762
+ const values = fields.map((f) => record[f]);
763
+ // A record that leaves one of the fields empty is not bound by the rule.
764
+ if (values.some((v) => v === undefined || v === null))
765
+ continue;
766
+ const long = fields.find((f) => {
767
+ const v = record[f];
768
+ return typeof v === 'string' && v.length > MAX_UNIQUE_TEXT;
769
+ });
770
+ if (long !== undefined)
771
+ throw new QuadError('VALIDATION', `${entity.name}.${long}: a value in a unique rule is at most ${MAX_UNIQUE_TEXT} characters`);
772
+ others ??= (await w.all(entity.name)).filter((r) => r.id !== record.id);
773
+ // Every record counts, whoever can read it; the refusal never says which one holds the values.
774
+ if (others.some((r) => fields.every((f) => r[f] === record[f])))
775
+ throw new QuadError('CONFLICT', `another ${entity.name} record already has this ${fields.join(' and ')}`, { entity: entity.name, fields: [...fields] });
776
+ }
777
+ }
778
+ /** D150: the write goes ahead only when the record's fields hold the values given; null means empty. */
779
+ checkIf(ctx, entity, existing, options) {
780
+ const condition = isObject(options) ? options.if : undefined;
781
+ if (condition === undefined)
782
+ return;
783
+ if (!isObject(condition) || Object.keys(condition).length === 0)
784
+ throw new QuadError('VALIDATION', 'if: an object of field values, as { status: "free" }');
785
+ const changed = [];
786
+ for (const [field, value] of Object.entries(condition)) {
787
+ const def = fieldOf(entity.def, field);
788
+ if (!def || def.kind === 'list')
789
+ throw new QuadError('VALIDATION', `if.${field}: not a single-valued field of ${entity.name}`);
790
+ if (!this.fieldVisible(ctx, entity.def, field))
791
+ throw new QuadError('NOT_PERMITTED', `${entity.name}.${field} isn't available to you`);
792
+ if (value !== null && !['string', 'number', 'boolean'].includes(typeof value))
793
+ throw new QuadError('VALIDATION', `if.${field}: a value, or null for empty`);
794
+ if ((existing[field] ?? null) !== value)
795
+ changed.push(field);
796
+ }
797
+ if (changed.length > 0)
798
+ throw new QuadError('CONFLICT', `this ${entity.name} record no longer has the ${changed.join(' and ')} you expected`, { entity: entity.name, id: existing.id, fields: changed });
799
+ }
800
+ async dbCreate(ctx, w, entityValue, input, options) {
642
801
  const entity = this.dbEntity(ctx, entityValue);
643
802
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
644
803
  const key = this.idempotencyKey(options, `db.create:${entity.name}`);
645
- const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
804
+ const remembered = key ? await w.getKey(key) : undefined;
646
805
  if (typeof remembered === 'string') {
647
- const existing = await this.store.getRecord(ctx.app.manifest.id, entity.name, remembered);
806
+ const existing = await w.getRecord(entity.name, remembered);
648
807
  if (existing && this.canRead(ctx, entity.def, existing))
649
808
  return this.shapeRecord(ctx, entity.def, existing);
650
809
  }
@@ -652,7 +811,8 @@ export class Engine {
652
811
  for (const k of Object.keys(values))
653
812
  if (values[k] === null)
654
813
  delete values[k];
655
- await this.checkWrite(ctx, entity, values);
814
+ await this.checkWrite(ctx, entity, values, w);
815
+ const files = await this.planFiles(ctx, w, entity, values);
656
816
  const now = this.nowIso();
657
817
  const record = {
658
818
  id: `${entity.name}_${crypto.randomUUID()}`,
@@ -665,20 +825,24 @@ export class Engine {
665
825
  if (!this.matches(ctx, entity.def, rules, record)) {
666
826
  throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
667
827
  }
668
- await this.store.putRecord(ctx.app.manifest.id, entity.name, record);
828
+ await this.checkUnique(w, entity, record);
829
+ await w.putRecord(entity.name, record);
830
+ this.applyFiles(w, entity.name, record.id, files);
669
831
  if (key)
670
- await this.remember(ctx, key, record.id);
832
+ w.putKey(key, record.id);
671
833
  return this.shapeRecord(ctx, entity.def, record);
672
834
  }
673
- async dbUpdate(ctx, entityValue, id, patch) {
835
+ async dbUpdate(ctx, w, entityValue, id, patch, options) {
674
836
  const entity = this.dbEntity(ctx, entityValue);
675
- const existing = await this.readable(ctx, entity, id);
837
+ const existing = await this.readable(ctx, entity, id, w);
676
838
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
677
839
  if (!this.matches(ctx, entity.def, rules, existing)) {
678
840
  throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
679
841
  }
842
+ this.checkIf(ctx, entity, existing, options);
680
843
  const values = validateInput(entity.name, entity.def, patch, { partial: true });
681
- await this.checkWrite(ctx, entity, values);
844
+ await this.checkWrite(ctx, entity, values, w);
845
+ const files = await this.planFiles(ctx, w, entity, values, existing);
682
846
  const record = { ...existing };
683
847
  for (const [k, v] of Object.entries(values)) {
684
848
  if (v === null)
@@ -691,7 +855,9 @@ export class Engine {
691
855
  if (!this.matches(ctx, entity.def, rules, record)) {
692
856
  throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
693
857
  }
694
- await this.store.putRecord(ctx.app.manifest.id, entity.name, record, existing);
858
+ await this.checkUnique(w, entity, record);
859
+ await w.putRecord(entity.name, record);
860
+ this.applyFiles(w, entity.name, existing.id, files);
695
861
  return this.shapeRecord(ctx, entity.def, record);
696
862
  }
697
863
  async dbGet(ctx, entityValue, id) {
@@ -699,21 +865,12 @@ export class Engine {
699
865
  this.requireOperation(ctx, entity.name, entity.def, 'read');
700
866
  return this.shapeRecord(ctx, entity.def, await this.readable(ctx, entity, id));
701
867
  }
702
- async dbList(ctx, entityValue, options) {
703
- const entity = this.dbEntity(ctx, entityValue);
704
- const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
705
- const { include, ...query } = (isObject(options) ? options : {});
706
- const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
707
- if (!includes)
708
- throw new QuadError('VALIDATION', 'include must be an array of ref field names');
709
- for (const f of includes) {
710
- if (typeof f !== 'string' ||
711
- fieldOf(entity.def, f)?.kind !== 'ref' ||
712
- !this.fieldVisible(ctx, entity.def, f)) {
713
- throw new QuadError('VALIDATION', `include: '${String(f)}' is not a ref field of ${entity.name}`);
714
- }
715
- }
716
- // Access first, then filters and pages: results and cursors only ever cover readable records.
868
+ /**
869
+ * The records of an entity the caller may read, with what a query over them may use: the fields they can see,
870
+ * which of those are lists, and where a search looks (D153). Access comes first: filters, pages, counts and
871
+ * totals only ever cover readable records.
872
+ */
873
+ async dbReadable(ctx, entity, rules, query) {
717
874
  const candidates = await this.store.candidates(ctx.app.manifest.id, entity.name, {
718
875
  // A rule the caller doesn't pass adds nothing, so only the ones that could match decide the hint.
719
876
  ...(rules !== 'system' &&
@@ -731,9 +888,85 @@ export class Engine {
731
888
  ...SYSTEM_FIELDS,
732
889
  ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
733
890
  ]);
891
+ const lists = new Set(Object.entries(entity.def.fields)
892
+ .filter(([, f]) => f.kind === 'list')
893
+ .map(([name]) => name));
894
+ // D153: a search never looks in a field hidden from the reader, so a match tells them nothing about it.
895
+ const searchFields = entity.def.search
896
+ ? entity.def.search.filter((f) => fields.has(f))
897
+ : {
898
+ refusal: `${entity.name} can't be searched: add search: ['field', …] to it in schema/, naming its text fields`,
899
+ };
734
900
  // D37: sorts and range filters need a declared index, as on the platform's data API.
735
901
  checkIndexCoverage(entity.name, entity.def.indexes, query, fields);
736
- const page = runQuery(readable, query, fields);
902
+ return { readable, fields, lists, searchFields };
903
+ }
904
+ /**
905
+ * D157: a stamp for each entity, different after any write to it, for a caller who may read the entity. It
906
+ * reads no records. An entity's stamp also moves with every table its rules look people up in (`listed:`),
907
+ * because a change there changes who may read what.
908
+ */
909
+ async dbChanges(ctx, value) {
910
+ const count = Object.keys(ctx.app.schema).length;
911
+ if (!Array.isArray(value) || value.length < 1 || value.length > count)
912
+ throw new QuadError('VALIDATION', "db.watch takes a list of one or more of the app's entities");
913
+ const names = new Map();
914
+ for (const item of value) {
915
+ const entity = this.dbEntity(ctx, item);
916
+ this.requireOperation(ctx, entity.name, entity.def, 'read');
917
+ const related = new Set([entity.name]);
918
+ for (const ops of Object.values(entity.def.access ?? {}))
919
+ for (const rules of Object.values(ops ?? {}))
920
+ for (const rule of Array.isArray(rules) ? rules : [rules]) {
921
+ const listed = parseListed(rule);
922
+ if (listed && ctx.app.schema[listed.entity])
923
+ related.add(listed.entity);
924
+ }
925
+ names.set(entity.name, [...related]);
926
+ }
927
+ const stamps = await this.store.versions(ctx.app.manifest.id, [
928
+ ...new Set([...names.values()].flat()),
929
+ ]);
930
+ return Object.fromEntries([...names].map(([name, related]) => [name, related.map((r) => stamps[r]).join('.')]));
931
+ }
932
+ /** D154: how many records match, of those the caller may read. */
933
+ async dbCount(ctx, entityValue, options) {
934
+ const entity = this.dbEntity(ctx, entityValue);
935
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
936
+ const query = queryOptions(options, ['where', 'search'], 'count');
937
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
938
+ const count = filterRows(readable, query, fields, lists, searchFields).length;
939
+ checkSummarySize(entity.name, count);
940
+ return count;
941
+ }
942
+ /** D154: the count, and totals of number fields, of the records the caller may read; by group when asked. */
943
+ async dbSummarise(ctx, entityValue, options) {
944
+ const entity = this.dbEntity(ctx, entityValue);
945
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
946
+ const query = queryOptions(options, ['where', 'search', 'groupBy', ...TOTALS], 'summarise');
947
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
948
+ const plan = summaryPlan(entity.name, entity.def, query, fields);
949
+ const rows = filterRows(readable, query, fields, lists, searchFields);
950
+ return summarise(entity.name, rows, plan);
951
+ }
952
+ async dbList(ctx, entityValue, options) {
953
+ const entity = this.dbEntity(ctx, entityValue);
954
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
955
+ const { include, ...query } = (isObject(options) ? options : {});
956
+ const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
957
+ if (!includes)
958
+ throw new QuadError('VALIDATION', 'include must be an array of ref field names');
959
+ for (const f of includes) {
960
+ const field = typeof f === 'string' ? fieldOf(entity.def, f) : undefined;
961
+ if (typeof f !== 'string' ||
962
+ !field ||
963
+ heldBy(field).kind !== 'ref' ||
964
+ !this.fieldVisible(ctx, entity.def, f)) {
965
+ throw new QuadError('VALIDATION', `include: '${String(f)}' is not a ref field of ${entity.name}`);
966
+ }
967
+ }
968
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
969
+ const page = runQuery(readable, query, fields, lists, searchFields);
737
970
  const items = page.items.map((r) => this.shapeRecord(ctx, entity.def, r));
738
971
  if (includes.length === 0)
739
972
  return { items, nextCursor: page.nextCursor };
@@ -741,8 +974,19 @@ export class Engine {
741
974
  const withIncluded = [];
742
975
  for (const r of items) {
743
976
  const included = {};
744
- for (const f of includes)
745
- included[f] = await this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads);
977
+ for (const f of includes) {
978
+ const field = entity.def.fields[f];
979
+ const held = heldBy(field);
980
+ if (field.kind !== 'list')
981
+ included[f] = await this.resolveRef(ctx, held, r[f], schoolReads);
982
+ else {
983
+ // D147: the linked records in the list's order, null where one is missing or out of reach.
984
+ const found = [];
985
+ for (const item of valuesOf(field, r[f]))
986
+ found.push(await this.resolveRef(ctx, held, item, schoolReads));
987
+ included[f] = found;
988
+ }
989
+ }
746
990
  withIncluded.push({ ...r, $included: included });
747
991
  }
748
992
  for (const [target, count] of schoolReads) {
@@ -771,16 +1015,129 @@ export class Engine {
771
1015
  ? this.shapeRecord(ctx, def, record)
772
1016
  : null;
773
1017
  }
774
- async dbDelete(ctx, entityValue, id) {
1018
+ async dbDelete(ctx, w, entityValue, id, options) {
775
1019
  const entity = this.dbEntity(ctx, entityValue);
776
- const existing = await this.readable(ctx, entity, id);
1020
+ const existing = await this.readable(ctx, entity, id, w);
777
1021
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
778
1022
  if (!this.matches(ctx, entity.def, rules, existing)) {
779
1023
  throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
780
1024
  }
781
- await this.store.deleteRecord(ctx.app.manifest.id, entity.name, existing);
1025
+ this.checkIf(ctx, entity, existing, options);
1026
+ await w.deleteRecord(entity.name, existing);
1027
+ // D148: a record's files go with it.
1028
+ for (const ids of filesNamed(entity.def, existing).values())
1029
+ for (const id of ids)
1030
+ w.deleteFile(id);
782
1031
  return null;
783
1032
  }
1033
+ // ---- files (D148, ADR 0039) ----
1034
+ /** A file nobody attached within a day of its upload is gone, by the engine's clock. */
1035
+ fileExpired(file) {
1036
+ return (!file.attachedTo &&
1037
+ file.sentWith === undefined &&
1038
+ this.nowMs() - Date.parse(file.createdAt) >= UNATTACHED_MS);
1039
+ }
1040
+ async filesUpload(ctx, params) {
1041
+ if (!schemaKeepsFiles(ctx.app.schema))
1042
+ throw new QuadError('VALIDATION', "this app's schema has no file field, so there is nowhere to attach a file: add file() to an entity in schema/");
1043
+ const { name, type, bytes } = checkUpload(params);
1044
+ const appId = ctx.app.manifest.id;
1045
+ let total = bytes.length;
1046
+ for (const kept of await this.store.allFiles(appId)) {
1047
+ if (this.fileExpired(kept))
1048
+ await this.store.deleteFile(appId, kept.id);
1049
+ else
1050
+ total += kept.size;
1051
+ }
1052
+ if (total > MAX_APP_FILE_BYTES)
1053
+ throw new QuadError('VALIDATION', `this app's files would total more than ${MAX_APP_FILE_BYTES / (1024 * 1024)} MB`);
1054
+ const file = {
1055
+ id: `file_${crypto.randomUUID()}`,
1056
+ name,
1057
+ type,
1058
+ size: bytes.length,
1059
+ createdAt: this.nowIso(),
1060
+ createdBy: ctx.actorId,
1061
+ };
1062
+ await this.store.putFile(appId, file, bytes);
1063
+ return fileInfo(file);
1064
+ }
1065
+ /**
1066
+ * A file the caller may read, or NOT_FOUND whether it is missing or just not theirs. Unattached, it is its
1067
+ * uploader's alone; attached, it follows the field of the record that holds it.
1068
+ */
1069
+ async readableFile(ctx, id) {
1070
+ const appId = ctx.app.manifest.id;
1071
+ const file = await this.store.getFile(appId, id);
1072
+ const missing = new QuadError('NOT_FOUND', `no file ${id}`);
1073
+ // A copy a notification carries is the message's, not a file an app reads (D152).
1074
+ if (!file || this.fileExpired(file) || file.sentWith !== undefined)
1075
+ throw missing;
1076
+ if (!file.attachedTo) {
1077
+ if (file.createdBy !== ctx.actorId)
1078
+ throw missing;
1079
+ return file;
1080
+ }
1081
+ const { entity, recordId, field } = file.attachedTo;
1082
+ const def = entityOf(ctx.app.schema, entity);
1083
+ const record = await this.store.getRecord(appId, entity, recordId);
1084
+ if (!def ||
1085
+ !record ||
1086
+ !this.canRead(ctx, def, record) ||
1087
+ !this.fieldVisible(ctx, def, field) ||
1088
+ !filesNamed(def, record).get(field)?.includes(id))
1089
+ throw missing;
1090
+ return file;
1091
+ }
1092
+ async filesRead(ctx, id) {
1093
+ const file = await this.readableFile(ctx, id);
1094
+ const bytes = await this.store.fileBytes(ctx.app.manifest.id, id);
1095
+ if (!bytes)
1096
+ throw new QuadError('NOT_FOUND', `no file ${id}`);
1097
+ return { info: fileInfo(file), data: toBase64(bytes) };
1098
+ }
1099
+ /**
1100
+ * What a write does to files: which to attach and which to remove. A file is attached once, by whoever uploaded
1101
+ * it, to one field of one record; an id the record's field already holds stays as it is.
1102
+ */
1103
+ async planFiles(ctx, w, entity, values, existing) {
1104
+ const next = filesNamed(entity.def, values);
1105
+ const before = existing ? filesNamed(entity.def, existing) : new Map();
1106
+ const named = new Set();
1107
+ for (const [field, ids] of before)
1108
+ if (!next.has(field))
1109
+ for (const id of ids)
1110
+ named.add(id);
1111
+ const attach = [];
1112
+ const remove = [];
1113
+ for (const [field, ids] of next) {
1114
+ const had = before.get(field) ?? [];
1115
+ for (const id of ids) {
1116
+ if (named.has(id))
1117
+ throw new QuadError('VALIDATION', `${field}: file ${id} is named more than once`);
1118
+ named.add(id);
1119
+ if (had.includes(id))
1120
+ continue;
1121
+ const file = await w.getFile(id);
1122
+ if (!file || this.fileExpired(file) || file.attachedTo || file.createdBy !== ctx.actorId)
1123
+ throw new QuadError('VALIDATION', `${field}: no file ${id} of yours to attach. Upload it with sdk.files.upload first; a file is attached once, by whoever uploaded it`);
1124
+ const problem = acceptProblem(heldBy(fieldOf(entity.def, field)), file);
1125
+ if (problem)
1126
+ throw new QuadError('VALIDATION', `${field}: ${problem}`);
1127
+ attach.push({ file, field });
1128
+ }
1129
+ for (const id of had)
1130
+ if (!ids.includes(id))
1131
+ remove.push(id);
1132
+ }
1133
+ return { attach, remove };
1134
+ }
1135
+ applyFiles(w, entity, recordId, files) {
1136
+ for (const { file, field } of files.attach)
1137
+ w.putFile({ ...file, attachedTo: { entity, recordId, field } });
1138
+ for (const id of files.remove)
1139
+ w.deleteFile(id);
1140
+ }
784
1141
  // ---- notify (D10, D17) ----
785
1142
  async notify(ctx, input) {
786
1143
  const { manifest } = ctx.app;
@@ -793,7 +1150,10 @@ export class Engine {
793
1150
  if (remembered !== undefined)
794
1151
  return remembered;
795
1152
  const subject = str(input.subject, 'subject');
796
- const body = str(input.body, 'body');
1153
+ // D151: a message in blocks, plain text, or both; with blocks alone the plain text is made from them.
1154
+ const content = input.content === undefined ? undefined : checkContent(input.content);
1155
+ const body = content && input.body === undefined ? plainText(content) : str(input.body, 'body');
1156
+ const attached = await this.attachmentsFor(ctx, input.attachments);
797
1157
  const channel = input.channel ?? 'inApp';
798
1158
  if (channel !== 'inApp' && channel !== 'email')
799
1159
  throw new QuadError('VALIDATION', "channel must be 'inApp' or 'email'");
@@ -810,7 +1170,9 @@ export class Engine {
810
1170
  throw new QuadError('VALIDATION', `no student ${regarding}`);
811
1171
  }
812
1172
  const { recipients, suppressed } = await this.resolveRecipients(ctx, input.to, regarding);
1173
+ this.checkAttachmentRoles(ctx, attached, recipients);
813
1174
  const sentAt = this.nowIso();
1175
+ const copies = recipients.length > 0 ? await this.copyAttachments(ctx, attached, sentAt) : [];
814
1176
  const entries = recipients.map((r) => ({
815
1177
  id: `out_${crypto.randomUUID()}`,
816
1178
  appId: manifest.id,
@@ -820,6 +1182,8 @@ export class Engine {
820
1182
  recipientRole: r.role,
821
1183
  subject,
822
1184
  body,
1185
+ ...(content ? { content } : {}),
1186
+ ...(copies.length > 0 ? { attachments: copies } : {}),
823
1187
  ...(typeof input.link === 'string' ? { link: input.link } : {}),
824
1188
  ...(r.regarding ? { regardingStudentId: r.regarding } : {}),
825
1189
  sentAt,
@@ -836,12 +1200,99 @@ export class Engine {
836
1200
  visibility: 'app',
837
1201
  data: { type, channel: channel, recipients: entries.map((e) => e.recipientId) },
838
1202
  });
1203
+ if (copies.length > 0)
1204
+ // For the school, not the app: which files left their records, and for whom (D152).
1205
+ await appendAudit(this, ctx.app, {
1206
+ source: 'platform',
1207
+ action: 'notification.attachments',
1208
+ actor: ctx.actorId,
1209
+ summary: `${copies.length} file${copies.length === 1 ? '' : 's'} sent with ${type} to ${entries.length} recipient${entries.length === 1 ? '' : 's'}`,
1210
+ entity: 'notification',
1211
+ visibility: 'cio',
1212
+ data: {
1213
+ type,
1214
+ recipients: entries.map((e) => e.recipientId),
1215
+ files: attached.map((f) => ({ name: f.name, ...(f.attachedTo ?? {}) })),
1216
+ },
1217
+ });
839
1218
  await this.auditSuppressed(ctx, 'notification.suppressed', type, suppressed);
840
1219
  const result = { recipients: recipients.map(({ personId, role }) => ({ personId, role })) };
841
1220
  if (key)
842
1221
  await this.remember(ctx, key, result);
843
1222
  return result;
844
1223
  }
1224
+ /** D152: the files a notification names, each one the sender can read, within the limits. */
1225
+ async attachmentsFor(ctx, value) {
1226
+ if (value === undefined)
1227
+ return [];
1228
+ if (!Array.isArray(value) ||
1229
+ value.length === 0 ||
1230
+ value.length > MAX_ATTACHMENTS ||
1231
+ !value.every((id) => typeof id === 'string' && id.length > 0) ||
1232
+ new Set(value).size !== value.length)
1233
+ throw new QuadError('VALIDATION', `attachments: 1 to ${MAX_ATTACHMENTS} different file ids`);
1234
+ const files = [];
1235
+ for (const id of value)
1236
+ files.push(await this.readableFile(ctx, id));
1237
+ if (files.reduce((n, f) => n + f.size, 0) > MAX_ATTACHMENT_BYTES)
1238
+ throw new QuadError('VALIDATION', `attachments can total at most ${MAX_ATTACHMENT_BYTES / (1024 * 1024)} MB`);
1239
+ return files;
1240
+ }
1241
+ /**
1242
+ * D152: a file never goes to a role its field is hidden from (`visibleTo`), and one at a staff-only level goes
1243
+ * only to staff. The app declared both; a notification does not get round them.
1244
+ */
1245
+ checkAttachmentRoles(ctx, files, recipients) {
1246
+ for (const file of files) {
1247
+ if (!file.attachedTo)
1248
+ continue;
1249
+ const { entity, field } = file.attachedTo;
1250
+ const def = entityOf(ctx.app.schema, entity);
1251
+ const fieldDef = def ? fieldOf(def, field) : undefined;
1252
+ if (!fieldDef)
1253
+ continue;
1254
+ const allowed = STAFF_ONLY_TIERS.includes(fieldDef.tier)
1255
+ ? ['staff']
1256
+ : fieldDef.visibleTo?.map((r) => r.toLowerCase());
1257
+ const refused = allowed ? recipients.find((r) => !allowed.includes(r.role)) : undefined;
1258
+ if (refused)
1259
+ throw new QuadError('NOT_PERMITTED', `'${file.name}' comes from ${entity}.${field}, which only ${allowed.join(' and ')} may see, so it can't be sent to a ${refused.role}`);
1260
+ }
1261
+ }
1262
+ /** D152: the copies a message carries, made as it is sent, so they outlast the records they came from. */
1263
+ async copyAttachments(ctx, files, sentAt) {
1264
+ if (files.length === 0)
1265
+ return [];
1266
+ const appId = ctx.app.manifest.id;
1267
+ const kept = (await this.store.allFiles(appId)).reduce((n, f) => n + f.size, 0);
1268
+ if (kept + files.reduce((n, f) => n + f.size, 0) > MAX_APP_FILE_BYTES)
1269
+ throw new QuadError('VALIDATION', `this app's files would total more than ${MAX_APP_FILE_BYTES / (1024 * 1024)} MB`);
1270
+ const sentWith = `send_${crypto.randomUUID()}`;
1271
+ const copies = [];
1272
+ for (const file of files) {
1273
+ const bytes = await this.store.fileBytes(appId, file.id);
1274
+ if (!bytes)
1275
+ throw new QuadError('NOT_FOUND', `no file ${file.id}`);
1276
+ const copy = {
1277
+ id: `sent_${crypto.randomUUID()}`,
1278
+ name: file.name,
1279
+ type: file.type,
1280
+ size: file.size,
1281
+ createdAt: sentAt,
1282
+ createdBy: ctx.actorId,
1283
+ sentWith,
1284
+ };
1285
+ await this.store.putFile(appId, copy, bytes);
1286
+ copies.push({ id: copy.id, name: copy.name, type: copy.type, size: copy.size });
1287
+ }
1288
+ return copies;
1289
+ }
1290
+ /** A file a sent notification carries, for the shell's outbox and tests. Never part of the SDK. */
1291
+ async sentFile(appId, id) {
1292
+ const file = await this.store.getFile(appId, id);
1293
+ const bytes = file?.sentWith === undefined ? undefined : await this.store.fileBytes(appId, id);
1294
+ return file && bytes ? { info: fileInfo(file), bytes } : undefined;
1295
+ }
845
1296
  roleOf(personId) {
846
1297
  const entity = this.byId.get(personId)?.entity;
847
1298
  return entity === 'staff'