@composable-os/client 0.1.0-beta.10 → 0.1.0-beta.13

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/dist/client.js CHANGED
@@ -36,7 +36,9 @@ function globalFetch() {
36
36
  async function readEnvelope(response) {
37
37
  let body;
38
38
  try {
39
- body = JSON.parse(await response.text());
39
+ const parsed = JSON.parse(await response.text());
40
+ // A JSON value that is not an object (a string a proxy sent, say) is no envelope.
41
+ body = parsed !== null && typeof parsed === "object" ? parsed : null;
40
42
  }
41
43
  catch {
42
44
  throw new ApiError("internal", `The host answered ${response.status} without JSON`, response.status);
@@ -103,7 +105,6 @@ export function createClient(specs, options) {
103
105
  }
104
106
  /** `mutationOptions` for a write: one idempotency key per mutation, kept across its retries. */
105
107
  function mutation(name) {
106
- const spec = specs[name];
107
108
  return {
108
109
  mutationKey: [name],
109
110
  mutationFn: (input) => {
@@ -116,7 +117,7 @@ export function createClient(specs, options) {
116
117
  }
117
118
  return call(name, input, { idempotencyKey: key });
118
119
  },
119
- meta: { invalidates: (spec?.invalidates ?? []).map((q) => [q]) },
120
+ meta: { invalidates: invalidates(name) },
120
121
  };
121
122
  }
122
123
  /** The query key prefixes a mutation makes stale, for `queryClient.invalidateQueries`. */
@@ -125,7 +126,9 @@ export function createClient(specs, options) {
125
126
  }
126
127
  // `operations`: which operations this client holds, so a pack's hooks can offer exactly the
127
128
  // ones it can back (ADR 0453).
128
- return { call, query, mutation, invalidates, operations: specs };
129
+ // `baseUrl`: the host this client talks to, for a screen that shows an address on it (a calendar
130
+ // feed's, stage 45): taken from the client, never from the page's own address or query.
131
+ return { call, query, mutation, invalidates, operations: specs, baseUrl: base };
129
132
  }
130
133
  /**
131
134
  * For a MutationCache's `onSuccess`: invalidates what a mutation made by this client lists in
package/dist/hooks.d.ts CHANGED
@@ -12,6 +12,8 @@ export type OperationsOf<C> = C extends {
12
12
  * hooks are written against. Every generated client that holds them fits it.
13
13
  */
14
14
  export interface PackClient<T extends OperationTypes> {
15
+ /** The host the client talks to (a generated client's `baseUrl`), when it has one. */
16
+ readonly baseUrl?: string;
15
17
  query<N extends QueryName<T>>(name: N, input: T[N]["input"]): {
16
18
  queryKey: readonly unknown[];
17
19
  queryFn: () => Promise<T[N]["output"]>;
@@ -21,19 +23,62 @@ export interface PackClient<T extends OperationTypes> {
21
23
  mutationFn: (input: T[N]["input"]) => Promise<T[N]["output"]>;
22
24
  };
23
25
  }
26
+ /** The app's `useQuery` (TanStack Query's), as far as a pack's hooks use it. */
27
+ export type UseQuery = <T>(options: {
28
+ queryKey: readonly unknown[];
29
+ queryFn: () => Promise<T>;
30
+ enabled?: boolean;
31
+ gcTime?: number;
32
+ }) => {
33
+ data: T | undefined;
34
+ isPending: boolean;
35
+ error: unknown;
36
+ refetch?: () => unknown;
37
+ };
38
+ /** The app's `useMutation` (TanStack Query's), as far as a pack's hooks use it. */
39
+ export type UseMutation = <I, O>(options: {
40
+ mutationKey: readonly unknown[];
41
+ mutationFn: (input: I) => Promise<O>;
42
+ gcTime?: number;
43
+ }) => {
44
+ mutate(input: I): void;
45
+ mutateAsync(input: I): Promise<O>;
46
+ data: O | undefined;
47
+ isPending: boolean;
48
+ error: unknown;
49
+ /** Forgets the call: its variables and its answer (TanStack Query's reset). */
50
+ reset?: () => void;
51
+ };
52
+ /**
53
+ * What one hook calls: every operation of a list, or every operation of one of several lists
54
+ * (`anyOf`, the first one the client holds), for a read each audience makes its own way.
55
+ */
56
+ export type HookCalls<N extends string = string> = readonly N[] | {
57
+ readonly anyOf: readonly (readonly N[])[];
58
+ };
59
+ /** Every operation a hook may call, whichever of its alternatives a client holds. */
60
+ export declare function hookOperations(calls: HookCalls): string[];
61
+ /** Every operation any of the hooks may call: what a client holding them all holds. */
62
+ export declare function hooksOperations(calls: Readonly<Record<string, HookCalls>>): string[];
63
+ /** Whether a client holding `Names` backs `C`: all of a list, or all of one list of `anyOf`. */
64
+ type Backed<C, Names extends string> = C extends {
65
+ readonly anyOf: readonly (infer L)[];
66
+ } ? L extends readonly string[] ? L[number] extends Names ? true : never : never : C extends readonly string[] ? C[number] extends Names ? true : never : never;
24
67
  /** The hooks of `H` a client holding `Names` can back: those all of whose operations it holds. */
25
68
  export type HooksFor<H, Calls extends {
26
- readonly [K in keyof H]: readonly string[];
69
+ readonly [K in keyof H]: HookCalls;
27
70
  }, Names extends string> = {
28
- [K in keyof H as Calls[K][number] extends Names ? K : never]: H[K];
71
+ [K in keyof H as [Backed<Calls[K], Names>] extends [never] ? never : K]: H[K];
29
72
  };
30
73
  /**
31
74
  * The hooks `make` writes, keeping only those whose operations (`calls`, one list per hook, an
32
75
  * empty list for a hook that calls none) the client holds: in the type and at run time.
33
76
  *
34
- * `make` is given the client typed over all the pack's operations; a hook it writes over an
77
+ * `make` is given the client typed over all the pack's operations, and `holds`, which says
78
+ * whether the client holds an operation (for a hook with `anyOf`); a hook it writes over an
35
79
  * operation the client lacks is never returned, so it is never called.
36
80
  */
37
81
  export declare function packHooks<T extends OperationTypes, H extends object, const Calls extends {
38
- readonly [K in keyof H]: readonly (keyof T & string)[];
39
- }, C extends ClientHolding>(api: C, calls: Calls, make: (api: PackClient<T>) => H): HooksFor<H, Calls, OperationsOf<C>>;
82
+ readonly [K in keyof H]: HookCalls<keyof T & string>;
83
+ }, C extends ClientHolding>(api: C, calls: Calls, make: (api: PackClient<T>, holds: (operation: keyof T & string) => boolean) => H): HooksFor<H, Calls, OperationsOf<C>>;
84
+ export {};
package/dist/hooks.js CHANGED
@@ -1,21 +1,32 @@
1
+ /** Every operation a hook may call, whichever of its alternatives a client holds. */
2
+ export function hookOperations(calls) {
3
+ return "anyOf" in calls ? [...new Set(calls.anyOf.flat())] : [...calls];
4
+ }
5
+ /** Every operation any of the hooks may call: what a client holding them all holds. */
6
+ export function hooksOperations(calls) {
7
+ return [...new Set(Object.values(calls).flatMap(hookOperations))];
8
+ }
1
9
  /**
2
10
  * The hooks `make` writes, keeping only those whose operations (`calls`, one list per hook, an
3
11
  * empty list for a hook that calls none) the client holds: in the type and at run time.
4
12
  *
5
- * `make` is given the client typed over all the pack's operations; a hook it writes over an
13
+ * `make` is given the client typed over all the pack's operations, and `holds`, which says
14
+ * whether the client holds an operation (for a hook with `anyOf`); a hook it writes over an
6
15
  * operation the client lacks is never returned, so it is never called.
7
16
  */
8
17
  export function packHooks(api, calls, make) {
9
18
  const held = new Set(Object.keys(api.operations));
19
+ const holds = (operation) => held.has(operation);
10
20
  // The one place the client is used as the client of every operation: only the hooks whose
11
21
  // operations it holds leave this function.
12
- const hooks = make(api);
22
+ const hooks = make(api, holds);
13
23
  const out = {};
14
24
  for (const [name, hook] of Object.entries(hooks)) {
15
25
  const needs = calls[name];
16
26
  if (!needs)
17
27
  throw new Error(`packHooks: ${name} does not say which operations it calls`);
18
- if (needs.every((op) => held.has(op)))
28
+ const lists = "anyOf" in needs ? needs.anyOf : [needs];
29
+ if (lists.some((list) => list.every(holds)))
19
30
  out[name] = hook;
20
31
  }
21
32
  return out;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,10 @@
1
+ export * from "./account.ts";
2
+ export * from "./agreements.ts";
1
3
  export * from "./binding.ts";
2
4
  export * from "./client.ts";
3
5
  export * from "./errors.ts";
4
6
  export * from "./hooks.ts";
7
+ export * from "./notes.ts";
8
+ export * from "./owner.ts";
5
9
  export * from "./session.ts";
6
10
  export type * from "./types.ts";
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
1
  // @composable-os/client: the typed client's runtime (stage 23, ADR 0403, ADR 0418).
2
+ export * from "./account.js";
3
+ export * from "./agreements.js";
2
4
  export * from "./binding.js";
3
5
  export * from "./client.js";
4
6
  export * from "./errors.js";
5
7
  export * from "./hooks.js";
8
+ export * from "./notes.js";
9
+ export * from "./owner.js";
6
10
  export * from "./session.js";
@@ -0,0 +1,169 @@
1
+ import { type ClientHolding, type PackClient } from "./hooks.ts";
2
+ /** Who may read a note: every staff account, the client's coaches, or the people named one by one. */
3
+ export type NoteLevel = "staff" | "coaches" | "sensitive";
4
+ export interface NoteKindSection {
5
+ key: string;
6
+ label: string;
7
+ hint: string | null;
8
+ required: boolean;
9
+ }
10
+ /** A kind of note as the composer uses it (`note.kinds.list`). */
11
+ export interface NoteKind {
12
+ id: string;
13
+ key: string | null;
14
+ name: string;
15
+ defaultLevel: NoteLevel;
16
+ lowestLevel: NoteLevel;
17
+ /** The levels a note of it may have, lowest first: the host's list, offered as it is. */
18
+ levels: NoteLevel[];
19
+ sections: NoteKindSection[];
20
+ active: boolean;
21
+ }
22
+ /** A record the note is about or on: a Person, a class, a session, a deal. */
23
+ export interface NoteAbout {
24
+ object: string;
25
+ id: string;
26
+ }
27
+ /** What writing a note sends (`activity.log`). */
28
+ export type WriteNoteInput = {
29
+ type: "note";
30
+ kindId: string;
31
+ level: NoteLevel;
32
+ links: NoteAbout[];
33
+ sections?: {
34
+ key: string;
35
+ text: string;
36
+ }[];
37
+ body?: string;
38
+ };
39
+ /** The operations this entry calls, as the generated client types them. */
40
+ export type NotesOperations = {
41
+ "note.kinds.list": {
42
+ kind: "query";
43
+ input: {
44
+ includeRetired?: boolean;
45
+ };
46
+ output: {
47
+ items: NoteKind[];
48
+ };
49
+ };
50
+ "activity.log": {
51
+ kind: "mutation";
52
+ input: WriteNoteInput;
53
+ output: {
54
+ id: string;
55
+ };
56
+ };
57
+ };
58
+ export type NotesClient = PackClient<NotesOperations>;
59
+ /** A level's name and a line saying who reads a note at it. */
60
+ export declare function levelWords(level: NoteLevel): {
61
+ label: string;
62
+ hint: string;
63
+ };
64
+ /** A note being written: kept in the screen's memory only, until the one call that writes it. */
65
+ export interface NoteDraft {
66
+ kindId: string;
67
+ level: NoteLevel;
68
+ /** Each template section's text, by its key. */
69
+ sections: Record<string, string>;
70
+ /** The note's text, for a kind with no template. */
71
+ body: string;
72
+ }
73
+ /** A new draft of a kind: at the kind's own level, empty. */
74
+ export declare function blankDraft(kind: NoteKind): NoteDraft;
75
+ /**
76
+ * The draft moved to another kind: the text of sections the two templates share is kept, and the
77
+ * level is the new kind's own (a person lowers it themselves, as far as the host lets them).
78
+ */
79
+ export declare function draftForKind(draft: NoteDraft, kind: NoteKind): NoteDraft;
80
+ /** The labels of what is still empty: a required section, or the text of a kind with no template. */
81
+ export declare function missingFromDraft(kind: NoteKind, draft: NoteDraft): string[];
82
+ /** What writing the draft sends: the sections of a template, or the body of a kind with none. */
83
+ export declare function noteInput(kind: NoteKind, draft: NoteDraft, about: NoteAbout[]): WriteNoteInput;
84
+ /**
85
+ * The words for the host's refusal of a note, or its own message. The host's message already says
86
+ * what to fix (a required section, a level below the kind's lowest).
87
+ */
88
+ export declare function noteRefusalWords(error: unknown): string;
89
+ /** The app's `useQuery`, as far as these hooks use it. */
90
+ export type NotesUseQuery = <T>(options: {
91
+ queryKey: readonly unknown[];
92
+ queryFn: () => Promise<T>;
93
+ enabled?: boolean;
94
+ }) => {
95
+ data: T | undefined;
96
+ isPending: boolean;
97
+ error: unknown;
98
+ };
99
+ /** The app's `useMutation`, as far as these hooks use it. */
100
+ export type NotesUseMutation = <I, O>(options: {
101
+ mutationKey: readonly unknown[];
102
+ mutationFn: (input: I) => Promise<O>;
103
+ gcTime?: number;
104
+ }) => {
105
+ mutateAsync(input: I): Promise<O>;
106
+ isPending: boolean;
107
+ error: unknown;
108
+ reset?: () => void;
109
+ };
110
+ /** The operations each hook calls (ADR 0453). */
111
+ export declare const NOTES_HOOKS_CALL: {
112
+ readonly useNoteKinds: readonly ["note.kinds.list"];
113
+ readonly useWriteNote: readonly ["activity.log"];
114
+ };
115
+ /**
116
+ * Hooks for a React or React Native staff screen:
117
+ * `const notes = createNotesHooks({ useQuery, useMutation }, api)`, with the staff client. The
118
+ * hooks it cannot back are not there.
119
+ */
120
+ export declare function createNotesHooks<C extends ClientHolding>(react: {
121
+ useQuery: NotesUseQuery;
122
+ useMutation: NotesUseMutation;
123
+ }, client: C): import("./hooks.ts").HooksFor<{
124
+ /** The kinds the composer offers, in the business's order. */
125
+ useNoteKinds(): {
126
+ data: {
127
+ items: NoteKind[];
128
+ } | undefined;
129
+ isPending: boolean;
130
+ error: unknown;
131
+ };
132
+ /** Write a note. What was sent is not kept once the call is over (use `forgetAfter`). */
133
+ useWriteNote(): {
134
+ mutateAsync(input: WriteNoteInput): Promise<{
135
+ id: string;
136
+ }>;
137
+ isPending: boolean;
138
+ error: unknown;
139
+ reset?: () => void;
140
+ };
141
+ }, {
142
+ readonly useNoteKinds: readonly ["note.kinds.list"];
143
+ readonly useWriteNote: readonly ["activity.log"];
144
+ }, import("./hooks.ts").OperationsOf<C>>;
145
+ declare function allNotesHooks(react: {
146
+ useQuery: NotesUseQuery;
147
+ useMutation: NotesUseMutation;
148
+ }, api: NotesClient): {
149
+ /** The kinds the composer offers, in the business's order. */
150
+ useNoteKinds(): {
151
+ data: {
152
+ items: NoteKind[];
153
+ } | undefined;
154
+ isPending: boolean;
155
+ error: unknown;
156
+ };
157
+ /** Write a note. What was sent is not kept once the call is over (use `forgetAfter`). */
158
+ useWriteNote(): {
159
+ mutateAsync(input: WriteNoteInput): Promise<{
160
+ id: string;
161
+ }>;
162
+ isPending: boolean;
163
+ error: unknown;
164
+ reset?: () => void;
165
+ };
166
+ };
167
+ /** Every hook of this entry. A block takes the ones it calls: `Pick<NotesHooks, "useNoteKinds">`. */
168
+ export type NotesHooks = ReturnType<typeof allNotesHooks>;
169
+ export {};
package/dist/notes.js ADDED
@@ -0,0 +1,108 @@
1
+ // Notes for a staff screen (stage 56 step 2, ADR 0833): the headless entry the note composer
2
+ // shares, web and native and the admin's own timeline. Functions and hooks over a staff client, no
3
+ // markup: the blocks draw the kinds, the template's sections and the levels, and use what is here.
4
+ //
5
+ // It holds no rules. Which kinds there are, the levels a note of each may have, which sections are
6
+ // required and who reads a note at each level are the host's (`note.kinds.list`, and
7
+ // `activity.log`, which checks everything again in full): a block offers what the host listed and
8
+ // shows the host's refusal. `missingFromDraft` only says what is empty before a call.
9
+ //
10
+ // What a person writes in a note may be health information: nothing here logs, stores or sends it
11
+ // anywhere but the one call that writes the note. It lives in the screen's memory until then, and
12
+ // the mutation is forgotten after it (`forgetAfter`).
13
+ import { packHooks } from "./hooks.js";
14
+ // --- Words ---------------------------------------------------------------------------------------
15
+ const LEVEL_WORDS = {
16
+ staff: { label: "Staff", hint: "Everyone on the staff can read it." },
17
+ coaches: {
18
+ label: "Client's coaches",
19
+ hint: "Read by you, the staff who look after this person, and managers.",
20
+ },
21
+ sensitive: {
22
+ label: "Sensitive",
23
+ hint: "Read by you and the people the business named one by one. Every opening is recorded.",
24
+ },
25
+ };
26
+ /** A level's name and a line saying who reads a note at it. */
27
+ export function levelWords(level) {
28
+ return LEVEL_WORDS[level];
29
+ }
30
+ /** A new draft of a kind: at the kind's own level, empty. */
31
+ export function blankDraft(kind) {
32
+ return { kindId: kind.id, level: kind.defaultLevel, sections: {}, body: "" };
33
+ }
34
+ /**
35
+ * The draft moved to another kind: the text of sections the two templates share is kept, and the
36
+ * level is the new kind's own (a person lowers it themselves, as far as the host lets them).
37
+ */
38
+ export function draftForKind(draft, kind) {
39
+ const sections = {};
40
+ for (const section of kind.sections) {
41
+ const text = draft.sections[section.key];
42
+ if (text)
43
+ sections[section.key] = text;
44
+ }
45
+ const body = kind.sections.length === 0 && !draft.body
46
+ ? Object.values(draft.sections).filter(Boolean).join("\n\n")
47
+ : draft.body;
48
+ return { kindId: kind.id, level: kind.defaultLevel, sections, body };
49
+ }
50
+ /** The labels of what is still empty: a required section, or the text of a kind with no template. */
51
+ export function missingFromDraft(kind, draft) {
52
+ if (kind.sections.length === 0)
53
+ return draft.body.trim() ? [] : ["The note"];
54
+ const missing = kind.sections
55
+ .filter((s) => s.required && !draft.sections[s.key]?.trim())
56
+ .map((s) => s.label);
57
+ if (missing.length)
58
+ return missing;
59
+ return kind.sections.some((s) => draft.sections[s.key]?.trim()) ? [] : ["The note"];
60
+ }
61
+ /** What writing the draft sends: the sections of a template, or the body of a kind with none. */
62
+ export function noteInput(kind, draft, about) {
63
+ const base = { type: "note", kindId: kind.id, level: draft.level, links: about };
64
+ if (kind.sections.length === 0)
65
+ return { ...base, body: draft.body };
66
+ return {
67
+ ...base,
68
+ sections: kind.sections
69
+ .map((s) => ({ key: s.key, text: draft.sections[s.key]?.trim() ?? "" }))
70
+ .filter((s) => s.text),
71
+ };
72
+ }
73
+ /**
74
+ * The words for the host's refusal of a note, or its own message. The host's message already says
75
+ * what to fix (a required section, a level below the kind's lowest).
76
+ */
77
+ export function noteRefusalWords(error) {
78
+ const message = error !== null && typeof error === "object" && "message" in error
79
+ ? String(error.message)
80
+ : "";
81
+ return message || "The note could not be saved. Try again.";
82
+ }
83
+ /** The operations each hook calls (ADR 0453). */
84
+ export const NOTES_HOOKS_CALL = {
85
+ useNoteKinds: ["note.kinds.list"],
86
+ useWriteNote: ["activity.log"],
87
+ };
88
+ /**
89
+ * Hooks for a React or React Native staff screen:
90
+ * `const notes = createNotesHooks({ useQuery, useMutation }, api)`, with the staff client. The
91
+ * hooks it cannot back are not there.
92
+ */
93
+ export function createNotesHooks(react, client) {
94
+ return packHooks(client, NOTES_HOOKS_CALL, (api) => allNotesHooks(react, api));
95
+ }
96
+ function allNotesHooks(react, api) {
97
+ const { useQuery, useMutation } = react;
98
+ return {
99
+ /** The kinds the composer offers, in the business's order. */
100
+ useNoteKinds() {
101
+ return useQuery(api.query("note.kinds.list", {}));
102
+ },
103
+ /** Write a note. What was sent is not kept once the call is over (use `forgetAfter`). */
104
+ useWriteNote() {
105
+ return useMutation({ ...api.mutation("activity.log"), gcTime: 0 });
106
+ },
107
+ };
108
+ }