@quad-education/sdk 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE.md +15 -0
  2. package/README.md +105 -2
  3. package/dist/contract-tests/apps.d.ts +332 -0
  4. package/dist/contract-tests/apps.js +261 -0
  5. package/dist/contract-tests/index.d.ts +3 -0
  6. package/dist/contract-tests/index.js +2 -0
  7. package/dist/contract-tests/suite.d.ts +57 -0
  8. package/dist/contract-tests/suite.js +1286 -0
  9. package/dist/src/client/connect.d.ts +10 -0
  10. package/dist/src/client/connect.js +12 -0
  11. package/dist/src/client/create-client.d.ts +14 -0
  12. package/dist/src/client/create-client.js +76 -0
  13. package/dist/src/client/handshake-client.d.ts +16 -0
  14. package/dist/src/client/handshake-client.js +37 -0
  15. package/dist/src/contract/errors.d.ts +8 -0
  16. package/dist/src/contract/errors.js +13 -0
  17. package/dist/src/contract/recipients.d.ts +28 -0
  18. package/dist/src/contract/recipients.js +12 -0
  19. package/dist/src/contract/types.d.ts +421 -0
  20. package/dist/src/contract/types.js +1 -0
  21. package/dist/src/engine/audit.d.ts +27 -0
  22. package/dist/src/engine/audit.js +105 -0
  23. package/dist/src/engine/cron.d.ts +17 -0
  24. package/dist/src/engine/cron.js +143 -0
  25. package/dist/src/engine/db-indexes.d.ts +11 -0
  26. package/dist/src/engine/db-indexes.js +82 -0
  27. package/dist/src/engine/engine.d.ts +153 -0
  28. package/dist/src/engine/engine.js +922 -0
  29. package/dist/src/engine/host.d.ts +39 -0
  30. package/dist/src/engine/host.js +70 -0
  31. package/dist/src/engine/in-process.d.ts +5 -0
  32. package/dist/src/engine/in-process.js +18 -0
  33. package/dist/src/engine/index.d.ts +10 -0
  34. package/dist/src/engine/index.js +8 -0
  35. package/dist/src/engine/query.d.ts +16 -0
  36. package/dist/src/engine/query.js +106 -0
  37. package/dist/src/engine/runner.d.ts +26 -0
  38. package/dist/src/engine/runner.js +260 -0
  39. package/dist/src/engine/state.d.ts +107 -0
  40. package/dist/src/engine/state.js +16 -0
  41. package/dist/src/engine/storage.d.ts +46 -0
  42. package/dist/src/engine/storage.js +86 -0
  43. package/dist/src/engine/tasks.d.ts +17 -0
  44. package/dist/src/engine/tasks.js +245 -0
  45. package/dist/src/engine/validate-input.d.ts +9 -0
  46. package/dist/src/engine/validate-input.js +76 -0
  47. package/dist/src/engine/values.d.ts +10 -0
  48. package/dist/src/engine/values.js +58 -0
  49. package/dist/src/handshake.d.ts +16 -0
  50. package/dist/src/handshake.js +9 -0
  51. package/dist/src/index.d.ts +3 -0
  52. package/dist/src/index.js +4 -0
  53. package/dist/src/jobs/define.d.ts +41 -0
  54. package/dist/src/jobs/define.js +28 -0
  55. package/dist/src/jobs/host.d.ts +13 -0
  56. package/dist/src/jobs/host.js +22 -0
  57. package/dist/src/jobs/index.d.ts +1 -0
  58. package/dist/src/jobs/index.js +2 -0
  59. package/dist/src/jobs/worker.d.ts +17 -0
  60. package/dist/src/jobs/worker.js +25 -0
  61. package/dist/src/platform-types.d.ts +19 -0
  62. package/dist/src/platform-types.js +1 -0
  63. package/dist/src/port-rpc.d.ts +42 -0
  64. package/dist/src/port-rpc.js +85 -0
  65. package/dist/src/protocol.d.ts +41 -0
  66. package/dist/src/protocol.js +45 -0
  67. package/dist/src/testing/index.d.ts +78 -0
  68. package/dist/src/testing/index.js +118 -0
  69. package/package.json +71 -3
@@ -0,0 +1,27 @@
1
+ import type { AuditEntry } from '../contract/types.ts';
2
+ import { type App, type Ctx, type Kernel, type StoredAudit } from './state.ts';
3
+ export type AuditInput = {
4
+ source: 'app' | 'platform';
5
+ action: string;
6
+ actor: string;
7
+ summary: string;
8
+ visibility: 'app' | 'cio';
9
+ entity?: string;
10
+ recordId?: string;
11
+ /** The student an entry is about; it then follows that student's visibility (D25). */
12
+ regardingStudentId?: string;
13
+ data?: Record<string, unknown>;
14
+ };
15
+ export declare function appendAudit(k: Kernel, app: App, input: AuditInput): Promise<StoredAudit>;
16
+ export declare function auditView(e: StoredAudit): AuditEntry;
17
+ export declare function recordAudit(k: Kernel, ctx: Ctx, input: unknown): Promise<AuditEntry>;
18
+ /**
19
+ * App-recorded entries only (D19): platform entries (tasks, notifications, jobs, sensitive
20
+ * reads, suppressions) are never exposed through the SDK. Staff see the app's entries;
21
+ * parents and students only their own. An entry about a student also needs that student
22
+ * to be visible, staff included (D25). The system principal sees all app entries.
23
+ */
24
+ export declare function listAudit(k: Kernel, ctx: Ctx, options: unknown): {
25
+ items: AuditEntry[];
26
+ nextCursor: string | null;
27
+ };
@@ -0,0 +1,105 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { runQuery } from "./query.js";
3
+ import { isStaffOrSystem, seesSubject, } from "./state.js";
4
+ import { isObject, jsonObject, onlyKeys, optionalStr, str } from "./values.js";
5
+ export async function appendAudit(k, app, input) {
6
+ const seq = (app.audit[app.audit.length - 1]?.seq ?? 0) + 1;
7
+ const entry = {
8
+ id: `aud-${String(seq).padStart(7, '0')}`,
9
+ seq,
10
+ appId: app.manifest.id,
11
+ at: k.nowIso(),
12
+ source: input.source,
13
+ action: input.action,
14
+ actor: input.actor,
15
+ summary: input.summary,
16
+ visibility: input.visibility,
17
+ ...(input.entity !== undefined ? { entity: input.entity } : {}),
18
+ ...(input.recordId !== undefined ? { recordId: input.recordId } : {}),
19
+ ...(input.regardingStudentId !== undefined
20
+ ? { regardingStudentId: input.regardingStudentId }
21
+ : {}),
22
+ ...(input.data !== undefined ? { data: input.data } : {}),
23
+ };
24
+ app.audit.push(entry);
25
+ await k.persistPlatform(app, 'audit', [entry]);
26
+ return entry;
27
+ }
28
+ export function auditView(e) {
29
+ const { seq: _seq, visibility: _visibility, ...view } = e;
30
+ return view;
31
+ }
32
+ const ACTION_RE = /^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*$/;
33
+ export async function recordAudit(k, ctx, input) {
34
+ if (!isObject(input))
35
+ throw new QuadError('VALIDATION', 'audit.record takes an object');
36
+ onlyKeys(input, ['action', 'summary', 'entity', 'recordId', 'regarding', 'data', 'idempotencyKey'], 'audit.record');
37
+ const key = k.idempotencyKey(input, 'audit.record');
38
+ if (key && ctx.app.keys.has(key)) {
39
+ const existing = ctx.app.audit.find((e) => e.id === ctx.app.keys.get(key));
40
+ if (existing)
41
+ return auditView(existing);
42
+ }
43
+ const action = str(input.action, 'action');
44
+ if (!ACTION_RE.test(action) || action.length > 100) {
45
+ throw new QuadError('VALIDATION', 'action must be dotted lowercase, e.g. greeting.approved');
46
+ }
47
+ const summary = str(input.summary, 'summary');
48
+ if (summary.length > 500)
49
+ throw new QuadError('VALIDATION', 'summary must be at most 500 characters');
50
+ const entity = optionalStr(input.entity, 'entity', 100);
51
+ const recordId = optionalStr(input.recordId, 'recordId', 200);
52
+ const data = jsonObject(input.data, 'data');
53
+ let regardingStudentId;
54
+ if (input.regarding !== undefined) {
55
+ if (!isObject(input.regarding))
56
+ throw new QuadError('VALIDATION', 'regarding must be { studentId }');
57
+ regardingStudentId = str(input.regarding.studentId, 'regarding.studentId');
58
+ if (!seesSubject(k, ctx, regardingStudentId)) {
59
+ throw new QuadError('NOT_PERMITTED', 'regarding: not a student you can see');
60
+ }
61
+ }
62
+ const entry = await appendAudit(k, ctx.app, {
63
+ source: 'app',
64
+ action,
65
+ actor: ctx.actorId,
66
+ summary,
67
+ visibility: 'app',
68
+ ...(entity !== undefined ? { entity } : {}),
69
+ ...(regardingStudentId !== undefined ? { regardingStudentId } : {}),
70
+ ...(recordId !== undefined ? { recordId } : {}),
71
+ ...(data !== undefined ? { data } : {}),
72
+ });
73
+ if (key)
74
+ await k.remember(ctx, key, entry.id);
75
+ return auditView(entry);
76
+ }
77
+ /**
78
+ * App-recorded entries only (D19): platform entries (tasks, notifications, jobs, sensitive
79
+ * reads, suppressions) are never exposed through the SDK. Staff see the app's entries;
80
+ * parents and students only their own. An entry about a student also needs that student
81
+ * to be visible, staff included (D25). The system principal sees all app entries.
82
+ */
83
+ export function listAudit(k, ctx, options) {
84
+ const opts = (isObject(options) ? options : {});
85
+ const { entity, recordId, action, limit, cursor } = opts;
86
+ const where = {};
87
+ if (entity !== undefined)
88
+ where.entity = str(entity, 'entity');
89
+ if (recordId !== undefined)
90
+ where.recordId = str(recordId, 'recordId');
91
+ if (action !== undefined)
92
+ where.action = str(action, 'action');
93
+ const visible = ctx.app.audit.filter((e) => e.source === 'app' &&
94
+ (isStaffOrSystem(ctx) || e.actor === ctx.actorId) &&
95
+ seesSubject(k, ctx, e.regardingStudentId));
96
+ const page = runQuery(visible, {
97
+ where,
98
+ ...(limit !== undefined ? { limit } : {}),
99
+ ...(cursor !== undefined ? { cursor } : {}),
100
+ }, new Set(['entity', 'recordId', 'action']));
101
+ return {
102
+ items: page.items.map(auditView),
103
+ nextCursor: page.nextCursor,
104
+ };
105
+ }
@@ -0,0 +1,17 @@
1
+ type Spec = {
2
+ minutes: number[];
3
+ hours: number[];
4
+ dom: Set<number>;
5
+ months: Set<number>;
6
+ dow: Set<number>;
7
+ domAny: boolean;
8
+ dowAny: boolean;
9
+ };
10
+ export declare function parseCron(expr: string): Spec;
11
+ /** UTC instant for a local wall-clock time in `tz`. */
12
+ export declare function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number;
13
+ /** The latest occurrence in (afterMs, upToMs], or null. Missed runs collapse to this one (D8). */
14
+ export declare function latestOccurrence(expr: string, tz: string, afterMs: number, upToMs: number): number | null;
15
+ /** The first occurrence strictly after `afterMs`, or null within a year and a bit. */
16
+ export declare function nextOccurrence(expr: string, tz: string, afterMs: number): number | null;
17
+ export {};
@@ -0,0 +1,143 @@
1
+ // Cron evaluation in the school's timezone (D8, D21), without a timezone library: local
2
+ // calendar days are walked directly and each local time is converted to UTC with Intl.
3
+ const RANGES = [
4
+ [0, 59],
5
+ [0, 23],
6
+ [1, 31],
7
+ [1, 12],
8
+ [0, 6],
9
+ ];
10
+ function field(part, [min, max]) {
11
+ const out = new Set();
12
+ for (const item of part.split(',')) {
13
+ const [range, stepText] = item.split('/');
14
+ const step = stepText ? Number(stepText) : 1;
15
+ const [lo, hi] = range === '*'
16
+ ? [min, max]
17
+ : range.includes('-')
18
+ ? range.split('-').map(Number)
19
+ : [Number(range), Number(range)];
20
+ if (![lo, hi, step].every(Number.isInteger) ||
21
+ lo < min ||
22
+ hi > max ||
23
+ lo > hi ||
24
+ step < 1) {
25
+ throw new Error(`invalid cron field '${part}'`);
26
+ }
27
+ for (let v = lo; v <= hi; v += step)
28
+ out.add(v);
29
+ }
30
+ return [...out].sort((a, b) => a - b);
31
+ }
32
+ const specs = new Map();
33
+ export function parseCron(expr) {
34
+ const cached = specs.get(expr);
35
+ if (cached)
36
+ return cached;
37
+ const parts = expr.trim().split(/\s+/);
38
+ if (parts.length !== 5)
39
+ throw new Error(`cron needs 5 fields: '${expr}'`);
40
+ const [m, h, dom, mon, dow] = parts.map((p, i) => field(p, RANGES[i]));
41
+ const spec = {
42
+ minutes: m,
43
+ hours: h,
44
+ dom: new Set(dom),
45
+ months: new Set(mon),
46
+ dow: new Set(dow),
47
+ domAny: parts[2] === '*',
48
+ dowAny: parts[4] === '*',
49
+ };
50
+ specs.set(expr, spec);
51
+ return spec;
52
+ }
53
+ const formatters = new Map();
54
+ /** The local wall-clock fields of an instant in a timezone. */
55
+ function localParts(ms, tz) {
56
+ let f = formatters.get(tz);
57
+ if (!f) {
58
+ f = new Intl.DateTimeFormat('en-US', {
59
+ timeZone: tz,
60
+ hourCycle: 'h23',
61
+ year: 'numeric',
62
+ month: 'numeric',
63
+ day: 'numeric',
64
+ hour: 'numeric',
65
+ minute: 'numeric',
66
+ });
67
+ formatters.set(tz, f);
68
+ }
69
+ const p = Object.fromEntries(f.formatToParts(ms).map((x) => [x.type, x.value]));
70
+ return {
71
+ y: Number(p.year),
72
+ mo: Number(p.month),
73
+ d: Number(p.day),
74
+ h: Number(p.hour),
75
+ mi: Number(p.minute),
76
+ };
77
+ }
78
+ /** UTC instant for a local wall-clock time in `tz`. */
79
+ export function zonedToUtc(y, mo, d, h, mi, tz) {
80
+ const asUtc = Date.UTC(y, mo - 1, d, h, mi);
81
+ let guess = asUtc;
82
+ for (let i = 0; i < 2; i++) {
83
+ const l = localParts(guess, tz);
84
+ const offset = Date.UTC(l.y, l.mo - 1, l.d, l.h, l.mi) - guess;
85
+ guess = asUtc - offset;
86
+ }
87
+ return guess;
88
+ }
89
+ function matchesDay(spec, y, mo, d) {
90
+ if (!spec.months.has(mo))
91
+ return false;
92
+ const dow = new Date(Date.UTC(y, mo - 1, d)).getUTCDay();
93
+ const domOk = spec.dom.has(d);
94
+ const dowOk = spec.dow.has(dow);
95
+ // Standard cron: if both day fields are restricted, either may match.
96
+ if (!spec.domAny && !spec.dowAny)
97
+ return domOk || dowOk;
98
+ return domOk && dowOk;
99
+ }
100
+ /** Occurrences on one local day, ascending, as UTC ms. */
101
+ function dayOccurrences(spec, y, mo, d, tz) {
102
+ if (!matchesDay(spec, y, mo, d))
103
+ return [];
104
+ const out = [];
105
+ for (const h of spec.hours)
106
+ for (const mi of spec.minutes)
107
+ out.push(zonedToUtc(y, mo, d, h, mi, tz));
108
+ return out.sort((a, b) => a - b);
109
+ }
110
+ const MAX_DAYS = 400;
111
+ function shiftDay(y, mo, d, days) {
112
+ const t = new Date(Date.UTC(y, mo - 1, d + days));
113
+ return { y: t.getUTCFullYear(), mo: t.getUTCMonth() + 1, d: t.getUTCDate() };
114
+ }
115
+ /** The latest occurrence in (afterMs, upToMs], or null. Missed runs collapse to this one (D8). */
116
+ export function latestOccurrence(expr, tz, afterMs, upToMs) {
117
+ if (upToMs <= afterMs)
118
+ return null;
119
+ const spec = parseCron(expr);
120
+ const end = localParts(upToMs, tz);
121
+ for (let i = 0; i <= MAX_DAYS; i++) {
122
+ const day = shiftDay(end.y, end.mo, end.d, -i);
123
+ const times = dayOccurrences(spec, day.y, day.mo, day.d, tz).filter((t) => t <= upToMs);
124
+ const latest = times[times.length - 1];
125
+ if (latest !== undefined)
126
+ return latest > afterMs ? latest : null;
127
+ if (zonedToUtc(day.y, day.mo, day.d, 0, 0, tz) <= afterMs)
128
+ return null;
129
+ }
130
+ return null;
131
+ }
132
+ /** The first occurrence strictly after `afterMs`, or null within a year and a bit. */
133
+ export function nextOccurrence(expr, tz, afterMs) {
134
+ const spec = parseCron(expr);
135
+ const start = localParts(afterMs, tz);
136
+ for (let i = 0; i <= MAX_DAYS; i++) {
137
+ const day = shiftDay(start.y, start.mo, start.d, i);
138
+ const next = dayOccurrences(spec, day.y, day.mo, day.d, tz).find((t) => t > afterMs);
139
+ if (next !== undefined)
140
+ return next;
141
+ }
142
+ return null;
143
+ }
@@ -0,0 +1,11 @@
1
+ /** Every app entity is indexed on these, with no declaration needed. */
2
+ export declare const IMPLICIT_INDEXES: readonly (readonly string[])[];
3
+ /**
4
+ * Throws VALIDATION unless every orderBy and range filter in `query` is covered by one of
5
+ * the entity's indexes. Fields outside `allowedFields`, and malformed options, are left for
6
+ * the query validator to report, so this never reveals anything about hidden fields.
7
+ */
8
+ export declare function checkIndexCoverage(entityName: string, declared: readonly (readonly string[])[], query: {
9
+ where?: unknown;
10
+ orderBy?: unknown;
11
+ }, allowedFields?: ReadonlySet<string>): void;
@@ -0,0 +1,82 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ // The D37 query rule for sdk.db lists. On the platform, app data lives in DynamoDB, where a
3
+ // sort or range filter needs an index. So orderBy and range filters (gt, gte, lt, lte) must
4
+ // be covered by an index the app declares in its schema, or by the implicit id and createdAt
5
+ // indexes. Equality, `in` and `ne` filters work on any visible field; they only ever scan the
6
+ // app's own data. Pure, so the serverless data API can apply exactly the same rule.
7
+ /** Every app entity is indexed on these, with no declaration needed. */
8
+ export const IMPLICIT_INDEXES = [['id'], ['createdAt']];
9
+ const RANGE_OPS = ['gt', 'gte', 'lt', 'lte'];
10
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
11
+ const isRange = (condition) => isPlainObject(condition) &&
12
+ Object.keys(condition).length > 0 &&
13
+ Object.keys(condition).every((k) => RANGE_OPS.includes(k));
14
+ // A plain value; `in` and `ne` would need several index reads, so they don't count.
15
+ const isEquality = (condition) => !isPlainObject(condition);
16
+ function covers(index, equality, range, orders) {
17
+ for (let k = 0; k < index.length; k++) {
18
+ // index[0..k) must all be equality-filtered; index[k] is where the sort or range starts.
19
+ if (k > 0 && !equality.has(index[k - 1]))
20
+ return false;
21
+ const rest = index.slice(k);
22
+ if (range !== undefined && rest[0] !== range)
23
+ continue;
24
+ if (orders.length > rest.length)
25
+ continue;
26
+ if (orders.every((o, i) => o.field === rest[i]))
27
+ return true;
28
+ }
29
+ return false;
30
+ }
31
+ const quote = (fields) => `[${fields.map((f) => `'${f}'`).join(', ')}]`;
32
+ /**
33
+ * Throws VALIDATION unless every orderBy and range filter in `query` is covered by one of
34
+ * the entity's indexes. Fields outside `allowedFields`, and malformed options, are left for
35
+ * the query validator to report, so this never reveals anything about hidden fields.
36
+ */
37
+ export function checkIndexCoverage(entityName, declared, query, allowedFields) {
38
+ const where = isPlainObject(query.where) ? query.where : {};
39
+ const rawOrders = query.orderBy === undefined
40
+ ? []
41
+ : Array.isArray(query.orderBy)
42
+ ? query.orderBy
43
+ : [query.orderBy];
44
+ if (!rawOrders.every((o) => isPlainObject(o) && typeof o.field === 'string'))
45
+ return;
46
+ const orders = rawOrders.map((o) => ({
47
+ field: o.field,
48
+ direction: o.direction === 'desc' ? 'desc' : 'asc',
49
+ }));
50
+ const fields = [...Object.keys(where), ...orders.map((o) => o.field)];
51
+ if (allowedFields && !fields.every((f) => allowedFields.has(f)))
52
+ return;
53
+ const ranges = Object.entries(where)
54
+ .filter(([, c]) => isRange(c))
55
+ .map(([f]) => f);
56
+ if (ranges.length === 0 && orders.length === 0)
57
+ return;
58
+ if (new Set(orders.map((o) => o.direction)).size > 1) {
59
+ throw new QuadError('VALIDATION', `orderBy fields must all use the same direction: an index on ${entityName} is read one way`);
60
+ }
61
+ if (ranges.length > 1) {
62
+ throw new QuadError('VALIDATION', `range filters (gt, gte, lt, lte) work on one field at a time; ${entityName} got ${quote(ranges)}`);
63
+ }
64
+ const range = ranges[0];
65
+ if (range !== undefined && orders.length > 0 && orders[0].field !== range) {
66
+ throw new QuadError('VALIDATION', `a range filter on '${range}' needs orderBy to start with '${range}', or no orderBy`);
67
+ }
68
+ const equality = new Set(Object.entries(where)
69
+ .filter(([, c]) => isEquality(c))
70
+ .map(([f]) => f));
71
+ const indexes = [...IMPLICIT_INDEXES, ...declared];
72
+ if (indexes.some((index) => covers(index, equality, range, orders)))
73
+ return;
74
+ const needed = range !== undefined
75
+ ? [range, ...orders.slice(1).map((o) => o.field)]
76
+ : orders.map((o) => o.field);
77
+ const suggestion = [...equality, ...needed];
78
+ const what = orders.length > 0
79
+ ? `orderBy ${needed.length === 1 ? `'${needed[0]}'` : quote(needed)}`
80
+ : `a range filter on '${range}'`;
81
+ throw new QuadError('VALIDATION', `${what} needs an index: add indexes: [${quote(suggestion)}] to ${entityName} in schema/`);
82
+ }
@@ -0,0 +1,153 @@
1
+ import { type Dataset, type Principal } from '@quad-education/canonical';
2
+ import { type AppSchema, type Manifest } from '@quad-education/schema';
3
+ import type { OutboxEntry } from '../platform-types.ts';
4
+ import { type ClockState, type Method, type SessionInfo } from '../protocol.ts';
5
+ import { type RunRequest, type RunResult } from './runner.ts';
6
+ import type { App, Ctx, Kernel, ResolvedRecipients, StoredRun } from './state.ts';
7
+ import { type PlatformKind } from './storage.ts';
8
+ export type EngineOptions = {
9
+ dataset: Dataset;
10
+ indexedDB: IDBFactory;
11
+ /** IndexedDB database name; defaults to `quad-engine`. */
12
+ dbName?: string;
13
+ };
14
+ /**
15
+ * The in-browser implementation of the @quad-education/sdk contract (D15). It runs in the demo
16
+ * shell's origin, holds the fictional school, and enforces visibility, scopes and D17 on
17
+ * every call. Apps reach it only through a transport.
18
+ */
19
+ export declare class Engine implements Kernel {
20
+ private readonly apps;
21
+ private clock;
22
+ private readonly byId;
23
+ readonly dataset: Dataset;
24
+ private readonly storage;
25
+ private constructor();
26
+ static create(options: EngineOptions): Promise<Engine>;
27
+ close(): void;
28
+ /** Load an app, resetting its store if the schema changed since last time (D12). */
29
+ installApp({ manifest, schema }: {
30
+ manifest: unknown;
31
+ schema: AppSchema;
32
+ }): Promise<void>;
33
+ manifest(appId: string): Manifest;
34
+ /** Clear an app's data and outbox (the shell's reset button). */
35
+ resetApp(appId: string): Promise<void>;
36
+ /** Open tasks assigned to a person: the shell's inbox (D6). */
37
+ inbox(appId: string, personId: string): import("../index.ts").Task[];
38
+ /** Every audit entry, including CIO-only ones (the shell's audit viewer, D19). */
39
+ auditLog(appId: string): {
40
+ visibility: "app" | "cio";
41
+ id: string;
42
+ appId: string;
43
+ source: "app" | "platform";
44
+ action: string;
45
+ actor: string;
46
+ at: string;
47
+ entity?: string;
48
+ recordId?: string;
49
+ regardingStudentId?: string;
50
+ summary: string;
51
+ data?: {
52
+ readonly [key: string]: import("../index.ts").JsonValue;
53
+ };
54
+ }[];
55
+ /** Counts of everything a job can change, for run-twice tests (D20). */
56
+ effectsSnapshot(appId: string): Promise<{
57
+ outbox: number;
58
+ tasks: {
59
+ [k: string]: import("../index.ts").TaskStatus;
60
+ };
61
+ schedules: {
62
+ [k: string]: "pending" | "done" | "cancelled";
63
+ };
64
+ audit: number;
65
+ records: Record<string, Record<string, string>>;
66
+ }>;
67
+ /** Runs for the job log, newest first. */
68
+ runs(appId: string): StoredRun[];
69
+ /**
70
+ * Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
71
+ * Only runs that are currently running count, so a finished run's id can't be replayed.
72
+ */
73
+ runPrincipal(appId: string, runId: string | undefined): Principal;
74
+ /** Start due runs; the caller executes each as its `runAs` principal and calls finishRun. */
75
+ startDueRuns(appId: string): Promise<RunRequest[]>;
76
+ finishRun(appId: string, runId: string, result: RunResult): Promise<void>;
77
+ releaseRun(appId: string, runId: string): Promise<void>;
78
+ redeliverRun(appId: string, runId: string): Promise<void>;
79
+ /** Move the demo clock forward (D14). Works whether it's frozen or running. */
80
+ advanceClock(ms: number): void;
81
+ timezone(): string;
82
+ persistPlatform(app: App, kind: PlatformKind, items: readonly {
83
+ id: string;
84
+ }[]): Promise<void>;
85
+ outbox(appId: string): Promise<OutboxEntry[]>;
86
+ /** Freeze the clock at an instant, or return to real time with `null` (D14). */
87
+ setClock(iso: string | null): Promise<void>;
88
+ /** Carry a clock across an engine restart (tests and the shell keep the demo time). */
89
+ restoreClock(state: ClockState): void;
90
+ /** After the clock moves, cron baselines that are now in the future move back (D14). */
91
+ private rebaseCron;
92
+ clockState(): ClockState;
93
+ nowMs(): number;
94
+ sessionInfo(appId: string): SessionInfo;
95
+ /** Handle one SDK call from `appId` on behalf of `principal`. */
96
+ handle(appId: string, principal: Principal, method: Method, params: unknown): Promise<unknown>;
97
+ private appFor;
98
+ private context;
99
+ private me;
100
+ private schoolInfo;
101
+ private entityName;
102
+ /** Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has none. */
103
+ private tiers;
104
+ private allowedFields;
105
+ private visible;
106
+ private shape;
107
+ private schoolGet;
108
+ private schoolList;
109
+ private cohortByCode;
110
+ private cohortMembers;
111
+ private studentParents;
112
+ private parentChildren;
113
+ private calendar;
114
+ private dbEntity;
115
+ nowIso(): string;
116
+ /** The rules for an operation: 'system' (full access), or the role's rules (empty = denied). */
117
+ private rules;
118
+ /** Whether the current user may see a student, under the school's visibility policy (D4). */
119
+ private seesStudent;
120
+ private matches;
121
+ private canRead;
122
+ /** Fields the current role may see or write (D25 visibleTo). The system principal sees all. */
123
+ private fieldVisible;
124
+ /** A record as the current role receives it: hidden fields removed, not just emptied. */
125
+ private shapeRecord;
126
+ private requireOperation;
127
+ /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
128
+ private readable;
129
+ /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
130
+ private checkWrite;
131
+ remember(ctx: Ctx, key: string, result: unknown): Promise<void>;
132
+ idempotencyKey(options: unknown, scope: string): string | undefined;
133
+ private persist;
134
+ private dbCreate;
135
+ private dbUpdate;
136
+ private dbGet;
137
+ private dbList;
138
+ private resolveRef;
139
+ private dbDelete;
140
+ private notify;
141
+ private roleOf;
142
+ /**
143
+ * Resolves recipients to people, applying the app's roles and D17. Parents are only ever
144
+ * reached about a specific student, and only through an eligible, unrestricted link.
145
+ */
146
+ resolveRecipients(ctx: Ctx, to: unknown, regarding: string | undefined): ResolvedRecipients;
147
+ private suppressionReason;
148
+ /** D17/D19: each suppressed parent is recorded, visible only to the CIO view. */
149
+ private auditSuppressed;
150
+ /** D19: one CIO-visible entry per call that returns pastoral or medical fields. */
151
+ private auditSensitiveRead;
152
+ }
153
+ export declare const ENGINE_SDK_VERSION = "0.1.2";