@quad-education/sdk 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/contract-tests/apps.d.ts +617 -0
- package/dist/contract-tests/apps.js +215 -1
- package/dist/contract-tests/harness.d.ts +1 -1
- package/dist/contract-tests/harness.js +7 -0
- package/dist/contract-tests/lists-and-files.d.ts +19 -0
- package/dist/contract-tests/lists-and-files.js +279 -0
- package/dist/contract-tests/live.d.ts +3 -0
- package/dist/contract-tests/live.js +156 -0
- package/dist/contract-tests/notifications.d.ts +3 -0
- package/dist/contract-tests/notifications.js +218 -0
- package/dist/contract-tests/search-and-totals.d.ts +13 -0
- package/dist/contract-tests/search-and-totals.js +226 -0
- package/dist/contract-tests/suite.d.ts +7 -0
- package/dist/contract-tests/suite.js +180 -2
- package/dist/contract-tests/writes.d.ts +3 -0
- package/dist/contract-tests/writes.js +265 -0
- package/dist/src/base64.d.ts +3 -0
- package/dist/src/base64.js +52 -0
- package/dist/src/client/connect.d.ts +1 -0
- package/dist/src/client/connect.js +1 -0
- package/dist/src/client/create-client.js +39 -5
- package/dist/src/client/save-file.d.ts +16 -0
- package/dist/src/client/save-file.js +28 -0
- package/dist/src/client/watch.d.ts +20 -0
- package/dist/src/client/watch.js +175 -0
- package/dist/src/contract/errors.d.ts +1 -1
- package/dist/src/contract/types.d.ts +220 -10
- package/dist/src/contract/types.js +4 -1
- package/dist/src/engine/engine.d.ts +91 -2
- package/dist/src/engine/engine.js +604 -67
- package/dist/src/engine/files.d.ts +25 -0
- package/dist/src/engine/files.js +88 -0
- package/dist/src/engine/index.d.ts +1 -1
- package/dist/src/engine/memory-store.d.ts +33 -3
- package/dist/src/engine/memory-store.js +116 -8
- package/dist/src/engine/notify-content.d.ts +9 -0
- package/dist/src/engine/notify-content.js +88 -0
- package/dist/src/engine/query.d.ts +14 -2
- package/dist/src/engine/query.js +45 -13
- package/dist/src/engine/search.d.ts +8 -0
- package/dist/src/engine/search.js +32 -0
- package/dist/src/engine/state.d.ts +5 -0
- package/dist/src/engine/storage.d.ts +46 -1
- package/dist/src/engine/storage.js +46 -3
- package/dist/src/engine/store.d.ts +39 -2
- package/dist/src/engine/summary.d.ts +25 -0
- package/dist/src/engine/summary.js +107 -0
- package/dist/src/engine/validate-input.d.ts +7 -1
- package/dist/src/engine/validate-input.js +28 -1
- package/dist/src/engine/working-copy.d.ts +30 -0
- package/dist/src/engine/working-copy.js +91 -0
- package/dist/src/platform-types.d.ts +11 -1
- package/dist/src/protocol.d.ts +1 -1
- package/dist/src/protocol.js +9 -0
- package/dist/src/testing/index.d.ts +9 -0
- package/dist/src/testing/index.js +16 -1
- package/package.json +4 -4
|
@@ -62,6 +62,11 @@ export type Ctx = {
|
|
|
62
62
|
actorId: string;
|
|
63
63
|
/** Students this principal can see, computed once per call. */
|
|
64
64
|
students?: 'all' | Set<string>;
|
|
65
|
+
/**
|
|
66
|
+
* The `appAdmin` and `listed:` rules this principal passes (D142), worked out once per db call, before any row is
|
|
67
|
+
* checked: a listing is a lookup in the app's store, and the row check is synchronous.
|
|
68
|
+
*/
|
|
69
|
+
grants?: ReadonlySet<string>;
|
|
65
70
|
};
|
|
66
71
|
export declare const isStaffOrSystem: (ctx: Ctx) => boolean;
|
|
67
72
|
export declare const roleOfPrincipal: (ctx: Ctx) => Role | "system";
|
|
@@ -21,12 +21,57 @@ export type StoredPlatform = {
|
|
|
21
21
|
id: string;
|
|
22
22
|
data: unknown;
|
|
23
23
|
};
|
|
24
|
-
|
|
24
|
+
/** A file an app keeps (D148), and where it is attached once a record holds its id. */
|
|
25
|
+
export type StoredFile = {
|
|
26
|
+
id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
type: string;
|
|
29
|
+
size: number;
|
|
30
|
+
createdAt: string;
|
|
31
|
+
createdBy: string;
|
|
32
|
+
attachedTo?: {
|
|
33
|
+
entity: string;
|
|
34
|
+
recordId: string;
|
|
35
|
+
field: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Set on the copy a notification carries (D152): kept as long as the app's data, and never readable through
|
|
39
|
+
* `sdk.files`.
|
|
40
|
+
*/
|
|
41
|
+
sentWith?: string;
|
|
42
|
+
};
|
|
43
|
+
export type StoredFileRow = {
|
|
44
|
+
appId: string;
|
|
45
|
+
id: string;
|
|
46
|
+
data: StoredFile;
|
|
47
|
+
};
|
|
48
|
+
type Store = 'records' | 'outbox' | 'keys' | 'meta' | 'platform' | 'files' | 'fileBytes';
|
|
25
49
|
export declare class EngineStorage {
|
|
26
50
|
private readonly db;
|
|
27
51
|
private constructor();
|
|
28
52
|
static open(factory: IDBFactory, name?: string): Promise<EngineStorage>;
|
|
29
53
|
close(): void;
|
|
54
|
+
/** A file's details and contents, written together. */
|
|
55
|
+
putFile(appId: string, file: StoredFile, bytes?: Uint8Array): Promise<void>;
|
|
56
|
+
/** One transaction for everything a write call stores (D150). */
|
|
57
|
+
commit(appId: string, writes: {
|
|
58
|
+
put: {
|
|
59
|
+
entity: string;
|
|
60
|
+
record: Record<string, unknown>;
|
|
61
|
+
}[];
|
|
62
|
+
delete: {
|
|
63
|
+
entity: string;
|
|
64
|
+
record: Record<string, unknown>;
|
|
65
|
+
}[];
|
|
66
|
+
putFiles: StoredFile[];
|
|
67
|
+
deleteFiles: string[];
|
|
68
|
+
keys: {
|
|
69
|
+
key: string;
|
|
70
|
+
result: unknown;
|
|
71
|
+
}[];
|
|
72
|
+
}): Promise<void>;
|
|
73
|
+
fileBytes(appId: string, id: string): Promise<Uint8Array | undefined>;
|
|
74
|
+
deleteFile(appId: string, id: string): Promise<void>;
|
|
30
75
|
getAll<T>(store: Exclude<Store, 'meta'>, appId: string): Promise<T[]>;
|
|
31
76
|
getMeta(appId: string): Promise<StoredMeta | undefined>;
|
|
32
77
|
put(store: Store, values: readonly unknown[]): Promise<void>;
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// never has a handle to them. The engine keeps a write-through copy of each app's data in memory.
|
|
3
3
|
export const ENGINE_DB_NAME = 'quad-engine';
|
|
4
4
|
// v2 adds the 'platform' store (Slice B: tasks, schedules, runs, cron state, audit).
|
|
5
|
-
|
|
5
|
+
// v3 adds 'files' and 'fileBytes' (D148): a file's details, and its contents, which are read only when asked for.
|
|
6
|
+
const VERSION = 3;
|
|
6
7
|
const req = (r) => new Promise((resolve, reject) => {
|
|
7
8
|
r.onsuccess = () => resolve(r.result);
|
|
8
9
|
r.onerror = () => reject(r.error);
|
|
@@ -30,12 +31,53 @@ export class EngineStorage {
|
|
|
30
31
|
if (e.oldVersion < 2) {
|
|
31
32
|
db.createObjectStore('platform', { keyPath: ['appId', 'kind', 'id'] }).createIndex('byApp', 'appId');
|
|
32
33
|
}
|
|
34
|
+
if (e.oldVersion < 3) {
|
|
35
|
+
for (const store of ['files', 'fileBytes'])
|
|
36
|
+
db.createObjectStore(store, { keyPath: ['appId', 'id'] }).createIndex('byApp', 'appId');
|
|
37
|
+
}
|
|
33
38
|
};
|
|
34
39
|
return new EngineStorage(await req(open));
|
|
35
40
|
}
|
|
36
41
|
close() {
|
|
37
42
|
this.db.close();
|
|
38
43
|
}
|
|
44
|
+
/** A file's details and contents, written together. */
|
|
45
|
+
async putFile(appId, file, bytes) {
|
|
46
|
+
const tx = this.db.transaction(['files', 'fileBytes'], 'readwrite');
|
|
47
|
+
tx.objectStore('files').put({ appId, id: file.id, data: file });
|
|
48
|
+
if (bytes)
|
|
49
|
+
tx.objectStore('fileBytes').put({ appId, id: file.id, bytes });
|
|
50
|
+
await done(tx);
|
|
51
|
+
}
|
|
52
|
+
/** One transaction for everything a write call stores (D150). */
|
|
53
|
+
async commit(appId, writes) {
|
|
54
|
+
const tx = this.db.transaction(['records', 'keys', 'files', 'fileBytes'], 'readwrite');
|
|
55
|
+
const records = tx.objectStore('records');
|
|
56
|
+
for (const { entity, record } of writes.put)
|
|
57
|
+
records.put({ appId, entity, id: record.id, data: record });
|
|
58
|
+
for (const { entity, record } of writes.delete)
|
|
59
|
+
records.delete([appId, entity, record.id]);
|
|
60
|
+
for (const file of writes.putFiles)
|
|
61
|
+
tx.objectStore('files').put({ appId, id: file.id, data: file });
|
|
62
|
+
for (const id of writes.deleteFiles) {
|
|
63
|
+
tx.objectStore('files').delete([appId, id]);
|
|
64
|
+
tx.objectStore('fileBytes').delete([appId, id]);
|
|
65
|
+
}
|
|
66
|
+
for (const { key, result } of writes.keys)
|
|
67
|
+
tx.objectStore('keys').put({ appId, key, result });
|
|
68
|
+
await done(tx);
|
|
69
|
+
}
|
|
70
|
+
async fileBytes(appId, id) {
|
|
71
|
+
const tx = this.db.transaction('fileBytes', 'readonly');
|
|
72
|
+
const row = (await req(tx.objectStore('fileBytes').get([appId, id])));
|
|
73
|
+
return row?.bytes;
|
|
74
|
+
}
|
|
75
|
+
async deleteFile(appId, id) {
|
|
76
|
+
const tx = this.db.transaction(['files', 'fileBytes'], 'readwrite');
|
|
77
|
+
tx.objectStore('files').delete([appId, id]);
|
|
78
|
+
tx.objectStore('fileBytes').delete([appId, id]);
|
|
79
|
+
await done(tx);
|
|
80
|
+
}
|
|
39
81
|
async getAll(store, appId) {
|
|
40
82
|
const tx = this.db.transaction(store, 'readonly');
|
|
41
83
|
return req(tx.objectStore(store).index('byApp').getAll(appId));
|
|
@@ -66,9 +108,10 @@ export class EngineStorage {
|
|
|
66
108
|
* shell's reset button clears everything, including the outbox and platform state.
|
|
67
109
|
*/
|
|
68
110
|
async clearApp(appId, { schemaChangeOnly = false } = {}) {
|
|
111
|
+
// Files go with the records they are attached to (D148).
|
|
69
112
|
const stores = schemaChangeOnly
|
|
70
|
-
? ['records', 'keys']
|
|
71
|
-
: ['records', 'keys', 'outbox', 'platform'];
|
|
113
|
+
? ['records', 'keys', 'files', 'fileBytes']
|
|
114
|
+
: ['records', 'keys', 'outbox', 'platform', 'files', 'fileBytes'];
|
|
72
115
|
const tx = this.db.transaction([...stores], 'readwrite');
|
|
73
116
|
for (const store of stores) {
|
|
74
117
|
const index = tx.objectStore(store).index('byApp');
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AppSchema } from '@quad-education/schema';
|
|
2
2
|
import type { OutboxEntry } from '../platform-types.ts';
|
|
3
|
-
import type { PlatformKind } from './storage.ts';
|
|
4
|
-
export type { PlatformKind };
|
|
3
|
+
import type { PlatformKind, StoredFile } from './storage.ts';
|
|
4
|
+
export type { PlatformKind, StoredFile };
|
|
5
5
|
/** A stored record: the app's fields plus the system fields (id, createdAt, createdBy, updatedAt, updatedBy). */
|
|
6
6
|
export type StoredRecordData = Record<string, unknown>;
|
|
7
7
|
/**
|
|
@@ -17,6 +17,25 @@ export type ReadHint = {
|
|
|
17
17
|
/** The entity's declared indexes, each a list of field names. */
|
|
18
18
|
readonly indexes: readonly (readonly string[])[];
|
|
19
19
|
};
|
|
20
|
+
/** Everything one write call stores, together or not at all (D150). */
|
|
21
|
+
export type StoreWrites = {
|
|
22
|
+
put: {
|
|
23
|
+
entity: string;
|
|
24
|
+
record: StoredRecordData;
|
|
25
|
+
previous?: StoredRecordData;
|
|
26
|
+
}[];
|
|
27
|
+
delete: {
|
|
28
|
+
entity: string;
|
|
29
|
+
record: StoredRecordData;
|
|
30
|
+
}[];
|
|
31
|
+
/** Files whose details changed (attached). Contents are never part of a commit. */
|
|
32
|
+
putFiles: StoredFile[];
|
|
33
|
+
deleteFiles: string[];
|
|
34
|
+
keys: {
|
|
35
|
+
key: string;
|
|
36
|
+
result: unknown;
|
|
37
|
+
}[];
|
|
38
|
+
};
|
|
20
39
|
export interface AppStore {
|
|
21
40
|
/**
|
|
22
41
|
* Get the app's state ready. When the stored schema hash differs from `schemaHash`, records and idempotency keys
|
|
@@ -33,6 +52,17 @@ export interface AppStore {
|
|
|
33
52
|
candidates(appId: string, entity: string, hint: ReadHint): Promise<StoredRecordData[]>;
|
|
34
53
|
/** Every record id and update time, by entity (for the run-twice effects snapshot). */
|
|
35
54
|
recordStamps(appId: string): Promise<Record<string, Record<string, string>>>;
|
|
55
|
+
/**
|
|
56
|
+
* Store a write call's records, files and idempotency keys in one step (D150): all of it, or none. On a school
|
|
57
|
+
* environment's store this is one transaction, with a unique rule's markers in it (D149).
|
|
58
|
+
*/
|
|
59
|
+
commit(appId: string, writes: StoreWrites): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* A stamp for each entity asked about, different after any write to that entity (D157). It says nothing else:
|
|
62
|
+
* a caller only ever compares it with the one it was given before. On a school environment's store it is one
|
|
63
|
+
* small item for each entity, brought up to date from the table's change stream.
|
|
64
|
+
*/
|
|
65
|
+
versions(appId: string, entities: readonly string[]): Promise<Record<string, string>>;
|
|
36
66
|
getKey(appId: string, key: string): Promise<unknown>;
|
|
37
67
|
putKey(appId: string, key: string, result: unknown): Promise<void>;
|
|
38
68
|
getPlatform<T>(appId: string, kind: PlatformKind, id: string): Promise<T | undefined>;
|
|
@@ -42,6 +72,13 @@ export interface AppStore {
|
|
|
42
72
|
}[]): Promise<void>;
|
|
43
73
|
/** The next audit sequence number for the app: 1, then 2 and so on, never repeated. */
|
|
44
74
|
nextAuditSeq(appId: string): Promise<number>;
|
|
75
|
+
/** A file's details (D148). Its contents are read apart, only when asked for. */
|
|
76
|
+
getFile(appId: string, id: string): Promise<StoredFile | undefined>;
|
|
77
|
+
allFiles(appId: string): Promise<StoredFile[]>;
|
|
78
|
+
/** Write a file's details, and its contents when it is new. */
|
|
79
|
+
putFile(appId: string, file: StoredFile, bytes?: Uint8Array): Promise<void>;
|
|
80
|
+
fileBytes(appId: string, id: string): Promise<Uint8Array | undefined>;
|
|
81
|
+
deleteFile(appId: string, id: string): Promise<void>;
|
|
45
82
|
putOutbox(appId: string, entries: readonly OutboxEntry[]): Promise<void>;
|
|
46
83
|
outbox(appId: string): Promise<OutboxEntry[]>;
|
|
47
84
|
close(): void | Promise<void>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AppEntityDef } from '@quad-education/schema';
|
|
2
|
+
/** The most records a count or a summary reads: a school environment's read limit (ADR 0007). */
|
|
3
|
+
export declare const MAX_SUMMARY_RECORDS = 20000;
|
|
4
|
+
export declare const MAX_GROUPS = 200;
|
|
5
|
+
export declare const TOTALS: readonly ["sum", "min", "max", "avg"];
|
|
6
|
+
type Total = (typeof TOTALS)[number];
|
|
7
|
+
type Plan = {
|
|
8
|
+
groupBy?: string;
|
|
9
|
+
} & Partial<Record<Total, string[]>>;
|
|
10
|
+
type Totals = {
|
|
11
|
+
count: number;
|
|
12
|
+
} & Partial<Record<Total, Record<string, number | null>>>;
|
|
13
|
+
/** The options of a count or a summary, with nothing else on them. */
|
|
14
|
+
export declare function queryOptions(options: unknown, allowed: readonly string[], what: string): Record<string, unknown>;
|
|
15
|
+
/** What a summary is asked for, checked against the entity and the fields this caller can see. */
|
|
16
|
+
export declare function summaryPlan(entity: string, def: AppEntityDef, options: Record<string, unknown>, visible: ReadonlySet<string>): Plan;
|
|
17
|
+
/** Past the read limit a count or a summary is refused, never wrong. */
|
|
18
|
+
export declare function checkSummarySize(entity: string, matching: number): void;
|
|
19
|
+
/** The count and totals of rows, and of each group when the plan groups them. Throws VALIDATION past a limit. */
|
|
20
|
+
export declare function summarise(entity: string, rows: readonly Record<string, unknown>[], plan: Plan): Totals & {
|
|
21
|
+
groups?: (Totals & {
|
|
22
|
+
value: unknown;
|
|
23
|
+
})[];
|
|
24
|
+
};
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
import { isObject } from "./values.js";
|
|
3
|
+
import { fieldOf } from "./validate-input.js";
|
|
4
|
+
// Counts and totals (D154, ADR 0042): how many records match, and the sum, least, greatest and average of number
|
|
5
|
+
// fields, for all of them or for each value of one field. The engine hands in only records the caller may read,
|
|
6
|
+
// and only fields they can see may be grouped or totalled, so a total never reveals what a list would not.
|
|
7
|
+
/** The most records a count or a summary reads: a school environment's read limit (ADR 0007). */
|
|
8
|
+
export const MAX_SUMMARY_RECORDS = 20_000;
|
|
9
|
+
export const MAX_GROUPS = 200;
|
|
10
|
+
export const TOTALS = ['sum', 'min', 'max', 'avg'];
|
|
11
|
+
/** The options of a count or a summary, with nothing else on them. */
|
|
12
|
+
export function queryOptions(options, allowed, what) {
|
|
13
|
+
if (options !== undefined && !isObject(options))
|
|
14
|
+
throw new QuadError('VALIDATION', `${what}: options must be an object`);
|
|
15
|
+
const given = options ?? {};
|
|
16
|
+
const extra = Object.keys(given).filter((k) => !allowed.includes(k));
|
|
17
|
+
if (extra.length > 0)
|
|
18
|
+
throw new QuadError('VALIDATION', `${what}: unknown option${extra.length > 1 ? 's' : ''} ${extra.join(', ')}; it takes ${allowed.join(', ')}`);
|
|
19
|
+
return given;
|
|
20
|
+
}
|
|
21
|
+
/** What a summary is asked for, checked against the entity and the fields this caller can see. */
|
|
22
|
+
export function summaryPlan(entity, def, options, visible) {
|
|
23
|
+
const plan = {};
|
|
24
|
+
const seen = (field) => {
|
|
25
|
+
if (!visible.has(field))
|
|
26
|
+
throw new QuadError('VALIDATION', `${entity}.${field} isn't a field you can use here`);
|
|
27
|
+
};
|
|
28
|
+
if (options.groupBy !== undefined) {
|
|
29
|
+
const field = options.groupBy;
|
|
30
|
+
if (typeof field !== 'string')
|
|
31
|
+
throw new QuadError('VALIDATION', 'groupBy: the name of one field');
|
|
32
|
+
seen(field);
|
|
33
|
+
const kind = field === 'createdBy' ? 'text' : fieldOf(def, field)?.kind;
|
|
34
|
+
if (kind === undefined || kind === 'list' || kind === 'file')
|
|
35
|
+
throw new QuadError('VALIDATION', `groupBy: '${field}' must be a single-valued field of ${entity} (not a list or a file), or createdBy`);
|
|
36
|
+
plan.groupBy = field;
|
|
37
|
+
}
|
|
38
|
+
for (const total of TOTALS) {
|
|
39
|
+
const fields = options[total];
|
|
40
|
+
if (fields === undefined)
|
|
41
|
+
continue;
|
|
42
|
+
if (!Array.isArray(fields) ||
|
|
43
|
+
fields.length === 0 ||
|
|
44
|
+
!fields.every((f) => typeof f === 'string') ||
|
|
45
|
+
new Set(fields).size !== fields.length)
|
|
46
|
+
throw new QuadError('VALIDATION', `${total}: a list of number fields, each once`);
|
|
47
|
+
for (const field of fields) {
|
|
48
|
+
seen(field);
|
|
49
|
+
if (fieldOf(def, field)?.kind !== 'number')
|
|
50
|
+
throw new QuadError('VALIDATION', `${total}: '${field}' is not a number field of ${entity}`);
|
|
51
|
+
}
|
|
52
|
+
plan[total] = fields;
|
|
53
|
+
}
|
|
54
|
+
return plan;
|
|
55
|
+
}
|
|
56
|
+
function totalsOf(rows, plan) {
|
|
57
|
+
const out = { count: rows.length };
|
|
58
|
+
const numbers = (field) => rows.map((r) => r[field]).filter((v) => typeof v === 'number');
|
|
59
|
+
// Rounded to twelve significant digits, so 0.1 + 0.2 is 0.3 here as it is on paper.
|
|
60
|
+
const tidy = (n) => Number(n.toPrecision(12));
|
|
61
|
+
const work = {
|
|
62
|
+
sum: (v) => tidy(v.reduce((a, b) => a + b, 0)),
|
|
63
|
+
min: (v) => (v.length ? Math.min(...v) : null),
|
|
64
|
+
max: (v) => (v.length ? Math.max(...v) : null),
|
|
65
|
+
avg: (v) => (v.length ? tidy(v.reduce((a, b) => a + b, 0) / v.length) : null),
|
|
66
|
+
};
|
|
67
|
+
for (const total of TOTALS) {
|
|
68
|
+
const fields = plan[total];
|
|
69
|
+
if (fields)
|
|
70
|
+
out[total] = Object.fromEntries(fields.map((f) => [f, work[total](numbers(f))]));
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
/** Past the read limit a count or a summary is refused, never wrong. */
|
|
75
|
+
export function checkSummarySize(entity, matching) {
|
|
76
|
+
if (matching > MAX_SUMMARY_RECORDS)
|
|
77
|
+
throw new QuadError('VALIDATION', `more than ${MAX_SUMMARY_RECORDS.toLocaleString('en-AU')} ${entity} records match: narrow it with where, or keep a summary record up to date in a scheduled job`);
|
|
78
|
+
}
|
|
79
|
+
/** The count and totals of rows, and of each group when the plan groups them. Throws VALIDATION past a limit. */
|
|
80
|
+
export function summarise(entity, rows, plan) {
|
|
81
|
+
checkSummarySize(entity, rows.length);
|
|
82
|
+
const all = totalsOf(rows, plan);
|
|
83
|
+
if (plan.groupBy === undefined)
|
|
84
|
+
return all;
|
|
85
|
+
const groups = new Map();
|
|
86
|
+
for (const row of rows) {
|
|
87
|
+
const value = row[plan.groupBy] ?? null;
|
|
88
|
+
let group = groups.get(value);
|
|
89
|
+
if (!group)
|
|
90
|
+
groups.set(value, (group = []));
|
|
91
|
+
group.push(row);
|
|
92
|
+
}
|
|
93
|
+
if (groups.size > MAX_GROUPS)
|
|
94
|
+
throw new QuadError('VALIDATION', `'${plan.groupBy}' has more than ${MAX_GROUPS} different values among these ${entity} records: narrow it with where, or group by another field`);
|
|
95
|
+
// In order of value, with the records that leave the field empty last.
|
|
96
|
+
const ordered = [...groups.entries()].sort(([a], [b]) => a === null
|
|
97
|
+
? 1
|
|
98
|
+
: b === null
|
|
99
|
+
? -1
|
|
100
|
+
: typeof a === 'number' && typeof b === 'number'
|
|
101
|
+
? a - b
|
|
102
|
+
: String(a).localeCompare(String(b)));
|
|
103
|
+
return {
|
|
104
|
+
...all,
|
|
105
|
+
groups: ordered.map(([value, members]) => ({ value, ...totalsOf(members, plan) })),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AppEntityDef, type AppFieldDef, type AppSchema, type ListItemDef } from '@quad-education/schema';
|
|
2
|
+
/** The single values a field holds: a list's items, or the one value of any other field. */
|
|
3
|
+
export declare function valuesOf(def: AppFieldDef, value: unknown): readonly unknown[];
|
|
4
|
+
/** What a field holds one of: what a list holds, or the field itself. */
|
|
5
|
+
export declare function heldBy(def: AppFieldDef): ListItemDef | {
|
|
6
|
+
readonly kind: 'boolean';
|
|
7
|
+
};
|
|
2
8
|
/** An entity of the app's schema, by name. */
|
|
3
9
|
export declare function entityOf(schema: AppSchema, name: string): AppEntityDef | undefined;
|
|
4
10
|
/** A field of an entity, by name. */
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
+
import { MAX_LIST_ITEMS, } from '@quad-education/schema';
|
|
1
2
|
import { QuadError } from "../contract/errors.js";
|
|
2
3
|
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
3
4
|
const DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
4
|
-
|
|
5
|
+
/** A single value of a field's kind: a field that is not a list, or one item of a list. */
|
|
6
|
+
function itemProblem(def, value) {
|
|
5
7
|
switch (def.kind) {
|
|
6
8
|
case 'text':
|
|
7
9
|
case 'ref':
|
|
10
|
+
case 'file':
|
|
8
11
|
return typeof value === 'string' ? null : 'expected a string';
|
|
9
12
|
case 'number':
|
|
10
13
|
return typeof value === 'number' && Number.isFinite(value) ? null : 'expected a number';
|
|
@@ -26,6 +29,30 @@ function problem(def, value) {
|
|
|
26
29
|
: `expected one of: ${def.values.join(', ')}`;
|
|
27
30
|
}
|
|
28
31
|
}
|
|
32
|
+
function problem(def, value) {
|
|
33
|
+
if (def.kind !== 'list')
|
|
34
|
+
return itemProblem(def, value);
|
|
35
|
+
if (!Array.isArray(value))
|
|
36
|
+
return 'expected a list';
|
|
37
|
+
if (value.length > MAX_LIST_ITEMS)
|
|
38
|
+
return `a list holds at most ${MAX_LIST_ITEMS} items`;
|
|
39
|
+
for (const [i, item] of value.entries()) {
|
|
40
|
+
const p = itemProblem(def.of, item);
|
|
41
|
+
if (p)
|
|
42
|
+
return `item ${i + 1}: ${p}`;
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
/** The single values a field holds: a list's items, or the one value of any other field. */
|
|
47
|
+
export function valuesOf(def, value) {
|
|
48
|
+
if (value === undefined || value === null)
|
|
49
|
+
return [];
|
|
50
|
+
return def.kind === 'list' ? (Array.isArray(value) ? value : []) : [value];
|
|
51
|
+
}
|
|
52
|
+
/** What a field holds one of: what a list holds, or the field itself. */
|
|
53
|
+
export function heldBy(def) {
|
|
54
|
+
return def.kind === 'list' ? def.of : def;
|
|
55
|
+
}
|
|
29
56
|
// Own properties only: names inherited from Object.prototype (`constructor`, `toString`)
|
|
30
57
|
// are never entities or fields, whatever a caller or a fetched schema says.
|
|
31
58
|
/** An entity of the app's schema, by name. */
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { AppStore, StoredFile, StoredRecordData } from './store.ts';
|
|
2
|
+
/**
|
|
3
|
+
* What one write call has done so far, before any of it is stored (D150). A create, an update, a delete and a
|
|
4
|
+
* batch all run against a working copy: reads see the store with the call's own changes laid over it, and
|
|
5
|
+
* `commit` stores records, files and idempotency keys together or not at all. A call that fails simply drops it.
|
|
6
|
+
*/
|
|
7
|
+
export declare class WorkingCopy {
|
|
8
|
+
private readonly store;
|
|
9
|
+
private readonly appId;
|
|
10
|
+
/** entity → id → the record as written, or null when the call deleted it. */
|
|
11
|
+
private readonly records;
|
|
12
|
+
private readonly originals;
|
|
13
|
+
private readonly files;
|
|
14
|
+
private readonly keys;
|
|
15
|
+
constructor(store: AppStore, appId: string);
|
|
16
|
+
getRecord(entity: string, id: string): Promise<StoredRecordData | undefined>;
|
|
17
|
+
/** Every record of an entity as it would stand after this call. */
|
|
18
|
+
all(entity: string): Promise<StoredRecordData[]>;
|
|
19
|
+
private change;
|
|
20
|
+
putRecord(entity: string, record: StoredRecordData): Promise<void>;
|
|
21
|
+
deleteRecord(entity: string, record: StoredRecordData): Promise<void>;
|
|
22
|
+
getFile(id: string): Promise<StoredFile | undefined>;
|
|
23
|
+
/** A file's details only: its contents were stored when it was uploaded. */
|
|
24
|
+
putFile(file: StoredFile): void;
|
|
25
|
+
deleteFile(id: string): void;
|
|
26
|
+
getKey(key: string): Promise<unknown>;
|
|
27
|
+
putKey(key: string, result: unknown): void;
|
|
28
|
+
/** Store everything the call did, together. */
|
|
29
|
+
commit(): Promise<void>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one write call has done so far, before any of it is stored (D150). A create, an update, a delete and a
|
|
3
|
+
* batch all run against a working copy: reads see the store with the call's own changes laid over it, and
|
|
4
|
+
* `commit` stores records, files and idempotency keys together or not at all. A call that fails simply drops it.
|
|
5
|
+
*/
|
|
6
|
+
export class WorkingCopy {
|
|
7
|
+
store;
|
|
8
|
+
appId;
|
|
9
|
+
/** entity → id → the record as written, or null when the call deleted it. */
|
|
10
|
+
records = new Map();
|
|
11
|
+
originals = new Map();
|
|
12
|
+
files = new Map();
|
|
13
|
+
keys = new Map();
|
|
14
|
+
constructor(store, appId) {
|
|
15
|
+
this.store = store;
|
|
16
|
+
this.appId = appId;
|
|
17
|
+
}
|
|
18
|
+
async getRecord(entity, id) {
|
|
19
|
+
const changed = this.records.get(entity);
|
|
20
|
+
if (changed?.has(id))
|
|
21
|
+
return changed.get(id) ?? undefined;
|
|
22
|
+
return this.store.getRecord(this.appId, entity, id);
|
|
23
|
+
}
|
|
24
|
+
/** Every record of an entity as it would stand after this call. */
|
|
25
|
+
async all(entity) {
|
|
26
|
+
const stored = await this.store.candidates(this.appId, entity, { indexes: [] });
|
|
27
|
+
const changed = this.records.get(entity);
|
|
28
|
+
if (!changed)
|
|
29
|
+
return stored;
|
|
30
|
+
const out = stored.filter((r) => !changed.has(r.id));
|
|
31
|
+
for (const r of changed.values())
|
|
32
|
+
if (r)
|
|
33
|
+
out.push(r);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
async change(entity, id, record) {
|
|
37
|
+
const stored = await this.store.getRecord(this.appId, entity, id);
|
|
38
|
+
if (stored && !this.originals.has(`${entity}\n${id}`))
|
|
39
|
+
this.originals.set(`${entity}\n${id}`, stored);
|
|
40
|
+
let changed = this.records.get(entity);
|
|
41
|
+
if (!changed)
|
|
42
|
+
this.records.set(entity, (changed = new Map()));
|
|
43
|
+
changed.set(id, record);
|
|
44
|
+
}
|
|
45
|
+
async putRecord(entity, record) {
|
|
46
|
+
await this.change(entity, record.id, record);
|
|
47
|
+
}
|
|
48
|
+
async deleteRecord(entity, record) {
|
|
49
|
+
await this.change(entity, record.id, null);
|
|
50
|
+
}
|
|
51
|
+
async getFile(id) {
|
|
52
|
+
if (this.files.has(id))
|
|
53
|
+
return this.files.get(id) ?? undefined;
|
|
54
|
+
return this.store.getFile(this.appId, id);
|
|
55
|
+
}
|
|
56
|
+
/** A file's details only: its contents were stored when it was uploaded. */
|
|
57
|
+
putFile(file) {
|
|
58
|
+
this.files.set(file.id, file);
|
|
59
|
+
}
|
|
60
|
+
deleteFile(id) {
|
|
61
|
+
this.files.set(id, null);
|
|
62
|
+
}
|
|
63
|
+
async getKey(key) {
|
|
64
|
+
return this.keys.has(key) ? this.keys.get(key) : this.store.getKey(this.appId, key);
|
|
65
|
+
}
|
|
66
|
+
putKey(key, result) {
|
|
67
|
+
this.keys.set(key, result);
|
|
68
|
+
}
|
|
69
|
+
/** Store everything the call did, together. */
|
|
70
|
+
async commit() {
|
|
71
|
+
const writes = { put: [], delete: [], putFiles: [], deleteFiles: [], keys: [] };
|
|
72
|
+
for (const [entity, changed] of this.records) {
|
|
73
|
+
for (const [id, record] of changed) {
|
|
74
|
+
const previous = this.originals.get(`${entity}\n${id}`);
|
|
75
|
+
if (record)
|
|
76
|
+
writes.put.push({ entity, record, ...(previous ? { previous } : {}) });
|
|
77
|
+
else if (previous)
|
|
78
|
+
writes.delete.push({ entity, record: previous });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const [id, file] of this.files) {
|
|
82
|
+
if (file)
|
|
83
|
+
writes.putFiles.push(file);
|
|
84
|
+
else
|
|
85
|
+
writes.deleteFiles.push(id);
|
|
86
|
+
}
|
|
87
|
+
for (const [key, result] of this.keys)
|
|
88
|
+
writes.keys.push({ key, result });
|
|
89
|
+
await this.store.commit(this.appId, writes);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Role } from '@quad-education/canonical';
|
|
2
|
-
import type { Channel } from './contract/types.ts';
|
|
2
|
+
import type { Channel, NotifyBlock } from './contract/types.ts';
|
|
3
3
|
/** A simulated outbox entry (D10). Visible to the demo shell and tests, never to apps. */
|
|
4
4
|
export type OutboxEntry = {
|
|
5
5
|
readonly id: string;
|
|
@@ -9,7 +9,17 @@ export type OutboxEntry = {
|
|
|
9
9
|
readonly recipientId: string;
|
|
10
10
|
readonly recipientRole: Role;
|
|
11
11
|
readonly subject: string;
|
|
12
|
+
/** The message as plain text: what the app gave, or made from `content`. */
|
|
12
13
|
readonly body: string;
|
|
14
|
+
/** The message in blocks, when the app sent it formatted (D151). */
|
|
15
|
+
readonly content?: readonly NotifyBlock[];
|
|
16
|
+
/** The copies sent with the message (D152): read one with the engine's `sentFile`. */
|
|
17
|
+
readonly attachments?: readonly {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly type: string;
|
|
21
|
+
readonly size: number;
|
|
22
|
+
}[];
|
|
13
23
|
readonly link?: string;
|
|
14
24
|
readonly regardingStudentId?: string;
|
|
15
25
|
readonly sentAt: string;
|
package/dist/src/protocol.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { QuadError, type QuadErrorCode } from './contract/errors.ts';
|
|
2
|
-
export declare const METHODS: readonly ["auth.me", "auth.appAdmins", "school.info", "school.get", "school.list", "school.cohortByCode", "school.cohortMembers", "school.studentParents", "school.parentChildren", "db.create", "db.update", "db.get", "db.list", "db.delete", "notify.send", "tasks.assign", "tasks.get", "tasks.list", "tasks.complete", "tasks.cancel", "schedule.at", "schedule.cancel", "schedule.list", "cron.list", "audit.record", "audit.list"];
|
|
2
|
+
export declare const METHODS: readonly ["auth.me", "auth.appAdmins", "school.info", "school.get", "school.list", "school.cohortByCode", "school.cohortMembers", "school.studentParents", "school.parentChildren", "db.create", "db.update", "db.get", "db.list", "db.count", "db.summarise", "db.delete", "db.batch", "db.changes", "notify.send", "tasks.assign", "tasks.get", "tasks.list", "tasks.complete", "tasks.cancel", "schedule.at", "schedule.cancel", "schedule.list", "cron.list", "audit.record", "audit.list", "files.upload", "files.info", "files.read"];
|
|
3
3
|
export type Method = (typeof METHODS)[number];
|
|
4
4
|
export type SerializedError = {
|
|
5
5
|
code: QuadErrorCode;
|
package/dist/src/protocol.js
CHANGED
|
@@ -15,7 +15,12 @@ export const METHODS = [
|
|
|
15
15
|
'db.update',
|
|
16
16
|
'db.get',
|
|
17
17
|
'db.list',
|
|
18
|
+
'db.count',
|
|
19
|
+
'db.summarise',
|
|
18
20
|
'db.delete',
|
|
21
|
+
'db.batch',
|
|
22
|
+
// D157: a stamp for each entity, different after any write to it. No records.
|
|
23
|
+
'db.changes',
|
|
19
24
|
'notify.send',
|
|
20
25
|
'tasks.assign',
|
|
21
26
|
'tasks.get',
|
|
@@ -28,6 +33,10 @@ export const METHODS = [
|
|
|
28
33
|
'cron.list',
|
|
29
34
|
'audit.record',
|
|
30
35
|
'audit.list',
|
|
36
|
+
// D148: a file's contents travel as base64 text, so params stay JSON.
|
|
37
|
+
'files.upload',
|
|
38
|
+
'files.info',
|
|
39
|
+
'files.read',
|
|
31
40
|
];
|
|
32
41
|
export function clockNow(state, wallClockMs) {
|
|
33
42
|
return state.kind === 'fixed' ? state.at : wallClockMs + state.offsetMs;
|
|
@@ -21,6 +21,11 @@ export type TestPlatform = {
|
|
|
21
21
|
* None by default, so a test says who is an admin.
|
|
22
22
|
*/
|
|
23
23
|
setAppAdmins(who: readonly PersonWho[]): void;
|
|
24
|
+
/**
|
|
25
|
+
* Give people the app's own roles, as a school does (D143): a suggested person's rule or anyone's id, to the names
|
|
26
|
+
* from the manifest's `roles`. It replaces any given before; nobody holds one unless a test says so.
|
|
27
|
+
*/
|
|
28
|
+
setAppRoles(roles: Readonly<Partial<Record<PersonWho, readonly string[]>>>): void;
|
|
24
29
|
setClock(iso: string | null): Promise<void>;
|
|
25
30
|
close(): void;
|
|
26
31
|
};
|
|
@@ -31,6 +36,8 @@ export declare function createTestPlatform(app: {
|
|
|
31
36
|
now?: string;
|
|
32
37
|
/** The app's admins from the start (D133); see `TestPlatform.setAppAdmins`. */
|
|
33
38
|
appAdmins?: readonly PersonWho[];
|
|
39
|
+
/** Who holds the app's own roles from the start (D143); see `TestPlatform.setAppRoles`. */
|
|
40
|
+
appRoles?: Readonly<Partial<Record<PersonWho, readonly string[]>>>;
|
|
34
41
|
}): Promise<TestPlatform>;
|
|
35
42
|
/** A suggestion rule, such as `parent-of-siblings` (see `SUGGESTION_RULES`), or a person's id. */
|
|
36
43
|
export type PersonWho = SuggestionRule | (string & {});
|
|
@@ -47,6 +54,8 @@ export type Effects = {
|
|
|
47
54
|
updated: number;
|
|
48
55
|
deleted: number;
|
|
49
56
|
}>;
|
|
57
|
+
/** Files uploaded (D148): a job that uploads the same file on each run leaves one behind every time. */
|
|
58
|
+
filesUploaded: number;
|
|
50
59
|
};
|
|
51
60
|
/** True if a run changed anything at all. */
|
|
52
61
|
export declare function hasEffects(e: Effects): boolean;
|