@photonhealth/client 2.0.0-rc.1 → 2.0.0-rc.3

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 (158) hide show
  1. package/README.md +150 -5
  2. package/dist/analytics/lifecycleEvents.d.ts +32 -0
  3. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  4. package/dist/analytics/lifecycleEvents.js +75 -0
  5. package/dist/analytics/lifecycleEvents.js.map +1 -0
  6. package/dist/analytics/track.d.ts +39 -0
  7. package/dist/analytics/track.d.ts.map +1 -0
  8. package/dist/analytics/track.js +91 -0
  9. package/dist/analytics/track.js.map +1 -0
  10. package/dist/api/changes/applyOption.d.ts +4 -1
  11. package/dist/api/changes/applyOption.d.ts.map +1 -1
  12. package/dist/api/changes/applyOption.js +23 -2
  13. package/dist/api/changes/applyOption.js.map +1 -1
  14. package/dist/api/client.d.ts +6 -1
  15. package/dist/api/client.d.ts.map +1 -1
  16. package/dist/api/client.js +47 -33
  17. package/dist/api/client.js.map +1 -1
  18. package/dist/api/index.d.ts +2 -0
  19. package/dist/api/index.d.ts.map +1 -1
  20. package/dist/api/index.js +2 -0
  21. package/dist/api/index.js.map +1 -1
  22. package/dist/api/me.d.ts +37 -0
  23. package/dist/api/me.d.ts.map +1 -0
  24. package/dist/api/me.js +6 -0
  25. package/dist/api/me.js.map +1 -0
  26. package/dist/api/orders.d.ts +1047 -0
  27. package/dist/api/orders.d.ts.map +1 -0
  28. package/dist/api/orders.js +7 -0
  29. package/dist/api/orders.js.map +1 -0
  30. package/dist/api/patient.d.ts +5 -2
  31. package/dist/api/patient.d.ts.map +1 -1
  32. package/dist/api/patient.js +1 -1
  33. package/dist/api/patient.js.map +1 -1
  34. package/dist/api/prescription.d.ts +7 -1
  35. package/dist/api/prescription.d.ts.map +1 -1
  36. package/dist/api/prescription.js +10 -1
  37. package/dist/api/prescription.js.map +1 -1
  38. package/dist/gql/gql.d.ts +11 -3
  39. package/dist/gql/gql.d.ts.map +1 -1
  40. package/dist/gql/gql.js +5 -3
  41. package/dist/gql/gql.js.map +1 -1
  42. package/dist/gql/graphql.d.ts +10507 -1563
  43. package/dist/gql/graphql.d.ts.map +1 -1
  44. package/dist/gql/graphql.js +2984 -435
  45. package/dist/gql/graphql.js.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +1 -1
  48. package/dist/meta/version.d.ts +2 -0
  49. package/dist/meta/version.d.ts.map +1 -0
  50. package/dist/meta/version.js +2 -0
  51. package/dist/meta/version.js.map +1 -0
  52. package/dist/photon/auth.d.ts +9 -5
  53. package/dist/photon/auth.d.ts.map +1 -1
  54. package/dist/photon/auth.js +2 -6
  55. package/dist/photon/auth.js.map +1 -1
  56. package/dist/photon/choices.d.ts +1 -1
  57. package/dist/photon/choices.js +2 -2
  58. package/dist/photon/choices.js.map +1 -1
  59. package/dist/photon/environments.d.ts +2 -1
  60. package/dist/photon/environments.d.ts.map +1 -1
  61. package/dist/photon/environments.js +2 -1
  62. package/dist/photon/environments.js.map +1 -1
  63. package/dist/photon/index.d.ts +6 -3
  64. package/dist/photon/index.d.ts.map +1 -1
  65. package/dist/photon/index.js +2 -1
  66. package/dist/photon/index.js.map +1 -1
  67. package/dist/photon/machine.d.ts +28 -0
  68. package/dist/photon/machine.d.ts.map +1 -0
  69. package/dist/photon/machine.js +53 -0
  70. package/dist/photon/machine.js.map +1 -0
  71. package/dist/photon/map.d.ts +6 -2
  72. package/dist/photon/map.d.ts.map +1 -1
  73. package/dist/photon/map.js +133 -33
  74. package/dist/photon/map.js.map +1 -1
  75. package/dist/photon/order.d.ts +24 -5
  76. package/dist/photon/order.d.ts.map +1 -1
  77. package/dist/photon/order.js +85 -23
  78. package/dist/photon/order.js.map +1 -1
  79. package/dist/photon/orders.d.ts +5 -0
  80. package/dist/photon/orders.d.ts.map +1 -0
  81. package/dist/photon/orders.js +39 -0
  82. package/dist/photon/orders.js.map +1 -0
  83. package/dist/photon/patient.d.ts +8 -6
  84. package/dist/photon/patient.d.ts.map +1 -1
  85. package/dist/photon/patient.js +61 -30
  86. package/dist/photon/patient.js.map +1 -1
  87. package/dist/photon/photon.d.ts +39 -1
  88. package/dist/photon/photon.d.ts.map +1 -1
  89. package/dist/photon/photon.js +85 -5
  90. package/dist/photon/photon.js.map +1 -1
  91. package/dist/photon/prescription.d.ts +17 -4
  92. package/dist/photon/prescription.d.ts.map +1 -1
  93. package/dist/photon/prescription.js +48 -11
  94. package/dist/photon/prescription.js.map +1 -1
  95. package/dist/photon/session.d.ts +16 -10
  96. package/dist/photon/session.d.ts.map +1 -1
  97. package/dist/photon/session.js +26 -11
  98. package/dist/photon/session.js.map +1 -1
  99. package/dist/photon/types.d.ts +278 -46
  100. package/dist/photon/types.d.ts.map +1 -1
  101. package/dist/test-utils/msw.d.ts +2 -2
  102. package/dist/test-utils/msw.d.ts.map +1 -1
  103. package/dist/test-utils/msw.js +5 -5
  104. package/dist/test-utils/msw.js.map +1 -1
  105. package/dist/testing/{scriptedClient.d.ts → fakeNetworkApiClient.d.ts} +5 -4
  106. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  107. package/dist/testing/{scriptedClient.js → fakeNetworkApiClient.js} +8 -4
  108. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  109. package/dist/testing/fixtures.d.ts +1047 -0
  110. package/dist/testing/fixtures.d.ts.map +1 -1
  111. package/dist/testing/fixtures.js +47 -13
  112. package/dist/testing/fixtures.js.map +1 -1
  113. package/dist/testing.d.ts +4 -4
  114. package/dist/testing.d.ts.map +1 -1
  115. package/dist/testing.js +4 -4
  116. package/dist/testing.js.map +1 -1
  117. package/package.json +2 -2
  118. package/src/analytics/lifecycleEvents.test.ts +437 -0
  119. package/src/analytics/lifecycleEvents.ts +172 -0
  120. package/src/analytics/track.test.ts +231 -0
  121. package/src/analytics/track.ts +129 -0
  122. package/src/api/changes/applyOption.ts +25 -2
  123. package/src/api/client.ts +71 -46
  124. package/src/api/index.ts +2 -0
  125. package/src/api/me.ts +7 -0
  126. package/src/api/orders.ts +8 -0
  127. package/src/api/patient.ts +11 -2
  128. package/src/api/prescription.ts +18 -0
  129. package/src/gql/gql.ts +21 -9
  130. package/src/gql/graphql.ts +4280 -597
  131. package/src/index.ts +1 -1
  132. package/src/meta/version.test.ts +10 -0
  133. package/src/meta/version.ts +1 -0
  134. package/src/operations/fragments.graphql +166 -20
  135. package/src/operations/me.graphql +38 -0
  136. package/src/operations/orders.graphql +35 -0
  137. package/src/operations/patient.graphql +29 -3
  138. package/src/operations/prescription.graphql +20 -0
  139. package/src/photon/auth.ts +9 -10
  140. package/src/photon/choices.ts +2 -2
  141. package/src/photon/environments.ts +3 -1
  142. package/src/photon/index.ts +17 -2
  143. package/src/photon/machine.ts +90 -0
  144. package/src/photon/map.ts +151 -35
  145. package/src/photon/order.test.ts +142 -0
  146. package/src/photon/order.ts +99 -24
  147. package/src/photon/orders.ts +42 -0
  148. package/src/photon/patient.ts +73 -33
  149. package/src/photon/photon.ts +139 -6
  150. package/src/photon/prescription.ts +71 -12
  151. package/src/photon/session.ts +39 -16
  152. package/src/photon/types.ts +280 -26
  153. package/src/test-utils/msw.ts +16 -5
  154. package/src/testing/{scriptedClient.ts → fakeNetworkApiClient.ts} +8 -4
  155. package/src/testing/fixtures.ts +55 -13
  156. package/src/testing.ts +6 -3
  157. package/dist/testing/scriptedClient.d.ts.map +0 -1
  158. package/dist/testing/scriptedClient.js.map +0 -1
@@ -0,0 +1,42 @@
1
+ import { orders, type NetworkClient } from "../api/index.ts";
2
+ import { guarded } from "./errors.ts";
3
+ import { toChoice, toOrder } from "./map.ts";
4
+ import type { OrdersInput, OrdersResult } from "./types.ts";
5
+
6
+ /** Map the query directly: no live-object hydration, follow-up mutations, or local workflow effects. */
7
+ export async function readOrders(client: NetworkClient, input: OrdersInput = {}): Promise<OrdersResult> {
8
+ const result = await guarded(() =>
9
+ orders(client, {
10
+ filter: input.filter,
11
+ limit: input.limit,
12
+ pharmacy: input.routablePharmacies?.pharmacy,
13
+ page: input.routablePharmacies?.page,
14
+ includePharmacies: input.routablePharmacies !== undefined,
15
+ }),
16
+ );
17
+ if (result.__typename === "AmbiguousPatientMatch")
18
+ return {
19
+ orders: [],
20
+ candidates: result.candidates.map((c) => ({
21
+ id: c.id,
22
+ firstName: c.firstName,
23
+ lastName: c.lastName,
24
+ dateOfBirth: c.dateOfBirth,
25
+ })),
26
+ reason: result.reason,
27
+ };
28
+ return {
29
+ orders: result.orders.map((o) => ({
30
+ ...toOrder(o),
31
+ routablePharmacies: o.routablePharmacies
32
+ ? {
33
+ options: o.routablePharmacies.options.map(toChoice),
34
+ totalCount: o.routablePharmacies.totalCount,
35
+ nextOffset: o.routablePharmacies.nextOffset,
36
+ }
37
+ : null,
38
+ })),
39
+ candidates: [],
40
+ reason: null,
41
+ };
42
+ }
@@ -7,6 +7,9 @@ import { noChanges, toChanges, toPatient } from "./map.ts";
7
7
  import type { ChangeOption, Changes, PatientCandidate, PatientInput, PatientRecord } from "./types.ts";
8
8
 
9
9
  type Demographic = NonNullable<PatientInput["demographic"]>;
10
+ type Contact = NonNullable<PatientInput["contact"]>;
11
+ /** sent before the record */
12
+ type Known = Pick<PatientInput, "demographic" | "contact" | "preferredPharmacy">;
10
13
  type Clinical = NonNullable<PatientInput["clinical"]>;
11
14
 
12
15
  export interface PatientExtra {
@@ -14,7 +17,7 @@ export interface PatientExtra {
14
17
  candidates: PatientCandidate[];
15
18
  /**
16
19
  * Names for clinical entries the server returns with name = id (allergies, diagnoses on boson): what the
17
- * prescriber typed or picked, by entry id (docs/api-gaps.md).
20
+ * prescriber typed or picked, by entry id.
18
21
  */
19
22
  pickedNames: Readonly<Record<string, string>>;
20
23
  }
@@ -33,26 +36,56 @@ const validDob = (dob?: string) => Boolean(dob && /^\d{4}-\d{2}-\d{2}$/.test(dob
33
36
  const trimmed = (v?: string) => v?.trim() || undefined;
34
37
 
35
38
  /** What's synced before the record: trimmed, empty fields dropped, a date of birth only when it's a whole date. */
36
- function cleanDemographic(d: Demographic): Demographic {
39
+ function cleanDemographic(d: Demographic = {}): Demographic {
37
40
  const first = trimmed(d.name?.first);
38
41
  const last = trimmed(d.name?.last);
39
- const clean: Demographic = {
42
+ return {
40
43
  ...(first || last ? { name: { first, last } } : {}),
41
44
  ...(validDob(d.dateOfBirth) ? { dateOfBirth: d.dateOfBirth } : {}),
42
45
  ...(d.sex ? { sex: d.sex } : {}),
43
46
  ...(trimmed(d.gender) ? { gender: trimmed(d.gender) } : {}),
44
- ...(trimmed(d.phone) ? { phone: trimmed(d.phone) } : {}),
45
- ...(trimmed(d.email) ? { email: trimmed(d.email) } : {}),
46
- ...(d.address ? { address: d.address } : {}),
47
47
  };
48
- return clean;
49
48
  }
50
49
 
51
- const mergeDemographic = (a: Demographic, b: Demographic): Demographic => ({
52
- ...a,
53
- ...b,
54
- ...(a.name || b.name ? { name: { ...a.name, ...b.name } } : {}),
55
- ...(a.address || b.address ? { address: { ...a.address, ...b.address } } : {}),
50
+ function cleanContact(c: Contact = {}): Contact {
51
+ return {
52
+ ...(trimmed(c.phone) ? { phone: trimmed(c.phone) } : {}),
53
+ ...(trimmed(c.email) ? { email: trimmed(c.email) } : {}),
54
+ ...(c.address ? { address: c.address } : {}),
55
+ };
56
+ }
57
+
58
+ const nonEmpty = <T extends object>(v: T) => (Object.keys(v).length ? v : undefined);
59
+
60
+ /** drops empty groups */
61
+ function cleanKnown(k: Known): Known {
62
+ const demographic = nonEmpty(cleanDemographic(k.demographic));
63
+ const contact = nonEmpty(cleanContact(k.contact));
64
+ return {
65
+ ...(demographic ? { demographic } : {}),
66
+ ...(contact ? { contact } : {}),
67
+ ...(k.preferredPharmacy ? { preferredPharmacy: k.preferredPharmacy } : {}),
68
+ };
69
+ }
70
+
71
+ const mergeKnown = (a: Known, b: Known): Known => ({
72
+ preferredPharmacy: b.preferredPharmacy ?? a.preferredPharmacy,
73
+ demographic: {
74
+ ...a.demographic,
75
+ ...b.demographic,
76
+ ...(a.demographic?.name || b.demographic?.name ? { name: { ...a.demographic?.name, ...b.demographic?.name } } : {}),
77
+ },
78
+ contact: {
79
+ ...a.contact,
80
+ ...b.contact,
81
+ ...(a.contact?.address || b.contact?.address ? { address: { ...a.contact?.address, ...b.contact?.address } } : {}),
82
+ },
83
+ });
84
+
85
+ const knownOf = ({ demographic, contact, preferredPharmacy }: Omit<PatientInput, "id">): Known => ({
86
+ demographic,
87
+ contact,
88
+ preferredPharmacy,
56
89
  });
57
90
 
58
91
  const clinicalIds = (p: PatientRecord | null) =>
@@ -63,7 +96,7 @@ const clinicalIds = (p: PatientRecord | null) =>
63
96
  );
64
97
 
65
98
  /**
66
- * A patient — from an id, from a record the host has, or not yet known. `sync({ demographic })` sends what
99
+ * A patient — from an id, from a record the host has, or not yet known. `sync({ demographic, contact })` sends what
67
100
  * you know, and the server decides — the patient (found, or created when nothing matches and it has enough),
68
101
  * candidates (pick one), or nothing yet (`changes` says what's missing). Keep adding what you know until it
69
102
  * has an id; then `update(fields)` changes that patient. The client never decides "now create".
@@ -74,7 +107,7 @@ const clinicalIds = (p: PatientRecord | null) =>
74
107
  export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
75
108
  readonly #ctx: Context;
76
109
  /** Everything synced so far, before the record — each sync adds to it. */
77
- #known: Demographic = {};
110
+ #known: Known = {};
78
111
  #lastQuery: string | null = null;
79
112
  /** The search in flight: any newer query aborts it. */
80
113
  #searching: AbortController | null = null;
@@ -83,7 +116,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
83
116
  #declared = new Set<string>();
84
117
  /**
85
118
  * Lists recorded as "none" here: their record says `[]`, not null (not recorded). network-api can't read a
86
- * "none" back for these yet (docs/api-gaps.md) — so only this object knows, until an entry is added to the list.
119
+ * "none" back for these yet — so only this object knows, until an entry is added to the list.
87
120
  */
88
121
  #none = new Set<NoneList>();
89
122
 
@@ -108,7 +141,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
108
141
  * What's been sent to find or add the patient, before the record — e.g. a host's details the server hasn't
109
142
  * matched yet (not enough to add them). A form starts from it.
110
143
  */
111
- get known(): Readonly<Demographic> {
144
+ get known(): Readonly<Known> {
112
145
  return this.#known;
113
146
  }
114
147
 
@@ -118,17 +151,18 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
118
151
  */
119
152
  sync(input: Omit<PatientInput, "id">): Promise<{ changes: Changes }> {
120
153
  if (this.id)
121
- return input.demographic || input.clinical
154
+ return Object.values(input).some(Boolean)
122
155
  ? this.#write("sync", input)
123
156
  : Promise.resolve({ changes: this.changes });
124
157
  if (input.clinical)
125
158
  return Promise.reject(new PhotonError("invalid", "Clinical changes need the patient's id: sync them first."));
126
- return this.#match(input.demographic ?? {});
159
+ return this.#match(knownOf(input));
127
160
  }
128
161
 
129
162
  /**
130
- * UpdatePatient: change this patient — only what's given: demographics and/or clinical lists
131
- * (`{ allergies: { add: [{ name }] } }`, `{ allergies: { none: true } }` for no known allergies). Needs its id.
163
+ * UpdatePatient: change this patient — only what's given: demographics, contact, benefits, preferred pharmacy
164
+ * and/or clinical lists (`{ allergies: { add: [{ name }] } }`, `{ allergies: { none: true } }` for no known
165
+ * allergies). Needs its id.
132
166
  */
133
167
  update(input: Omit<PatientInput, "id">): Promise<{ changes: Changes }> {
134
168
  if (!this.id)
@@ -144,7 +178,10 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
144
178
  */
145
179
  search(input: Omit<PatientInput, "id">): Promise<{ changes: Changes }> {
146
180
  if (this.id) return Promise.resolve({ changes: this.changes });
147
- const { sex: _, ...query } = cleanDemographic(mergeDemographic(this.#known, input.demographic ?? {}));
181
+ const { demographic: { sex: _, ...demographic } = {}, contact } = cleanKnown(
182
+ mergeKnown(this.#known, knownOf(input)),
183
+ );
184
+ const query = { ...(nonEmpty(demographic) ? { demographic } : {}), ...(contact ? { contact } : {}) };
148
185
  const key = JSON.stringify(query);
149
186
  if (!Object.keys(query).length || key === this.#lastQuery) return Promise.resolve({ changes: this.changes });
150
187
  this.#lastQuery = key;
@@ -155,7 +192,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
155
192
  if (key !== this.#lastQuery || this.id) return { changes: this.changes };
156
193
  let outcome: PatientOutcome;
157
194
  try {
158
- outcome = await syncPatient(this.#ctx.client, { demographic: query }, search.signal);
195
+ outcome = await syncPatient(this.#ctx.client, query, search.signal);
159
196
  } catch (e) {
160
197
  if (search.signal.aborted) return { changes: this.changes }; // a newer query answers instead
161
198
  throw e;
@@ -185,6 +222,8 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
185
222
 
186
223
  /** A choice the server asked for (e.g. which penicillin): sent again with the pick applied to the last patch. */
187
224
  choose(option: ChangeOption): Promise<{ changes: Changes }> {
225
+ if (option.operation === "patient" && /^(demographic|contact|benefits|preferredPharmacy)\./.test(option.path ?? ""))
226
+ return this.update(withChoice<Omit<PatientInput, "id">>({}, option));
188
227
  if (option.id && option.displayName)
189
228
  this.patch({ pickedNames: { ...this.snapshot.pickedNames, [option.id]: option.displayName } });
190
229
  const rooted = option.path?.startsWith("clinical.");
@@ -229,9 +268,9 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
229
268
  }).then((result) => this.#takeDeclared(result));
230
269
  }
231
270
 
232
- #match(demographic: Demographic): Promise<{ changes: Changes }> {
233
- this.#known = mergeDemographic(this.#known, demographic);
234
- const query = cleanDemographic(this.#known);
271
+ #match(known: Known): Promise<{ changes: Changes }> {
272
+ this.#known = mergeKnown(this.#known, known);
273
+ const query = cleanKnown(this.#known);
235
274
  if (!Object.keys(query).length) return Promise.resolve({ changes: this.changes });
236
275
  const key = JSON.stringify(query);
237
276
  // The same query gets the same answer: keep it (blur and a debounce often ask twice).
@@ -241,7 +280,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
241
280
  return this.run("loading", async () => {
242
281
  // A newer query was made while this one waited: it answers instead.
243
282
  if (key !== this.#lastQuery || this.id) return { changes: this.changes };
244
- const outcome = await syncPatient(this.#ctx.client, { demographic: query });
283
+ const outcome = await syncPatient(this.#ctx.client, query);
245
284
  // Answered after a newer query was made: only a patient found (or added) still counts.
246
285
  if (key !== this.#lastQuery && !(outcome.kind === "ok" && outcome.patient)) return { changes: this.changes };
247
286
  if (outcome.kind === "ambiguous") {
@@ -258,14 +297,15 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
258
297
  * doesn't have — fill in, never overwrite.
259
298
  */
260
299
  async #fillMissingContact(result: { changes: Changes }) {
261
- const d = this.state?.demographic;
262
- if (!this.id || !d) return result;
300
+ if (!this.id || !this.state) return result;
301
+ const had = this.state.contact;
302
+ const sent = this.#known.contact;
263
303
  const missing = {
264
- ...(this.#known.phone && !d.phone ? { phone: trimmed(this.#known.phone) } : {}),
265
- ...(this.#known.email && !d.email ? { email: trimmed(this.#known.email) } : {}),
304
+ ...(sent?.phone && !had?.phone ? { phone: trimmed(sent.phone) } : {}),
305
+ ...(sent?.email && !had?.email ? { email: trimmed(sent.email) } : {}),
266
306
  };
267
307
  this.#known = {};
268
- return Object.keys(missing).length ? this.update({ demographic: missing }) : result;
308
+ return Object.keys(missing).length ? this.update({ contact: missing }) : result;
269
309
  }
270
310
 
271
311
  /** A choice the server declared (one option, an exact match) or a clinical match it is sure of is taken without asking — once each. */
@@ -297,7 +337,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
297
337
  const patches = {
298
338
  medications: input.clinical?.medications,
299
339
  diagnoses: input.clinical?.diagnoses,
300
- benefits: input.demographic?.benefits,
340
+ benefits: input.benefits,
301
341
  };
302
342
  for (const [list, patch] of Object.entries(patches) as [NoneList, typeof patches.medications][]) {
303
343
  if (patch?.none) this.#none.add(list);
@@ -311,7 +351,7 @@ export class Patient extends LiveRecord<PatientRecord, PatientExtra> {
311
351
  const none = <T>(list: T[] | null, name: NoneList): T[] | null => list ?? (this.#none.has(name) ? [] : null);
312
352
  return {
313
353
  ...p,
314
- demographic: p.demographic && { ...p.demographic, benefits: none(p.demographic.benefits, "benefits") },
354
+ benefits: none(p.benefits, "benefits"),
315
355
  clinical: p.clinical && {
316
356
  ...p.clinical,
317
357
  medications: none(p.clinical.medications, "medications"),
@@ -1,19 +1,32 @@
1
- import { createNetworkClient, getOrder, getPatient, getPrescription, ping, type NetworkClient } from "../api/index.ts";
2
- import { linkAuthOf, refuseSecretInBrowser, signsIn, tokenSource, type LinkAuth, type PhotonAuth } from "./auth.ts";
1
+ import {
2
+ createNetworkClient,
3
+ getOrder,
4
+ getPatient,
5
+ getPrescription,
6
+ me,
7
+ ping,
8
+ type NetworkClient,
9
+ } from "../api/index.ts";
10
+ import { isMachine, linkAuthOf, refuseSecretInBrowser, signsIn, type LinkAuth, type PhotonAuth } from "./auth.ts";
11
+ import { machineCredentials, type MachineCredentials } from "./machine.ts";
3
12
  import { sessionFor, type Session } from "./session.ts";
4
13
  import type { Context } from "./context.ts";
14
+ import { analyticsFor, type Analytics, type AnalyticsTarget } from "../analytics/track.ts";
5
15
  import { environmentUrls, type EnvironmentUrls, type PhotonEnvironment } from "./environments.ts";
6
16
  import { linkPath, parseLinkPath, type FlowLink } from "./links.ts";
7
17
  import { guarded, PhotonError, refuse } from "./errors.ts";
8
18
  import { noChanges, toChanges, toPatient, toPrescription } from "./map.ts";
9
19
  import { adoptOrder, Order } from "./order.ts";
10
20
  import { Patient } from "./patient.ts";
21
+ import { readOrders } from "./orders.ts";
11
22
  import { Prescription } from "./prescription.ts";
12
23
  import type {
13
24
  Changes,
14
25
  OrderCandidate,
15
26
  OrderInput,
16
27
  OrderRecord,
28
+ OrdersInput,
29
+ OrdersResult,
17
30
  PatientCandidate,
18
31
  PatientInput,
19
32
  PatientRecord,
@@ -84,6 +97,11 @@ export interface PhotonOptions {
84
97
  * `organizationId`.
85
98
  */
86
99
  organization?: string;
100
+ /**
101
+ * Turns analytics off: `ph.analytics` is null and nothing is sent. Analytics is on by default — prescribing events
102
+ * go to Photon's analytics-api with the prescriber's token (never for M2M, never PHI).
103
+ */
104
+ disableAnalytics?: boolean;
87
105
  }
88
106
 
89
107
  /** Link to a flow: a live object (its record), or what a flow is given. `.parse(href)` reads a link back. */
@@ -124,6 +142,12 @@ export interface Photon {
124
142
  /** The environment's URLs, when created from one. */
125
143
  readonly environment: EnvironmentUrls | null;
126
144
 
145
+ /**
146
+ * Photon's analytics, as the signed-in prescriber: `ph.analytics.track(event, properties)`. Null for M2M, without
147
+ * an `environment`, or with `disableAnalytics`.
148
+ */
149
+ readonly analytics: Analytics | null;
150
+
127
151
  /**
128
152
  * Patients. `sync({ demographic })` finds the patient, lists candidates, says what's missing, or creates one
129
153
  * when nothing matches and it has enough. `ph.patient()`: a new patient to `sync` as the prescriber types.
@@ -142,6 +166,9 @@ export interface Photon {
142
166
  */
143
167
  readonly order: Calls<Order, OrderInput, Omit<OrderInput, "id" | "patient">, OrderResult>;
144
168
 
169
+ /** Read-only order snapshots and optional pharmacy choices. No live objects are opened or updated. */
170
+ orders(input?: OrdersInput): Promise<OrdersResult>;
171
+
145
172
  /**
146
173
  * network-api's health check: resolves once it's reachable and accepts this instance's token. Throws
147
174
  * `PhotonError` — `unauthorized` (a token it won't take), `network` (unreachable, or `getToken` threw),
@@ -149,6 +176,8 @@ export interface Photon {
149
176
  */
150
177
  ping(): Promise<void>;
151
178
 
179
+ me(): Promise<Caller>;
180
+
152
181
  /**
153
182
  * The prescriber's sign-in, when core runs it (`auth: { clientId }`): a live object — `status`, `user`,
154
183
  * `start()`, `signIn()`. Null when the host signs in (`auth: { getToken }`).
@@ -170,6 +199,32 @@ export interface Photon {
170
199
  readonly frame: LinkTo;
171
200
  }
172
201
 
202
+ export interface CallerName {
203
+ first: string | null;
204
+ last: string | null;
205
+ }
206
+
207
+ export interface CallerOrganization {
208
+ id: string;
209
+ name: string;
210
+ }
211
+
212
+ export type Caller =
213
+ | {
214
+ type: "user";
215
+ id: string;
216
+ name: CallerName;
217
+ organization: CallerOrganization | null;
218
+ permissions: string[];
219
+ }
220
+ | { type: "patient"; id: string; name: CallerName }
221
+ | { type: "machine"; organization: CallerOrganization | null; permissions: string[] };
222
+
223
+ const callerOrganization = (
224
+ organization: { __typename: "Organization"; id: string; name: string } | { __typename: "OperationError" },
225
+ ): CallerOrganization | null =>
226
+ organization.__typename === "Organization" ? { id: organization.id, name: organization.name } : null;
227
+
173
228
  /** The client a photon instance calls through — internal. */
174
229
  const clients = new WeakMap<Photon, NetworkClient>();
175
230
  export const clientOf = (ph: Photon): NetworkClient => {
@@ -194,18 +249,60 @@ export function photon(options: PhotonOptions): Photon {
194
249
  clientId: auth.clientId,
195
250
  });
196
251
  }
252
+ // A client secret: the backend's own token, by client credentials (machine.ts).
253
+ let machine: MachineCredentials | null = null;
254
+ if (isMachine(auth)) {
255
+ if (!environment)
256
+ throw new PhotonError("invalid", "Client credentials need an `environment`: it names the Auth0 tenant.");
257
+ if (!auth.organizationId)
258
+ throw new PhotonError("invalid", "Client credentials need the `organizationId` (org_…) they're for.");
259
+ machine = machineCredentials({
260
+ domain: environment.auth0Domain,
261
+ audience: environment.auth0Audience,
262
+ clientId: auth.clientId,
263
+ clientSecret: auth.clientSecret,
264
+ organizationId: auth.organizationId,
265
+ fetch: options.fetch,
266
+ });
267
+ }
197
268
  const signedIn = session;
269
+ const owned = machine;
270
+ const getToken = signedIn
271
+ ? () => signedIn.token()
272
+ : owned
273
+ ? () => owned.token()
274
+ : "getToken" in auth
275
+ ? auth.getToken
276
+ : null;
277
+ if (!getToken)
278
+ throw new PhotonError("invalid", "photon() needs `auth`: { clientId }, { getToken } or client credentials.");
198
279
  return photonOver(
199
280
  createNetworkClient({
200
281
  url,
201
- getToken: signedIn ? () => signedIn.token() : tokenSource(auth),
282
+ getToken,
283
+ // A refused machine token is dropped and the call tried once more with a new one.
284
+ onUnauthorized: owned ? () => owned.forget() : undefined,
202
285
  source: options.source,
203
286
  clientName: options.clientName,
204
287
  sourceVersion: options.sourceVersion,
205
288
  fetch: options.fetch,
206
289
  }),
207
290
  environment,
208
- { appUrl: options.appUrl ?? environment?.appUrl, session, linkAuth: linkAuthOf(auth, options.organization) },
291
+ {
292
+ appUrl: options.appUrl ?? environment?.appUrl,
293
+ session,
294
+ linkAuth: linkAuthOf(auth, options.organization),
295
+ analytics:
296
+ environment && !owned && !options.disableAnalytics
297
+ ? {
298
+ url: environment.analyticsApiUrl,
299
+ token: getToken,
300
+ clientName: options.clientName ?? null,
301
+ // The MCP's events say so on every one; React's cards set their own.
302
+ integration: options.source === "MCP_CONNECTOR" ? "mcp" : null,
303
+ }
304
+ : null,
305
+ },
209
306
  );
210
307
  }
211
308
 
@@ -213,7 +310,7 @@ export function photon(options: PhotonOptions): Photon {
213
310
  export function photonOver(
214
311
  client: NetworkClient,
215
312
  environment: EnvironmentUrls | null = null,
216
- options: { appUrl?: string; session?: Session | null; linkAuth?: LinkAuth } = {},
313
+ options: { appUrl?: string; session?: Session | null; linkAuth?: LinkAuth; analytics?: AnalyticsTarget | null } = {},
217
314
  ): Photon {
218
315
  const held = {
219
316
  patients: new Map<string, Patient>(),
@@ -402,7 +499,8 @@ export function photonOver(
402
499
  }
403
500
  if (input.clinical)
404
501
  throw new PhotonError("invalid", "Clinical changes need the patient's id: sync their demographics first.");
405
- if (!input.demographic) throw new PhotonError("invalid", "Send the patient's id, or what you know of them.");
502
+ if (!input.demographic && !input.contact)
503
+ throw new PhotonError("invalid", "Send the patient's id, or what you know of them.");
406
504
  const patient = new Patient(ctx, null);
407
505
  const { changes } = await patient.sync(fields);
408
506
  return { patient: theHeld(held.patients, patient), candidates: [...patient.snapshot.candidates], changes };
@@ -502,8 +600,43 @@ export function photonOver(
502
600
  updatePrescription,
503
601
  ),
504
602
  order: calls("order", () => new Order(ctx, null), openOrder, syncOrder, updateOrder),
603
+ orders: (input) => readOrders(client, input),
505
604
  ping: async () => void (await guarded(() => ping(client))),
605
+ me: async (): Promise<Caller> => {
606
+ const caller = await guarded(() => me(client));
607
+ switch (caller.__typename) {
608
+ case "User":
609
+ return {
610
+ type: "user",
611
+ id: caller.id,
612
+ name: { first: caller.name.first ?? null, last: caller.name.last ?? null },
613
+ organization: callerOrganization(caller.organization),
614
+ permissions: caller.permissions,
615
+ };
616
+ case "Patient":
617
+ return {
618
+ type: "patient",
619
+ id: caller.id,
620
+ name: { first: caller.name.first ?? null, last: caller.name.last ?? null },
621
+ };
622
+ case "Machine":
623
+ return {
624
+ type: "machine",
625
+ organization: callerOrganization(caller.organization),
626
+ permissions: caller.permissions,
627
+ };
628
+ }
629
+ },
506
630
  session: options.session ?? null,
631
+ analytics: options.analytics
632
+ ? analyticsFor(options.analytics, {
633
+ environment,
634
+ providerId: async () => {
635
+ const caller = await ph.me();
636
+ return caller.type === "user" ? caller.id : null;
637
+ },
638
+ })
639
+ : null,
507
640
  url,
508
641
  frame,
509
642
  };