@quad-education/sdk 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +15 -0
- package/README.md +106 -2
- package/dist/contract-tests/apps.d.ts +373 -0
- package/dist/contract-tests/apps.js +309 -0
- package/dist/contract-tests/index.d.ts +3 -0
- package/dist/contract-tests/index.js +2 -0
- package/dist/contract-tests/suite.d.ts +57 -0
- package/dist/contract-tests/suite.js +1405 -0
- package/dist/src/client/connect.d.ts +10 -0
- package/dist/src/client/connect.js +12 -0
- package/dist/src/client/create-client.d.ts +14 -0
- package/dist/src/client/create-client.js +76 -0
- package/dist/src/client/handshake-client.d.ts +16 -0
- package/dist/src/client/handshake-client.js +37 -0
- package/dist/src/contract/errors.d.ts +8 -0
- package/dist/src/contract/errors.js +13 -0
- package/dist/src/contract/recipients.d.ts +28 -0
- package/dist/src/contract/recipients.js +12 -0
- package/dist/src/contract/types.d.ts +442 -0
- package/dist/src/contract/types.js +1 -0
- package/dist/src/engine/audit.d.ts +27 -0
- package/dist/src/engine/audit.js +105 -0
- package/dist/src/engine/cron.d.ts +17 -0
- package/dist/src/engine/cron.js +143 -0
- package/dist/src/engine/db-indexes.d.ts +11 -0
- package/dist/src/engine/db-indexes.js +82 -0
- package/dist/src/engine/engine.d.ts +156 -0
- package/dist/src/engine/engine.js +953 -0
- package/dist/src/engine/host.d.ts +39 -0
- package/dist/src/engine/host.js +73 -0
- package/dist/src/engine/in-process.d.ts +5 -0
- package/dist/src/engine/in-process.js +18 -0
- package/dist/src/engine/index.d.ts +10 -0
- package/dist/src/engine/index.js +8 -0
- package/dist/src/engine/query.d.ts +16 -0
- package/dist/src/engine/query.js +106 -0
- package/dist/src/engine/runner.d.ts +26 -0
- package/dist/src/engine/runner.js +260 -0
- package/dist/src/engine/state.d.ts +107 -0
- package/dist/src/engine/state.js +16 -0
- package/dist/src/engine/storage.d.ts +46 -0
- package/dist/src/engine/storage.js +86 -0
- package/dist/src/engine/tasks.d.ts +17 -0
- package/dist/src/engine/tasks.js +245 -0
- package/dist/src/engine/validate-input.d.ts +9 -0
- package/dist/src/engine/validate-input.js +76 -0
- package/dist/src/engine/values.d.ts +10 -0
- package/dist/src/engine/values.js +58 -0
- package/dist/src/handshake.d.ts +16 -0
- package/dist/src/handshake.js +9 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +4 -0
- package/dist/src/jobs/define.d.ts +41 -0
- package/dist/src/jobs/define.js +28 -0
- package/dist/src/jobs/host.d.ts +13 -0
- package/dist/src/jobs/host.js +22 -0
- package/dist/src/jobs/index.d.ts +1 -0
- package/dist/src/jobs/index.js +2 -0
- package/dist/src/jobs/worker.d.ts +17 -0
- package/dist/src/jobs/worker.js +25 -0
- package/dist/src/platform-types.d.ts +19 -0
- package/dist/src/platform-types.js +1 -0
- package/dist/src/port-rpc.d.ts +42 -0
- package/dist/src/port-rpc.js +85 -0
- package/dist/src/protocol.d.ts +41 -0
- package/dist/src/protocol.js +45 -0
- package/dist/src/testing/index.d.ts +78 -0
- package/dist/src/testing/index.js +118 -0
- package/package.json +71 -3
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { visibleStudentIds, } from '@quad-education/canonical';
|
|
2
|
+
export const isStaffOrSystem = (ctx) => ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
|
|
3
|
+
export const roleOfPrincipal = (ctx) => ctx.principal.kind === 'system' ? 'system' : ctx.principal.role;
|
|
4
|
+
/**
|
|
5
|
+
* Whether the current principal can see a subject student, under the school's visibility
|
|
6
|
+
* policy (D4). Tasks and audit entries about a student follow it for everyone, staff
|
|
7
|
+
* included; only the system principal is exempt.
|
|
8
|
+
*/
|
|
9
|
+
export function seesSubject(k, ctx, studentId) {
|
|
10
|
+
if (studentId === undefined || ctx.principal.kind === 'system')
|
|
11
|
+
return true;
|
|
12
|
+
ctx.students ??= visibleStudentIds(ctx.principal, k.dataset);
|
|
13
|
+
return ctx.students === 'all'
|
|
14
|
+
? k.dataset.students.some((s) => s.id === studentId)
|
|
15
|
+
: ctx.students.has(studentId);
|
|
16
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export declare const ENGINE_DB_NAME = "quad-engine";
|
|
2
|
+
export type StoredRecord = {
|
|
3
|
+
appId: string;
|
|
4
|
+
entity: string;
|
|
5
|
+
id: string;
|
|
6
|
+
data: Record<string, unknown>;
|
|
7
|
+
};
|
|
8
|
+
export type StoredMeta = {
|
|
9
|
+
appId: string;
|
|
10
|
+
schemaHash: string;
|
|
11
|
+
};
|
|
12
|
+
export type StoredKey = {
|
|
13
|
+
appId: string;
|
|
14
|
+
key: string;
|
|
15
|
+
result: unknown;
|
|
16
|
+
};
|
|
17
|
+
export type PlatformKind = 'task' | 'schedule' | 'run' | 'cron' | 'audit';
|
|
18
|
+
export type StoredPlatform = {
|
|
19
|
+
appId: string;
|
|
20
|
+
kind: PlatformKind;
|
|
21
|
+
id: string;
|
|
22
|
+
data: unknown;
|
|
23
|
+
};
|
|
24
|
+
type Store = 'records' | 'outbox' | 'keys' | 'meta' | 'platform';
|
|
25
|
+
export declare class EngineStorage {
|
|
26
|
+
private readonly db;
|
|
27
|
+
private constructor();
|
|
28
|
+
static open(factory: IDBFactory, name?: string): Promise<EngineStorage>;
|
|
29
|
+
close(): void;
|
|
30
|
+
getAll<T>(store: Exclude<Store, 'meta'>, appId: string): Promise<T[]>;
|
|
31
|
+
getMeta(appId: string): Promise<StoredMeta | undefined>;
|
|
32
|
+
put(store: Store, values: readonly unknown[]): Promise<void>;
|
|
33
|
+
deleteRecord(appId: string, entity: string, id: string): Promise<void>;
|
|
34
|
+
/** Store platform state (tasks, schedules, runs, cron state, audit) for an app. */
|
|
35
|
+
putPlatform(appId: string, kind: PlatformKind, items: readonly {
|
|
36
|
+
id: string;
|
|
37
|
+
}[]): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Remove an app's stored data. A schema change in V1 (D12) clears only app records; the
|
|
40
|
+
* shell's reset button clears everything, including the outbox and platform state.
|
|
41
|
+
*/
|
|
42
|
+
clearApp(appId: string, { schemaChangeOnly }?: {
|
|
43
|
+
schemaChangeOnly?: boolean | undefined;
|
|
44
|
+
}): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// IndexedDB persistence for the engine (D15). Stores live in the shell's origin; app code
|
|
2
|
+
// never has a handle to them. The engine keeps a write-through copy of each app's data in memory.
|
|
3
|
+
export const ENGINE_DB_NAME = 'quad-engine';
|
|
4
|
+
// v2 adds the 'platform' store (Slice B: tasks, schedules, runs, cron state, audit).
|
|
5
|
+
const VERSION = 2;
|
|
6
|
+
const req = (r) => new Promise((resolve, reject) => {
|
|
7
|
+
r.onsuccess = () => resolve(r.result);
|
|
8
|
+
r.onerror = () => reject(r.error);
|
|
9
|
+
});
|
|
10
|
+
const done = (tx) => new Promise((resolve, reject) => {
|
|
11
|
+
tx.oncomplete = () => resolve();
|
|
12
|
+
tx.onerror = () => reject(tx.error);
|
|
13
|
+
tx.onabort = () => reject(tx.error);
|
|
14
|
+
});
|
|
15
|
+
export class EngineStorage {
|
|
16
|
+
db;
|
|
17
|
+
constructor(db) {
|
|
18
|
+
this.db = db;
|
|
19
|
+
}
|
|
20
|
+
static async open(factory, name = ENGINE_DB_NAME) {
|
|
21
|
+
const open = factory.open(name, VERSION);
|
|
22
|
+
open.onupgradeneeded = (e) => {
|
|
23
|
+
const db = open.result;
|
|
24
|
+
if (e.oldVersion < 1) {
|
|
25
|
+
db.createObjectStore('records', { keyPath: ['appId', 'entity', 'id'] }).createIndex('byApp', 'appId');
|
|
26
|
+
db.createObjectStore('outbox', { keyPath: 'id' }).createIndex('byApp', 'appId');
|
|
27
|
+
db.createObjectStore('keys', { keyPath: ['appId', 'key'] }).createIndex('byApp', 'appId');
|
|
28
|
+
db.createObjectStore('meta', { keyPath: 'appId' });
|
|
29
|
+
}
|
|
30
|
+
if (e.oldVersion < 2) {
|
|
31
|
+
db.createObjectStore('platform', { keyPath: ['appId', 'kind', 'id'] }).createIndex('byApp', 'appId');
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
return new EngineStorage(await req(open));
|
|
35
|
+
}
|
|
36
|
+
close() {
|
|
37
|
+
this.db.close();
|
|
38
|
+
}
|
|
39
|
+
async getAll(store, appId) {
|
|
40
|
+
const tx = this.db.transaction(store, 'readonly');
|
|
41
|
+
return req(tx.objectStore(store).index('byApp').getAll(appId));
|
|
42
|
+
}
|
|
43
|
+
async getMeta(appId) {
|
|
44
|
+
const tx = this.db.transaction('meta', 'readonly');
|
|
45
|
+
return req(tx.objectStore('meta').get(appId));
|
|
46
|
+
}
|
|
47
|
+
async put(store, values) {
|
|
48
|
+
const tx = this.db.transaction(store, 'readwrite');
|
|
49
|
+
for (const v of values)
|
|
50
|
+
tx.objectStore(store).put(v);
|
|
51
|
+
await done(tx);
|
|
52
|
+
}
|
|
53
|
+
async deleteRecord(appId, entity, id) {
|
|
54
|
+
const tx = this.db.transaction('records', 'readwrite');
|
|
55
|
+
tx.objectStore('records').delete([appId, entity, id]);
|
|
56
|
+
await done(tx);
|
|
57
|
+
}
|
|
58
|
+
/** Store platform state (tasks, schedules, runs, cron state, audit) for an app. */
|
|
59
|
+
async putPlatform(appId, kind, items) {
|
|
60
|
+
if (items.length === 0)
|
|
61
|
+
return;
|
|
62
|
+
await this.put('platform', items.map((data) => ({ appId, kind, id: data.id, data })));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Remove an app's stored data. A schema change in V1 (D12) clears only app records; the
|
|
66
|
+
* shell's reset button clears everything, including the outbox and platform state.
|
|
67
|
+
*/
|
|
68
|
+
async clearApp(appId, { schemaChangeOnly = false } = {}) {
|
|
69
|
+
const stores = schemaChangeOnly
|
|
70
|
+
? ['records', 'keys']
|
|
71
|
+
: ['records', 'keys', 'outbox', 'platform'];
|
|
72
|
+
const tx = this.db.transaction([...stores], 'readwrite');
|
|
73
|
+
for (const store of stores) {
|
|
74
|
+
const index = tx.objectStore(store).index('byApp');
|
|
75
|
+
const cursorReq = index.openCursor(appId);
|
|
76
|
+
cursorReq.onsuccess = () => {
|
|
77
|
+
const cursor = cursorReq.result;
|
|
78
|
+
if (cursor) {
|
|
79
|
+
cursor.delete();
|
|
80
|
+
cursor.continue();
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
await done(tx);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Task } from '../contract/types.ts';
|
|
2
|
+
import { type Ctx, type Kernel, type StoredTask } from './state.ts';
|
|
3
|
+
export declare function taskView(ctx: Ctx, t: StoredTask): Task;
|
|
4
|
+
export declare function assignTask(k: Kernel, ctx: Ctx, input: Record<string, unknown>): Promise<{
|
|
5
|
+
tasks: Task[];
|
|
6
|
+
}>;
|
|
7
|
+
export declare function getTask(k: Kernel, ctx: Ctx, id: unknown): Task;
|
|
8
|
+
export declare function listTasks(k: Kernel, ctx: Ctx, options: unknown): {
|
|
9
|
+
items: Task[];
|
|
10
|
+
nextCursor: string | null;
|
|
11
|
+
};
|
|
12
|
+
export declare function completeTask(k: Kernel, ctx: Ctx, id: unknown, options: unknown): Promise<Task>;
|
|
13
|
+
export declare function cancelTask(k: Kernel, ctx: Ctx, id: unknown): Promise<Task>;
|
|
14
|
+
/** Open tasks assigned to a person (the shell's inbox). */
|
|
15
|
+
export declare function inbox(app: {
|
|
16
|
+
tasks: Map<string, StoredTask>;
|
|
17
|
+
}, personId: string): StoredTask[];
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { eligibleParents, visibleStudentIds } from '@quad-education/canonical';
|
|
2
|
+
import { QuadError } from "../contract/errors.js";
|
|
3
|
+
import { appendAudit } from "./audit.js";
|
|
4
|
+
import { runQuery } from "./query.js";
|
|
5
|
+
import { isStaffOrSystem, seesSubject } from "./state.js";
|
|
6
|
+
import { appLink, instant, isObject, jsonObject, optionalStr, str } from "./values.js";
|
|
7
|
+
// Tasks (D6): assigned to people, roles or relationships; completed only in the app by an
|
|
8
|
+
// assignee; parents only ever reached about a student they may be contacted about (D17).
|
|
9
|
+
export function taskView(ctx, t) {
|
|
10
|
+
const { appId: _appId, purpose: _purpose, assignees, ...rest } = t;
|
|
11
|
+
return {
|
|
12
|
+
...rest,
|
|
13
|
+
assignedToMe: ctx.principal.kind === 'user' && assignees.includes(ctx.actorId),
|
|
14
|
+
...(isStaffOrSystem(ctx) ? { assignees: [...assignees] } : {}),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Staff, assignees and the creator may see a task, and a task about a student (its
|
|
19
|
+
* `regardingStudentId`) also needs that student to be visible to them, staff included (D25).
|
|
20
|
+
*/
|
|
21
|
+
function canSee(k, ctx, t) {
|
|
22
|
+
if (ctx.principal.kind === 'system')
|
|
23
|
+
return true;
|
|
24
|
+
const involved = isStaffOrSystem(ctx) || t.assignees.includes(ctx.actorId) || t.createdBy === ctx.actorId;
|
|
25
|
+
return involved && seesSubject(k, ctx, t.regardingStudentId);
|
|
26
|
+
}
|
|
27
|
+
function visibleTask(k, ctx, id) {
|
|
28
|
+
const t = ctx.app.tasks.get(str(id, 'id'));
|
|
29
|
+
if (!t || !canSee(k, ctx, t))
|
|
30
|
+
throw new QuadError('NOT_FOUND', `no task ${String(id)}`);
|
|
31
|
+
return t;
|
|
32
|
+
}
|
|
33
|
+
export async function assignTask(k, ctx, input) {
|
|
34
|
+
const { manifest } = ctx.app;
|
|
35
|
+
const type = str(input.type, 'type');
|
|
36
|
+
if (!manifest.tasks.includes(type)) {
|
|
37
|
+
throw new QuadError('UNDECLARED_TYPE', `task type '${type}' isn't declared in app.manifest.json`);
|
|
38
|
+
}
|
|
39
|
+
const key = k.idempotencyKey(input, 'tasks.assign');
|
|
40
|
+
if (key && ctx.app.keys.has(key)) {
|
|
41
|
+
const ids = ctx.app.keys.get(key);
|
|
42
|
+
return {
|
|
43
|
+
tasks: ids
|
|
44
|
+
.map((id) => ctx.app.tasks.get(id))
|
|
45
|
+
.filter((t) => t !== undefined)
|
|
46
|
+
.map((t) => taskView(ctx, t)),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const title = str(input.title, 'title');
|
|
50
|
+
if (title.length > 200)
|
|
51
|
+
throw new QuadError('VALIDATION', 'title must be at most 200 characters');
|
|
52
|
+
const description = optionalStr(input.description, 'description', 2000);
|
|
53
|
+
const modeInput = input.mode ?? 'each';
|
|
54
|
+
if (modeInput !== 'each' && modeInput !== 'any')
|
|
55
|
+
throw new QuadError('VALIDATION', "mode must be 'each' or 'any'");
|
|
56
|
+
const mode = modeInput;
|
|
57
|
+
const dueAt = input.dueAt === undefined ? undefined : instant(input.dueAt, 'dueAt');
|
|
58
|
+
const link = appLink(input.link);
|
|
59
|
+
const data = jsonObject(input.data, 'data');
|
|
60
|
+
let regarding;
|
|
61
|
+
if (input.regarding !== undefined) {
|
|
62
|
+
if (!isObject(input.regarding))
|
|
63
|
+
throw new QuadError('VALIDATION', 'regarding must be { studentId }');
|
|
64
|
+
regarding = str(input.regarding.studentId, 'regarding.studentId');
|
|
65
|
+
}
|
|
66
|
+
if (regarding !== undefined && !seesSubject(k, ctx, regarding)) {
|
|
67
|
+
throw new QuadError('NOT_PERMITTED', 'regarding: not a student you can see');
|
|
68
|
+
}
|
|
69
|
+
const resolved = k.resolveRecipients(ctx, input.assignee, regarding);
|
|
70
|
+
const { suppressed } = resolved;
|
|
71
|
+
// A task about a student only goes to people who can see that student (D25); parents
|
|
72
|
+
// were already limited to eligible links (D17).
|
|
73
|
+
const recipients = resolved.recipients.filter((r) => {
|
|
74
|
+
const subject = r.regarding ?? regarding;
|
|
75
|
+
if (subject === undefined || r.role === 'parent')
|
|
76
|
+
return true;
|
|
77
|
+
const sees = visibleStudentIds({ kind: 'user', role: r.role, personId: r.personId }, k.dataset);
|
|
78
|
+
return sees === 'all' || sees.has(subject);
|
|
79
|
+
});
|
|
80
|
+
const now = k.nowIso();
|
|
81
|
+
const groupId = `grp_${crypto.randomUUID()}`;
|
|
82
|
+
const regardingStudentId = recipients.find((r) => r.regarding)?.regarding ?? regarding;
|
|
83
|
+
const purpose = recipients.some((r) => r.purpose === 'consent')
|
|
84
|
+
? 'consent'
|
|
85
|
+
: recipients.some((r) => r.role === 'parent')
|
|
86
|
+
? 'correspondence'
|
|
87
|
+
: undefined;
|
|
88
|
+
const base = {
|
|
89
|
+
appId: manifest.id,
|
|
90
|
+
type,
|
|
91
|
+
title,
|
|
92
|
+
status: 'open',
|
|
93
|
+
mode,
|
|
94
|
+
groupId,
|
|
95
|
+
createdAt: now,
|
|
96
|
+
createdBy: ctx.actorId,
|
|
97
|
+
...(description !== undefined ? { description } : {}),
|
|
98
|
+
...(regardingStudentId !== undefined ? { regardingStudentId } : {}),
|
|
99
|
+
...(dueAt !== undefined ? { dueAt } : {}),
|
|
100
|
+
...(link !== undefined ? { link } : {}),
|
|
101
|
+
...(data !== undefined ? { data: data } : {}),
|
|
102
|
+
...(purpose !== undefined ? { purpose } : {}),
|
|
103
|
+
};
|
|
104
|
+
const groups = recipients.length === 0
|
|
105
|
+
? []
|
|
106
|
+
: mode === 'each'
|
|
107
|
+
? recipients.map((r) => [r.personId])
|
|
108
|
+
: [recipients.map((r) => r.personId)];
|
|
109
|
+
const tasks = groups.map((assignees) => ({
|
|
110
|
+
...base,
|
|
111
|
+
id: `task_${crypto.randomUUID()}`,
|
|
112
|
+
assignees,
|
|
113
|
+
}));
|
|
114
|
+
for (const t of tasks)
|
|
115
|
+
ctx.app.tasks.set(t.id, t);
|
|
116
|
+
await k.persistPlatform(ctx.app, 'task', tasks);
|
|
117
|
+
for (const t of tasks) {
|
|
118
|
+
await appendAudit(k, ctx.app, {
|
|
119
|
+
source: 'platform',
|
|
120
|
+
action: 'task.assigned',
|
|
121
|
+
actor: ctx.actorId,
|
|
122
|
+
summary: `${type} assigned to ${t.assignees.length} ${t.assignees.length === 1 ? 'person' : 'people'} (${mode})`,
|
|
123
|
+
entity: 'task',
|
|
124
|
+
recordId: t.id,
|
|
125
|
+
visibility: 'app',
|
|
126
|
+
data: { type, mode, assignees: t.assignees, groupId },
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
for (const s of suppressed) {
|
|
130
|
+
await appendAudit(k, ctx.app, {
|
|
131
|
+
source: 'platform',
|
|
132
|
+
action: 'task.suppressed',
|
|
133
|
+
actor: ctx.actorId,
|
|
134
|
+
summary: `${type} not assigned to a parent (${s.reason})`,
|
|
135
|
+
entity: 'task',
|
|
136
|
+
visibility: 'cio',
|
|
137
|
+
data: {
|
|
138
|
+
type,
|
|
139
|
+
recipientId: s.personId,
|
|
140
|
+
regardingStudentId: s.regardingStudentId,
|
|
141
|
+
reason: s.reason,
|
|
142
|
+
groupId,
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (key)
|
|
147
|
+
await k.remember(ctx, key, tasks.map((t) => t.id));
|
|
148
|
+
return { tasks: tasks.map((t) => taskView(ctx, t)) };
|
|
149
|
+
}
|
|
150
|
+
export function getTask(k, ctx, id) {
|
|
151
|
+
return taskView(ctx, visibleTask(k, ctx, id));
|
|
152
|
+
}
|
|
153
|
+
export function listTasks(k, ctx, options) {
|
|
154
|
+
const o = isObject(options) ? options : {};
|
|
155
|
+
const where = {};
|
|
156
|
+
if (o.status !== undefined) {
|
|
157
|
+
if (!['open', 'completed', 'cancelled'].includes(o.status)) {
|
|
158
|
+
throw new QuadError('VALIDATION', "status must be 'open', 'completed' or 'cancelled'");
|
|
159
|
+
}
|
|
160
|
+
where.status = o.status;
|
|
161
|
+
}
|
|
162
|
+
if (o.type !== undefined)
|
|
163
|
+
where.type = str(o.type, 'type');
|
|
164
|
+
if (o.regardingStudentId !== undefined)
|
|
165
|
+
where.regardingStudentId = str(o.regardingStudentId, 'regardingStudentId');
|
|
166
|
+
if (o.groupId !== undefined)
|
|
167
|
+
where.groupId = str(o.groupId, 'groupId');
|
|
168
|
+
let tasks = [...ctx.app.tasks.values()].filter((t) => canSee(k, ctx, t));
|
|
169
|
+
if (o.assignedToMe !== undefined) {
|
|
170
|
+
if (typeof o.assignedToMe !== 'boolean')
|
|
171
|
+
throw new QuadError('VALIDATION', 'assignedToMe must be true or false');
|
|
172
|
+
tasks = tasks.filter((t) => t.assignees.includes(ctx.actorId) === o.assignedToMe);
|
|
173
|
+
}
|
|
174
|
+
const page = runQuery(tasks, {
|
|
175
|
+
where,
|
|
176
|
+
orderBy: { field: 'createdAt' },
|
|
177
|
+
...(o.limit !== undefined ? { limit: o.limit } : {}),
|
|
178
|
+
...(o.cursor !== undefined ? { cursor: o.cursor } : {}),
|
|
179
|
+
}, new Set(['status', 'type', 'regardingStudentId', 'groupId', 'createdAt']));
|
|
180
|
+
return {
|
|
181
|
+
items: page.items.map((t) => taskView(ctx, t)),
|
|
182
|
+
nextCursor: page.nextCursor,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
export async function completeTask(k, ctx, id, options) {
|
|
186
|
+
const t = visibleTask(k, ctx, id);
|
|
187
|
+
if (ctx.principal.kind === 'system' || !t.assignees.includes(ctx.actorId)) {
|
|
188
|
+
throw new QuadError('NOT_ASSIGNEE', 'only an assignee can complete this task, from the app');
|
|
189
|
+
}
|
|
190
|
+
// D17 is re-checked now, not just at assignment.
|
|
191
|
+
if (ctx.principal.role === 'parent' && t.regardingStudentId) {
|
|
192
|
+
if (!eligibleParents(k.dataset, t.regardingStudentId, t.purpose ?? 'correspondence').includes(ctx.actorId)) {
|
|
193
|
+
throw new QuadError('NOT_ASSIGNEE', 'you can no longer complete this task');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (t.status !== 'open')
|
|
197
|
+
throw new QuadError('VALIDATION', `this task is already ${t.status}`);
|
|
198
|
+
const outcome = optionalStr(isObject(options) ? options.outcome : undefined, 'outcome', 200);
|
|
199
|
+
t.status = 'completed';
|
|
200
|
+
t.completedAt = k.nowIso();
|
|
201
|
+
t.completedBy = ctx.actorId;
|
|
202
|
+
if (outcome !== undefined)
|
|
203
|
+
t.outcome = outcome;
|
|
204
|
+
await k.persistPlatform(ctx.app, 'task', [t]);
|
|
205
|
+
await appendAudit(k, ctx.app, {
|
|
206
|
+
source: 'platform',
|
|
207
|
+
action: 'task.completed',
|
|
208
|
+
actor: ctx.actorId,
|
|
209
|
+
summary: `${t.type} completed${outcome ? ` (${outcome})` : ''}`,
|
|
210
|
+
entity: 'task',
|
|
211
|
+
recordId: t.id,
|
|
212
|
+
visibility: 'app',
|
|
213
|
+
data: { type: t.type, ...(outcome !== undefined ? { outcome } : {}) },
|
|
214
|
+
});
|
|
215
|
+
return taskView(ctx, t);
|
|
216
|
+
}
|
|
217
|
+
export async function cancelTask(k, ctx, id) {
|
|
218
|
+
const t = visibleTask(k, ctx, id);
|
|
219
|
+
if (!isStaffOrSystem(ctx) && t.createdBy !== ctx.actorId) {
|
|
220
|
+
throw new QuadError('NOT_PERMITTED', 'only staff, the system or the task’s creator can cancel it');
|
|
221
|
+
}
|
|
222
|
+
if (t.status !== 'open')
|
|
223
|
+
throw new QuadError('VALIDATION', `this task is already ${t.status}`);
|
|
224
|
+
t.status = 'cancelled';
|
|
225
|
+
t.cancelledAt = k.nowIso();
|
|
226
|
+
t.cancelledBy = ctx.actorId;
|
|
227
|
+
await k.persistPlatform(ctx.app, 'task', [t]);
|
|
228
|
+
await appendAudit(k, ctx.app, {
|
|
229
|
+
source: 'platform',
|
|
230
|
+
action: 'task.cancelled',
|
|
231
|
+
actor: ctx.actorId,
|
|
232
|
+
summary: `${t.type} cancelled`,
|
|
233
|
+
entity: 'task',
|
|
234
|
+
recordId: t.id,
|
|
235
|
+
visibility: 'app',
|
|
236
|
+
data: { type: t.type },
|
|
237
|
+
});
|
|
238
|
+
return taskView(ctx, t);
|
|
239
|
+
}
|
|
240
|
+
/** Open tasks assigned to a person (the shell's inbox). */
|
|
241
|
+
export function inbox(app, personId) {
|
|
242
|
+
return [...app.tasks.values()]
|
|
243
|
+
.filter((t) => t.status === 'open' && t.assignees.includes(personId))
|
|
244
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
245
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AppEntityDef, AppFieldDef, AppSchema } from '@quad-education/schema';
|
|
2
|
+
/** An entity of the app's schema, by name. */
|
|
3
|
+
export declare function entityOf(schema: AppSchema, name: string): AppEntityDef | undefined;
|
|
4
|
+
/** A field of an entity, by name. */
|
|
5
|
+
export declare function fieldOf(def: AppEntityDef, name: string): AppFieldDef | undefined;
|
|
6
|
+
/** Checks app input against an entity definition. `partial` is for updates. Throws VALIDATION. */
|
|
7
|
+
export declare function validateInput(entity: string, def: AppEntityDef, input: unknown, { partial }: {
|
|
8
|
+
partial: boolean;
|
|
9
|
+
}): Record<string, unknown>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
3
|
+
const DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
4
|
+
function problem(def, value) {
|
|
5
|
+
switch (def.kind) {
|
|
6
|
+
case 'text':
|
|
7
|
+
case 'ref':
|
|
8
|
+
return typeof value === 'string' ? null : 'expected a string';
|
|
9
|
+
case 'number':
|
|
10
|
+
return typeof value === 'number' && Number.isFinite(value) ? null : 'expected a number';
|
|
11
|
+
case 'boolean':
|
|
12
|
+
return typeof value === 'boolean' ? null : 'expected true or false';
|
|
13
|
+
case 'date':
|
|
14
|
+
return typeof value === 'string' && DATE_RE.test(value)
|
|
15
|
+
? null
|
|
16
|
+
: 'expected a date (YYYY-MM-DD)';
|
|
17
|
+
case 'datetime':
|
|
18
|
+
return typeof value === 'string' &&
|
|
19
|
+
DATETIME_RE.test(value) &&
|
|
20
|
+
!Number.isNaN(Date.parse(value))
|
|
21
|
+
? null
|
|
22
|
+
: 'expected an ISO 8601 datetime';
|
|
23
|
+
case 'enum':
|
|
24
|
+
return def.values.includes(value)
|
|
25
|
+
? null
|
|
26
|
+
: `expected one of: ${def.values.join(', ')}`;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// Own properties only: names inherited from Object.prototype (`constructor`, `toString`)
|
|
30
|
+
// are never entities or fields, whatever a caller or a fetched schema says.
|
|
31
|
+
/** An entity of the app's schema, by name. */
|
|
32
|
+
export function entityOf(schema, name) {
|
|
33
|
+
return Object.hasOwn(schema, name) ? schema[name] : undefined;
|
|
34
|
+
}
|
|
35
|
+
/** A field of an entity, by name. */
|
|
36
|
+
export function fieldOf(def, name) {
|
|
37
|
+
return Object.hasOwn(def.fields, name) ? def.fields[name] : undefined;
|
|
38
|
+
}
|
|
39
|
+
/** Checks app input against an entity definition. `partial` is for updates. Throws VALIDATION. */
|
|
40
|
+
export function validateInput(entity, def, input, { partial }) {
|
|
41
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
|
42
|
+
throw new QuadError('VALIDATION', `${entity}: input must be an object`);
|
|
43
|
+
}
|
|
44
|
+
const problems = [];
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const [key, value] of Object.entries(input)) {
|
|
47
|
+
const field = fieldOf(def, key);
|
|
48
|
+
if (!field) {
|
|
49
|
+
problems.push(`${key}: not a field of ${entity}`);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (value === undefined)
|
|
53
|
+
continue;
|
|
54
|
+
if (value === null) {
|
|
55
|
+
if (!field.optional)
|
|
56
|
+
problems.push(`${key}: required`);
|
|
57
|
+
else
|
|
58
|
+
out[key] = null;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const p = problem(field, value);
|
|
62
|
+
if (p)
|
|
63
|
+
problems.push(`${key}: ${p}`);
|
|
64
|
+
else
|
|
65
|
+
out[key] = value;
|
|
66
|
+
}
|
|
67
|
+
if (!partial) {
|
|
68
|
+
for (const [key, field] of Object.entries(def.fields)) {
|
|
69
|
+
if (!field.optional && !(key in out))
|
|
70
|
+
problems.push(`${key}: required`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (problems.length > 0)
|
|
74
|
+
throw new QuadError('VALIDATION', `${entity}: ${problems.join('; ')}`, { problems });
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const isObject: (v: unknown) => v is Record<string, unknown>;
|
|
2
|
+
export declare function str(v: unknown, what: string): string;
|
|
3
|
+
export declare function optionalStr(v: unknown, what: string, max: number): string | undefined;
|
|
4
|
+
export declare function instant(v: unknown, what: string): string;
|
|
5
|
+
export declare function appLink(v: unknown): string | undefined;
|
|
6
|
+
/** A JSON value of bounded size (payloads, task and audit data). */
|
|
7
|
+
export declare function json(v: unknown, what: string): unknown;
|
|
8
|
+
export declare function jsonObject(v: unknown, what: string): Record<string, unknown> | undefined;
|
|
9
|
+
/** Rejects keys the caller may not set, e.g. an audit entry's actor or time. */
|
|
10
|
+
export declare function onlyKeys(input: Record<string, unknown>, allowed: readonly string[], what: string): void;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
// Small validators shared by the engine modules.
|
|
3
|
+
export const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
4
|
+
export function str(v, what) {
|
|
5
|
+
if (typeof v !== 'string' || v.length === 0)
|
|
6
|
+
throw new QuadError('VALIDATION', `${what} must be a non-empty string`);
|
|
7
|
+
return v;
|
|
8
|
+
}
|
|
9
|
+
export function optionalStr(v, what, max) {
|
|
10
|
+
if (v === undefined)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (typeof v !== 'string' || v.length > max)
|
|
13
|
+
throw new QuadError('VALIDATION', `${what} must be a string of at most ${max} characters`);
|
|
14
|
+
return v;
|
|
15
|
+
}
|
|
16
|
+
export function instant(v, what) {
|
|
17
|
+
if (typeof v !== 'string' || Number.isNaN(Date.parse(v)))
|
|
18
|
+
throw new QuadError('VALIDATION', `${what} must be an ISO 8601 instant`);
|
|
19
|
+
return new Date(Date.parse(v)).toISOString();
|
|
20
|
+
}
|
|
21
|
+
export function appLink(v) {
|
|
22
|
+
if (v === undefined)
|
|
23
|
+
return undefined;
|
|
24
|
+
if (typeof v !== 'string' || !v.startsWith('/') || v.startsWith('//')) {
|
|
25
|
+
throw new QuadError('VALIDATION', 'link must be an app-relative path starting with /');
|
|
26
|
+
}
|
|
27
|
+
return v;
|
|
28
|
+
}
|
|
29
|
+
const MAX_JSON = 10_000;
|
|
30
|
+
/** A JSON value of bounded size (payloads, task and audit data). */
|
|
31
|
+
export function json(v, what) {
|
|
32
|
+
let text;
|
|
33
|
+
try {
|
|
34
|
+
text = JSON.stringify(v);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new QuadError('VALIDATION', `${what} must be JSON`);
|
|
38
|
+
}
|
|
39
|
+
if (text === undefined)
|
|
40
|
+
throw new QuadError('VALIDATION', `${what} must be JSON`);
|
|
41
|
+
if (text.length > MAX_JSON)
|
|
42
|
+
throw new QuadError('VALIDATION', `${what} is larger than ${MAX_JSON} characters`);
|
|
43
|
+
return JSON.parse(text);
|
|
44
|
+
}
|
|
45
|
+
export function jsonObject(v, what) {
|
|
46
|
+
if (v === undefined)
|
|
47
|
+
return undefined;
|
|
48
|
+
if (!isObject(v))
|
|
49
|
+
throw new QuadError('VALIDATION', `${what} must be an object`);
|
|
50
|
+
return json(v, what);
|
|
51
|
+
}
|
|
52
|
+
/** Rejects keys the caller may not set, e.g. an audit entry's actor or time. */
|
|
53
|
+
export function onlyKeys(input, allowed, what) {
|
|
54
|
+
const extra = Object.keys(input).filter((k) => !allowed.includes(k));
|
|
55
|
+
if (extra.length > 0) {
|
|
56
|
+
throw new QuadError('VALIDATION', `${what}: unknown field${extra.length > 1 ? 's' : ''} ${extra.join(', ')} (the platform sets actor, time and source)`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SessionInfo } from './protocol.ts';
|
|
2
|
+
/** Window messages used only for the handshake. All RPC runs over the port afterwards (D15). */
|
|
3
|
+
/** `nonce` pairs each hello with the ready it answers, so concurrent connects never share a port. */
|
|
4
|
+
export type ReadyMessage = {
|
|
5
|
+
type: 'quad:ready';
|
|
6
|
+
protocol: 1;
|
|
7
|
+
nonce: string;
|
|
8
|
+
};
|
|
9
|
+
export type HelloMessage = {
|
|
10
|
+
type: 'quad:hello';
|
|
11
|
+
protocol: 1;
|
|
12
|
+
nonce: string;
|
|
13
|
+
session: SessionInfo;
|
|
14
|
+
};
|
|
15
|
+
export declare const isReady: (data: unknown) => data is ReadyMessage;
|
|
16
|
+
export declare const isHello: (data: unknown) => data is HelloMessage;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const isReady = (data) => !!data &&
|
|
2
|
+
typeof data === 'object' &&
|
|
3
|
+
data.type === 'quad:ready' &&
|
|
4
|
+
typeof data.nonce === 'string';
|
|
5
|
+
export const isHello = (data) => !!data &&
|
|
6
|
+
typeof data === 'object' &&
|
|
7
|
+
data.type === 'quad:hello' &&
|
|
8
|
+
typeof data.nonce === 'string' &&
|
|
9
|
+
typeof data.session?.appId === 'string';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Principal } from '@quad-education/canonical';
|
|
2
|
+
import type { AppConfig, CurrentApp, JsonValue, QuadSdk } from '../contract/types.ts';
|
|
3
|
+
export type JobContext<A extends AppConfig = CurrentApp> = {
|
|
4
|
+
/**
|
|
5
|
+
* Connected as the run's principal (D7): the system principal for cron jobs (full access
|
|
6
|
+
* to the app's own data, D25), or the user who scheduled the job, with only their access.
|
|
7
|
+
* Check with `sdk.auth.me()`.
|
|
8
|
+
*/
|
|
9
|
+
readonly sdk: QuadSdk<A>;
|
|
10
|
+
/** Stable across redelivery. Use it in idempotency keys so a second run has no extra effect. */
|
|
11
|
+
readonly runId: string;
|
|
12
|
+
readonly jobName: string;
|
|
13
|
+
/** The occurrence this run is for (ISO, UTC). */
|
|
14
|
+
readonly scheduledFor: string;
|
|
15
|
+
/** What `schedule.at` passed; null for cron runs. */
|
|
16
|
+
readonly payload: JsonValue;
|
|
17
|
+
};
|
|
18
|
+
export type Job<A extends AppConfig = CurrentApp> = {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
run(ctx: JobContext<A>): Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
/** Define a job. Its name must match a `cron` entry or a `scheduled` name in app.manifest.json. */
|
|
23
|
+
export declare function defineJob<A extends AppConfig = CurrentApp>(job: Job<A>): Job<A>;
|
|
24
|
+
/** One run as the engine hands it out. */
|
|
25
|
+
export type RunRequest = {
|
|
26
|
+
readonly runId: string;
|
|
27
|
+
readonly jobName: string;
|
|
28
|
+
readonly scheduledFor: string;
|
|
29
|
+
readonly payload: JsonValue;
|
|
30
|
+
readonly attempt: number;
|
|
31
|
+
/** Who the run acts as. The host must connect the job's SDK as this principal (D7). */
|
|
32
|
+
readonly runAs: Principal;
|
|
33
|
+
};
|
|
34
|
+
export type RunResult = {
|
|
35
|
+
ok: true;
|
|
36
|
+
} | {
|
|
37
|
+
ok: false;
|
|
38
|
+
error: string;
|
|
39
|
+
};
|
|
40
|
+
/** Runs one job for a run request. Used by the jobs worker, the test kit and contract tests. */
|
|
41
|
+
export declare function executeRun(jobs: readonly Job<AppConfig>[], run: RunRequest, sdk: QuadSdk<AppConfig>): Promise<RunResult>;
|