@quad-education/sdk 0.1.4 → 0.2.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 (54) hide show
  1. package/README.md +1 -0
  2. package/dist/contract-tests/apps.d.ts +79 -0
  3. package/dist/contract-tests/apps.js +56 -0
  4. package/dist/contract-tests/harness.d.ts +11 -0
  5. package/dist/contract-tests/harness.js +40 -0
  6. package/dist/contract-tests/helpers.d.ts +5 -0
  7. package/dist/contract-tests/helpers.js +25 -0
  8. package/dist/contract-tests/index.d.ts +4 -2
  9. package/dist/contract-tests/index.js +3 -1
  10. package/dist/contract-tests/standalone-apps.d.ts +183 -0
  11. package/dist/contract-tests/standalone-apps.js +178 -0
  12. package/dist/contract-tests/standalone.d.ts +2 -0
  13. package/dist/contract-tests/standalone.js +709 -0
  14. package/dist/contract-tests/suite.d.ts +10 -3
  15. package/dist/contract-tests/suite.js +207 -42
  16. package/dist/src/client/connect.d.ts +13 -3
  17. package/dist/src/client/connect.js +21 -3
  18. package/dist/src/client/handshake-client.d.ts +2 -0
  19. package/dist/src/client/handshake-client.js +2 -0
  20. package/dist/src/client/http-transport.d.ts +18 -0
  21. package/dist/src/client/http-transport.js +76 -0
  22. package/dist/src/client/live.d.ts +39 -0
  23. package/dist/src/client/live.js +122 -0
  24. package/dist/src/contract/errors.d.ts +1 -1
  25. package/dist/src/contract/principals.d.ts +30 -0
  26. package/dist/src/contract/principals.js +12 -0
  27. package/dist/src/contract/recipients.d.ts +8 -2
  28. package/dist/src/contract/types.d.ts +18 -2
  29. package/dist/src/contract/types.js +1 -1
  30. package/dist/src/engine/audit.d.ts +2 -2
  31. package/dist/src/engine/audit.js +8 -6
  32. package/dist/src/engine/db-indexes.js +6 -1
  33. package/dist/src/engine/engine.d.ts +53 -17
  34. package/dist/src/engine/engine.js +260 -156
  35. package/dist/src/engine/host.d.ts +2 -2
  36. package/dist/src/engine/host.js +1 -1
  37. package/dist/src/engine/in-process.d.ts +2 -2
  38. package/dist/src/engine/index.d.ts +3 -1
  39. package/dist/src/engine/index.js +1 -0
  40. package/dist/src/engine/memory-store.d.ts +32 -0
  41. package/dist/src/engine/memory-store.js +123 -0
  42. package/dist/src/engine/runner.d.ts +2 -2
  43. package/dist/src/engine/runner.js +31 -26
  44. package/dist/src/engine/state.d.ts +21 -15
  45. package/dist/src/engine/state.js +31 -3
  46. package/dist/src/engine/store.d.ts +48 -0
  47. package/dist/src/engine/store.js +1 -0
  48. package/dist/src/engine/tasks.d.ts +4 -6
  49. package/dist/src/engine/tasks.js +27 -24
  50. package/dist/src/index.d.ts +1 -0
  51. package/dist/src/index.js +1 -0
  52. package/dist/src/jobs/define.d.ts +2 -2
  53. package/dist/src/platform-types.d.ts +2 -2
  54. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
- import { type Principal } from '@quad-education/canonical';
1
+ import type { ActingAs } from '../src/contract/principals.ts';
2
2
  import type { AppSchema, Manifest } from '@quad-education/schema';
3
3
  import type { OutboxEntry } from '../src/platform-types.ts';
4
4
  import type { Job } from '../src/jobs/index.ts';
@@ -19,7 +19,7 @@ export type RunSummary = {
19
19
  /** One running implementation of the SDK contract, loaded with the fictional school. */
20
20
  export type ContractEnv = {
21
21
  /** An SDK connected as `principal`. Every connection shares the same engine and storage. */
22
- connect(principal: Principal): Promise<any>;
22
+ connect(principal: ActingAs): Promise<any>;
23
23
  control: {
24
24
  /** Freeze the engine clock at an instant, or `null` for real time. */
25
25
  setClock(iso: string | null): Promise<void>;
@@ -54,4 +54,11 @@ export type ContractEnv = {
54
54
  dispose(): Promise<void>;
55
55
  };
56
56
  export type ContractFactory = (app: TestApp) => Promise<ContractEnv>;
57
- export declare function defineContractSuite(name: string, factory: ContractFactory): void;
57
+ /**
58
+ * What the implementation under test has. The data API holds no school (non-negotiable 13), so it passes
59
+ * `school: false`: the sections that use school personas and school data are skipped, and the standalone ones run.
60
+ */
61
+ export type ContractOptions = {
62
+ school?: boolean;
63
+ };
64
+ export declare function defineContractSuite(name: string, factory: ContractFactory, options?: ContractOptions): void;
@@ -3,8 +3,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
3
  import { eligibleParents } from '@quad-education/canonical';
4
4
  import { personasFor, withDerived } from '@quad-education/fictional-school';
5
5
  import stored from '@quad-education/fictional-school/dataset' with { type: 'json' };
6
- import { isQuadError, parentsOf, staffOf, studentsOf } from "../src/index.js";
7
- import { ACCESS_APP, AWARDS_APP, BASIC_APP, DATA_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, ROLES_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
6
+ import { parentsOf, staffOf, studentsOf } from "../src/index.js";
7
+ import { ACCESS_APP, ACCOUNT_APP, AWARDS_APP, BASIC_APP, DATA_APP, DEMOGRAPHICS_APP, HR_APP, JOBS_APP, ROLES_APP, TEST_APP, WELLBEING_APP, slowGate, } from "./apps.js";
8
+ import { expectError, ids, listAll } from "./helpers.js";
9
+ import { defineStandaloneSections } from "./standalone.js";
8
10
  // The fictional school is the oracle: tests compare what the SDK returns with what the
9
11
  // dataset says should be visible. They never read an implementation's storage.
10
12
  const ds = withDerived(stored);
@@ -23,29 +25,9 @@ const RESTRICTED_PARENT = persona('restricted-parent');
23
25
  const childrenOf = (parentId) => ds.parentStudentLinks
24
26
  .filter((l) => l.parentId === parentId && !l.contactRestricted)
25
27
  .map((l) => l.studentId);
26
- async function listAll(collection, options = {}) {
27
- const items = [];
28
- let cursor;
29
- do {
30
- const page = await collection.list({ ...options, limit: 200, ...(cursor ? { cursor } : {}) });
31
- items.push(...page.items);
32
- cursor = page.nextCursor ?? undefined;
33
- } while (cursor);
34
- return items;
35
- }
36
- async function expectError(promise, code) {
37
- try {
38
- await promise;
39
- }
40
- catch (e) {
41
- expect(isQuadError(e), `expected a QuadError, got ${String(e)}`).toBe(true);
42
- expect(e.code).toBe(code);
43
- return e;
44
- }
45
- throw new Error(`expected ${code}, but the call succeeded`);
46
- }
47
- const ids = (records) => records.map((r) => r.id).sort();
48
- export function defineContractSuite(name, factory) {
28
+ export function defineContractSuite(name, factory, options = {}) {
29
+ const school = options.school !== false;
30
+ const schoolDescribe = school ? describe : describe.skip;
49
31
  describe(`@quad-education/sdk contract: ${name}`, () => {
50
32
  let env;
51
33
  const useApp = (app) => {
@@ -56,7 +38,190 @@ export function defineContractSuite(name, factory) {
56
38
  await env.dispose();
57
39
  });
58
40
  };
59
- describe('auth', () => {
41
+ describe('accounts and guests (V2c, D100)', () => {
42
+ useApp(ACCOUNT_APP);
43
+ const account = (accountId, ...roles) => ({
44
+ kind: 'account',
45
+ accountId,
46
+ roles,
47
+ });
48
+ const ADA = account('acc-ada', 'Teacher');
49
+ const BEN = account('acc-ben', 'Teacher', 'Student');
50
+ const CAI = account('acc-cai', 'Student');
51
+ const DEE = account('acc-dee', 'Student');
52
+ const GUEST1 = { kind: 'guest', guestId: 'guest-1' };
53
+ const GUEST2 = { kind: 'guest', guestId: 'guest-2' };
54
+ const notes = (sdk) => sdk.db.entity('note');
55
+ it('says who an account and a guest are', async () => {
56
+ expect(await (await env.connect(ADA)).auth.me()).toEqual({
57
+ kind: 'account',
58
+ account: { id: 'acc-ada', displayName: 'Ada Teacher' },
59
+ roles: ['Teacher'],
60
+ });
61
+ expect((await (await env.connect(BEN)).auth.me()).roles).toEqual(['Teacher', 'Student']);
62
+ expect(await (await env.connect(GUEST1)).auth.me()).toEqual({
63
+ kind: 'guest',
64
+ guest: { id: 'guest-1' },
65
+ });
66
+ });
67
+ it('refuses a role the app does not have, and guests when the app does not handle them', async () => {
68
+ const janitor = account('acc-ada', 'Janitor');
69
+ await expectError((await env.connect(janitor)).auth.me(), 'FORBIDDEN');
70
+ await env.control.restart({ manifest: { ...ACCOUNT_APP.manifest, guests: false } });
71
+ await expectError((await env.connect(GUEST1)).auth.me(), 'FORBIDDEN');
72
+ expect((await (await env.connect(ADA)).auth.me()).kind).toBe('account');
73
+ });
74
+ it('applies the rules of every role an account holds, matched ignoring case', async () => {
75
+ const [ada, ben, cai, dee] = await Promise.all([ADA, BEN, CAI, DEE].map((p) => env.connect(p)));
76
+ const fromBen = await notes(ben).create({ body: 'ben' });
77
+ const fromCai = await notes(cai).create({ body: 'cai' });
78
+ expect(fromBen.createdBy).toBe('acct:acc-ben');
79
+ // Teacher can read all; a Student only their own; Ben holds both, so he gets Teacher's `all`.
80
+ expect(ids(await listAll(notes(ada)))).toEqual(ids([fromBen, fromCai]));
81
+ expect(ids(await listAll(notes(ben)))).toEqual(ids([fromBen, fromCai]));
82
+ expect(ids(await listAll(notes(cai)))).toEqual([fromCai.id]);
83
+ expect(await listAll(notes(dee))).toEqual([]);
84
+ await expectError(notes(dee).get(fromCai.id), 'NOT_FOUND');
85
+ await expectError(notes(cai).get(fromBen.id), 'NOT_FOUND');
86
+ // A Student may change and delete only their own.
87
+ await notes(cai).update(fromCai.id, { body: 'cai again' });
88
+ await expectError(notes(cai).update(fromBen.id, { body: 'x' }), 'NOT_FOUND');
89
+ await notes(cai).delete(fromCai.id);
90
+ });
91
+ it('gives a guest only the guest rules, and never another guest’s records', async () => {
92
+ const [ada, guest1, guest2] = await Promise.all([ADA, GUEST1, GUEST2].map((p) => env.connect(p)));
93
+ const mine = await notes(guest1).create({ body: 'hello' });
94
+ expect(mine.createdBy).toBe('guest:guest-1');
95
+ expect(ids(await listAll(notes(guest1)))).toEqual([mine.id]);
96
+ expect(await listAll(notes(guest2))).toEqual([]);
97
+ await expectError(notes(guest2).get(mine.id), 'NOT_FOUND');
98
+ // `guest` has read and create, nothing else.
99
+ await expectError(notes(guest1).update(mine.id, { body: 'x' }), 'NOT_PERMITTED');
100
+ await expectError(notes(guest1).delete(mine.id), 'NOT_PERMITTED');
101
+ // A teacher reads everything, a guest's note included.
102
+ expect(ids(await listAll(notes(ada)))).toEqual([mine.id]);
103
+ });
104
+ it('sorts on createdBy, an implicit index with createdAt, and still refuses an unindexed sort', async () => {
105
+ const ada = await env.connect(ADA);
106
+ await notes(ada).create({ body: 'a' });
107
+ await notes(ada).create({ body: 'b' });
108
+ const sorted = await notes(ada).list({ orderBy: { field: 'createdBy' } });
109
+ expect(sorted.items).toHaveLength(2);
110
+ await expectError(notes(ada).list({ orderBy: { field: 'body' } }), 'VALIDATION');
111
+ });
112
+ it('gives NOT_AVAILABLE for everything under sdk.school, to accounts, guests and school personas alike', async () => {
113
+ const calls = (sdk) => [
114
+ () => sdk.school.info(),
115
+ () => sdk.school.students.list(),
116
+ () => sdk.school.students.get('stu-0001'),
117
+ () => sdk.school.students.parents('stu-0001'),
118
+ () => sdk.school.parents.children('par-0001'),
119
+ () => sdk.school.cohorts.byCode('y07'),
120
+ () => sdk.school.cohorts.members('coh-001'),
121
+ () => sdk.school.calendar.list({ from: '2026-01-01', to: '2026-12-31' }),
122
+ ];
123
+ // The standalone app is previewed by a school persona of the same role name: still no school.
124
+ for (const who of school ? [ADA, CAI, GUEST1, STUDENT] : [ADA, CAI, GUEST1]) {
125
+ const sdk = await env.connect(who);
126
+ for (const call of calls(sdk))
127
+ await expectError(call(), 'NOT_AVAILABLE');
128
+ }
129
+ });
130
+ it('gives NOT_AVAILABLE for relationship recipients, school people and `regarding`', async () => {
131
+ const ada = await env.connect(ADA);
132
+ const send = (to) => ada.notify.send({ type: 'test.message', to, subject: 'S', body: 'B' });
133
+ await expectError(send(parentsOf('stu-0001')), 'NOT_AVAILABLE');
134
+ await expectError(send(staffOf('coh-001')), 'NOT_AVAILABLE');
135
+ await expectError(send(studentsOf('coh-001')), 'NOT_AVAILABLE');
136
+ await expectError(send({ person: 'stu-0001' }), 'NOT_AVAILABLE');
137
+ await expectError(ada.tasks.assign({ type: 'test.review', title: 'T', assignee: parentsOf('stu-0001') }), 'NOT_AVAILABLE');
138
+ await expectError(ada.tasks.assign({
139
+ type: 'test.review',
140
+ title: 'T',
141
+ assignee: { role: 'Student' },
142
+ regarding: { studentId: 'stu-0001' },
143
+ }), 'NOT_AVAILABLE');
144
+ });
145
+ it('notifies accounts by id and by app role, never guests, into the simulated outbox', async () => {
146
+ const ada = await env.connect(ADA);
147
+ await ada.notify.send({
148
+ type: 'test.message',
149
+ to: [{ role: 'Student' }],
150
+ subject: 'Hello',
151
+ body: 'B',
152
+ });
153
+ const outbox = await env.control.outbox();
154
+ expect(outbox.map((e) => e.recipientId).sort()).toEqual([
155
+ 'acct:acc-ben',
156
+ 'acct:acc-cai',
157
+ 'acct:acc-dee',
158
+ ]);
159
+ expect(outbox.every((e) => e.simulated && e.sentBy === 'acct:acc-ada')).toBe(true);
160
+ await env.control.reset();
161
+ await ada.notify.send({
162
+ type: 'test.message',
163
+ to: [{ account: 'acc-cai' }, { role: 'teacher' }],
164
+ subject: 'S',
165
+ body: 'B',
166
+ });
167
+ expect((await env.control.outbox()).map((e) => e.recipientId).sort()).toEqual([
168
+ 'acct:acc-ada',
169
+ 'acct:acc-ben',
170
+ 'acct:acc-cai',
171
+ ]);
172
+ await expectError(ada.notify.send({
173
+ type: 'test.message',
174
+ to: [{ account: 'acc-zed' }],
175
+ subject: 'S',
176
+ body: 'B',
177
+ }), 'VALIDATION');
178
+ await expectError(ada.notify.send({
179
+ type: 'test.message',
180
+ to: [{ role: 'Janitor' }],
181
+ subject: 'S',
182
+ body: 'B',
183
+ }), 'VALIDATION');
184
+ const guest = await env.connect(GUEST1);
185
+ await expectError(guest.notify.send({
186
+ type: 'test.message',
187
+ to: [{ role: 'Teacher' }],
188
+ subject: 'S',
189
+ body: 'B',
190
+ }), 'FORBIDDEN');
191
+ });
192
+ it('assigns tasks to accounts and app roles, completed only by an assignee', async () => {
193
+ const [ada, cai, dee, guest] = await Promise.all([ADA, CAI, DEE, GUEST1].map((p) => env.connect(p)));
194
+ const { tasks } = await ada.tasks.assign({
195
+ type: 'test.review',
196
+ title: 'Review your notes',
197
+ assignee: { role: 'Student' },
198
+ });
199
+ expect(tasks).toHaveLength(3);
200
+ expect((await env.control.inbox('acct:acc-cai')).map((t) => t.type)).toEqual([
201
+ 'test.review',
202
+ ]);
203
+ const mine = (await cai.tasks.list()).items;
204
+ expect(mine).toHaveLength(1);
205
+ expect(mine[0].assignedToMe).toBe(true);
206
+ // Dee isn't involved in Cai's task, so it isn't there for her at all.
207
+ const caisTask = tasks.find((t) => t.id === mine[0].id);
208
+ await expectError(dee.tasks.complete(caisTask.id), 'NOT_FOUND');
209
+ expect((await cai.tasks.complete(caisTask.id)).status).toBe('completed');
210
+ await expectError(guest.tasks.assign({ type: 'test.review', title: 'T', assignee: { account: 'acc-cai' } }), 'FORBIDDEN');
211
+ });
212
+ it('runs a job an account scheduled as that account, and lets no guest schedule one', async () => {
213
+ const ada = await env.connect(ADA);
214
+ await ada.schedule.at({ job: 'remind', when: '2026-03-04T00:00:00Z' });
215
+ const runs = await env.control.runDueJobs();
216
+ expect(runs.map((r) => [r.jobName, r.ok])).toEqual([['remind', true]]);
217
+ const [made] = (await listAll(notes(ada))).filter((n) => n.body.includes('"kind"'));
218
+ expect(JSON.parse(made.body)).toMatchObject({ kind: 'account', account: { id: 'acc-ada' } });
219
+ const guest = await env.connect(GUEST1);
220
+ await expectError(guest.schedule.at({ job: 'remind', when: '2026-03-05T00:00:00Z' }), 'FORBIDDEN');
221
+ });
222
+ });
223
+ defineStandaloneSections(() => env, useApp);
224
+ schoolDescribe('auth', () => {
60
225
  useApp(TEST_APP);
61
226
  it('returns the connected user', async () => {
62
227
  const sdk = await env.connect(STAFF);
@@ -73,14 +238,14 @@ export function defineContractSuite(name, factory) {
73
238
  },
74
239
  });
75
240
  expect(sdk.appId).toBe(TEST_APP.manifest.id);
76
- expect(sdk.version).toBe('0.1.4');
241
+ expect(sdk.version).toBe('0.2.0');
77
242
  });
78
243
  it('knows parents and students', async () => {
79
244
  expect((await (await env.connect(STUDENT)).auth.me()).role).toBe('student');
80
245
  expect((await (await env.connect(SIBLINGS_PARENT)).auth.me()).role).toBe('parent');
81
246
  });
82
247
  });
83
- describe('school: visibility (D4)', () => {
248
+ schoolDescribe('school: visibility (D4)', () => {
84
249
  useApp(TEST_APP);
85
250
  it('staff see every student', async () => {
86
251
  const sdk = await env.connect(STAFF);
@@ -131,7 +296,7 @@ export function defineContractSuite(name, factory) {
131
296
  expect(await listAll((await env.connect(SIBLINGS_PARENT)).school.pastoralNotes)).toEqual([]);
132
297
  });
133
298
  });
134
- describe('school: scopes and tiers (D5, D23)', () => {
299
+ schoolDescribe('school: scopes and tiers (D5, D23)', () => {
135
300
  describe('with only students.basic:read', () => {
136
301
  useApp(BASIC_APP);
137
302
  it('returns basic fields and leaves other tiers absent', async () => {
@@ -189,7 +354,7 @@ export function defineContractSuite(name, factory) {
189
354
  });
190
355
  });
191
356
  });
192
- describe('app-defined roles are previewed by the persona of the same name (D84)', () => {
357
+ schoolDescribe('app-defined roles are previewed by the persona of the same name (D84)', () => {
193
358
  useApp(ROLES_APP);
194
359
  it('serves the personas whose role matches an app role, ignoring case, and refuses the rest', async () => {
195
360
  const staff = await env.connect(STAFF);
@@ -211,7 +376,7 @@ export function defineContractSuite(name, factory) {
211
376
  await expectError(student.db.entity('entry').delete(note.id), 'NOT_PERMITTED');
212
377
  });
213
378
  });
214
- describe('school: declared fields (D85)', () => {
379
+ schoolDescribe('school: declared fields (D85)', () => {
215
380
  useApp(DATA_APP);
216
381
  it('returns the core fields and the declared ones, and nothing else that varies', async () => {
217
382
  const sdk = await env.connect(STAFF);
@@ -253,7 +418,7 @@ export function defineContractSuite(name, factory) {
253
418
  expect('dateOfBirth' in included).toBe(true);
254
419
  });
255
420
  });
256
- describe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
421
+ schoolDescribe('school: no declaration (version 0) still gives every field of the granted tiers', () => {
257
422
  useApp(BASIC_APP);
258
423
  it('keeps yearLevel and preferredName available', async () => {
259
424
  const student = (await (await env.connect(STAFF)).school.students.list({ limit: 1 }))
@@ -261,7 +426,7 @@ export function defineContractSuite(name, factory) {
261
426
  expect('yearLevel' in student).toBe(true);
262
427
  });
263
428
  });
264
- describe('school: queries and helpers', () => {
429
+ schoolDescribe('school: queries and helpers', () => {
265
430
  useApp(TEST_APP);
266
431
  it('filters with where, orders and pages without gaps or repeats', async () => {
267
432
  const sdk = await env.connect(STAFF);
@@ -700,7 +865,7 @@ export function defineContractSuite(name, factory) {
700
865
  expect(forY7.some((e) => e.title === 'Year 7 camp')).toBe(true);
701
866
  });
702
867
  });
703
- describe('db', () => {
868
+ schoolDescribe('db', () => {
704
869
  useApp(TEST_APP);
705
870
  const studentId = ds.students[0].id;
706
871
  it('creates, reads, updates and deletes records with system fields', async () => {
@@ -884,7 +1049,7 @@ export function defineContractSuite(name, factory) {
884
1049
  expect((await (await env.connect(STAFF)).db.entity('greeting').list()).items).toEqual([]);
885
1050
  });
886
1051
  });
887
- describe('db access control (D25)', () => {
1052
+ schoolDescribe('db access control (D25)', () => {
888
1053
  useApp(ACCESS_APP);
889
1054
  const myChild = () => childrenOf(SIBLINGS_PARENT.personId)[0];
890
1055
  const otherChild = () => ds.students.find((s) => !childrenOf(SIBLINGS_PARENT.personId).includes(s.id) &&
@@ -1048,7 +1213,7 @@ export function defineContractSuite(name, factory) {
1048
1213
  expect((await system.db.entity('consent').list()).items).toHaveLength(1);
1049
1214
  });
1050
1215
  });
1051
- describe('notify (D10, D17)', () => {
1216
+ schoolDescribe('notify (D10, D17)', () => {
1052
1217
  useApp(TEST_APP);
1053
1218
  const message = { type: 'test.message', subject: 'Hello', body: 'Body text' };
1054
1219
  it('delivers to the simulated outbox only', async () => {
@@ -1159,7 +1324,7 @@ export function defineContractSuite(name, factory) {
1159
1324
  await expectError(sdk.notify.send({ ...message, to: { role: 'staff' }, subject: '' }), 'VALIDATION');
1160
1325
  });
1161
1326
  });
1162
- describe('notify: roles outside the manifest', () => {
1327
+ schoolDescribe('notify: roles outside the manifest', () => {
1163
1328
  useApp({
1164
1329
  ...TEST_APP,
1165
1330
  manifest: { ...TEST_APP.manifest, id: 'staff-only', roles: ['staff'] },
@@ -1194,7 +1359,7 @@ export function defineContractSuite(name, factory) {
1194
1359
  };
1195
1360
  const SYSTEM_JOBS = { kind: 'system', appId: 'contract-jobs' };
1196
1361
  const approval = { type: 'test.approval', title: 'Approve the excursion' };
1197
- describe('tasks (D6)', () => {
1362
+ schoolDescribe('tasks (D6)', () => {
1198
1363
  useApp(JOBS_APP);
1199
1364
  it("mode 'each' gives every assignee their own task and inbox entry", async () => {
1200
1365
  const sdk = await env.connect(STAFF);
@@ -1371,7 +1536,7 @@ export function defineContractSuite(name, factory) {
1371
1536
  expect((await (await env.connect(STAFF)).tasks.get(tasks[0].id)).regardingStudentId).toBe(childrenOf(SIBLINGS_PARENT.personId)[0]);
1372
1537
  });
1373
1538
  });
1374
- describe('schedule and cron (D7, D8, D20)', () => {
1539
+ schoolDescribe('schedule and cron (D7, D8, D20)', () => {
1375
1540
  useApp(JOBS_APP);
1376
1541
  const logs = async () => (await (await env.connect(STAFF)).db.entity('jobLog').list({ limit: 200 })).items;
1377
1542
  it('runs a scheduled job at its time, not before, as the user who scheduled it (D7)', async () => {
@@ -1557,7 +1722,7 @@ export function defineContractSuite(name, factory) {
1557
1722
  expect((await env.control.auditLog()).some((e) => e.action === 'job.redelivered')).toBe(true);
1558
1723
  });
1559
1724
  });
1560
- describe('audit (D19)', () => {
1725
+ schoolDescribe('audit (D19)', () => {
1561
1726
  useApp({
1562
1727
  ...JOBS_APP,
1563
1728
  manifest: { ...JOBS_APP.manifest, scopes: [...TEST_APP.manifest.scopes] },
@@ -1698,7 +1863,7 @@ export function defineContractSuite(name, factory) {
1698
1863
  expect(same).toEqual(entry);
1699
1864
  });
1700
1865
  });
1701
- describe('clock controls (D14)', () => {
1866
+ schoolDescribe('clock controls (D14)', () => {
1702
1867
  useApp(TEST_APP);
1703
1868
  it('advances a frozen clock', async () => {
1704
1869
  await env.control.setClock('2026-03-04T00:00:00.000Z');
@@ -1706,7 +1871,7 @@ export function defineContractSuite(name, factory) {
1706
1871
  expect((await env.connect(STAFF)).clock.now()).toBe('2026-03-05T00:00:00.000Z');
1707
1872
  });
1708
1873
  });
1709
- describe('clock (D14, D21)', () => {
1874
+ schoolDescribe('clock (D14, D21)', () => {
1710
1875
  useApp(TEST_APP);
1711
1876
  it('follows the engine clock', async () => {
1712
1877
  await env.control.setClock('2026-03-04T14:30:00.000Z');
@@ -1,10 +1,20 @@
1
1
  import type { QuadSdk } from '../contract/types.ts';
2
2
  import { type HandshakeOptions } from './handshake-client.ts';
3
+ import { type LiveOptions } from './live.ts';
3
4
  export { DEFAULT_SHELL_ORIGIN } from './handshake-client.ts';
4
- export type ConnectOptions = HandshakeOptions;
5
+ export { connectHttp, createHttpTransport, type HttpOptions, type HttpTransport, } from './http-transport.ts';
6
+ export { SignInRequired, connectLive, continueAsGuest, getLiveStatus, signIn, type LiveOptions, type LiveStatus, } from './live.ts';
7
+ export type ConnectOptions = HandshakeOptions & {
8
+ /** Connect the live way (a shell-less app at its own address), for tests and other runtimes. */
9
+ live?: LiveOptions;
10
+ };
5
11
  /**
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.
12
+ * Connect to the platform. In the demo shell's iframe (the Sandbox and `quad dev`), the shell hands over a
13
+ * private MessagePort and every SDK call goes through it. At a live address there is no shell: the app asks its
14
+ * own origin who is signed in and talks to the data API with a token. The same built code does both.
15
+ *
16
+ * Live and nobody signed in: if the app allows guests this throws `SignInRequired` (with `guests: true`) so the
17
+ * app can offer both choices; otherwise the page goes to Quad's sign-in and this never settles.
8
18
  */
9
19
  export declare function connect(options?: ConnectOptions): Promise<QuadSdk>;
10
20
  export type { QuadSdk };
@@ -1,12 +1,30 @@
1
1
  import { portTransport } from "../port-rpc.js";
2
2
  import { createSdkClient } from "./create-client.js";
3
- import { handshake } from "./handshake-client.js";
3
+ import { handshake, isFramed } from "./handshake-client.js";
4
+ import { connectSignedIn, getLiveStatus, signIn } from "./live.js";
4
5
  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";
5
8
  /**
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.
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.
8
15
  */
9
16
  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
+ }
10
26
  const { port, session } = await handshake(options);
11
27
  return createSdkClient(portTransport(port, session.clock), session);
12
28
  }
29
+ /** A page that is leaving has nothing to resolve to. */
30
+ const never = () => new Promise(() => { });
@@ -6,6 +6,8 @@ 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;
9
11
  /**
10
12
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
11
13
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -2,6 +2,8 @@ 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;
5
7
  /**
6
8
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
7
9
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -0,0 +1,18 @@
1
+ import type { QuadSdk } from '../contract/types.ts';
2
+ import { type SessionInfo } from '../protocol.ts';
3
+ import { type Transport } from './create-client.ts';
4
+ export type HttpOptions = {
5
+ /** The data API's address, e.g. https://data.us-east-1.quadapps.net */
6
+ baseUrl: string;
7
+ /** The current token. Called for every request, so the provider can keep it fresh. */
8
+ token: () => string | Promise<string>;
9
+ /** For tests and other runtimes; defaults to the global `fetch`. */
10
+ fetch?: typeof fetch;
11
+ };
12
+ /** Moves RPC calls to the data API. Also holds the session the first call to `/session` returned. */
13
+ export type HttpTransport = Transport & {
14
+ session: SessionInfo;
15
+ };
16
+ export declare function createHttpTransport(options: HttpOptions): Promise<HttpTransport>;
17
+ /** Connect to a live app's data: the SDK over HTTP, as the person the token names. */
18
+ export declare function connectHttp(options: HttpOptions): Promise<QuadSdk>;
@@ -0,0 +1,76 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { deserializeError, } from "../protocol.js";
3
+ import { createSdkClient } from "./create-client.js";
4
+ async function readEnvelope(response) {
5
+ try {
6
+ return (await response.json());
7
+ }
8
+ catch {
9
+ throw new QuadError('TRANSPORT', `the data API answered ${response.status} with no usable body`);
10
+ }
11
+ }
12
+ export async function createHttpTransport(options) {
13
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
14
+ const base = options.baseUrl.replace(/\/+$/, '');
15
+ let clock = { kind: 'offset', offsetMs: 0 };
16
+ let known = Date.now();
17
+ let sentAt = Date.now();
18
+ const learn = (env) => {
19
+ if (env.clock)
20
+ clock = env.clock;
21
+ if (typeof env.now === 'number') {
22
+ known = env.now;
23
+ sentAt = Date.now();
24
+ }
25
+ };
26
+ async function request(path, init) {
27
+ // A token that can't be had is its own error (a session that ended), not a network failure.
28
+ const token = await options.token();
29
+ let response;
30
+ try {
31
+ response = await doFetch(`${base}${path}`, {
32
+ method: init.method,
33
+ headers: {
34
+ authorization: `Bearer ${token}`,
35
+ ...(init.body !== undefined ? { 'content-type': 'application/json' } : {}),
36
+ },
37
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
38
+ });
39
+ }
40
+ catch (e) {
41
+ throw new QuadError('TRANSPORT', `couldn't reach the data API: ${e.message}`);
42
+ }
43
+ const env = await readEnvelope(response);
44
+ learn(env);
45
+ if (!env.ok) {
46
+ throw env.error
47
+ ? deserializeError(env.error)
48
+ : new QuadError('TRANSPORT', `the data API answered ${response.status}`);
49
+ }
50
+ return env;
51
+ }
52
+ const hello = (await request('/session', { method: 'GET' }));
53
+ const session = {
54
+ appId: hello.result.appId,
55
+ timezone: hello.result.timezone,
56
+ clock,
57
+ };
58
+ return {
59
+ session,
60
+ async call(method, params, context) {
61
+ const env = await request('/rpc', {
62
+ method: 'POST',
63
+ body: { method, params, ...(context?.runId !== undefined ? { runId: context.runId } : {}) },
64
+ });
65
+ return env.result;
66
+ },
67
+ nowMs() {
68
+ return clock.kind === 'fixed' ? clock.at : known + (Date.now() - sentAt);
69
+ },
70
+ };
71
+ }
72
+ /** Connect to a live app's data: the SDK over HTTP, as the person the token names. */
73
+ export async function connectHttp(options) {
74
+ const transport = await createHttpTransport(options);
75
+ return createSdkClient(transport, transport.session);
76
+ }
@@ -0,0 +1,39 @@
1
+ import { QuadError } from '../contract/errors.ts';
2
+ import type { QuadSdk } from '../contract/types.ts';
3
+ export type LiveOptions = {
4
+ /** For tests and other runtimes; defaults to the global `fetch`. */
5
+ fetch?: typeof fetch;
6
+ /** Where the page is and how to leave it; defaults to `window.location`. */
7
+ location?: {
8
+ pathname: string;
9
+ search: string;
10
+ hash: string;
11
+ assign(url: string): void;
12
+ };
13
+ /** Where the guest device id is kept; defaults to `localStorage`, or the page's memory if that is blocked. */
14
+ storage?: Pick<Storage, 'getItem' | 'setItem'>;
15
+ /** The time in ms; defaults to `Date.now`. */
16
+ now?: () => number;
17
+ };
18
+ export type LiveStatus = {
19
+ signedIn: true;
20
+ dataApi: string;
21
+ } | {
22
+ signedIn: false;
23
+ guests: boolean;
24
+ };
25
+ /** Thrown while nobody is signed in. Offer {@link signIn}, and {@link continueAsGuest} when `guests` is true. */
26
+ export declare class SignInRequired extends QuadError {
27
+ readonly guests: boolean;
28
+ constructor(guests: boolean);
29
+ }
30
+ /** Who is signed in at this address, and whether guests are welcome if no one is. */
31
+ export declare function getLiveStatus(options?: LiveOptions): Promise<LiveStatus>;
32
+ /** Leaves for Quad's sign-in, which returns the person to this page. */
33
+ export declare function signIn(options?: LiveOptions): void;
34
+ /** Starts a guest session. The device id stays on this origin; Quad keeps only a salted hash of it (ADR 0010). */
35
+ export declare function continueAsGuest(options?: LiveOptions): Promise<void>;
36
+ /** Connects as the signed-in person, or throws {@link SignInRequired}. */
37
+ export declare function connectLive(options?: LiveOptions): Promise<QuadSdk>;
38
+ /** Connects from a status already fetched; throws {@link SignInRequired} if it says nobody is signed in. */
39
+ export declare function connectSignedIn(status: LiveStatus, options: LiveOptions): Promise<QuadSdk>;