@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,10 @@
1
+ import type { QuadSdk } from '../contract/types.ts';
2
+ import { type HandshakeOptions } from './handshake-client.ts';
3
+ export { DEFAULT_SHELL_ORIGIN } from './handshake-client.ts';
4
+ export type ConnectOptions = HandshakeOptions;
5
+ /**
6
+ * Connect to the platform. In V1 the app runs in the demo shell's iframe; the shell hands
7
+ * over a private MessagePort, and every SDK call goes through it.
8
+ */
9
+ export declare function connect(options?: ConnectOptions): Promise<QuadSdk>;
10
+ export type { QuadSdk };
@@ -0,0 +1,12 @@
1
+ import { portTransport } from "../port-rpc.js";
2
+ import { createSdkClient } from "./create-client.js";
3
+ import { handshake } from "./handshake-client.js";
4
+ export { DEFAULT_SHELL_ORIGIN } from "./handshake-client.js";
5
+ /**
6
+ * Connect to the platform. In V1 the app runs in the demo shell's iframe; the shell hands
7
+ * over a private MessagePort, and every SDK call goes through it.
8
+ */
9
+ export async function connect(options = {}) {
10
+ const { port, session } = await handshake(options);
11
+ return createSdkClient(portTransport(port, session.clock), session);
12
+ }
@@ -0,0 +1,14 @@
1
+ import type { QuadSdk } from '../contract/types.ts';
2
+ import type { Method, SessionInfo } from '../protocol.ts';
3
+ /** Per-SDK call context: in the jobs worker, the run a call belongs to (D7). */
4
+ export type CallContext = {
5
+ readonly runId?: string;
6
+ };
7
+ /** Moves RPC calls to an engine. In-process for tests; postMessage in the demo shell. */
8
+ export type Transport = {
9
+ call(method: Method, params: unknown, context?: CallContext): Promise<unknown>;
10
+ /** The engine's current time in ms, kept in step by the transport (D14). */
11
+ nowMs(): number;
12
+ };
13
+ /** Builds the SDK surface over a transport. Both transports share this code, so the contract suite covers it. */
14
+ export declare function createSdkClient(transport: Transport, session: SessionInfo, context?: CallContext): QuadSdk;
@@ -0,0 +1,76 @@
1
+ import { ENTITY_NAMES } from '@quad-education/canonical';
2
+ import { SDK_VERSION } from "../contract/types.js";
3
+ const dateInZone = (instant, timeZone) => new Intl.DateTimeFormat('en-CA', {
4
+ timeZone,
5
+ year: 'numeric',
6
+ month: '2-digit',
7
+ day: '2-digit',
8
+ }).format(instant);
9
+ /** Builds the SDK surface over a transport. Both transports share this code, so the contract suite covers it. */
10
+ export function createSdkClient(transport, session, context) {
11
+ const call = (method, params = {}) => transport.call(method, params, context);
12
+ const nowMs = () => transport.nowMs();
13
+ const school = {
14
+ info: () => call('school.info'),
15
+ calendar: {
16
+ list: (options) => call('school.calendar', options),
17
+ },
18
+ };
19
+ for (const entity of ENTITY_NAMES) {
20
+ if (entity === 'schools')
21
+ continue;
22
+ const collection = {
23
+ get: (id) => call('school.get', { entity, id }),
24
+ list: (options = {}) => call('school.list', { entity, options }),
25
+ };
26
+ const helpers = {
27
+ cohorts: {
28
+ byCode: (code) => call('school.cohortByCode', { code }),
29
+ members: (cohortId, options = {}) => call('school.cohortMembers', { cohortId, options }),
30
+ },
31
+ students: { parents: (studentId) => call('school.studentParents', { studentId }) },
32
+ parents: { children: (parentId) => call('school.parentChildren', { parentId }) },
33
+ };
34
+ school[entity] = Object.freeze({ ...collection, ...helpers[entity] });
35
+ }
36
+ const sdk = {
37
+ version: SDK_VERSION,
38
+ appId: session.appId,
39
+ auth: { me: () => call('auth.me') },
40
+ school: Object.freeze(school),
41
+ db: {
42
+ entity: (name) => Object.freeze({
43
+ create: (input, options = {}) => call('db.create', { entity: name, input, options }),
44
+ update: (id, patch) => call('db.update', { entity: name, id, patch }),
45
+ get: (id) => call('db.get', { entity: name, id }),
46
+ list: (options = {}) => call('db.list', { entity: name, options }),
47
+ delete: async (id) => {
48
+ await call('db.delete', { entity: name, id });
49
+ },
50
+ }),
51
+ },
52
+ notify: { send: (input) => call('notify.send', input) },
53
+ tasks: {
54
+ assign: (input) => call('tasks.assign', input),
55
+ get: (id) => call('tasks.get', { id }),
56
+ list: (options = {}) => call('tasks.list', options),
57
+ complete: (id, options = {}) => call('tasks.complete', { id, options }),
58
+ cancel: (id) => call('tasks.cancel', { id }),
59
+ },
60
+ schedule: {
61
+ at: (input) => call('schedule.at', input),
62
+ cancel: (id) => call('schedule.cancel', { id }),
63
+ list: (options = {}) => call('schedule.list', options),
64
+ },
65
+ cron: { list: () => call('cron.list') },
66
+ audit: {
67
+ record: (input) => call('audit.record', input),
68
+ list: (options = {}) => call('audit.list', options),
69
+ },
70
+ clock: {
71
+ now: () => new Date(nowMs()).toISOString(),
72
+ today: () => dateInZone(new Date(nowMs()), session.timezone),
73
+ },
74
+ };
75
+ return Object.freeze(sdk);
76
+ }
@@ -0,0 +1,16 @@
1
+ import type { SessionInfo } from '../protocol.ts';
2
+ export type HandshakeOptions = {
3
+ /** The demo shell's origin. Messages from any other origin are ignored (D15). */
4
+ shellOrigin?: string;
5
+ /** How long to wait for the shell's handshake, in ms. */
6
+ timeoutMs?: number;
7
+ };
8
+ export declare const DEFAULT_SHELL_ORIGIN: string;
9
+ /**
10
+ * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
11
+ * origin, then accept the matching `quad:hello` and its private port, and nothing else.
12
+ */
13
+ export declare function handshake(options?: HandshakeOptions): Promise<{
14
+ port: MessagePort;
15
+ session: SessionInfo;
16
+ }>;
@@ -0,0 +1,37 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { isHello } from "../handshake.js";
3
+ const env = import.meta.env;
4
+ export const DEFAULT_SHELL_ORIGIN = env?.VITE_QUAD_SHELL_ORIGIN ?? 'http://localhost:5173';
5
+ /**
6
+ * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
7
+ * origin, then accept the matching `quad:hello` and its private port, and nothing else.
8
+ */
9
+ export function handshake(options = {}) {
10
+ const shellOrigin = options.shellOrigin ?? DEFAULT_SHELL_ORIGIN;
11
+ const timeoutMs = options.timeoutMs ?? 10_000;
12
+ if (window.parent === window) {
13
+ return Promise.reject(new QuadError('TRANSPORT', 'This app runs inside the Quad demo shell. Open it from there.'));
14
+ }
15
+ const nonce = crypto.randomUUID();
16
+ return new Promise((resolve, reject) => {
17
+ const timer = setTimeout(() => {
18
+ window.removeEventListener('message', onMessage);
19
+ reject(new QuadError('TRANSPORT', `no handshake from the demo shell (${shellOrigin}) within ${timeoutMs} ms`));
20
+ }, timeoutMs);
21
+ function onMessage(e) {
22
+ // Only the configured shell, and only our parent frame, may start a session.
23
+ if (e.origin !== shellOrigin || e.source !== window.parent) {
24
+ if (isHello(e.data))
25
+ console.warn(`[quad] ignored a handshake from ${e.origin}`);
26
+ return;
27
+ }
28
+ if (!isHello(e.data) || e.data.nonce !== nonce || !e.ports[0])
29
+ return;
30
+ clearTimeout(timer);
31
+ window.removeEventListener('message', onMessage);
32
+ resolve({ port: e.ports[0], session: e.data.session });
33
+ }
34
+ window.addEventListener('message', onMessage);
35
+ window.parent.postMessage({ type: 'quad:ready', protocol: 1, nonce }, shellOrigin);
36
+ });
37
+ }
@@ -0,0 +1,8 @@
1
+ /** Error codes the SDK contract can return. Both implementations use the same codes. */
2
+ export type QuadErrorCode = 'SCOPE_NOT_GRANTED' | 'UNDECLARED_TYPE' | 'NOT_FOUND' | 'VALIDATION' | 'FORBIDDEN' | 'NOT_PERMITTED' | 'NOT_ASSIGNEE' | 'TRANSPORT' | 'INTERNAL';
3
+ export declare class QuadError extends Error {
4
+ readonly code: QuadErrorCode;
5
+ readonly details: unknown;
6
+ constructor(code: QuadErrorCode, message: string, details?: unknown);
7
+ }
8
+ export declare function isQuadError(e: unknown, code?: QuadErrorCode): e is QuadError;
@@ -0,0 +1,13 @@
1
+ export class QuadError extends Error {
2
+ code;
3
+ details;
4
+ constructor(code, message, details) {
5
+ super(message);
6
+ this.name = 'QuadError';
7
+ this.code = code;
8
+ this.details = details;
9
+ }
10
+ }
11
+ export function isQuadError(e, code) {
12
+ return e instanceof QuadError && (code === undefined || e.code === code);
13
+ }
@@ -0,0 +1,28 @@
1
+ import type { ContactPurpose, Role } from '@quad-education/canonical';
2
+ /**
3
+ * Who a notification (or, in Slice B, a task) is for. Parent recipients always need a
4
+ * student they're being contacted about, so the platform can apply D17.
5
+ */
6
+ export type Recipient = {
7
+ readonly person: string;
8
+ } | {
9
+ readonly role: Role;
10
+ } | {
11
+ readonly relationship: 'parentsOf';
12
+ readonly studentId: string;
13
+ readonly purpose: ContactPurpose;
14
+ } | {
15
+ readonly relationship: 'staffOf';
16
+ readonly cohortId: string;
17
+ } | {
18
+ readonly relationship: 'studentsOf';
19
+ readonly cohortId: string;
20
+ };
21
+ /** The parents who may be contacted about a student (D17). Restricted parents are never included. */
22
+ export declare function parentsOf(studentId: string, options?: {
23
+ purpose?: ContactPurpose;
24
+ }): Recipient;
25
+ /** Staff members of a cohort, including teams and positions such as `deputy-principal` (D18). */
26
+ export declare function staffOf(cohortId: string): Recipient;
27
+ /** Student members of a cohort. */
28
+ export declare function studentsOf(cohortId: string): Recipient;
@@ -0,0 +1,12 @@
1
+ /** The parents who may be contacted about a student (D17). Restricted parents are never included. */
2
+ export function parentsOf(studentId, options = {}) {
3
+ return { relationship: 'parentsOf', studentId, purpose: options.purpose ?? 'correspondence' };
4
+ }
5
+ /** Staff members of a cohort, including teams and positions such as `deputy-principal` (D18). */
6
+ export function staffOf(cohortId) {
7
+ return { relationship: 'staffOf', cohortId };
8
+ }
9
+ /** Student members of a cohort. */
10
+ export function studentsOf(cohortId) {
11
+ return { relationship: 'studentsOf', cohortId };
12
+ }
@@ -0,0 +1,421 @@
1
+ import type { CanonicalRecord, ContactPurpose, Entities, EntityName, RecordWithTiers, Role, TiersFor } from '@quad-education/canonical';
2
+ import type { AppEntityDef, AppInput, AppSchema, FieldValue, SystemFields } from '@quad-education/schema';
3
+ import type { Recipient } from './recipients.ts';
4
+ export declare const SDK_VERSION = "0.1.2";
5
+ /**
6
+ * Describes the current app to the type system. `quad gen` augments it from
7
+ * app.manifest.json and schema/ (D23); without that, nothing is readable.
8
+ */
9
+ export interface QuadApp {
10
+ }
11
+ /** The resolved shape of an app's configuration. */
12
+ export type AppConfig = {
13
+ /** The roles the app serves (D2). Fields hidden from any of them are optional (D25). */
14
+ roles: string;
15
+ scopes: string;
16
+ notifications: string;
17
+ tasks: string;
18
+ /** Jobs that `schedule.at` may name (the manifest's `scheduled` list, D7). */
19
+ scheduled: string;
20
+ schema: AppSchema;
21
+ };
22
+ type Field<T, K extends string, Fallback> = T extends {
23
+ [P in K]: infer V;
24
+ } ? V : Fallback;
25
+ /** QuadApp with defaults filled in. */
26
+ export type CurrentApp = {
27
+ roles: Field<QuadApp, 'roles', Role> & string;
28
+ scopes: Field<QuadApp, 'scopes', never> & string;
29
+ notifications: Field<QuadApp, 'notifications', never> & string;
30
+ tasks: Field<QuadApp, 'tasks', never> & string;
31
+ scheduled: Field<QuadApp, 'scheduled', never> & string;
32
+ schema: Field<QuadApp, 'schema', Record<never, never>> & AppSchema;
33
+ };
34
+ type Scalar = string | number | boolean;
35
+ export type Condition<V> = V | {
36
+ readonly in: readonly V[];
37
+ } | {
38
+ readonly ne: V;
39
+ } | {
40
+ readonly gt?: V;
41
+ readonly gte?: V;
42
+ readonly lt?: V;
43
+ readonly lte?: V;
44
+ };
45
+ /** Field equality, `in`, `ne` and range conditions, combined with AND. */
46
+ export type Where<R> = {
47
+ readonly [K in keyof R]?: R[K] extends Scalar | undefined ? Condition<Exclude<R[K], undefined>> : never;
48
+ };
49
+ export type OrderBy<R> = {
50
+ readonly field: keyof R & string;
51
+ readonly direction?: 'asc' | 'desc';
52
+ };
53
+ export type ListOptions<R> = {
54
+ readonly where?: Where<R>;
55
+ readonly orderBy?: OrderBy<R> | readonly OrderBy<R>[];
56
+ /** 1–200, default 50. */
57
+ readonly limit?: number;
58
+ readonly cursor?: string;
59
+ };
60
+ export type Page<R> = {
61
+ readonly items: readonly R[];
62
+ readonly nextCursor: string | null;
63
+ };
64
+ export type PersonSummary = {
65
+ readonly id: string;
66
+ readonly givenName: string;
67
+ readonly familyName: string;
68
+ readonly displayName: string;
69
+ };
70
+ /** The current principal. Jobs (Slice B) run as `system` (D8). */
71
+ export type Me = {
72
+ readonly kind: 'user';
73
+ readonly role: Role;
74
+ readonly person: PersonSummary;
75
+ } | {
76
+ readonly kind: 'system';
77
+ readonly appId: string;
78
+ };
79
+ export type AuthApi = {
80
+ me(): Promise<Me>;
81
+ };
82
+ export type SchoolRecord<A extends AppConfig, N extends EntityName> = RecordWithTiers<Entities[N], TiersFor<A['scopes'], N>>;
83
+ export type Collection<R> = {
84
+ /** A record the current user can see; NOT_FOUND otherwise. */
85
+ get(id: string): Promise<R>;
86
+ list(options?: ListOptions<R>): Promise<Page<R>>;
87
+ };
88
+ export type SchoolInfo = {
89
+ readonly id: string;
90
+ readonly name: string;
91
+ readonly state: CanonicalRecord<'schools'>['state'];
92
+ /** IANA timezone. Dates, "today" and schedules follow it, never the browser's (D21). */
93
+ readonly timezone: string;
94
+ readonly yearLevelLabels: Readonly<Record<string, string>>;
95
+ };
96
+ type CohortHelpers<A extends AppConfig> = {
97
+ /** The cohort with this per-school code, e.g. `deputy-principal` (D18), or null. */
98
+ byCode(code: string): Promise<SchoolRecord<A, 'cohorts'> | null>;
99
+ /** Memberships of a cohort. Needs a `cohortMemberships` scope. */
100
+ members(cohortId: string, options?: {
101
+ memberType?: 'staff' | 'student';
102
+ }): Promise<readonly SchoolRecord<A, 'cohortMemberships'>[]>;
103
+ };
104
+ type StudentHelpers<A extends AppConfig> = {
105
+ /** Linked parents the current user can see. Needs a `parents` scope. Not a contact list: use `parentsOf` to contact parents. */
106
+ parents(studentId: string): Promise<readonly SchoolRecord<A, 'parents'>[]>;
107
+ };
108
+ type ParentHelpers<A extends AppConfig> = {
109
+ /** Children of a parent that the current user can see. Needs a `students` scope. */
110
+ children(parentId: string): Promise<readonly SchoolRecord<A, 'students'>[]>;
111
+ };
112
+ type Helpers<A extends AppConfig, N extends EntityName> = N extends 'cohorts' ? CohortHelpers<A> : N extends 'students' ? StudentHelpers<A> : N extends 'parents' ? ParentHelpers<A> : unknown;
113
+ type Readable<A extends AppConfig> = {
114
+ [N in Exclude<EntityName, 'schools'>]: [TiersFor<A['scopes'], N>] extends [never] ? never : N;
115
+ }[Exclude<EntityName, 'schools'>];
116
+ /** Canonical school data, filtered by the app's scopes and the user's visibility. Read-only. */
117
+ export type SchoolApi<A extends AppConfig> = {
118
+ info(): Promise<SchoolInfo>;
119
+ } & {
120
+ readonly [N in Readable<A>]: Collection<SchoolRecord<A, N>> & Helpers<A, N>;
121
+ } & ('calendarEvents' extends Readable<A> ? {
122
+ readonly calendar: {
123
+ /** Events overlapping [from, to); with `cohortId`, that cohort's events plus whole-school ones. */
124
+ list(options: {
125
+ from: string;
126
+ to: string;
127
+ cohortId?: string;
128
+ }): Promise<readonly SchoolRecord<A, 'calendarEvents'>[]>;
129
+ };
130
+ } : unknown);
131
+ type Simplify<T> = {
132
+ [K in keyof T]: T[K];
133
+ };
134
+ /** True when every role the app serves may see the field (D25). */
135
+ type SeenByAll<D, R extends string> = D extends {
136
+ visibleTo: readonly (infer V)[];
137
+ } ? [Exclude<R, V>] extends [never] ? true : false : true;
138
+ type AlwaysPresent<A extends AppConfig, D> = D extends {
139
+ optional: true;
140
+ } ? false : SeenByAll<D, A['roles']>;
141
+ /**
142
+ * An app record as this app's users receive it. A field with `visibleTo` is optional unless
143
+ * every role the app serves may see it, since other roles never receive it (D25).
144
+ */
145
+ export type RecordFor<A extends AppConfig, E extends AppEntityDef> = Simplify<SystemFields & {
146
+ readonly [K in keyof E['fields'] as AlwaysPresent<A, E['fields'][K]> extends true ? K : never]: FieldValue<E['fields'][K]>;
147
+ } & {
148
+ readonly [K in keyof E['fields'] as AlwaysPresent<A, E['fields'][K]> extends true ? never : K]?: FieldValue<E['fields'][K]>;
149
+ }>;
150
+ type RefFields<E extends AppEntityDef> = {
151
+ [K in keyof E['fields']]: E['fields'][K] extends {
152
+ kind: 'ref';
153
+ } ? K : never;
154
+ }[keyof E['fields']] & string;
155
+ type RefTarget<E extends AppEntityDef, K extends keyof E['fields']> = E['fields'][K] extends {
156
+ to: infer T;
157
+ } ? T : never;
158
+ type Resolved<A extends AppConfig, T> = T extends `school.${infer N extends EntityName}` ? SchoolRecord<A, N> : T extends keyof A['schema'] ? RecordFor<A, A['schema'][T]> : never;
159
+ export type WithIncluded<A extends AppConfig, E extends AppEntityDef, I extends string> = RecordFor<A, E> & {
160
+ /** Included refs; null when the target doesn't exist or isn't visible to the current user. */
161
+ readonly $included: {
162
+ readonly [K in I]: K extends keyof E['fields'] ? Resolved<A, RefTarget<E, K>> | null : never;
163
+ };
164
+ };
165
+ /**
166
+ * Fields an app entity may sort on or range-filter (D37): any field in a declared index,
167
+ * plus `id` and `createdAt`, which are always indexed. The engine also checks the exact
168
+ * rule at runtime: index order, an equality prefix, one range field and one sort direction.
169
+ */
170
+ export type IndexedField<E extends AppEntityDef> = 'id' | 'createdAt' | (E['indexes'][number][number] & string);
171
+ type EqualityCondition<V> = V | {
172
+ readonly in: readonly V[];
173
+ } | {
174
+ readonly ne: V;
175
+ };
176
+ /** Like `Where`, but range conditions only on indexed fields (D37). */
177
+ export type DbWhere<R, IX extends string> = {
178
+ readonly [K in keyof R]?: R[K] extends Scalar | undefined ? K extends IX ? Condition<Exclude<R[K], undefined>> : EqualityCondition<Exclude<R[K], undefined>> : never;
179
+ };
180
+ export type DbOrderBy<R, IX extends string> = {
181
+ readonly field: keyof R & IX & string;
182
+ readonly direction?: 'asc' | 'desc';
183
+ };
184
+ export type DbListOptions<A extends AppConfig, E extends AppEntityDef, I extends RefFields<E>> = Omit<ListOptions<RecordFor<A, E>>, 'where' | 'orderBy'> & {
185
+ readonly where?: DbWhere<RecordFor<A, E>, IndexedField<E>>;
186
+ readonly orderBy?: DbOrderBy<RecordFor<A, E>, IndexedField<E>> | readonly DbOrderBy<RecordFor<A, E>, IndexedField<E>>[];
187
+ readonly include?: readonly I[];
188
+ };
189
+ /** Operations on one app entity. A future `db.transaction(tx => …)` hands out the same interface (D12). */
190
+ export type DbOps<A extends AppConfig, E extends AppEntityDef> = {
191
+ /** NOT_PERMITTED if the access rules deny it, or the subject is a student you can't see (D25). */
192
+ create(input: AppInput<E>, options?: {
193
+ idempotencyKey?: string;
194
+ }): Promise<RecordFor<A, E>>;
195
+ update(id: string, patch: Partial<AppInput<E>>): Promise<RecordFor<A, E>>;
196
+ /** NOT_FOUND if the record doesn't exist or you may not read it (D25). */
197
+ get(id: string): Promise<RecordFor<A, E>>;
198
+ /** Only records you may read; filters and pages apply after access checks (D25). */
199
+ list<const I extends RefFields<E> = never>(options?: DbListOptions<A, E, I>): Promise<Page<[I] extends [never] ? RecordFor<A, E> : WithIncluded<A, E, I>>>;
200
+ delete(id: string): Promise<void>;
201
+ };
202
+ /** The app's own data, stored by the platform (IndexedDB in V1). */
203
+ export type DbApi<A extends AppConfig> = {
204
+ entity<N extends keyof A['schema'] & string>(name: N): DbOps<A, A['schema'][N]>;
205
+ };
206
+ export type Channel = 'inApp' | 'email';
207
+ export type NotifyInput<A extends AppConfig> = {
208
+ readonly type: A['notifications'];
209
+ readonly to: Recipient | readonly Recipient[];
210
+ /** Required whenever a recipient is a parent: the student they're being contacted about (D17). */
211
+ readonly regarding?: {
212
+ readonly studentId: string;
213
+ };
214
+ readonly channel?: Channel;
215
+ readonly subject: string;
216
+ readonly body: string;
217
+ /** An app-relative link, e.g. `/greetings/abc`. */
218
+ readonly link?: string;
219
+ readonly idempotencyKey?: string;
220
+ };
221
+ export type ResolvedRecipient = {
222
+ readonly personId: string;
223
+ readonly role: Role;
224
+ };
225
+ export type NotifyApi<A extends AppConfig> = {
226
+ /**
227
+ * Queue a notification. In V1 it lands in the simulated outbox and is never sent (D10).
228
+ * Returns the recipients it resolved to; ineligible parents are left out without saying why (D17).
229
+ */
230
+ send(input: NotifyInput<A>): Promise<{
231
+ readonly recipients: readonly ResolvedRecipient[];
232
+ }>;
233
+ };
234
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
235
+ readonly [key: string]: JsonValue;
236
+ };
237
+ export type TaskStatus = 'open' | 'completed' | 'cancelled';
238
+ export type TaskMode = 'each' | 'any';
239
+ export type Task = {
240
+ readonly id: string;
241
+ readonly type: string;
242
+ readonly title: string;
243
+ readonly description?: string;
244
+ readonly status: TaskStatus;
245
+ readonly mode: TaskMode;
246
+ /** Tasks created together by one `assign` call share a group. */
247
+ readonly groupId: string;
248
+ /** Whether the current user is one of the assignees. */
249
+ readonly assignedToMe: boolean;
250
+ /** Who it's assigned to. Only staff and the system principal see this. */
251
+ readonly assignees?: readonly string[];
252
+ readonly regardingStudentId?: string;
253
+ readonly dueAt?: string;
254
+ /** An app-relative link; the shell's inbox opens the app there. */
255
+ readonly link?: string;
256
+ readonly data?: {
257
+ readonly [key: string]: JsonValue;
258
+ };
259
+ readonly createdAt: string;
260
+ readonly createdBy: string;
261
+ readonly completedAt?: string;
262
+ readonly completedBy?: string;
263
+ readonly outcome?: string;
264
+ readonly cancelledAt?: string;
265
+ readonly cancelledBy?: string;
266
+ };
267
+ export type AssignInput<A extends AppConfig> = {
268
+ readonly type: A['tasks'];
269
+ readonly title: string;
270
+ readonly description?: string;
271
+ readonly assignee: Recipient | readonly Recipient[];
272
+ /** `each` (default): one task per person. `any`: one shared task; the first to complete closes it. */
273
+ readonly mode?: TaskMode;
274
+ /** Required when an assignee is a parent (D17). */
275
+ readonly regarding?: {
276
+ readonly studentId: string;
277
+ };
278
+ readonly dueAt?: string;
279
+ readonly link?: string;
280
+ readonly data?: {
281
+ readonly [key: string]: JsonValue;
282
+ };
283
+ readonly idempotencyKey?: string;
284
+ };
285
+ export type TaskListOptions = {
286
+ readonly assignedToMe?: boolean;
287
+ readonly status?: TaskStatus;
288
+ readonly type?: string;
289
+ readonly regardingStudentId?: string;
290
+ readonly groupId?: string;
291
+ readonly limit?: number;
292
+ readonly cursor?: string;
293
+ };
294
+ export type TasksApi<A extends AppConfig> = {
295
+ /** Assign a task. Ineligible parents are left out without saying why (D17). */
296
+ assign(input: AssignInput<A>): Promise<{
297
+ readonly tasks: readonly Task[];
298
+ }>;
299
+ /** NOT_FOUND unless you're an assignee, its creator, or staff. */
300
+ get(id: string): Promise<Task>;
301
+ list(options?: TaskListOptions): Promise<Page<Task>>;
302
+ /** Only an assignee can complete a task, from the app. NOT_ASSIGNEE otherwise (D6). */
303
+ complete(id: string, options?: {
304
+ outcome?: string;
305
+ }): Promise<Task>;
306
+ /** Its creator, staff or the system principal can cancel an open task. */
307
+ cancel(id: string): Promise<Task>;
308
+ };
309
+ export type ScheduledRun = {
310
+ readonly id: string;
311
+ readonly job: string;
312
+ readonly when: string;
313
+ readonly payload: JsonValue;
314
+ readonly status: 'pending' | 'done' | 'cancelled';
315
+ readonly createdAt: string;
316
+ readonly createdBy: string;
317
+ /** `user`: runs as whoever scheduled it, with their access. `system`: scheduled by a system job. */
318
+ readonly runsAs: 'user' | 'system';
319
+ };
320
+ export type ScheduleApi<A extends AppConfig> = {
321
+ /**
322
+ * Run a job from `jobs/` once, at or after `when` (D7). It runs as the caller: a job
323
+ * scheduled in a user's session runs with that user's permissions and visibility, and a
324
+ * job scheduled from inside another job runs as that job's principal.
325
+ */
326
+ at(input: {
327
+ readonly when: string;
328
+ readonly job: A['scheduled'];
329
+ readonly payload?: JsonValue;
330
+ readonly idempotencyKey?: string;
331
+ }): Promise<ScheduledRun>;
332
+ /** Your own scheduled jobs; the system principal can cancel any. */
333
+ cancel(id: string): Promise<ScheduledRun>;
334
+ /** Jobs you scheduled; the system principal sees all. */
335
+ list(options?: {
336
+ readonly status?: ScheduledRun['status'];
337
+ }): Promise<readonly ScheduledRun[]>;
338
+ };
339
+ export type CronJobInfo = {
340
+ readonly name: string;
341
+ readonly schedule: string;
342
+ readonly description: string;
343
+ /** The next run, in UTC, computed in the school's timezone (D21). */
344
+ readonly nextRunAt: string | null;
345
+ readonly lastScheduledFor: string | null;
346
+ };
347
+ export type CronApi = {
348
+ list(): Promise<readonly CronJobInfo[]>;
349
+ };
350
+ export type AuditEntry = {
351
+ readonly id: string;
352
+ readonly appId: string;
353
+ readonly source: 'app' | 'platform';
354
+ readonly action: string;
355
+ /** Who did it: a person id, or `system:<appId>`. Stamped by the platform. */
356
+ readonly actor: string;
357
+ /** When, stamped by the platform. */
358
+ readonly at: string;
359
+ readonly entity?: string;
360
+ readonly recordId?: string;
361
+ /** The student the entry is about; it then follows that student's visibility (D25). */
362
+ readonly regardingStudentId?: string;
363
+ readonly summary: string;
364
+ readonly data?: {
365
+ readonly [key: string]: JsonValue;
366
+ };
367
+ };
368
+ export type AuditApi = {
369
+ /** Record an app event. The platform stamps actor and time; entries are append-only. */
370
+ record(input: {
371
+ readonly action: string;
372
+ readonly summary: string;
373
+ readonly entity?: string;
374
+ readonly recordId?: string;
375
+ /** The student this is about. NOT_PERMITTED unless you can see them. */
376
+ readonly regarding?: {
377
+ readonly studentId: string;
378
+ };
379
+ readonly data?: {
380
+ readonly [key: string]: JsonValue;
381
+ };
382
+ readonly idempotencyKey?: string;
383
+ }): Promise<AuditEntry>;
384
+ /**
385
+ * App-recorded entries only: platform entries (sensitive reads, notifications sent and so
386
+ * on) are never exposed through the SDK (D19). Staff see the app's entries; parents and
387
+ * students only their own. Entries about a student follow that student's visibility, for
388
+ * staff too (D25).
389
+ */
390
+ list(options?: {
391
+ readonly entity?: string;
392
+ readonly recordId?: string;
393
+ readonly action?: string;
394
+ readonly limit?: number;
395
+ readonly cursor?: string;
396
+ }): Promise<Page<AuditEntry>>;
397
+ };
398
+ export type ClockApi = {
399
+ /** The current instant (ISO 8601, UTC). Follows the demo clock, not the wall clock (D14). */
400
+ now(): string;
401
+ /** Today's date (YYYY-MM-DD) in the school's timezone (D21). */
402
+ today(): string;
403
+ };
404
+ export type QuadSdk<A extends AppConfig = CurrentApp> = {
405
+ readonly version: string;
406
+ readonly appId: string;
407
+ readonly auth: AuthApi;
408
+ readonly school: SchoolApi<A>;
409
+ readonly db: DbApi<A>;
410
+ readonly notify: NotifyApi<A>;
411
+ readonly tasks: TasksApi<A>;
412
+ readonly schedule: ScheduleApi<A>;
413
+ readonly cron: CronApi;
414
+ readonly audit: AuditApi;
415
+ readonly clock: ClockApi;
416
+ };
417
+ export type { ContactPurpose, Recipient, Role };
418
+ /** A canonical record as this app sees it, e.g. `SchoolRecordOf<'students'>` (D23). */
419
+ export type SchoolRecordOf<N extends EntityName> = SchoolRecord<CurrentApp, N>;
420
+ /** A stored record of one of this app's own entities, e.g. `AppRecordOf<'greeting'>`. */
421
+ export type AppRecordOf<N extends keyof CurrentApp['schema'] & string> = RecordFor<CurrentApp, CurrentApp['schema'][N]>;
@@ -0,0 +1 @@
1
+ export const SDK_VERSION = '0.1.2';