@quad-education/sdk 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/contract-tests/apps.d.ts +430 -0
- package/dist/contract-tests/apps.js +143 -1
- package/dist/contract-tests/harness.d.ts +1 -1
- package/dist/contract-tests/harness.js +4 -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 +5 -0
- package/dist/contract-tests/suite.js +27 -1
- 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 +214 -10
- package/dist/src/contract/types.js +4 -1
- package/dist/src/engine/engine.d.ts +68 -1
- package/dist/src/engine/engine.js +508 -57
- 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/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 +2 -0
- package/dist/src/testing/index.js +9 -1
- package/package.json +4 -4
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type AppEntityDef, type AppSchema, type FileGroup } from '@quad-education/schema';
|
|
2
|
+
import type { FileInfo } from '../contract/types.ts';
|
|
3
|
+
import type { StoredFile } from './storage.ts';
|
|
4
|
+
/** How long an uploaded file may stay unattached. */
|
|
5
|
+
export declare const UNATTACHED_MS: number;
|
|
6
|
+
/** The most one app's files may total in the Sandbox, where they live in the viewer's browser. */
|
|
7
|
+
export declare const MAX_APP_FILE_BYTES: number;
|
|
8
|
+
export declare const fileInfo: (f: StoredFile) => FileInfo;
|
|
9
|
+
/** Whether any field of the app's schema holds a file. An app with none has nowhere to attach one. */
|
|
10
|
+
export declare function schemaKeepsFiles(schema: AppSchema): boolean;
|
|
11
|
+
/** An upload's name, type and contents, checked. Throws VALIDATION. */
|
|
12
|
+
export declare function checkUpload(params: Record<string, unknown>): {
|
|
13
|
+
name: string;
|
|
14
|
+
type: string;
|
|
15
|
+
bytes: Uint8Array;
|
|
16
|
+
};
|
|
17
|
+
/** Why a file can't go in a field, or null: the field's `accept` narrows the kinds (D148). */
|
|
18
|
+
export declare function acceptProblem(held: {
|
|
19
|
+
readonly kind: string;
|
|
20
|
+
readonly accept?: readonly FileGroup[];
|
|
21
|
+
}, file: StoredFile): string | null;
|
|
22
|
+
/** The file ids each file field of a record names: field to ids. */
|
|
23
|
+
export declare function filesNamed(def: AppEntityDef, record: Record<string, unknown>): Map<string, string[]>;
|
|
24
|
+
/** An id as a caller gave it. */
|
|
25
|
+
export declare function fileId(params: unknown): string;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { MAX_FILE_BYTES, fileTypesFor, } from '@quad-education/schema';
|
|
2
|
+
import { fromBase64 } from "../base64.js";
|
|
3
|
+
import { QuadError } from "../contract/errors.js";
|
|
4
|
+
import { heldBy, valuesOf } from "./validate-input.js";
|
|
5
|
+
import { isObject } from "./values.js";
|
|
6
|
+
// Files an app keeps (D148, ADR 0039). A file belongs to one field of one record, and whoever can read that field
|
|
7
|
+
// can read the file. This module holds what needs no access rule: the checks of an upload, and which files a
|
|
8
|
+
// record's fields name. The engine decides who may read, attach and remove.
|
|
9
|
+
/** How long an uploaded file may stay unattached. */
|
|
10
|
+
export const UNATTACHED_MS = 24 * 60 * 60 * 1000;
|
|
11
|
+
/** The most one app's files may total in the Sandbox, where they live in the viewer's browser. */
|
|
12
|
+
export const MAX_APP_FILE_BYTES = 200 * 1024 * 1024;
|
|
13
|
+
const MAX_NAME = 200;
|
|
14
|
+
/** The first bytes a file of a type must have. Types not listed are not checked. */
|
|
15
|
+
const SIGNATURES = {
|
|
16
|
+
'image/png': (b) => startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
17
|
+
'image/jpeg': (b) => startsWith(b, [0xff, 0xd8, 0xff]),
|
|
18
|
+
'image/gif': (b) => startsWith(b, [0x47, 0x49, 0x46, 0x38]),
|
|
19
|
+
// RIFF....WEBP
|
|
20
|
+
'image/webp': (b) => startsWith(b, [0x52, 0x49, 0x46, 0x46]) && startsWith(b.subarray(8), [0x57, 0x45, 0x42, 0x50]),
|
|
21
|
+
'application/pdf': (b) => startsWith(b, [0x25, 0x50, 0x44, 0x46, 0x2d]),
|
|
22
|
+
};
|
|
23
|
+
function startsWith(bytes, signature) {
|
|
24
|
+
return bytes.length >= signature.length && signature.every((v, i) => bytes[i] === v);
|
|
25
|
+
}
|
|
26
|
+
export const fileInfo = (f) => ({
|
|
27
|
+
id: f.id,
|
|
28
|
+
name: f.name,
|
|
29
|
+
type: f.type,
|
|
30
|
+
size: f.size,
|
|
31
|
+
createdAt: f.createdAt,
|
|
32
|
+
createdBy: f.createdBy,
|
|
33
|
+
});
|
|
34
|
+
/** Whether any field of the app's schema holds a file. An app with none has nowhere to attach one. */
|
|
35
|
+
export function schemaKeepsFiles(schema) {
|
|
36
|
+
return Object.values(schema).some((def) => Object.values(def.fields).some((f) => heldBy(f).kind === 'file'));
|
|
37
|
+
}
|
|
38
|
+
/** An upload's name, type and contents, checked. Throws VALIDATION. */
|
|
39
|
+
export function checkUpload(params) {
|
|
40
|
+
const { name = 'file', type, data } = params;
|
|
41
|
+
if (typeof name !== 'string' || name.length === 0 || name.length > MAX_NAME)
|
|
42
|
+
throw new QuadError('VALIDATION', `a file's name is 1 to ${MAX_NAME} characters`);
|
|
43
|
+
// A name is shown and offered as a download's name: never a path, and nothing unprintable.
|
|
44
|
+
if (/[\\/]/.test(name) || [...name].some((c) => c.charCodeAt(0) < 32))
|
|
45
|
+
throw new QuadError('VALIDATION', "a file's name can't contain / or \\ or control characters");
|
|
46
|
+
const allowed = fileTypesFor(undefined);
|
|
47
|
+
if (typeof type !== 'string' || !allowed.includes(type))
|
|
48
|
+
throw new QuadError('VALIDATION', `Quad doesn't keep files of type '${String(type)}'. It keeps images (PNG, JPEG, GIF, WebP), PDF, plain text and CSV, and Word, Excel and PowerPoint documents`);
|
|
49
|
+
// Four characters of base64 hold three bytes, so the length is known before decoding.
|
|
50
|
+
if (typeof data !== 'string' || data.length > Math.ceil(MAX_FILE_BYTES / 3) * 4)
|
|
51
|
+
throw new QuadError('VALIDATION', typeof data === 'string'
|
|
52
|
+
? `a file can be at most ${MAX_FILE_BYTES / (1024 * 1024)} MB`
|
|
53
|
+
: "a file's contents are missing");
|
|
54
|
+
const bytes = fromBase64(data);
|
|
55
|
+
if (!bytes)
|
|
56
|
+
throw new QuadError('VALIDATION', "a file's contents could not be read");
|
|
57
|
+
if (bytes.length === 0)
|
|
58
|
+
throw new QuadError('VALIDATION', 'the file is empty');
|
|
59
|
+
if (bytes.length > MAX_FILE_BYTES)
|
|
60
|
+
throw new QuadError('VALIDATION', `a file can be at most ${MAX_FILE_BYTES / (1024 * 1024)} MB`);
|
|
61
|
+
const signature = SIGNATURES[type];
|
|
62
|
+
if (signature && !signature(bytes))
|
|
63
|
+
throw new QuadError('VALIDATION', `the file's contents are not ${type}`);
|
|
64
|
+
return { name, type, bytes };
|
|
65
|
+
}
|
|
66
|
+
/** Why a file can't go in a field, or null: the field's `accept` narrows the kinds (D148). */
|
|
67
|
+
export function acceptProblem(held, file) {
|
|
68
|
+
return fileTypesFor(held.accept).includes(file.type)
|
|
69
|
+
? null
|
|
70
|
+
: `takes ${(held.accept ?? []).join(' or ')} files, not ${file.type}`;
|
|
71
|
+
}
|
|
72
|
+
/** The file ids each file field of a record names: field to ids. */
|
|
73
|
+
export function filesNamed(def, record) {
|
|
74
|
+
const out = new Map();
|
|
75
|
+
for (const [name, field] of Object.entries(def.fields)) {
|
|
76
|
+
if (heldBy(field).kind !== 'file' || !(name in record))
|
|
77
|
+
continue;
|
|
78
|
+
out.set(name, valuesOf(field, record[name]).filter((v) => typeof v === 'string'));
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
/** An id as a caller gave it. */
|
|
83
|
+
export function fileId(params) {
|
|
84
|
+
const id = isObject(params) ? params.id : undefined;
|
|
85
|
+
if (typeof id !== 'string' || id.length === 0)
|
|
86
|
+
throw new QuadError('VALIDATION', 'id must be a non-empty string');
|
|
87
|
+
return id;
|
|
88
|
+
}
|
|
@@ -4,7 +4,7 @@ export { connectInProcess } from './in-process.ts';
|
|
|
4
4
|
export { hostApp, type AppHost, type HostOptions, type HostedFrame, type RejectedMessage, } from './host.ts';
|
|
5
5
|
export type { RunRequest, RunResult } from '../jobs/define.ts';
|
|
6
6
|
export type { CronState, StoredAudit, StoredRun, StoredSchedule, StoredTask } from './state.ts';
|
|
7
|
-
export { MemoryStore } from './memory-store.ts';
|
|
7
|
+
export { MemoryStore, type StoreChannel } from './memory-store.ts';
|
|
8
8
|
export type { AppStore, PlatformKind, ReadHint, StoredRecordData } from './store.ts';
|
|
9
9
|
export { servePort } from '../port-rpc.ts';
|
|
10
10
|
export { ENGINE_DB_NAME } from './storage.ts';
|
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import type { OutboxEntry } from '../platform-types.ts';
|
|
2
|
-
import { type PlatformKind } from './storage.ts';
|
|
3
|
-
import type { AppStore, ReadHint, StoredRecordData } from './store.ts';
|
|
2
|
+
import { type PlatformKind, type StoredFile } from './storage.ts';
|
|
3
|
+
import type { AppStore, ReadHint, StoreWrites, StoredRecordData } from './store.ts';
|
|
4
|
+
/**
|
|
5
|
+
* How windows of one browser tell each other what they stored (D158): a `BroadcastChannel`, or anything shaped
|
|
6
|
+
* like one. Each window keeps its own copy of an app's records in memory, so without this a second window never
|
|
7
|
+
* sees the first one's writes.
|
|
8
|
+
*/
|
|
9
|
+
export type StoreChannel = {
|
|
10
|
+
postMessage(message: unknown): void;
|
|
11
|
+
onmessage: ((event: {
|
|
12
|
+
data: unknown;
|
|
13
|
+
}) => void) | null;
|
|
14
|
+
close(): void;
|
|
15
|
+
};
|
|
4
16
|
/**
|
|
5
17
|
* The in-browser store (D15): an app's state in memory, written through to IndexedDB. Reads hand out the stored
|
|
6
18
|
* objects themselves, and the engine changes them and puts them back, which is how it has always worked.
|
|
@@ -8,9 +20,21 @@ import type { AppStore, ReadHint, StoredRecordData } from './store.ts';
|
|
|
8
20
|
export declare class MemoryStore implements AppStore {
|
|
9
21
|
private readonly storage;
|
|
10
22
|
private readonly apps;
|
|
23
|
+
/** Told apart from every other store's stamps, so one from before a reload never matches (D157). */
|
|
24
|
+
private readonly run;
|
|
25
|
+
private writes;
|
|
26
|
+
private readonly channel;
|
|
11
27
|
private constructor();
|
|
12
|
-
static open(indexedDB: IDBFactory, dbName?: string): Promise<MemoryStore>;
|
|
28
|
+
static open(indexedDB: IDBFactory, dbName?: string, channel?: StoreChannel): Promise<MemoryStore>;
|
|
29
|
+
/** Tell the other windows what was just stored (D158). */
|
|
30
|
+
private tell;
|
|
31
|
+
/** Another window stored something: lay it over this window's copy, if it has the app open. */
|
|
32
|
+
private heard;
|
|
13
33
|
private state;
|
|
34
|
+
private changed;
|
|
35
|
+
versions(appId: string, entities: readonly string[]): Promise<{
|
|
36
|
+
[k: string]: string;
|
|
37
|
+
}>;
|
|
14
38
|
open(appId: string, schemaHash: string): Promise<void>;
|
|
15
39
|
clear(appId: string): Promise<void>;
|
|
16
40
|
getRecord(appId: string, entity: string, id: string): Promise<StoredRecordData | undefined>;
|
|
@@ -18,6 +42,7 @@ export declare class MemoryStore implements AppStore {
|
|
|
18
42
|
deleteRecord(appId: string, entity: string, record: StoredRecordData): Promise<void>;
|
|
19
43
|
candidates(appId: string, entity: string, _hint: ReadHint): Promise<StoredRecordData[]>;
|
|
20
44
|
recordStamps(appId: string): Promise<Record<string, Record<string, string>>>;
|
|
45
|
+
commit(appId: string, writes: StoreWrites): Promise<void>;
|
|
21
46
|
getKey(appId: string, key: string): Promise<unknown>;
|
|
22
47
|
putKey(appId: string, key: string, result: unknown): Promise<void>;
|
|
23
48
|
getPlatform<T>(appId: string, kind: PlatformKind, id: string): Promise<T | undefined>;
|
|
@@ -26,6 +51,11 @@ export declare class MemoryStore implements AppStore {
|
|
|
26
51
|
id: string;
|
|
27
52
|
}[]): Promise<void>;
|
|
28
53
|
nextAuditSeq(appId: string): Promise<number>;
|
|
54
|
+
getFile(appId: string, id: string): Promise<StoredFile | undefined>;
|
|
55
|
+
allFiles(appId: string): Promise<StoredFile[]>;
|
|
56
|
+
putFile(appId: string, file: StoredFile, bytes?: Uint8Array): Promise<void>;
|
|
57
|
+
fileBytes(appId: string, id: string): Promise<Uint8Array<ArrayBufferLike> | undefined>;
|
|
58
|
+
deleteFile(appId: string, id: string): Promise<void>;
|
|
29
59
|
putOutbox(_appId: string, entries: readonly OutboxEntry[]): Promise<void>;
|
|
30
60
|
outbox(appId: string): Promise<OutboxEntry[]>;
|
|
31
61
|
close(): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EngineStorage, } from "./storage.js";
|
|
2
|
-
const emptyState = () => ({
|
|
2
|
+
const emptyState = (since) => ({
|
|
3
3
|
records: new Map(),
|
|
4
4
|
keys: new Map(),
|
|
5
5
|
platform: {
|
|
@@ -10,6 +10,9 @@ const emptyState = () => ({
|
|
|
10
10
|
audit: new Map(),
|
|
11
11
|
},
|
|
12
12
|
auditSeq: 0,
|
|
13
|
+
files: new Map(),
|
|
14
|
+
versions: new Map(),
|
|
15
|
+
since,
|
|
13
16
|
});
|
|
14
17
|
/**
|
|
15
18
|
* The in-browser store (D15): an app's state in memory, written through to IndexedDB. Reads hand out the stored
|
|
@@ -18,24 +21,73 @@ const emptyState = () => ({
|
|
|
18
21
|
export class MemoryStore {
|
|
19
22
|
storage;
|
|
20
23
|
apps = new Map();
|
|
21
|
-
|
|
24
|
+
/** Told apart from every other store's stamps, so one from before a reload never matches (D157). */
|
|
25
|
+
run = crypto.randomUUID();
|
|
26
|
+
writes = 0;
|
|
27
|
+
channel;
|
|
28
|
+
constructor(storage, channel) {
|
|
22
29
|
this.storage = storage;
|
|
30
|
+
this.channel = channel;
|
|
31
|
+
if (channel)
|
|
32
|
+
channel.onmessage = (event) => this.heard(event.data);
|
|
23
33
|
}
|
|
24
|
-
static async open(indexedDB, dbName) {
|
|
25
|
-
return new MemoryStore(await EngineStorage.open(indexedDB, dbName));
|
|
34
|
+
static async open(indexedDB, dbName, channel) {
|
|
35
|
+
return new MemoryStore(await EngineStorage.open(indexedDB, dbName), channel);
|
|
36
|
+
}
|
|
37
|
+
/** Tell the other windows what was just stored (D158). */
|
|
38
|
+
tell(message) {
|
|
39
|
+
this.channel?.postMessage(message);
|
|
40
|
+
}
|
|
41
|
+
/** Another window stored something: lay it over this window's copy, if it has the app open. */
|
|
42
|
+
heard(message) {
|
|
43
|
+
if (!message || typeof message.appId !== 'string' || !this.apps.has(message.appId))
|
|
44
|
+
return;
|
|
45
|
+
const { appId } = message;
|
|
46
|
+
if (message.cleared) {
|
|
47
|
+
this.apps.set(appId, emptyState(++this.writes));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const s = this.state(appId);
|
|
51
|
+
for (const { entity, record } of message.put ?? []) {
|
|
52
|
+
let rows = s.records.get(entity);
|
|
53
|
+
if (!rows)
|
|
54
|
+
s.records.set(entity, (rows = new Map()));
|
|
55
|
+
rows.set(record.id, record);
|
|
56
|
+
}
|
|
57
|
+
for (const { entity, id } of message.delete ?? [])
|
|
58
|
+
s.records.get(entity)?.delete(id);
|
|
59
|
+
for (const file of message.putFiles ?? [])
|
|
60
|
+
s.files.set(file.id, file);
|
|
61
|
+
for (const id of message.deleteFiles ?? [])
|
|
62
|
+
s.files.delete(id);
|
|
63
|
+
for (const { key, result } of message.keys ?? [])
|
|
64
|
+
s.keys.set(key, result);
|
|
65
|
+
this.changed(appId, new Set([...(message.put ?? []), ...(message.delete ?? [])].map((w) => w.entity)));
|
|
26
66
|
}
|
|
27
67
|
state(appId) {
|
|
28
68
|
let s = this.apps.get(appId);
|
|
29
69
|
if (!s)
|
|
30
|
-
this.apps.set(appId, (s = emptyState()));
|
|
70
|
+
this.apps.set(appId, (s = emptyState(++this.writes)));
|
|
31
71
|
return s;
|
|
32
72
|
}
|
|
73
|
+
changed(appId, entities) {
|
|
74
|
+
const s = this.state(appId);
|
|
75
|
+
const at = ++this.writes;
|
|
76
|
+
for (const entity of entities)
|
|
77
|
+
s.versions.set(entity, at);
|
|
78
|
+
}
|
|
79
|
+
async versions(appId, entities) {
|
|
80
|
+
const s = this.state(appId);
|
|
81
|
+
return Object.fromEntries(entities.map((e) => [e, `${this.run}:${Math.max(s.since, s.versions.get(e) ?? 0)}`]));
|
|
82
|
+
}
|
|
33
83
|
async open(appId, schemaHash) {
|
|
34
84
|
const meta = await this.storage.getMeta(appId);
|
|
35
|
-
if (meta && meta.schemaHash !== schemaHash)
|
|
85
|
+
if (meta && meta.schemaHash !== schemaHash) {
|
|
36
86
|
await this.storage.clearApp(appId, { schemaChangeOnly: true });
|
|
87
|
+
this.tell({ appId, cleared: true });
|
|
88
|
+
}
|
|
37
89
|
await this.storage.put('meta', [{ appId, schemaHash }]);
|
|
38
|
-
const state = emptyState();
|
|
90
|
+
const state = emptyState(++this.writes);
|
|
39
91
|
for (const r of await this.storage.getAll('records', appId)) {
|
|
40
92
|
let rows = state.records.get(r.entity);
|
|
41
93
|
if (!rows)
|
|
@@ -53,11 +105,14 @@ export class MemoryStore {
|
|
|
53
105
|
if (row.kind === 'audit')
|
|
54
106
|
state.auditSeq = Math.max(state.auditSeq, data.seq ?? 0);
|
|
55
107
|
}
|
|
108
|
+
for (const f of await this.storage.getAll('files', appId))
|
|
109
|
+
state.files.set(f.id, f.data);
|
|
56
110
|
this.apps.set(appId, state);
|
|
57
111
|
}
|
|
58
112
|
async clear(appId) {
|
|
59
113
|
await this.storage.clearApp(appId);
|
|
60
|
-
this.apps.set(appId, emptyState());
|
|
114
|
+
this.apps.set(appId, emptyState(++this.writes));
|
|
115
|
+
this.tell({ appId, cleared: true });
|
|
61
116
|
}
|
|
62
117
|
async getRecord(appId, entity, id) {
|
|
63
118
|
return this.state(appId).records.get(entity)?.get(id);
|
|
@@ -69,12 +124,16 @@ export class MemoryStore {
|
|
|
69
124
|
s.records.set(entity, (rows = new Map()));
|
|
70
125
|
rows.set(record.id, record);
|
|
71
126
|
await this.storage.put('records', [{ appId, entity, id: record.id, data: record }]);
|
|
127
|
+
this.changed(appId, [entity]);
|
|
128
|
+
this.tell({ appId, put: [{ entity, record }] });
|
|
72
129
|
}
|
|
73
130
|
async deleteRecord(appId, entity, record) {
|
|
74
131
|
this.state(appId)
|
|
75
132
|
.records.get(entity)
|
|
76
133
|
?.delete(record.id);
|
|
77
134
|
await this.storage.deleteRecord(appId, entity, record.id);
|
|
135
|
+
this.changed(appId, [entity]);
|
|
136
|
+
this.tell({ appId, delete: [{ entity, id: record.id }] });
|
|
78
137
|
}
|
|
79
138
|
async candidates(appId, entity, _hint) {
|
|
80
139
|
return [...(this.state(appId).records.get(entity)?.values() ?? [])];
|
|
@@ -86,12 +145,41 @@ export class MemoryStore {
|
|
|
86
145
|
}
|
|
87
146
|
return out;
|
|
88
147
|
}
|
|
148
|
+
async commit(appId, writes) {
|
|
149
|
+
// Stored first, in one transaction; memory follows only once that has succeeded.
|
|
150
|
+
await this.storage.commit(appId, writes);
|
|
151
|
+
const s = this.state(appId);
|
|
152
|
+
for (const { entity, record } of writes.put) {
|
|
153
|
+
let rows = s.records.get(entity);
|
|
154
|
+
if (!rows)
|
|
155
|
+
s.records.set(entity, (rows = new Map()));
|
|
156
|
+
rows.set(record.id, record);
|
|
157
|
+
}
|
|
158
|
+
for (const { entity, record } of writes.delete)
|
|
159
|
+
s.records.get(entity)?.delete(record.id);
|
|
160
|
+
for (const file of writes.putFiles)
|
|
161
|
+
s.files.set(file.id, file);
|
|
162
|
+
for (const id of writes.deleteFiles)
|
|
163
|
+
s.files.delete(id);
|
|
164
|
+
for (const { key, result } of writes.keys)
|
|
165
|
+
s.keys.set(key, result);
|
|
166
|
+
this.changed(appId, new Set([...writes.put, ...writes.delete].map((w) => w.entity)));
|
|
167
|
+
this.tell({
|
|
168
|
+
appId,
|
|
169
|
+
put: writes.put.map(({ entity, record }) => ({ entity, record })),
|
|
170
|
+
delete: writes.delete.map(({ entity, record }) => ({ entity, id: record.id })),
|
|
171
|
+
putFiles: writes.putFiles,
|
|
172
|
+
deleteFiles: writes.deleteFiles,
|
|
173
|
+
keys: writes.keys,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
89
176
|
async getKey(appId, key) {
|
|
90
177
|
return this.state(appId).keys.get(key);
|
|
91
178
|
}
|
|
92
179
|
async putKey(appId, key, result) {
|
|
93
180
|
this.state(appId).keys.set(key, result);
|
|
94
181
|
await this.storage.put('keys', [{ appId, key, result }]);
|
|
182
|
+
this.tell({ appId, keys: [{ key, result }] });
|
|
95
183
|
}
|
|
96
184
|
async getPlatform(appId, kind, id) {
|
|
97
185
|
return this.state(appId).platform[kind].get(id);
|
|
@@ -110,6 +198,25 @@ export class MemoryStore {
|
|
|
110
198
|
async nextAuditSeq(appId) {
|
|
111
199
|
return ++this.state(appId).auditSeq;
|
|
112
200
|
}
|
|
201
|
+
async getFile(appId, id) {
|
|
202
|
+
return this.state(appId).files.get(id);
|
|
203
|
+
}
|
|
204
|
+
async allFiles(appId) {
|
|
205
|
+
return [...this.state(appId).files.values()];
|
|
206
|
+
}
|
|
207
|
+
async putFile(appId, file, bytes) {
|
|
208
|
+
this.state(appId).files.set(file.id, file);
|
|
209
|
+
await this.storage.putFile(appId, file, bytes);
|
|
210
|
+
this.tell({ appId, putFiles: [file] });
|
|
211
|
+
}
|
|
212
|
+
async fileBytes(appId, id) {
|
|
213
|
+
return this.storage.fileBytes(appId, id);
|
|
214
|
+
}
|
|
215
|
+
async deleteFile(appId, id) {
|
|
216
|
+
this.state(appId).files.delete(id);
|
|
217
|
+
await this.storage.deleteFile(appId, id);
|
|
218
|
+
this.tell({ appId, deleteFiles: [id] });
|
|
219
|
+
}
|
|
113
220
|
async putOutbox(_appId, entries) {
|
|
114
221
|
if (entries.length > 0)
|
|
115
222
|
await this.storage.put('outbox', entries);
|
|
@@ -118,6 +225,7 @@ export class MemoryStore {
|
|
|
118
225
|
return this.storage.getAll('outbox', appId);
|
|
119
226
|
}
|
|
120
227
|
close() {
|
|
228
|
+
this.channel?.close();
|
|
121
229
|
this.storage.close();
|
|
122
230
|
}
|
|
123
231
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { NotifyBlock } from '../contract/types.ts';
|
|
2
|
+
export declare const MAX_BLOCKS = 30;
|
|
3
|
+
/** The most files one notification carries, and the most they total (D152). */
|
|
4
|
+
export declare const MAX_ATTACHMENTS = 5;
|
|
5
|
+
export declare const MAX_ATTACHMENT_BYTES: number;
|
|
6
|
+
/** The blocks of a message, checked: only the kinds Quad renders, with nothing else on them. */
|
|
7
|
+
export declare function checkContent(value: unknown): NotifyBlock[];
|
|
8
|
+
/** A message's blocks as plain text: for the in-app list, plain-text mail and digests. */
|
|
9
|
+
export declare function plainText(blocks: readonly NotifyBlock[]): string;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
import { appLink, isObject } from "./values.js";
|
|
3
|
+
// A formatted notification (D151, ADR 0041). An app describes a message in a small set of blocks and Quad renders
|
|
4
|
+
// them: an app never writes HTML, so a message can't imitate another sender, hide a link or carry tracking.
|
|
5
|
+
// Everything here is plain text, checked and bounded.
|
|
6
|
+
export const MAX_BLOCKS = 30;
|
|
7
|
+
const MAX_SHORT = 200;
|
|
8
|
+
const MAX_PARAGRAPH = 2000;
|
|
9
|
+
const MAX_ITEMS = 20;
|
|
10
|
+
const MAX_ITEM = 500;
|
|
11
|
+
const MAX_MESSAGE = 10_000;
|
|
12
|
+
/** The most files one notification carries, and the most they total (D152). */
|
|
13
|
+
export const MAX_ATTACHMENTS = 5;
|
|
14
|
+
export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
|
|
15
|
+
const SHAPE = 'content is a list of blocks: { heading }, { text }, { list: [...] }, { details: [[label, value], ...] } or { button: { label, link } }';
|
|
16
|
+
function words(value, what, max) {
|
|
17
|
+
if (typeof value !== 'string' || value.trim().length === 0 || value.length > max)
|
|
18
|
+
throw new QuadError('VALIDATION', `${what}: text of 1 to ${max} characters`);
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
/** The blocks of a message, checked: only the kinds Quad renders, with nothing else on them. */
|
|
22
|
+
export function checkContent(value) {
|
|
23
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > MAX_BLOCKS)
|
|
24
|
+
throw new QuadError('VALIDATION', `${SHAPE}; 1 to ${MAX_BLOCKS} of them`);
|
|
25
|
+
let buttons = 0;
|
|
26
|
+
const blocks = value.map((block, i) => {
|
|
27
|
+
const at = `content[${i}]`;
|
|
28
|
+
const keys = isObject(block) ? Object.keys(block) : [];
|
|
29
|
+
if (!isObject(block) || keys.length !== 1)
|
|
30
|
+
throw new QuadError('VALIDATION', `${at}: ${SHAPE}`);
|
|
31
|
+
if ('heading' in block)
|
|
32
|
+
return { heading: words(block.heading, `${at}.heading`, MAX_SHORT) };
|
|
33
|
+
if ('text' in block)
|
|
34
|
+
return { text: words(block.text, `${at}.text`, MAX_PARAGRAPH) };
|
|
35
|
+
if ('list' in block) {
|
|
36
|
+
const items = block.list;
|
|
37
|
+
if (!Array.isArray(items) || items.length === 0 || items.length > MAX_ITEMS)
|
|
38
|
+
throw new QuadError('VALIDATION', `${at}.list: 1 to ${MAX_ITEMS} items`);
|
|
39
|
+
return { list: items.map((item, k) => words(item, `${at}.list[${k}]`, MAX_ITEM)) };
|
|
40
|
+
}
|
|
41
|
+
if ('details' in block) {
|
|
42
|
+
const rows = block.details;
|
|
43
|
+
if (!Array.isArray(rows) || rows.length === 0 || rows.length > MAX_ITEMS)
|
|
44
|
+
throw new QuadError('VALIDATION', `${at}.details: 1 to ${MAX_ITEMS} rows of [label, value]`);
|
|
45
|
+
return {
|
|
46
|
+
details: rows.map((row, k) => {
|
|
47
|
+
if (!Array.isArray(row) || row.length !== 2)
|
|
48
|
+
throw new QuadError('VALIDATION', `${at}.details[${k}]: a [label, value] pair`);
|
|
49
|
+
return [
|
|
50
|
+
words(row[0], `${at}.details[${k}] label`, MAX_SHORT),
|
|
51
|
+
words(row[1], `${at}.details[${k}] value`, MAX_ITEM),
|
|
52
|
+
];
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if ('button' in block) {
|
|
57
|
+
const button = block.button;
|
|
58
|
+
if (!isObject(button) || Object.keys(button).some((k) => k !== 'label' && k !== 'link'))
|
|
59
|
+
throw new QuadError('VALIDATION', `${at}.button: { label, link }`);
|
|
60
|
+
if (++buttons > 1)
|
|
61
|
+
throw new QuadError('VALIDATION', `${at}: a message has one button`);
|
|
62
|
+
const link = appLink(button.link);
|
|
63
|
+
if (link === undefined)
|
|
64
|
+
throw new QuadError('VALIDATION', `${at}.button.link: an app-relative path starting with /`);
|
|
65
|
+
return { button: { label: words(button.label, `${at}.button.label`, MAX_SHORT), link } };
|
|
66
|
+
}
|
|
67
|
+
throw new QuadError('VALIDATION', `${at}: ${SHAPE}`);
|
|
68
|
+
});
|
|
69
|
+
if (JSON.stringify(blocks).length > MAX_MESSAGE)
|
|
70
|
+
throw new QuadError('VALIDATION', `content is larger than ${MAX_MESSAGE} characters`);
|
|
71
|
+
return blocks;
|
|
72
|
+
}
|
|
73
|
+
/** A message's blocks as plain text: for the in-app list, plain-text mail and digests. */
|
|
74
|
+
export function plainText(blocks) {
|
|
75
|
+
return blocks
|
|
76
|
+
.map((block) => {
|
|
77
|
+
if ('heading' in block)
|
|
78
|
+
return block.heading;
|
|
79
|
+
if ('text' in block)
|
|
80
|
+
return block.text;
|
|
81
|
+
if ('list' in block)
|
|
82
|
+
return block.list.map((item) => `- ${item}`).join('\n');
|
|
83
|
+
if ('details' in block)
|
|
84
|
+
return block.details.map(([label, value]) => `${label}: ${value}`).join('\n');
|
|
85
|
+
return `${block.button.label}: ${block.button.link}`;
|
|
86
|
+
})
|
|
87
|
+
.join('\n\n');
|
|
88
|
+
}
|
|
@@ -4,12 +4,24 @@ export type QueryOptions = {
|
|
|
4
4
|
orderBy?: unknown;
|
|
5
5
|
limit?: unknown;
|
|
6
6
|
cursor?: unknown;
|
|
7
|
+
search?: unknown;
|
|
7
8
|
};
|
|
8
9
|
/**
|
|
9
|
-
*
|
|
10
|
+
* The rows a `where` and a `search` leave (D153). `searchFields` are the fields a search looks in for this
|
|
11
|
+
* reader; `undefined` means the rows can't be searched, and `refusal` says why.
|
|
12
|
+
*/
|
|
13
|
+
export declare function filterRows<T extends Row>(rows: readonly T[], options: Pick<QueryOptions, 'where' | 'search'>, allowedFields: ReadonlySet<string>, listFields?: ReadonlySet<string>, searchFields?: readonly string[] | {
|
|
14
|
+
refusal: string;
|
|
15
|
+
}): T[];
|
|
16
|
+
/**
|
|
17
|
+
* Applies where, search, orderBy, limit and cursor to rows. `allowedFields` are the fields a caller
|
|
10
18
|
* may filter or sort on; anything else is a VALIDATION error (so ungranted tiers can't be probed).
|
|
11
19
|
*/
|
|
12
|
-
export declare function runQuery<T extends Row>(rows: readonly T[], options: QueryOptions, allowedFields: ReadonlySet<string
|
|
20
|
+
export declare function runQuery<T extends Row>(rows: readonly T[], options: QueryOptions, allowedFields: ReadonlySet<string>,
|
|
21
|
+
/** Fields that hold a list (D147): filtered with `has`, never sorted by. */
|
|
22
|
+
listFields?: ReadonlySet<string>, searchFields?: readonly string[] | {
|
|
23
|
+
refusal: string;
|
|
24
|
+
}): {
|
|
13
25
|
items: T[];
|
|
14
26
|
nextCursor: string | null;
|
|
15
27
|
};
|
package/dist/src/engine/query.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
import { matchesSearch, searchWords } from "./search.js";
|
|
2
3
|
const MAX_LIMIT = 200;
|
|
3
4
|
const DEFAULT_LIMIT = 50;
|
|
4
5
|
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
@@ -15,7 +16,17 @@ function compare(a, b) {
|
|
|
15
16
|
return Number(a) - Number(b);
|
|
16
17
|
return String(a).localeCompare(String(b));
|
|
17
18
|
}
|
|
18
|
-
|
|
19
|
+
const isScalar = (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';
|
|
20
|
+
function matcher(field, condition, list) {
|
|
21
|
+
// D147: a list is asked one thing, whether it has a value.
|
|
22
|
+
if (list) {
|
|
23
|
+
if (!isPlainObject(condition) ||
|
|
24
|
+
Object.keys(condition).length !== 1 ||
|
|
25
|
+
!isScalar(condition.has))
|
|
26
|
+
throw new QuadError('VALIDATION', `where.${field}: a list is filtered with { has: value }`);
|
|
27
|
+
const wanted = condition.has;
|
|
28
|
+
return (v) => Array.isArray(v) && v.includes(wanted);
|
|
29
|
+
}
|
|
19
30
|
if (!isPlainObject(condition))
|
|
20
31
|
return (v) => v === condition;
|
|
21
32
|
const keys = Object.keys(condition);
|
|
@@ -57,16 +68,11 @@ function decodeCursor(cursor, fingerprint) {
|
|
|
57
68
|
throw new QuadError('VALIDATION', 'invalid cursor; pass the nextCursor from the previous page with the same query');
|
|
58
69
|
}
|
|
59
70
|
/**
|
|
60
|
-
*
|
|
61
|
-
*
|
|
71
|
+
* The rows a `where` and a `search` leave (D153). `searchFields` are the fields a search looks in for this
|
|
72
|
+
* reader; `undefined` means the rows can't be searched, and `refusal` says why.
|
|
62
73
|
*/
|
|
63
|
-
export function
|
|
64
|
-
|
|
65
|
-
throw new QuadError('VALIDATION', 'options must be an object');
|
|
66
|
-
const { where, orderBy, limit = DEFAULT_LIMIT, cursor } = options;
|
|
67
|
-
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
68
|
-
throw new QuadError('VALIDATION', `limit must be an integer from 1 to ${MAX_LIMIT}`);
|
|
69
|
-
}
|
|
74
|
+
export function filterRows(rows, options, allowedFields, listFields = new Set(), searchFields) {
|
|
75
|
+
const { where, search } = options;
|
|
70
76
|
let result = [...rows];
|
|
71
77
|
if (where !== undefined) {
|
|
72
78
|
if (!isPlainObject(where))
|
|
@@ -74,13 +80,39 @@ export function runQuery(rows, options, allowedFields) {
|
|
|
74
80
|
for (const [field, condition] of Object.entries(where)) {
|
|
75
81
|
if (!allowedFields.has(field))
|
|
76
82
|
throw new QuadError('VALIDATION', `can't filter on '${field}'`);
|
|
77
|
-
const match = matcher(field, condition);
|
|
83
|
+
const match = matcher(field, condition, listFields.has(field));
|
|
78
84
|
result = result.filter((r) => match(r[field]));
|
|
79
85
|
}
|
|
80
86
|
}
|
|
87
|
+
if (search !== undefined) {
|
|
88
|
+
if (searchFields === undefined || !Array.isArray(searchFields))
|
|
89
|
+
throw new QuadError('VALIDATION', searchFields?.refusal ??
|
|
90
|
+
"these records can't be searched");
|
|
91
|
+
const words = searchWords(search);
|
|
92
|
+
result = result.filter((r) => matchesSearch(r, searchFields, words));
|
|
93
|
+
}
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Applies where, search, orderBy, limit and cursor to rows. `allowedFields` are the fields a caller
|
|
98
|
+
* may filter or sort on; anything else is a VALIDATION error (so ungranted tiers can't be probed).
|
|
99
|
+
*/
|
|
100
|
+
export function runQuery(rows, options, allowedFields,
|
|
101
|
+
/** Fields that hold a list (D147): filtered with `has`, never sorted by. */
|
|
102
|
+
listFields = new Set(), searchFields) {
|
|
103
|
+
if (options !== undefined && !isPlainObject(options))
|
|
104
|
+
throw new QuadError('VALIDATION', 'options must be an object');
|
|
105
|
+
const { where, orderBy, limit = DEFAULT_LIMIT, cursor, search } = options;
|
|
106
|
+
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
107
|
+
throw new QuadError('VALIDATION', `limit must be an integer from 1 to ${MAX_LIMIT}`);
|
|
108
|
+
}
|
|
109
|
+
const result = filterRows(rows, { where, search }, allowedFields, listFields, searchFields);
|
|
81
110
|
const orders = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
82
111
|
for (const o of orders) {
|
|
83
|
-
if (!isPlainObject(o) ||
|
|
112
|
+
if (!isPlainObject(o) ||
|
|
113
|
+
typeof o.field !== 'string' ||
|
|
114
|
+
!allowedFields.has(o.field) ||
|
|
115
|
+
listFields.has(o.field)) {
|
|
84
116
|
throw new QuadError('VALIDATION', `can't order by '${String(isPlainObject(o) ? o.field : o)}'`);
|
|
85
117
|
}
|
|
86
118
|
if (o.direction !== undefined && o.direction !== 'asc' && o.direction !== 'desc') {
|
|
@@ -96,7 +128,7 @@ export function runQuery(rows, options, allowedFields) {
|
|
|
96
128
|
}
|
|
97
129
|
return compare(a.id, b.id);
|
|
98
130
|
});
|
|
99
|
-
const fingerprint = JSON.stringify({ where, orderBy, limit });
|
|
131
|
+
const fingerprint = JSON.stringify({ where, orderBy, limit, search });
|
|
100
132
|
const offset = cursor === undefined ? 0 : typeof cursor === 'string' ? decodeCursor(cursor, fingerprint) : -1;
|
|
101
133
|
if (offset < 0)
|
|
102
134
|
throw new QuadError('VALIDATION', 'cursor must be a string');
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const MAX_SEARCH_LENGTH = 100;
|
|
2
|
+
export declare const MAX_SEARCH_WORDS = 5;
|
|
3
|
+
/** Lower case with accents removed: "Zoë" and "zoe" fold to the same text. */
|
|
4
|
+
export declare function fold(text: string): string;
|
|
5
|
+
/** The words of a search, folded. Throws VALIDATION for anything but 1 to 5 words in at most 100 characters. */
|
|
6
|
+
export declare function searchWords(value: unknown): string[];
|
|
7
|
+
/** Whether every word appears in the row's searchable fields: text, or lists of text. */
|
|
8
|
+
export declare function matchesSearch(row: Record<string, unknown>, fields: readonly string[], words: readonly string[]): boolean;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { QuadError } from "../contract/errors.js";
|
|
2
|
+
// Search by words (D153, ADR 0042). A record matches when every word appears somewhere in its searchable fields,
|
|
3
|
+
// ignoring case and accents; a word matches part of a word. Pure, so a school environment's data API applies the
|
|
4
|
+
// same rule to the folded text it stores.
|
|
5
|
+
export const MAX_SEARCH_LENGTH = 100;
|
|
6
|
+
export const MAX_SEARCH_WORDS = 5;
|
|
7
|
+
/** Lower case with accents removed: "Zoë" and "zoe" fold to the same text. */
|
|
8
|
+
export function fold(text) {
|
|
9
|
+
return text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
|
10
|
+
}
|
|
11
|
+
/** The words of a search, folded. Throws VALIDATION for anything but 1 to 5 words in at most 100 characters. */
|
|
12
|
+
export function searchWords(value) {
|
|
13
|
+
const words = typeof value === 'string' ? fold(value).split(/\s+/).filter(Boolean) : [];
|
|
14
|
+
if (typeof value !== 'string' ||
|
|
15
|
+
value.length > MAX_SEARCH_LENGTH ||
|
|
16
|
+
words.length === 0 ||
|
|
17
|
+
words.length > MAX_SEARCH_WORDS)
|
|
18
|
+
throw new QuadError('VALIDATION', `search: 1 to ${MAX_SEARCH_WORDS} words, in at most ${MAX_SEARCH_LENGTH} characters`);
|
|
19
|
+
return words;
|
|
20
|
+
}
|
|
21
|
+
/** Whether every word appears in the row's searchable fields: text, or lists of text. */
|
|
22
|
+
export function matchesSearch(row, fields, words) {
|
|
23
|
+
const parts = [];
|
|
24
|
+
for (const field of fields) {
|
|
25
|
+
const value = row[field];
|
|
26
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
27
|
+
if (typeof item === 'string')
|
|
28
|
+
parts.push(fold(item));
|
|
29
|
+
}
|
|
30
|
+
const text = parts.join('\n');
|
|
31
|
+
return words.every((word) => text.includes(word));
|
|
32
|
+
}
|