@quad-education/sdk 0.1.3 → 0.2.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.
Files changed (54) hide show
  1. package/README.md +2 -0
  2. package/dist/contract-tests/apps.d.ts +105 -0
  3. package/dist/contract-tests/apps.js +167 -0
  4. package/dist/contract-tests/harness.d.ts +11 -0
  5. package/dist/contract-tests/harness.js +40 -0
  6. package/dist/contract-tests/helpers.d.ts +5 -0
  7. package/dist/contract-tests/helpers.js +25 -0
  8. package/dist/contract-tests/index.d.ts +4 -2
  9. package/dist/contract-tests/index.js +3 -1
  10. package/dist/contract-tests/standalone-apps.d.ts +183 -0
  11. package/dist/contract-tests/standalone-apps.js +178 -0
  12. package/dist/contract-tests/standalone.d.ts +2 -0
  13. package/dist/contract-tests/standalone.js +709 -0
  14. package/dist/contract-tests/suite.d.ts +10 -3
  15. package/dist/contract-tests/suite.js +536 -44
  16. package/dist/src/client/connect.d.ts +13 -3
  17. package/dist/src/client/connect.js +21 -3
  18. package/dist/src/client/handshake-client.d.ts +2 -0
  19. package/dist/src/client/handshake-client.js +2 -0
  20. package/dist/src/client/http-transport.d.ts +18 -0
  21. package/dist/src/client/http-transport.js +76 -0
  22. package/dist/src/client/live.d.ts +39 -0
  23. package/dist/src/client/live.js +122 -0
  24. package/dist/src/contract/errors.d.ts +1 -1
  25. package/dist/src/contract/principals.d.ts +30 -0
  26. package/dist/src/contract/principals.js +12 -0
  27. package/dist/src/contract/recipients.d.ts +8 -2
  28. package/dist/src/contract/types.d.ts +18 -2
  29. package/dist/src/contract/types.js +1 -1
  30. package/dist/src/engine/audit.d.ts +2 -2
  31. package/dist/src/engine/audit.js +8 -6
  32. package/dist/src/engine/db-indexes.js +6 -1
  33. package/dist/src/engine/engine.d.ts +60 -22
  34. package/dist/src/engine/engine.js +281 -162
  35. package/dist/src/engine/host.d.ts +2 -2
  36. package/dist/src/engine/host.js +1 -1
  37. package/dist/src/engine/in-process.d.ts +2 -2
  38. package/dist/src/engine/index.d.ts +3 -1
  39. package/dist/src/engine/index.js +1 -0
  40. package/dist/src/engine/memory-store.d.ts +32 -0
  41. package/dist/src/engine/memory-store.js +123 -0
  42. package/dist/src/engine/runner.d.ts +2 -2
  43. package/dist/src/engine/runner.js +31 -26
  44. package/dist/src/engine/state.d.ts +21 -15
  45. package/dist/src/engine/state.js +31 -3
  46. package/dist/src/engine/store.d.ts +48 -0
  47. package/dist/src/engine/store.js +1 -0
  48. package/dist/src/engine/tasks.d.ts +4 -6
  49. package/dist/src/engine/tasks.js +27 -24
  50. package/dist/src/index.d.ts +1 -0
  51. package/dist/src/index.js +1 -0
  52. package/dist/src/jobs/define.d.ts +2 -2
  53. package/dist/src/platform-types.d.ts +2 -2
  54. package/package.json +4 -4
@@ -1,10 +1,20 @@
1
1
  import type { QuadSdk } from '../contract/types.ts';
2
2
  import { type HandshakeOptions } from './handshake-client.ts';
3
+ import { type LiveOptions } from './live.ts';
3
4
  export { DEFAULT_SHELL_ORIGIN } from './handshake-client.ts';
4
- export type ConnectOptions = HandshakeOptions;
5
+ export { connectHttp, createHttpTransport, type HttpOptions, type HttpTransport, } from './http-transport.ts';
6
+ export { SignInRequired, connectLive, continueAsGuest, getLiveStatus, signIn, type LiveOptions, type LiveStatus, } from './live.ts';
7
+ export type ConnectOptions = HandshakeOptions & {
8
+ /** Connect the live way (a shell-less app at its own address), for tests and other runtimes. */
9
+ live?: LiveOptions;
10
+ };
5
11
  /**
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.
12
+ * Connect to the platform. In the demo shell's iframe (the Sandbox and `quad dev`), the shell hands over a
13
+ * private MessagePort and every SDK call goes through it. At a live address there is no shell: the app asks its
14
+ * own origin who is signed in and talks to the data API with a token. The same built code does both.
15
+ *
16
+ * Live and nobody signed in: if the app allows guests this throws `SignInRequired` (with `guests: true`) so the
17
+ * app can offer both choices; otherwise the page goes to Quad's sign-in and this never settles.
8
18
  */
9
19
  export declare function connect(options?: ConnectOptions): Promise<QuadSdk>;
10
20
  export type { QuadSdk };
@@ -1,12 +1,30 @@
1
1
  import { portTransport } from "../port-rpc.js";
2
2
  import { createSdkClient } from "./create-client.js";
3
- import { handshake } from "./handshake-client.js";
3
+ import { handshake, isFramed } from "./handshake-client.js";
4
+ import { connectSignedIn, getLiveStatus, signIn } from "./live.js";
4
5
  export { DEFAULT_SHELL_ORIGIN } from "./handshake-client.js";
6
+ export { connectHttp, createHttpTransport, } from "./http-transport.js";
7
+ export { SignInRequired, connectLive, continueAsGuest, getLiveStatus, signIn, } from "./live.js";
5
8
  /**
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.
9
+ * Connect to the platform. In the demo shell's iframe (the Sandbox and `quad dev`), the shell hands over a
10
+ * private MessagePort and every SDK call goes through it. At a live address there is no shell: the app asks its
11
+ * own origin who is signed in and talks to the data API with a token. The same built code does both.
12
+ *
13
+ * Live and nobody signed in: if the app allows guests this throws `SignInRequired` (with `guests: true`) so the
14
+ * app can offer both choices; otherwise the page goes to Quad's sign-in and this never settles.
8
15
  */
9
16
  export async function connect(options = {}) {
17
+ if (options.live || !isFramed()) {
18
+ const live = options.live ?? {};
19
+ const status = await getLiveStatus(live);
20
+ if (!status.signedIn && !status.guests) {
21
+ signIn(live);
22
+ return never();
23
+ }
24
+ return connectSignedIn(status, live);
25
+ }
10
26
  const { port, session } = await handshake(options);
11
27
  return createSdkClient(portTransport(port, session.clock), session);
12
28
  }
29
+ /** A page that is leaving has nothing to resolve to. */
30
+ const never = () => new Promise(() => { });
@@ -6,6 +6,8 @@ export type HandshakeOptions = {
6
6
  timeoutMs?: number;
7
7
  };
8
8
  export declare const DEFAULT_SHELL_ORIGIN: string;
9
+ /** Whether this page is inside another frame, as an app in the demo shell is. */
10
+ export declare const isFramed: () => boolean;
9
11
  /**
10
12
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
11
13
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -2,6 +2,8 @@ import { QuadError } from "../contract/errors.js";
2
2
  import { isHello } from "../handshake.js";
3
3
  const env = import.meta.env;
4
4
  export const DEFAULT_SHELL_ORIGIN = env?.VITE_QUAD_SHELL_ORIGIN ?? 'http://localhost:5173';
5
+ /** Whether this page is inside another frame, as an app in the demo shell is. */
6
+ export const isFramed = () => typeof window !== 'undefined' && window.parent !== window;
5
7
  /**
6
8
  * The window handshake (D15): announce `quad:ready` to the parent frame on the shell's
7
9
  * origin, then accept the matching `quad:hello` and its private port, and nothing else.
@@ -0,0 +1,18 @@
1
+ import type { QuadSdk } from '../contract/types.ts';
2
+ import { type SessionInfo } from '../protocol.ts';
3
+ import { type Transport } from './create-client.ts';
4
+ export type HttpOptions = {
5
+ /** The data API's address, e.g. https://data.us-east-1.quadapps.net */
6
+ baseUrl: string;
7
+ /** The current token. Called for every request, so the provider can keep it fresh. */
8
+ token: () => string | Promise<string>;
9
+ /** For tests and other runtimes; defaults to the global `fetch`. */
10
+ fetch?: typeof fetch;
11
+ };
12
+ /** Moves RPC calls to the data API. Also holds the session the first call to `/session` returned. */
13
+ export type HttpTransport = Transport & {
14
+ session: SessionInfo;
15
+ };
16
+ export declare function createHttpTransport(options: HttpOptions): Promise<HttpTransport>;
17
+ /** Connect to a live app's data: the SDK over HTTP, as the person the token names. */
18
+ export declare function connectHttp(options: HttpOptions): Promise<QuadSdk>;
@@ -0,0 +1,76 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { deserializeError, } from "../protocol.js";
3
+ import { createSdkClient } from "./create-client.js";
4
+ async function readEnvelope(response) {
5
+ try {
6
+ return (await response.json());
7
+ }
8
+ catch {
9
+ throw new QuadError('TRANSPORT', `the data API answered ${response.status} with no usable body`);
10
+ }
11
+ }
12
+ export async function createHttpTransport(options) {
13
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
14
+ const base = options.baseUrl.replace(/\/+$/, '');
15
+ let clock = { kind: 'offset', offsetMs: 0 };
16
+ let known = Date.now();
17
+ let sentAt = Date.now();
18
+ const learn = (env) => {
19
+ if (env.clock)
20
+ clock = env.clock;
21
+ if (typeof env.now === 'number') {
22
+ known = env.now;
23
+ sentAt = Date.now();
24
+ }
25
+ };
26
+ async function request(path, init) {
27
+ // A token that can't be had is its own error (a session that ended), not a network failure.
28
+ const token = await options.token();
29
+ let response;
30
+ try {
31
+ response = await doFetch(`${base}${path}`, {
32
+ method: init.method,
33
+ headers: {
34
+ authorization: `Bearer ${token}`,
35
+ ...(init.body !== undefined ? { 'content-type': 'application/json' } : {}),
36
+ },
37
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
38
+ });
39
+ }
40
+ catch (e) {
41
+ throw new QuadError('TRANSPORT', `couldn't reach the data API: ${e.message}`);
42
+ }
43
+ const env = await readEnvelope(response);
44
+ learn(env);
45
+ if (!env.ok) {
46
+ throw env.error
47
+ ? deserializeError(env.error)
48
+ : new QuadError('TRANSPORT', `the data API answered ${response.status}`);
49
+ }
50
+ return env;
51
+ }
52
+ const hello = (await request('/session', { method: 'GET' }));
53
+ const session = {
54
+ appId: hello.result.appId,
55
+ timezone: hello.result.timezone,
56
+ clock,
57
+ };
58
+ return {
59
+ session,
60
+ async call(method, params, context) {
61
+ const env = await request('/rpc', {
62
+ method: 'POST',
63
+ body: { method, params, ...(context?.runId !== undefined ? { runId: context.runId } : {}) },
64
+ });
65
+ return env.result;
66
+ },
67
+ nowMs() {
68
+ return clock.kind === 'fixed' ? clock.at : known + (Date.now() - sentAt);
69
+ },
70
+ };
71
+ }
72
+ /** Connect to a live app's data: the SDK over HTTP, as the person the token names. */
73
+ export async function connectHttp(options) {
74
+ const transport = await createHttpTransport(options);
75
+ return createSdkClient(transport, transport.session);
76
+ }
@@ -0,0 +1,39 @@
1
+ import { QuadError } from '../contract/errors.ts';
2
+ import type { QuadSdk } from '../contract/types.ts';
3
+ export type LiveOptions = {
4
+ /** For tests and other runtimes; defaults to the global `fetch`. */
5
+ fetch?: typeof fetch;
6
+ /** Where the page is and how to leave it; defaults to `window.location`. */
7
+ location?: {
8
+ pathname: string;
9
+ search: string;
10
+ hash: string;
11
+ assign(url: string): void;
12
+ };
13
+ /** Where the guest device id is kept; defaults to `localStorage`, or the page's memory if that is blocked. */
14
+ storage?: Pick<Storage, 'getItem' | 'setItem'>;
15
+ /** The time in ms; defaults to `Date.now`. */
16
+ now?: () => number;
17
+ };
18
+ export type LiveStatus = {
19
+ signedIn: true;
20
+ dataApi: string;
21
+ } | {
22
+ signedIn: false;
23
+ guests: boolean;
24
+ };
25
+ /** Thrown while nobody is signed in. Offer {@link signIn}, and {@link continueAsGuest} when `guests` is true. */
26
+ export declare class SignInRequired extends QuadError {
27
+ readonly guests: boolean;
28
+ constructor(guests: boolean);
29
+ }
30
+ /** Who is signed in at this address, and whether guests are welcome if no one is. */
31
+ export declare function getLiveStatus(options?: LiveOptions): Promise<LiveStatus>;
32
+ /** Leaves for Quad's sign-in, which returns the person to this page. */
33
+ export declare function signIn(options?: LiveOptions): void;
34
+ /** Starts a guest session. The device id stays on this origin; Quad keeps only a salted hash of it (ADR 0010). */
35
+ export declare function continueAsGuest(options?: LiveOptions): Promise<void>;
36
+ /** Connects as the signed-in person, or throws {@link SignInRequired}. */
37
+ export declare function connectLive(options?: LiveOptions): Promise<QuadSdk>;
38
+ /** Connects from a status already fetched; throws {@link SignInRequired} if it says nobody is signed in. */
39
+ export declare function connectSignedIn(status: LiveStatus, options: LiveOptions): Promise<QuadSdk>;
@@ -0,0 +1,122 @@
1
+ import { QuadError } from "../contract/errors.js";
2
+ import { connectHttp } from "./http-transport.js";
3
+ // A live app's connection (V2c C3a, ADR 0008). The app runs at its own address, with no shell around it, so it
4
+ // asks that same origin (`/__quad/live/*`, which the edge forwards to the control plane) who is signed in, gets a
5
+ // short-lived token for them, and sends every call to the data API with it. The app never sees the session
6
+ // cookie (it is HttpOnly) or any key.
7
+ const LIVE = '/__quad/live';
8
+ /** Ask for a new token when this little time is left, so a call never goes out with one about to lapse. */
9
+ const REFRESH_MARGIN_MS = 60_000;
10
+ const DEVICE_KEY = 'quad:device';
11
+ /** Thrown while nobody is signed in. Offer {@link signIn}, and {@link continueAsGuest} when `guests` is true. */
12
+ export class SignInRequired extends QuadError {
13
+ guests;
14
+ constructor(guests) {
15
+ super('FORBIDDEN', 'not signed in');
16
+ this.name = 'SignInRequired';
17
+ this.guests = guests;
18
+ }
19
+ }
20
+ const doFetch = (options) => options.fetch ?? globalThis.fetch.bind(globalThis);
21
+ const clock = (options) => options.now ?? Date.now;
22
+ const here = (options) => options.location ?? globalThis.location;
23
+ /** A plain request to the live origin: same-origin, cookies included, and marked so a stray page can't forge it. */
24
+ async function ask(options, path, init) {
25
+ try {
26
+ return await doFetch(options)(`${LIVE}${path}`, {
27
+ method: init.method,
28
+ credentials: 'same-origin',
29
+ headers: {
30
+ 'x-quad-live': '1',
31
+ ...(init.body !== undefined ? { 'content-type': 'application/json' } : {}),
32
+ },
33
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
34
+ });
35
+ }
36
+ catch (e) {
37
+ throw new QuadError('TRANSPORT', `couldn't reach Quad: ${e.message}`);
38
+ }
39
+ }
40
+ /** Who is signed in at this address, and whether guests are welcome if no one is. */
41
+ export async function getLiveStatus(options = {}) {
42
+ const response = await ask(options, '/session', { method: 'GET' });
43
+ if (response.status === 404)
44
+ throw new QuadError('TRANSPORT', 'This app runs inside the Quad demo shell, or at its live address. Open it from there.');
45
+ const body = (await response.json().catch(() => null));
46
+ if (!response.ok || !body)
47
+ throw new QuadError('TRANSPORT', `Quad answered ${response.status} with no usable session`);
48
+ if (body.signedIn && typeof body.dataApi === 'string')
49
+ return { signedIn: true, dataApi: body.dataApi };
50
+ return { signedIn: false, guests: body.guests === true };
51
+ }
52
+ /** Leaves for Quad's sign-in, which returns the person to this page. */
53
+ export function signIn(options = {}) {
54
+ const page = here(options);
55
+ const next = `${page.pathname}${page.search}${page.hash}`;
56
+ page.assign(`${LIVE}/signin?next=${encodeURIComponent(next)}`);
57
+ }
58
+ function device(options) {
59
+ const storage = options.storage ?? safeStorage();
60
+ const known = storage?.getItem(DEVICE_KEY);
61
+ if (known)
62
+ return known;
63
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
64
+ const fresh = btoa(String.fromCharCode(...bytes))
65
+ .replace(/\+/g, '-')
66
+ .replace(/\//g, '_')
67
+ .replace(/=+$/, '');
68
+ storage?.setItem(DEVICE_KEY, fresh);
69
+ return fresh;
70
+ }
71
+ let memory = null;
72
+ function safeStorage() {
73
+ try {
74
+ return globalThis.localStorage;
75
+ }
76
+ catch {
77
+ // Blocked storage: the id lasts as long as the page, which is a new guest after a reload.
78
+ return { getItem: () => memory, setItem: (_k, v) => void (memory = v) };
79
+ }
80
+ }
81
+ /** Starts a guest session. The device id stays on this origin; Quad keeps only a salted hash of it (ADR 0010). */
82
+ export async function continueAsGuest(options = {}) {
83
+ const response = await ask(options, '/guest', {
84
+ method: 'POST',
85
+ body: { device: device(options) },
86
+ });
87
+ if (!response.ok)
88
+ throw new QuadError('FORBIDDEN', 'this app does not let guests in');
89
+ }
90
+ /** Connects as the signed-in person, or throws {@link SignInRequired}. */
91
+ export async function connectLive(options = {}) {
92
+ return connectSignedIn(await getLiveStatus(options), options);
93
+ }
94
+ /** Connects from a status already fetched; throws {@link SignInRequired} if it says nobody is signed in. */
95
+ export async function connectSignedIn(status, options) {
96
+ if (!status.signedIn)
97
+ throw new SignInRequired(status.guests);
98
+ let current;
99
+ let pending;
100
+ const mint = async () => {
101
+ const response = await ask(options, '/token', { method: 'POST' });
102
+ if (response.status === 401 || response.status === 403)
103
+ throw new QuadError('FORBIDDEN', 'your session has ended; sign in again');
104
+ const body = (await response.json().catch(() => null));
105
+ if (!response.ok || !body?.token || typeof body.expiresAt !== 'number')
106
+ throw new QuadError('TRANSPORT', `Quad answered ${response.status} with no usable token`);
107
+ current = { token: body.token, expiresAtMs: body.expiresAt * 1000 };
108
+ return body.token;
109
+ };
110
+ const token = () => {
111
+ if (current && current.expiresAtMs - clock(options)() > REFRESH_MARGIN_MS)
112
+ return current.token;
113
+ // Calls made together share one request.
114
+ pending ??= mint().finally(() => (pending = undefined));
115
+ return pending;
116
+ };
117
+ return connectHttp({
118
+ baseUrl: status.dataApi,
119
+ token,
120
+ ...(options.fetch ? { fetch: options.fetch } : {}),
121
+ });
122
+ }
@@ -1,5 +1,5 @@
1
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';
2
+ export type QuadErrorCode = 'SCOPE_NOT_GRANTED' | 'UNDECLARED_TYPE' | 'NOT_FOUND' | 'VALIDATION' | 'FORBIDDEN' | 'NOT_AVAILABLE' | 'NOT_PERMITTED' | 'NOT_ASSIGNEE' | 'TRANSPORT' | 'INTERNAL';
3
3
  export declare class QuadError extends Error {
4
4
  readonly code: QuadErrorCode;
5
5
  readonly details: unknown;
@@ -0,0 +1,30 @@
1
+ import type { Principal } from '@quad-education/canonical';
2
+ /** A Quad account using a live or Sandbox app, with the app-defined roles the owner assigned it (V2c, D100). */
3
+ export type AccountPrincipal = {
4
+ readonly kind: 'account';
5
+ readonly accountId: string;
6
+ readonly roles: readonly string[];
7
+ /** Carried by a live token, so a call doesn't need the directory to say who this is. */
8
+ readonly displayName?: string;
9
+ };
10
+ /** Someone not signed in, identified only by a device id (V2c, D100). */
11
+ export type GuestPrincipal = {
12
+ readonly kind: 'guest';
13
+ readonly guestId: string;
14
+ };
15
+ /** One account in the directory an engine is given: who exists and the app roles they hold (V2c, D100). */
16
+ export type AccountRecord = {
17
+ readonly id: string;
18
+ readonly displayName: string;
19
+ readonly roles: readonly string[];
20
+ };
21
+ /** Who the Quad accounts are: live, the control plane; in the shell and tests, a fixed list. */
22
+ export interface AccountDirectory {
23
+ get(id: string): Promise<AccountRecord | undefined>;
24
+ /** Every account holding an app role, matched ignoring case. */
25
+ withRole(role: string): Promise<readonly AccountRecord[]>;
26
+ }
27
+ /** A directory over a fixed list of accounts. */
28
+ export declare function staticDirectory(accounts: readonly AccountRecord[]): AccountDirectory;
29
+ /** Who a call is made as: a school user or the system (D2, D8), a Quad account or a guest. */
30
+ export type ActingAs = Principal | AccountPrincipal | GuestPrincipal;
@@ -0,0 +1,12 @@
1
+ /** A directory over a fixed list of accounts. */
2
+ export function staticDirectory(accounts) {
3
+ const byId = new Map(accounts.map((a) => [a.id, a]));
4
+ return {
5
+ async get(id) {
6
+ return byId.get(id);
7
+ },
8
+ async withRole(role) {
9
+ return accounts.filter((a) => a.roles.some((r) => r.toLowerCase() === role.toLowerCase()));
10
+ },
11
+ };
12
+ }
@@ -5,8 +5,14 @@ import type { ContactPurpose, Role } from '@quad-education/canonical';
5
5
  */
6
6
  export type Recipient = {
7
7
  readonly person: string;
8
- } | {
9
- readonly role: Role;
8
+ }
9
+ /** A school role, or (outside a school) one of the app's own roles (V2c, D100). */
10
+ | {
11
+ readonly role: Role | (string & {});
12
+ }
13
+ /** A Quad account, outside a school (V2c, D100). */
14
+ | {
15
+ readonly account: string;
10
16
  } | {
11
17
  readonly relationship: 'parentsOf';
12
18
  readonly studentId: string;
@@ -1,7 +1,7 @@
1
1
  import type { CanonicalRecord, ContactPurpose, Entities, EntityName, RecordWithFields, RecordWithTiers, Role, TiersFor } from '@quad-education/canonical';
2
2
  import type { AppEntityDef, AppInput, AppSchema, FieldValue, SystemFields } from '@quad-education/schema';
3
3
  import type { Recipient } from './recipients.ts';
4
- export declare const SDK_VERSION = "0.1.3";
4
+ export declare const SDK_VERSION = "0.2.0";
5
5
  /**
6
6
  * Describes the current app to the type system. `quad gen` augments it from
7
7
  * app.manifest.json and schema/ (D23); without that, nothing is readable.
@@ -78,6 +78,22 @@ export type Me = {
78
78
  readonly kind: 'user';
79
79
  readonly role: Role;
80
80
  readonly person: PersonSummary;
81
+ }
82
+ /** A Quad account using an app, with the app-defined roles it was assigned (V2c, D100). */
83
+ | {
84
+ readonly kind: 'account';
85
+ readonly account: {
86
+ readonly id: string;
87
+ readonly displayName: string;
88
+ };
89
+ readonly roles: readonly string[];
90
+ }
91
+ /** Someone not signed in, identified only by a device id (V2c, D100). */
92
+ | {
93
+ readonly kind: 'guest';
94
+ readonly guest: {
95
+ readonly id: string;
96
+ };
81
97
  } | {
82
98
  readonly kind: 'system';
83
99
  readonly appId: string;
@@ -241,7 +257,7 @@ export type NotifyInput<A extends AppConfig> = {
241
257
  };
242
258
  export type ResolvedRecipient = {
243
259
  readonly personId: string;
244
- readonly role: Role;
260
+ readonly role: Role | (string & {});
245
261
  };
246
262
  export type NotifyApi<A extends AppConfig> = {
247
263
  /**
@@ -1 +1 @@
1
- export const SDK_VERSION = '0.1.3';
1
+ export const SDK_VERSION = '0.2.0';
@@ -21,7 +21,7 @@ export declare function recordAudit(k: Kernel, ctx: Ctx, input: unknown): Promis
21
21
  * parents and students only their own. An entry about a student also needs that student
22
22
  * to be visible, staff included (D25). The system principal sees all app entries.
23
23
  */
24
- export declare function listAudit(k: Kernel, ctx: Ctx, options: unknown): {
24
+ export declare function listAudit(k: Kernel, ctx: Ctx, options: unknown): Promise<{
25
25
  items: AuditEntry[];
26
26
  nextCursor: string | null;
27
- };
27
+ }>;
@@ -3,7 +3,7 @@ import { runQuery } from "./query.js";
3
3
  import { isStaffOrSystem, seesSubject, } from "./state.js";
4
4
  import { isObject, jsonObject, onlyKeys, optionalStr, str } from "./values.js";
5
5
  export async function appendAudit(k, app, input) {
6
- const seq = (app.audit[app.audit.length - 1]?.seq ?? 0) + 1;
6
+ const seq = await k.store.nextAuditSeq(app.manifest.id);
7
7
  const entry = {
8
8
  id: `aud-${String(seq).padStart(7, '0')}`,
9
9
  seq,
@@ -21,7 +21,6 @@ export async function appendAudit(k, app, input) {
21
21
  : {}),
22
22
  ...(input.data !== undefined ? { data: input.data } : {}),
23
23
  };
24
- app.audit.push(entry);
25
24
  await k.persistPlatform(app, 'audit', [entry]);
26
25
  return entry;
27
26
  }
@@ -35,8 +34,9 @@ export async function recordAudit(k, ctx, input) {
35
34
  throw new QuadError('VALIDATION', 'audit.record takes an object');
36
35
  onlyKeys(input, ['action', 'summary', 'entity', 'recordId', 'regarding', 'data', 'idempotencyKey'], 'audit.record');
37
36
  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));
37
+ const remembered = key ? await k.store.getKey(ctx.app.manifest.id, key) : undefined;
38
+ if (typeof remembered === 'string') {
39
+ const existing = await k.store.getPlatform(ctx.app.manifest.id, 'audit', remembered);
40
40
  if (existing)
41
41
  return auditView(existing);
42
42
  }
@@ -80,7 +80,7 @@ export async function recordAudit(k, ctx, input) {
80
80
  * parents and students only their own. An entry about a student also needs that student
81
81
  * to be visible, staff included (D25). The system principal sees all app entries.
82
82
  */
83
- export function listAudit(k, ctx, options) {
83
+ export async function listAudit(k, ctx, options) {
84
84
  const opts = (isObject(options) ? options : {});
85
85
  const { entity, recordId, action, limit, cursor } = opts;
86
86
  const where = {};
@@ -90,7 +90,9 @@ export function listAudit(k, ctx, options) {
90
90
  where.recordId = str(recordId, 'recordId');
91
91
  if (action !== undefined)
92
92
  where.action = str(action, 'action');
93
- const visible = ctx.app.audit.filter((e) => e.source === 'app' &&
93
+ const entries = await k.store.allPlatform(ctx.app.manifest.id, 'audit');
94
+ entries.sort((a, b) => a.seq - b.seq);
95
+ const visible = entries.filter((e) => e.source === 'app' &&
94
96
  (isStaffOrSystem(ctx) || e.actor === ctx.actorId) &&
95
97
  seesSubject(k, ctx, e.regardingStudentId));
96
98
  const page = runQuery(visible, {
@@ -5,7 +5,12 @@ import { QuadError } from "../contract/errors.js";
5
5
  // indexes. Equality, `in` and `ne` filters work on any visible field; they only ever scan the
6
6
  // app's own data. Pure, so the serverless data API can apply exactly the same rule.
7
7
  /** Every app entity is indexed on these, with no declaration needed. */
8
- export const IMPLICIT_INDEXES = [['id'], ['createdAt']];
8
+ export const IMPLICIT_INDEXES = [
9
+ ['id'],
10
+ ['createdAt'],
11
+ // So a list of one's own records (the `own` rule) is an index read, in DynamoDB too (V2c, D96).
12
+ ['createdBy', 'createdAt'],
13
+ ];
9
14
  const RANGE_OPS = ['gt', 'gte', 'lt', 'lte'];
10
15
  const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
11
16
  const isRange = (condition) => isPlainObject(condition) &&