@quad-education/sdk 0.2.0 → 0.3.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 (39) hide show
  1. package/README.md +3 -2
  2. package/dist/contract-tests/apps.d.ts +1 -80
  3. package/dist/contract-tests/apps.js +1 -57
  4. package/dist/contract-tests/harness.d.ts +2 -2
  5. package/dist/contract-tests/index.d.ts +2 -3
  6. package/dist/contract-tests/index.js +1 -2
  7. package/dist/contract-tests/suite.d.ts +3 -10
  8. package/dist/contract-tests/suite.js +19 -205
  9. package/dist/src/client/connect.d.ts +3 -13
  10. package/dist/src/client/connect.js +3 -21
  11. package/dist/src/client/handshake-client.d.ts +0 -2
  12. package/dist/src/client/handshake-client.js +0 -2
  13. package/dist/src/contract/errors.d.ts +1 -1
  14. package/dist/src/contract/recipients.d.ts +2 -8
  15. package/dist/src/contract/types.d.ts +2 -18
  16. package/dist/src/contract/types.js +1 -1
  17. package/dist/src/engine/engine.d.ts +8 -42
  18. package/dist/src/engine/engine.js +34 -173
  19. package/dist/src/engine/host.d.ts +2 -2
  20. package/dist/src/engine/in-process.d.ts +2 -2
  21. package/dist/src/engine/runner.js +2 -4
  22. package/dist/src/engine/state.d.ts +6 -17
  23. package/dist/src/engine/state.js +3 -31
  24. package/dist/src/engine/tasks.js +3 -10
  25. package/dist/src/index.d.ts +0 -1
  26. package/dist/src/index.js +0 -1
  27. package/dist/src/jobs/define.d.ts +2 -2
  28. package/dist/src/platform-types.d.ts +2 -2
  29. package/package.json +4 -4
  30. package/dist/contract-tests/standalone-apps.d.ts +0 -183
  31. package/dist/contract-tests/standalone-apps.js +0 -178
  32. package/dist/contract-tests/standalone.d.ts +0 -2
  33. package/dist/contract-tests/standalone.js +0 -709
  34. package/dist/src/client/http-transport.d.ts +0 -18
  35. package/dist/src/client/http-transport.js +0 -76
  36. package/dist/src/client/live.d.ts +0 -39
  37. package/dist/src/client/live.js +0 -122
  38. package/dist/src/contract/principals.d.ts +0 -30
  39. package/dist/src/contract/principals.js +0 -12
@@ -1,30 +1,12 @@
1
1
  import { portTransport } from "../port-rpc.js";
2
2
  import { createSdkClient } from "./create-client.js";
3
- import { handshake, isFramed } from "./handshake-client.js";
4
- import { connectSignedIn, getLiveStatus, signIn } from "./live.js";
3
+ import { handshake } from "./handshake-client.js";
5
4
  export { DEFAULT_SHELL_ORIGIN } from "./handshake-client.js";
6
- export { connectHttp, createHttpTransport, } from "./http-transport.js";
7
- export { SignInRequired, connectLive, continueAsGuest, getLiveStatus, signIn, } from "./live.js";
8
5
  /**
9
- * Connect to the platform. In the demo shell's iframe (the Sandbox and `quad dev`), the shell hands over a
10
- * private MessagePort and every SDK call goes through it. At a live address there is no shell: the app asks its
11
- * own origin who is signed in and talks to the data API with a token. The same built code does both.
12
- *
13
- * Live and nobody signed in: if the app allows guests this throws `SignInRequired` (with `guests: true`) so the
14
- * app can offer both choices; otherwise the page goes to Quad's sign-in and this never settles.
6
+ * Connect to the platform. In V1 the app runs in the demo shell's iframe; the shell hands
7
+ * over a private MessagePort, and every SDK call goes through it.
15
8
  */
16
9
  export async function connect(options = {}) {
17
- if (options.live || !isFramed()) {
18
- const live = options.live ?? {};
19
- const status = await getLiveStatus(live);
20
- if (!status.signedIn && !status.guests) {
21
- signIn(live);
22
- return never();
23
- }
24
- return connectSignedIn(status, live);
25
- }
26
10
  const { port, session } = await handshake(options);
27
11
  return createSdkClient(portTransport(port, session.clock), session);
28
12
  }
29
- /** A page that is leaving has nothing to resolve to. */
30
- const never = () => new Promise(() => { });
@@ -6,8 +6,6 @@ export type HandshakeOptions = {
6
6
  timeoutMs?: number;
7
7
  };
8
8
  export declare const DEFAULT_SHELL_ORIGIN: string;
9
- /** Whether this page is inside another frame, as an app in the demo shell is. */
10
- export declare const isFramed: () => boolean;
11
9
  /**
12
10
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
13
11
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -2,8 +2,6 @@ import { QuadError } from "../contract/errors.js";
2
2
  import { isHello } from "../handshake.js";
3
3
  const env = import.meta.env;
4
4
  export const DEFAULT_SHELL_ORIGIN = env?.VITE_QUAD_SHELL_ORIGIN ?? 'http://localhost:5173';
5
- /** Whether this page is inside another frame, as an app in the demo shell is. */
6
- export const isFramed = () => typeof window !== 'undefined' && window.parent !== window;
7
5
  /**
8
6
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
9
7
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -1,5 +1,5 @@
1
1
  /** Error codes the SDK contract can return. Both implementations use the same codes. */
2
- export type QuadErrorCode = 'SCOPE_NOT_GRANTED' | 'UNDECLARED_TYPE' | 'NOT_FOUND' | 'VALIDATION' | 'FORBIDDEN' | 'NOT_AVAILABLE' | 'NOT_PERMITTED' | 'NOT_ASSIGNEE' | 'TRANSPORT' | 'INTERNAL';
2
+ export type QuadErrorCode = 'SCOPE_NOT_GRANTED' | 'UNDECLARED_TYPE' | 'NOT_FOUND' | 'VALIDATION' | 'FORBIDDEN' | 'NOT_PERMITTED' | 'NOT_ASSIGNEE' | 'TRANSPORT' | 'INTERNAL';
3
3
  export declare class QuadError extends Error {
4
4
  readonly code: QuadErrorCode;
5
5
  readonly details: unknown;
@@ -5,14 +5,8 @@ import type { ContactPurpose, Role } from '@quad-education/canonical';
5
5
  */
6
6
  export type Recipient = {
7
7
  readonly person: string;
8
- }
9
- /** A school role, or (outside a school) one of the app's own roles (V2c, D100). */
10
- | {
11
- readonly role: Role | (string & {});
12
- }
13
- /** A Quad account, outside a school (V2c, D100). */
14
- | {
15
- readonly account: string;
8
+ } | {
9
+ readonly role: Role;
16
10
  } | {
17
11
  readonly relationship: 'parentsOf';
18
12
  readonly studentId: string;
@@ -1,7 +1,7 @@
1
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.2.0";
4
+ export declare const SDK_VERSION = "0.3.0";
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.
@@ -78,22 +78,6 @@ export type Me = {
78
78
  readonly kind: 'user';
79
79
  readonly role: Role;
80
80
  readonly person: PersonSummary;
81
- }
82
- /** A Quad account using an app, with the app-defined roles it was assigned (V2c, D100). */
83
- | {
84
- readonly kind: 'account';
85
- readonly account: {
86
- readonly id: string;
87
- readonly displayName: string;
88
- };
89
- readonly roles: readonly string[];
90
- }
91
- /** Someone not signed in, identified only by a device id (V2c, D100). */
92
- | {
93
- readonly kind: 'guest';
94
- readonly guest: {
95
- readonly id: string;
96
- };
97
81
  } | {
98
82
  readonly kind: 'system';
99
83
  readonly appId: string;
@@ -257,7 +241,7 @@ export type NotifyInput<A extends AppConfig> = {
257
241
  };
258
242
  export type ResolvedRecipient = {
259
243
  readonly personId: string;
260
- readonly role: Role | (string & {});
244
+ readonly role: Role;
261
245
  };
262
246
  export type NotifyApi<A extends AppConfig> = {
263
247
  /**
@@ -1 +1 @@
1
- export const SDK_VERSION = '0.2.0';
1
+ export const SDK_VERSION = '0.3.0';
@@ -1,26 +1,18 @@
1
- import { type Dataset } from '@quad-education/canonical';
1
+ import { type Dataset, type Principal } from '@quad-education/canonical';
2
2
  import { type AppSchema, type Manifest } from '@quad-education/schema';
3
- import { type AccountDirectory, type AccountRecord, type ActingAs } from '../contract/principals.ts';
4
3
  import type { OutboxEntry } from '../platform-types.ts';
5
4
  import { type ClockState, type Method, type SessionInfo } from '../protocol.ts';
6
5
  import { type RunRequest, type RunResult } from './runner.ts';
7
6
  import { type App, type Ctx, type Kernel, type ResolvedRecipients, type StoredRun } from './state.ts';
8
7
  import type { AppStore, PlatformKind } from './store.ts';
9
8
  export type EngineOptions = {
10
- /** The school. Absent, with `school: false`, for an engine that has none, like the data API (V2c). */
11
- dataset?: Dataset;
9
+ dataset: Dataset;
12
10
  /** Where in-browser state is kept; ignored when `store` is given. */
13
11
  indexedDB?: IDBFactory;
14
- /** Quad accounts a standalone app may notify and assign to, with their app roles (V2c, D100). */
15
- accounts?: readonly AccountRecord[] | AccountDirectory;
16
- /** False for an environment with no school: every school call is NOT_AVAILABLE (V2c, D100). */
17
- school?: boolean;
18
12
  /** IndexedDB database name; defaults to `quad-engine`. */
19
13
  dbName?: string;
20
- /** Keep state here instead of in memory and IndexedDB (the data API's DynamoDB store). */
14
+ /** Keep state here instead of in memory and IndexedDB (a school instance's data API, Phase 4). */
21
15
  store?: AppStore;
22
- /** The timezone of an engine with no school; defaults to Australia/Sydney. */
23
- timezone?: string;
24
16
  };
25
17
  export declare class Engine implements Kernel {
26
18
  private readonly apps;
@@ -28,33 +20,14 @@ export declare class Engine implements Kernel {
28
20
  private readonly byId;
29
21
  readonly dataset: Dataset;
30
22
  readonly store: AppStore;
31
- private readonly zone;
32
- private directory;
33
- private readonly hasSchool;
34
23
  private constructor();
35
24
  static create(options: EngineOptions): Promise<Engine>;
36
25
  close(): void;
37
26
  /** Load an app, resetting its store if the schema changed since last time (D12). */
38
- installApp({ manifest, schema, timezone, }: {
27
+ installApp({ manifest, schema }: {
39
28
  manifest: unknown;
40
29
  schema: AppSchema;
41
- timezone?: string;
42
30
  }): Promise<void>;
43
- /**
44
- * Register an app that is already installed in the store, without touching its state. A stateless server
45
- * (the data API) does this on each cold start; `installApp` is for publishing and reinstalling.
46
- */
47
- attachApp({ manifest, schema, timezone, }: {
48
- manifest: unknown;
49
- schema: AppSchema;
50
- timezone?: string;
51
- }): void;
52
- /** Whether an app is registered with this engine. */
53
- hasApp(appId: string): boolean;
54
- /** Replace the account directory (the shell rebuilds it when a previewed app's roles change). */
55
- setAccounts(accounts: readonly AccountRecord[]): void;
56
- /** Whether the app has no school here, so its people are accounts and guests (V2c, D100). */
57
- isStandalone(appId: string): boolean;
58
31
  manifest(appId: string): Manifest;
59
32
  /** Clear an app's data and outbox (the shell's reset button). */
60
33
  resetApp(appId: string): Promise<void>;
@@ -95,7 +68,7 @@ export declare class Engine implements Kernel {
95
68
  * Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
96
69
  * Only runs that are currently running count, so a finished run's id can't be replayed.
97
70
  */
98
- runPrincipal(appId: string, runId: string | undefined): Promise<ActingAs>;
71
+ runPrincipal(appId: string, runId: string | undefined): Promise<Principal>;
99
72
  /** Start due runs; the caller executes each as its `runAs` principal and calls finishRun. */
100
73
  startDueRuns(appId: string): Promise<RunRequest[]>;
101
74
  finishRun(appId: string, runId: string, result: RunResult): Promise<void>;
@@ -103,7 +76,7 @@ export declare class Engine implements Kernel {
103
76
  redeliverRun(appId: string, runId: string): Promise<void>;
104
77
  /** Move the demo clock forward (D14). Works whether it's frozen or running. */
105
78
  advanceClock(ms: number): void;
106
- timezone(app?: App): string;
79
+ timezone(): string;
107
80
  persistPlatform(app: App, kind: PlatformKind, items: readonly {
108
81
  id: string;
109
82
  }[]): Promise<void>;
@@ -118,10 +91,8 @@ export declare class Engine implements Kernel {
118
91
  nowMs(): number;
119
92
  sessionInfo(appId: string): SessionInfo;
120
93
  /** Handle one SDK call from `appId` on behalf of `principal`. */
121
- handle(appId: string, principal: ActingAs, method: Method, params: unknown): Promise<unknown>;
94
+ handle(appId: string, principal: Principal, method: Method, params: unknown): Promise<unknown>;
122
95
  private appFor;
123
- /** A school app, in an environment that has a school: standalone apps and school-less environments have none. */
124
- private usesSchool;
125
96
  private context;
126
97
  private me;
127
98
  private schoolInfo;
@@ -180,15 +151,10 @@ export declare class Engine implements Kernel {
180
151
  * reached about a specific student, and only through an eligible, unrestricted link.
181
152
  */
182
153
  resolveRecipients(ctx: Ctx, to: unknown, regarding: string | undefined): Promise<ResolvedRecipients>;
183
- /**
184
- * Recipients outside a school (V2c, D100): Quad accounts, by id or by one of the app's own roles, from the
185
- * account directory. Everything that needs a school is NOT_AVAILABLE. Guests have no address, so never appear.
186
- */
187
- private resolveAppRecipients;
188
154
  private suppressionReason;
189
155
  /** D17/D19: each suppressed parent is recorded, visible only to the CIO view. */
190
156
  private auditSuppressed;
191
157
  /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
192
158
  private auditSensitiveRead;
193
159
  }
194
- export declare const ENGINE_SDK_VERSION = "0.2.0";
160
+ export declare const ENGINE_SDK_VERSION = "0.3.0";
@@ -1,14 +1,13 @@
1
1
  import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
- import { DEFAULT_ACCESS, classify, parseManifest, schemaHash, schoolRolesOf, servedRoles, } from '@quad-education/schema';
2
+ import { DEFAULT_ACCESS, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
3
3
  import { QuadError } from "../contract/errors.js";
4
- import { staticDirectory, } from "../contract/principals.js";
5
4
  import { SDK_VERSION } from "../contract/types.js";
6
5
  import { clockNow } from "../protocol.js";
7
6
  import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
8
7
  import { checkIndexCoverage } from "./db-indexes.js";
9
8
  import { runQuery } from "./query.js";
10
9
  import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
11
- import { isStaffOrSystem, roleNamesOf, schoolPrincipal, } from "./state.js";
10
+ import { isStaffOrSystem, } from "./state.js";
12
11
  import { MemoryStore } from "./memory-store.js";
13
12
  import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
14
13
  import { entityOf, fieldOf, validateInput } from "./validate-input.js";
@@ -37,18 +36,9 @@ export class Engine {
37
36
  byId = new Map();
38
37
  dataset;
39
38
  store;
40
- zone;
41
- directory;
42
- hasSchool;
43
- constructor(dataset, store, directory, hasSchool, zone) {
44
- // With no school nothing reaches the dataset: every school call is refused first (`schoolPrincipal`).
45
- this.dataset = dataset ?? {};
39
+ constructor(dataset, store) {
40
+ this.dataset = dataset;
46
41
  this.store = store;
47
- this.directory = directory;
48
- this.hasSchool = hasSchool;
49
- this.zone = zone;
50
- if (!dataset || !hasSchool)
51
- return;
52
42
  for (const entity of Object.keys(ENTITIES)) {
53
43
  if (isDerived(entity)) {
54
44
  // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
@@ -63,63 +53,27 @@ export class Engine {
63
53
  }
64
54
  }
65
55
  static async create(options) {
66
- const hasSchool = options.school !== false;
67
- if (hasSchool && !options.dataset)
68
- throw new Error('an engine with a school needs a dataset');
69
56
  const store = options.store ??
70
57
  (options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
71
58
  if (!store)
72
59
  throw new Error('an engine needs a store or an IndexedDB factory');
73
- const zone = hasSchool
74
- ? options.dataset.schools[0].timezone
75
- : (options.timezone ?? 'Australia/Sydney');
76
- const accounts = options.accounts ?? [];
77
- const directory = Array.isArray(accounts)
78
- ? staticDirectory(accounts)
79
- : accounts;
80
- return new Engine(options.dataset, store, directory, hasSchool, zone);
60
+ return new Engine(options.dataset, store);
81
61
  }
82
62
  close() {
83
63
  void this.store.close();
84
64
  }
85
65
  // ---- Platform-side API (shell and tests) ----
86
66
  /** Load an app, resetting its store if the schema changed since last time (D12). */
87
- async installApp({ manifest, schema, timezone, }) {
67
+ async installApp({ manifest, schema }) {
88
68
  const parsed = parseManifest(manifest);
89
69
  if (!parsed.ok)
90
70
  throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
91
71
  const appId = parsed.manifest.id;
92
72
  await this.store.open(appId, schemaHash(schema), schema);
93
- const app = { manifest: parsed.manifest, schema, ...(timezone ? { timezone } : {}) };
73
+ const app = { manifest: parsed.manifest, schema };
94
74
  this.apps.set(appId, app);
95
75
  await initCron(this, app);
96
76
  }
97
- /**
98
- * Register an app that is already installed in the store, without touching its state. A stateless server
99
- * (the data API) does this on each cold start; `installApp` is for publishing and reinstalling.
100
- */
101
- attachApp({ manifest, schema, timezone, }) {
102
- const parsed = parseManifest(manifest);
103
- if (!parsed.ok)
104
- throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
105
- this.apps.set(parsed.manifest.id, {
106
- manifest: parsed.manifest,
107
- schema,
108
- ...(timezone ? { timezone } : {}),
109
- });
110
- }
111
- /** Whether an app is registered with this engine. */
112
- hasApp(appId) {
113
- return this.apps.has(appId);
114
- }
115
- /** Replace the account directory (the shell rebuilds it when a previewed app's roles change). */
116
- setAccounts(accounts) {
117
- this.directory = staticDirectory(accounts);
118
- }
119
- /** Whether the app has no school here, so its people are accounts and guests (V2c, D100). */
120
- isStandalone(appId) {
121
- return !this.usesSchool(this.appFor(appId));
122
- }
123
77
  manifest(appId) {
124
78
  return this.appFor(appId).manifest;
125
79
  }
@@ -137,7 +91,6 @@ export class Engine {
137
91
  app,
138
92
  principal: { kind: 'system', appId },
139
93
  actorId: `system:${appId}`,
140
- school: this.usesSchool(app),
141
94
  };
142
95
  return (await inbox(this, appId, personId)).map((t) => taskView(ctx, t));
143
96
  }
@@ -205,8 +158,8 @@ export class Engine {
205
158
  : { kind: 'offset', offsetMs: this.clock.offsetMs + ms };
206
159
  }
207
160
  // ---- Kernel (used by the Slice B modules) ----
208
- timezone(app) {
209
- return app?.timezone ?? this.zone;
161
+ timezone() {
162
+ return this.dataset.schools[0].timezone;
210
163
  }
211
164
  async persistPlatform(app, kind, items) {
212
165
  await this.store.putPlatform(app.manifest.id, kind, items);
@@ -243,13 +196,12 @@ export class Engine {
243
196
  return clockNow(this.clock, Date.now());
244
197
  }
245
198
  sessionInfo(appId) {
246
- return { appId, timezone: this.timezone(this.appFor(appId)), clock: this.clock };
199
+ this.appFor(appId);
200
+ return { appId, timezone: this.timezone(), clock: this.clock };
247
201
  }
248
202
  /** Handle one SDK call from `appId` on behalf of `principal`. */
249
203
  async handle(appId, principal, method, params) {
250
- const ctx = await this.context(appId, principal);
251
- if (method.startsWith('school.'))
252
- schoolPrincipal(ctx);
204
+ const ctx = this.context(appId, principal);
253
205
  const p = (params ?? {});
254
206
  switch (method) {
255
207
  case 'auth.me':
@@ -315,40 +267,12 @@ export class Engine {
315
267
  throw new QuadError('NOT_FOUND', `app ${appId} is not installed`);
316
268
  return app;
317
269
  }
318
- /** A school app, in an environment that has a school: standalone apps and school-less environments have none. */
319
- usesSchool(app) {
320
- const m = app.manifest;
321
- return (this.hasSchool &&
322
- classify({
323
- roles: m.roles,
324
- schoolRoles: schoolRolesOf(m),
325
- scopes: m.scopes,
326
- entities: Object.keys(m.data ?? {}),
327
- connectorActions: [],
328
- }).class !== 'standalone');
329
- }
330
- async context(appId, principal) {
270
+ context(appId, principal) {
331
271
  const app = this.appFor(appId);
332
- const school = this.usesSchool(app);
333
272
  if (principal.kind === 'system') {
334
273
  if (principal.appId !== appId)
335
274
  throw new QuadError('FORBIDDEN', 'system principal belongs to another app');
336
- return { app, principal, actorId: `system:${appId}`, school };
337
- }
338
- if (principal.kind === 'guest') {
339
- if (!app.manifest.guests)
340
- throw new QuadError('FORBIDDEN', `${app.manifest.name} doesn't handle guests`);
341
- return { app, principal, actorId: `guest:${principal.guestId}`, school: false };
342
- }
343
- if (principal.kind === 'account') {
344
- const held = principal.roles.map((r) => r.toLowerCase());
345
- const served = app.manifest.roles.map((r) => r.toLowerCase());
346
- if (principal.displayName === undefined && !(await this.directory.get(principal.accountId)))
347
- throw new QuadError('FORBIDDEN', `no account ${principal.accountId}`);
348
- if (held.length === 0 || !held.every((r) => served.includes(r))) {
349
- throw new QuadError('FORBIDDEN', `${app.manifest.name} doesn't have those roles`);
350
- }
351
- return { app, principal, actorId: `acct:${principal.accountId}`, school: false };
275
+ return { app, principal, actorId: `system:${appId}` };
352
276
  }
353
277
  const person = this.byId.get(principal.personId);
354
278
  if (!person || person.entity !== PEOPLE[principal.role]) {
@@ -358,22 +282,12 @@ export class Engine {
358
282
  if (!servedRoles(app.manifest).includes(principal.role)) {
359
283
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
360
284
  }
361
- return { app, principal, actorId: principal.personId, school };
285
+ return { app, principal, actorId: principal.personId };
362
286
  }
363
- async me(ctx) {
287
+ me(ctx) {
364
288
  const { principal } = ctx;
365
289
  if (principal.kind === 'system')
366
290
  return { kind: 'system', appId: principal.appId };
367
- if (principal.kind === 'guest')
368
- return { kind: 'guest', guest: { id: principal.guestId } };
369
- if (principal.kind === 'account') {
370
- const displayName = principal.displayName ?? (await this.directory.get(principal.accountId))?.displayName;
371
- return {
372
- kind: 'account',
373
- account: { id: principal.accountId, displayName: displayName ?? principal.accountId },
374
- roles: [...principal.roles],
375
- };
376
- }
377
291
  const r = this.byId.get(principal.personId).record;
378
292
  return {
379
293
  kind: 'user',
@@ -412,7 +326,7 @@ export class Engine {
412
326
  if (granted.size === 0) {
413
327
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
414
328
  }
415
- const allowed = principalTiers(schoolPrincipal(ctx), entity);
329
+ const allowed = principalTiers(ctx.principal, entity);
416
330
  // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
417
331
  const entry = ctx.app.manifest.data?.[entity];
418
332
  const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
@@ -426,7 +340,7 @@ export class Engine {
426
340
  return fields;
427
341
  }
428
342
  visible(ctx, entity) {
429
- return visibleRecords(schoolPrincipal(ctx), entity, this.dataset);
343
+ return visibleRecords(ctx.principal, entity, this.dataset);
430
344
  }
431
345
  /**
432
346
  * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
@@ -440,13 +354,13 @@ export class Engine {
440
354
  : undefined;
441
355
  if (typeof select !== 'function')
442
356
  return this.visible(ctx, entity);
443
- ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
357
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
444
358
  const made = select.call(this.dataset, entity, { where, students: ctx.students });
445
359
  if (made === null)
446
360
  return this.visible(ctx, entity);
447
361
  if (!made.ok)
448
362
  throw new QuadError('VALIDATION', made.message);
449
- return visibleRecords(schoolPrincipal(ctx), entity, this.dataset, made.rows);
363
+ return visibleRecords(ctx.principal, entity, this.dataset, made.rows);
450
364
  }
451
365
  shape(entity, grant, records) {
452
366
  return records.map((r) => filterFields(entity, r, grant, grant.declared));
@@ -544,29 +458,18 @@ export class Engine {
544
458
  return 'system';
545
459
  const policy = def.access ?? DEFAULT_ACCESS;
546
460
  // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
547
- // An account holds several app roles: it gets the union of their rules (V2c, D100).
548
- const out = new Set();
549
- for (const role of roleNamesOf(ctx.principal)) {
550
- const key = Object.hasOwn(policy, role)
551
- ? role
552
- : Object.keys(policy).find((k) => k.toLowerCase() === role.toLowerCase());
553
- const value = key === undefined ? undefined : policy[key]?.[op];
554
- if (value === undefined)
555
- continue;
556
- for (const rule of Array.isArray(value) ? value : [value]) {
557
- // A guest only ever reaches their own records, whatever the policy says.
558
- if (ctx.principal.kind === 'guest' && rule !== 'own')
559
- continue;
560
- out.add(rule);
561
- }
562
- }
563
- return [...out];
461
+ const role = ctx.principal.role;
462
+ const key = Object.hasOwn(policy, role)
463
+ ? role
464
+ : Object.keys(policy).find((k) => k.toLowerCase() === role);
465
+ const value = key === undefined ? undefined : policy[key]?.[op];
466
+ return value === undefined ? [] : Array.isArray(value) ? value : [value];
564
467
  }
565
468
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
566
469
  seesStudent(ctx, studentId) {
567
470
  if (typeof studentId !== 'string')
568
471
  return false;
569
- ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
472
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
570
473
  return ctx.students === 'all'
571
474
  ? this.byId.get(studentId)?.entity === 'students'
572
475
  : ctx.students.has(studentId);
@@ -577,7 +480,6 @@ export class Engine {
577
480
  return rules.some((rule) => rule === 'all' ||
578
481
  (rule === 'own' && record.createdBy === ctx.actorId) ||
579
482
  (rule === 'subject' &&
580
- ctx.school &&
581
483
  def.subject !== undefined &&
582
484
  this.seesStudent(ctx, record[def.subject])));
583
485
  }
@@ -587,9 +489,11 @@ export class Engine {
587
489
  /** Fields the current role may see or write (D25 visibleTo). The system principal sees all. */
588
490
  fieldVisible(ctx, def, field) {
589
491
  const visibleTo = fieldOf(def, field)?.visibleTo;
590
- return (ctx.principal.kind === 'system' ||
591
- visibleTo === undefined ||
592
- roleNamesOf(ctx.principal).some((r) => visibleTo.some((v) => v.toLowerCase() === r.toLowerCase())));
492
+ if (ctx.principal.kind === 'system' || visibleTo === undefined)
493
+ return true;
494
+ // Written in any case: an app role `Staff` is previewed by the staff persona.
495
+ const role = ctx.principal.role;
496
+ return visibleTo.some((v) => v.toLowerCase() === role);
593
497
  }
594
498
  /** A record as the current role receives it: hidden fields removed, not just emptied. */
595
499
  shapeRecord(ctx, def, record) {
@@ -602,7 +506,7 @@ export class Engine {
602
506
  requireOperation(ctx, entity, def, op) {
603
507
  const rules = this.rules(ctx, def, op);
604
508
  if (rules !== 'system' && rules.length === 0) {
605
- const who = ctx.principal.kind === 'system' ? 'system' : roleNamesOf(ctx.principal).join('/');
509
+ const who = ctx.principal.kind === 'system' ? 'system' : ctx.principal.role;
606
510
  throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
607
511
  }
608
512
  return rules;
@@ -623,10 +527,7 @@ export class Engine {
623
527
  }
624
528
  }
625
529
  const subject = entity.def.subject;
626
- if (subject !== undefined &&
627
- subject in values &&
628
- ctx.principal.kind !== 'system' &&
629
- ctx.school) {
530
+ if (subject !== undefined && subject in values && ctx.principal.kind !== 'system') {
630
531
  if (!this.seesStudent(ctx, values[subject])) {
631
532
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${subject}: not a student you can see`);
632
533
  }
@@ -875,10 +776,6 @@ export class Engine {
875
776
  if (list.length === 0)
876
777
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
877
778
  const roles = servedRoles(ctx.app.manifest);
878
- if (ctx.principal.kind === 'guest')
879
- throw new QuadError('FORBIDDEN', 'guests cannot send notifications or assign tasks');
880
- if (!ctx.school)
881
- return await this.resolveAppRecipients(ctx, list);
882
779
  const senderIsStaff = isStaffOrSystem(ctx);
883
780
  const out = new Map();
884
781
  const suppressed = new Map();
@@ -985,42 +882,6 @@ export class Engine {
985
882
  }
986
883
  return { recipients: [...out.values()], suppressed: [...suppressed.values()] };
987
884
  }
988
- /**
989
- * Recipients outside a school (V2c, D100): Quad accounts, by id or by one of the app's own roles, from the
990
- * account directory. Everything that needs a school is NOT_AVAILABLE. Guests have no address, so never appear.
991
- */
992
- async resolveAppRecipients(ctx, list) {
993
- const appRoles = ctx.app.manifest.roles;
994
- const out = new Map();
995
- for (const r of list) {
996
- if (!isObject(r))
997
- throw new QuadError('VALIDATION', 'each recipient must be an object');
998
- if ('account' in r) {
999
- const account = await this.directory.get(str(r.account, 'account'));
1000
- if (!account)
1001
- throw new QuadError('VALIDATION', `no account ${String(r.account)}`);
1002
- const role = appRoles.find((a) => account.roles.some((x) => x.toLowerCase() === a.toLowerCase()));
1003
- out.set(`acct:${account.id}`, {
1004
- personId: `acct:${account.id}`,
1005
- role: role ?? account.roles[0],
1006
- });
1007
- }
1008
- else if ('role' in r) {
1009
- const role = appRoles.find((a) => a.toLowerCase() === String(r.role).toLowerCase());
1010
- if (role === undefined)
1011
- throw new QuadError('VALIDATION', `${ctx.app.manifest.name} has no role ${String(r.role)}`);
1012
- for (const a of await this.directory.withRole(role))
1013
- out.set(`acct:${a.id}`, { personId: `acct:${a.id}`, role });
1014
- }
1015
- else if ('person' in r || 'relationship' in r) {
1016
- throw new QuadError('NOT_AVAILABLE', 'there is no school here: people and relationships need one');
1017
- }
1018
- else {
1019
- throw new QuadError('VALIDATION', 'unknown recipient; use { account } or { role }');
1020
- }
1021
- }
1022
- return { recipients: [...out.values()], suppressed: [] };
1023
- }
1024
885
  suppressionReason(parentId, studentId, purpose) {
1025
886
  const link = this.dataset.parentStudentLinks.find((l) => l.parentId === parentId && l.studentId === studentId);
1026
887
  if (!link)
@@ -1,4 +1,4 @@
1
- import type { ActingAs } from '../contract/principals.ts';
1
+ import type { Principal } from '@quad-education/canonical';
2
2
  import type { RunRequest, RunResult } from '../jobs/define.ts';
3
3
  import type { Engine } from './engine.ts';
4
4
  export type RejectedMessage = {
@@ -11,7 +11,7 @@ export type HostedFrame = {
11
11
  readonly kind: 'ui' | 'jobs';
12
12
  readonly iframe: HTMLIFrameElement;
13
13
  /** Who the frame acts as. The app never chooses its own principal. */
14
- readonly principal: () => ActingAs;
14
+ readonly principal: () => Principal;
15
15
  };
16
16
  export type HostOptions = {
17
17
  engine: Engine;
@@ -1,5 +1,5 @@
1
- import type { ActingAs } from '../contract/principals.ts';
1
+ import type { Principal } from '@quad-education/canonical';
2
2
  import type { QuadSdk } from '../contract/types.ts';
3
3
  import type { Engine } from './engine.ts';
4
4
  /** An SDK connected to an engine in the same JavaScript context (tests). */
5
- export declare function connectInProcess(engine: Engine, appId: string, principal: ActingAs): QuadSdk;
5
+ export declare function connectInProcess(engine: Engine, appId: string, principal: Principal): QuadSdk;