@photonhealth/client 0.0.0-stage → 2.0.0-rc.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 (218) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +234 -2
  3. package/dist/analytics/lifecycleEvents.d.ts +29 -0
  4. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  5. package/dist/analytics/lifecycleEvents.js +72 -0
  6. package/dist/analytics/lifecycleEvents.js.map +1 -0
  7. package/dist/api/changes/applyOption.d.ts +41 -0
  8. package/dist/api/changes/applyOption.d.ts.map +1 -0
  9. package/dist/api/changes/applyOption.js +76 -0
  10. package/dist/api/changes/applyOption.js.map +1 -0
  11. package/dist/api/changes/classifyChanges.d.ts +9 -0
  12. package/dist/api/changes/classifyChanges.d.ts.map +1 -0
  13. package/dist/api/changes/classifyChanges.js +2 -0
  14. package/dist/api/changes/classifyChanges.js.map +1 -0
  15. package/dist/api/changes/index.d.ts +3 -0
  16. package/dist/api/changes/index.d.ts.map +1 -0
  17. package/dist/api/changes/index.js +3 -0
  18. package/dist/api/changes/index.js.map +1 -0
  19. package/dist/api/client.d.ts +48 -0
  20. package/dist/api/client.d.ts.map +1 -0
  21. package/dist/api/client.js +91 -0
  22. package/dist/api/client.js.map +1 -0
  23. package/dist/api/health.d.ts +4 -0
  24. package/dist/api/health.d.ts.map +1 -0
  25. package/dist/api/health.js +6 -0
  26. package/dist/api/health.js.map +1 -0
  27. package/dist/api/index.d.ts +24 -0
  28. package/dist/api/index.d.ts.map +1 -0
  29. package/dist/api/index.js +23 -0
  30. package/dist/api/index.js.map +1 -0
  31. package/dist/api/me.d.ts +37 -0
  32. package/dist/api/me.d.ts.map +1 -0
  33. package/dist/api/me.js +6 -0
  34. package/dist/api/me.js.map +1 -0
  35. package/dist/api/order.d.ts +33 -0
  36. package/dist/api/order.d.ts.map +1 -0
  37. package/dist/api/order.js +33 -0
  38. package/dist/api/order.js.map +1 -0
  39. package/dist/api/orders.d.ts +1047 -0
  40. package/dist/api/orders.d.ts.map +1 -0
  41. package/dist/api/orders.js +7 -0
  42. package/dist/api/orders.js.map +1 -0
  43. package/dist/api/patient.d.ts +36 -0
  44. package/dist/api/patient.d.ts.map +1 -0
  45. package/dist/api/patient.js +33 -0
  46. package/dist/api/patient.js.map +1 -0
  47. package/dist/api/prescription.d.ts +37 -0
  48. package/dist/api/prescription.d.ts.map +1 -0
  49. package/dist/api/prescription.js +39 -0
  50. package/dist/api/prescription.js.map +1 -0
  51. package/dist/api/results.d.ts +30 -0
  52. package/dist/api/results.d.ts.map +1 -0
  53. package/dist/api/results.js +26 -0
  54. package/dist/api/results.js.map +1 -0
  55. package/dist/gql/gql.d.ts +29 -0
  56. package/dist/gql/gql.d.ts.map +1 -0
  57. package/dist/gql/gql.js +15 -0
  58. package/dist/gql/gql.js.map +1 -0
  59. package/dist/gql/graphql.d.ts +18618 -0
  60. package/dist/gql/graphql.d.ts.map +1 -0
  61. package/dist/gql/graphql.js +6579 -0
  62. package/dist/gql/graphql.js.map +1 -0
  63. package/dist/gql/index.d.ts +2 -0
  64. package/dist/gql/index.d.ts.map +1 -0
  65. package/dist/gql/index.js +3 -0
  66. package/dist/gql/index.js.map +1 -0
  67. package/dist/index.d.ts +15 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +15 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/meta/version.d.ts +2 -0
  72. package/dist/meta/version.d.ts.map +1 -0
  73. package/dist/meta/version.js +2 -0
  74. package/dist/meta/version.js.map +1 -0
  75. package/dist/photon/analytics.d.ts +39 -0
  76. package/dist/photon/analytics.d.ts.map +1 -0
  77. package/dist/photon/analytics.js +91 -0
  78. package/dist/photon/analytics.js.map +1 -0
  79. package/dist/photon/auth.d.ts +52 -0
  80. package/dist/photon/auth.d.ts.map +1 -0
  81. package/dist/photon/auth.js +30 -0
  82. package/dist/photon/auth.js.map +1 -0
  83. package/dist/photon/choices.d.ts +44 -0
  84. package/dist/photon/choices.d.ts.map +1 -0
  85. package/dist/photon/choices.js +58 -0
  86. package/dist/photon/choices.js.map +1 -0
  87. package/dist/photon/context.d.ts +29 -0
  88. package/dist/photon/context.d.ts.map +1 -0
  89. package/dist/photon/context.js +2 -0
  90. package/dist/photon/context.js.map +1 -0
  91. package/dist/photon/environments.d.ts +27 -0
  92. package/dist/photon/environments.d.ts.map +1 -0
  93. package/dist/photon/environments.js +27 -0
  94. package/dist/photon/environments.js.map +1 -0
  95. package/dist/photon/errors.d.ts +26 -0
  96. package/dist/photon/errors.d.ts.map +1 -0
  97. package/dist/photon/errors.js +42 -0
  98. package/dist/photon/errors.js.map +1 -0
  99. package/dist/photon/index.d.ts +26 -0
  100. package/dist/photon/index.d.ts.map +1 -0
  101. package/dist/photon/index.js +12 -0
  102. package/dist/photon/index.js.map +1 -0
  103. package/dist/photon/inputs.d.ts +7 -0
  104. package/dist/photon/inputs.d.ts.map +1 -0
  105. package/dist/photon/inputs.js +25 -0
  106. package/dist/photon/inputs.js.map +1 -0
  107. package/dist/photon/links.d.ts +68 -0
  108. package/dist/photon/links.d.ts.map +1 -0
  109. package/dist/photon/links.js +187 -0
  110. package/dist/photon/links.js.map +1 -0
  111. package/dist/photon/live.d.ts +62 -0
  112. package/dist/photon/live.d.ts.map +1 -0
  113. package/dist/photon/live.js +107 -0
  114. package/dist/photon/live.js.map +1 -0
  115. package/dist/photon/machine.d.ts +28 -0
  116. package/dist/photon/machine.d.ts.map +1 -0
  117. package/dist/photon/machine.js +53 -0
  118. package/dist/photon/machine.js.map +1 -0
  119. package/dist/photon/map.d.ts +14 -0
  120. package/dist/photon/map.d.ts.map +1 -0
  121. package/dist/photon/map.js +311 -0
  122. package/dist/photon/map.js.map +1 -0
  123. package/dist/photon/order.d.ts +168 -0
  124. package/dist/photon/order.d.ts.map +1 -0
  125. package/dist/photon/order.js +558 -0
  126. package/dist/photon/order.js.map +1 -0
  127. package/dist/photon/orders.d.ts +5 -0
  128. package/dist/photon/orders.d.ts.map +1 -0
  129. package/dist/photon/orders.js +39 -0
  130. package/dist/photon/orders.js.map +1 -0
  131. package/dist/photon/patient.d.ts +80 -0
  132. package/dist/photon/patient.d.ts.map +1 -0
  133. package/dist/photon/patient.js +347 -0
  134. package/dist/photon/patient.js.map +1 -0
  135. package/dist/photon/photon.d.ts +188 -0
  136. package/dist/photon/photon.d.ts.map +1 -0
  137. package/dist/photon/photon.js +395 -0
  138. package/dist/photon/photon.js.map +1 -0
  139. package/dist/photon/prescription.d.ts +145 -0
  140. package/dist/photon/prescription.d.ts.map +1 -0
  141. package/dist/photon/prescription.js +418 -0
  142. package/dist/photon/prescription.js.map +1 -0
  143. package/dist/photon/session.d.ts +89 -0
  144. package/dist/photon/session.d.ts.map +1 -0
  145. package/dist/photon/session.js +352 -0
  146. package/dist/photon/session.js.map +1 -0
  147. package/dist/photon/types.d.ts +643 -0
  148. package/dist/photon/types.d.ts.map +1 -0
  149. package/dist/photon/types.js +7 -0
  150. package/dist/photon/types.js.map +1 -0
  151. package/dist/test-utils/msw.d.ts +23 -0
  152. package/dist/test-utils/msw.d.ts.map +1 -0
  153. package/dist/test-utils/msw.js +51 -0
  154. package/dist/test-utils/msw.js.map +1 -0
  155. package/dist/testing/fakeNetworkApiClient.d.ts +39 -0
  156. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  157. package/dist/testing/fakeNetworkApiClient.js +56 -0
  158. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  159. package/dist/testing/fixtures.d.ts +1098 -0
  160. package/dist/testing/fixtures.d.ts.map +1 -0
  161. package/dist/testing/fixtures.js +200 -0
  162. package/dist/testing/fixtures.js.map +1 -0
  163. package/dist/testing.d.ts +11 -0
  164. package/dist/testing.d.ts.map +1 -0
  165. package/dist/testing.js +10 -0
  166. package/dist/testing.js.map +1 -0
  167. package/package.json +67 -4
  168. package/src/analytics/lifecycleEvents.test.ts +417 -0
  169. package/src/analytics/lifecycleEvents.ts +155 -0
  170. package/src/api/changes/applyOption.ts +103 -0
  171. package/src/api/changes/classifyChanges.ts +10 -0
  172. package/src/api/changes/index.ts +2 -0
  173. package/src/api/client.ts +149 -0
  174. package/src/api/health.ts +7 -0
  175. package/src/api/index.ts +24 -0
  176. package/src/api/me.ts +7 -0
  177. package/src/api/order.ts +64 -0
  178. package/src/api/orders.ts +8 -0
  179. package/src/api/patient.ts +67 -0
  180. package/src/api/prescription.ts +86 -0
  181. package/src/api/results.ts +45 -0
  182. package/src/gql/gql.ts +68 -0
  183. package/src/gql/graphql.ts +9027 -0
  184. package/src/gql/index.ts +2 -0
  185. package/src/index.ts +14 -0
  186. package/src/meta/version.test.ts +10 -0
  187. package/src/meta/version.ts +1 -0
  188. package/src/operations/fragments.graphql +497 -0
  189. package/src/operations/health.graphql +4 -0
  190. package/src/operations/me.graphql +38 -0
  191. package/src/operations/order.graphql +42 -0
  192. package/src/operations/orders.graphql +35 -0
  193. package/src/operations/patient.graphql +62 -0
  194. package/src/operations/prescription.graphql +90 -0
  195. package/src/photon/analytics.ts +129 -0
  196. package/src/photon/auth.ts +69 -0
  197. package/src/photon/choices.ts +79 -0
  198. package/src/photon/context.ts +30 -0
  199. package/src/photon/environments.ts +49 -0
  200. package/src/photon/errors.ts +56 -0
  201. package/src/photon/index.ts +49 -0
  202. package/src/photon/inputs.ts +24 -0
  203. package/src/photon/links.ts +197 -0
  204. package/src/photon/live.ts +135 -0
  205. package/src/photon/machine.ts +90 -0
  206. package/src/photon/map.ts +371 -0
  207. package/src/photon/order.test.ts +142 -0
  208. package/src/photon/order.ts +661 -0
  209. package/src/photon/orders.ts +42 -0
  210. package/src/photon/patient.ts +386 -0
  211. package/src/photon/photon.ts +646 -0
  212. package/src/photon/prescription.ts +506 -0
  213. package/src/photon/session.ts +454 -0
  214. package/src/photon/types.ts +583 -0
  215. package/src/test-utils/msw.ts +72 -0
  216. package/src/testing/fakeNetworkApiClient.ts +56 -0
  217. package/src/testing/fixtures.ts +233 -0
  218. package/src/testing.ts +25 -0
@@ -0,0 +1,418 @@
1
+ import { getPrescription, getPrescriptionTemplates, syncPrescription, updatePrescription, } from "../api/index.js";
2
+ import { classify, declaredChoice, optionKey, withChoice } from "./choices.js";
3
+ import { PhotonError, refuse } from "./errors.js";
4
+ import { filled } from "./inputs.js";
5
+ import { LiveRecord } from "./live.js";
6
+ import { noChanges, toChanges, toPrescription, toPrescriptionTemplate } from "./map.js";
7
+ /** GetPrescription's copy — what was stored — or the given one if the read fails. */
8
+ async function storedCopy(client, rx) {
9
+ try {
10
+ const read = await getPrescription(client, rx.id);
11
+ return (read.kind === "ok" && read.prescription) || rx;
12
+ }
13
+ catch {
14
+ return rx;
15
+ }
16
+ }
17
+ const merged = (a, b) => ({
18
+ ...a,
19
+ ...b,
20
+ // Dispense arrives a field at a time: keep them all, so the create carries every one.
21
+ ...(a.dispense || b.dispense ? { dispense: { ...a.dispense, ...b.dispense } } : {}),
22
+ });
23
+ /**
24
+ * One prescription line — before its record exists and after. `sync(input)` sends what's known; the object
25
+ * decides what it means:
26
+ *
27
+ * - No record, drug not yet clear: look the drug up (SyncPrescription without a patient, so nothing can be
28
+ * created); the choices land in `changes`. Other fields wait here and go with the create.
29
+ * - A drug picked (`choose`), or declared by the server, and a patient known: create it (SyncPrescription
30
+ * with everything entered) — `id` fills in. Without a patient yet, the pick waits for `sync({ patient })`.
31
+ * - A record: the fields given are synced to it, then the stored copy is read back (its contentHash is what
32
+ * a signature must match).
33
+ *
34
+ * `update(edits)` changes the prescription by its id (UpdatePrescription). A signed prescription is final: a
35
+ * change is a new prescription.
36
+ */
37
+ export class Prescription extends LiveRecord {
38
+ #ctx;
39
+ #patientId;
40
+ #templateId;
41
+ #isTaken;
42
+ /** Everything entered on this line — what's sent at create, and what a choice's path applies to. */
43
+ #entered = {};
44
+ #declared = new Set();
45
+ /** The drug lookup for the latest text: newer text aborts it (in flight, or still waiting its turn). */
46
+ #lookup = null;
47
+ constructor(ctx, record, options = {}) {
48
+ super(record, { pick: null, drafts: null, templates: null }, options.changes);
49
+ this.#ctx = ctx;
50
+ this.#patientId = options.patientId ?? record?.patient?.id ?? null;
51
+ this.#templateId = options.templateId ?? null;
52
+ this.#isTaken = options.isTaken ?? (() => false);
53
+ this.#missing = options.missing ?? null;
54
+ }
55
+ #missing;
56
+ /**
57
+ * The prescription this line was given by id that the server doesn't have (e.g. an order link's `rx=` from
58
+ * another organization): the line stands in for it, empty, to fill in instead. null otherwise.
59
+ */
60
+ get missing() {
61
+ return this.#missing;
62
+ }
63
+ onRecord() {
64
+ this.#ctx.register(this);
65
+ }
66
+ /** Whether anything asked for templates (`loadTemplates()`); until then, saves never trigger the lookup. */
67
+ #templatesWanted = false;
68
+ /** The record, drug and patient the current `templates` are for: a change to any of them fetches again. */
69
+ #templatesFor = null;
70
+ /**
71
+ * Fetch this draft's templates into `templates`, and refetch whenever its drug or patient changes. Separate from
72
+ * every other call so saves don't wait on the Medi-Span sig lookup. A failed lookup leaves `templates` null.
73
+ */
74
+ loadTemplates() {
75
+ this.#templatesWanted = true;
76
+ this.#refreshTemplates();
77
+ }
78
+ patch(patch) {
79
+ super.patch(patch);
80
+ if (this.#templatesWanted)
81
+ this.#refreshTemplates();
82
+ }
83
+ #refreshTemplates() {
84
+ const rx = this.state;
85
+ const templatesFor = rx?.patient && !this.signed ? `${rx.id}:${rx.treatment.id}:${rx.patient.id}` : null;
86
+ if (templatesFor === this.#templatesFor)
87
+ return;
88
+ this.#templatesFor = templatesFor;
89
+ super.patch({ templates: null });
90
+ if (!rx || !templatesFor)
91
+ return;
92
+ getPrescriptionTemplates(this.#ctx.client, rx.id).then((templates) => {
93
+ if (this.#templatesFor === templatesFor) {
94
+ super.patch({ templates: templates && templates.map(toPrescriptionTemplate) });
95
+ }
96
+ }, () => { });
97
+ }
98
+ get signed() {
99
+ return this.state?.signing.state === "SIGNED";
100
+ }
101
+ /**
102
+ * The drug's name as the prescriber saw it (the pick), while that pick is the record's drug; else the server's
103
+ * product name (`prescribableName` — its `name` can be just the drug). Never an id: a drug given by id alone (e.g.
104
+ * from a link) has no name until network-api gives one — once it's drafted for a patient.
105
+ */
106
+ get name() {
107
+ const pick = this.snapshot.pick;
108
+ const named = pick && pick.name !== pick.id;
109
+ if (pick && !this.state)
110
+ return named ? pick.name : null;
111
+ if (pick && named && this.state.treatment.id === pick.id)
112
+ return pick.name;
113
+ const treatment = this.state?.treatment;
114
+ return treatment ? (treatment.prescribableName ?? treatment.name) : null;
115
+ }
116
+ /**
117
+ * The drug in parts (drug, form, route, strength) — the picked option's, while that pick is the record's drug
118
+ * (a lookup's option also says its DEA schedule); else the record's. null before either.
119
+ */
120
+ get treatment() {
121
+ const picked = this.snapshot.pick?.treatment;
122
+ if (picked && (!this.state || this.state.treatment.id === picked.id))
123
+ return picked;
124
+ return this.state?.treatment ?? null;
125
+ }
126
+ get patientId() {
127
+ return this.#patientId;
128
+ }
129
+ /**
130
+ * Everything entered on this line — what a create sends, and (before the record) what's known of it: the drug's
131
+ * text or id, the sig, the dispense. A form starts from it.
132
+ */
133
+ get entered() {
134
+ return this.#entered;
135
+ }
136
+ /** The template it was started from: the record's, or the one it was made with before it has a record. */
137
+ get templateId() {
138
+ return this.state?.templateId ?? this.#templateId;
139
+ }
140
+ /** SyncPrescription: what's known — see the class. */
141
+ sync(input) {
142
+ return this.#send("sync", input);
143
+ }
144
+ /** UpdatePrescription: change only the fields given, then read the stored copy. Needs its id. */
145
+ update(edits) {
146
+ if (!this.id)
147
+ return Promise.reject(new PhotonError("invalid", "update() needs the prescription's id; until it has one, sync()."));
148
+ return this.#send("update", edits);
149
+ }
150
+ #send(kind, input) {
151
+ const { patient, ...given } = input;
152
+ // Before the record, an empty field is "not known yet" (a lookup or a create sends only what's known).
153
+ const edits = this.id ? given : filled(given);
154
+ if (patient !== undefined) {
155
+ const patientId = patient?.id ?? null;
156
+ if (!this.id)
157
+ this.#patientId = patientId;
158
+ else if (patientId && patientId !== this.#patientId)
159
+ return Promise.reject(refuse("This prescription's patient is fixed: for another patient, start a new one."));
160
+ }
161
+ // Nothing to send: no field changed, and (before the record) no picked drug to create for a known patient.
162
+ const canCreate = !this.id && Boolean(this.#patientId && (this.snapshot.pick || this.#templateId));
163
+ if (!Object.keys(edits).length && !canCreate)
164
+ return Promise.resolve({ changes: this.changes });
165
+ if (this.signed)
166
+ return Promise.reject(refuse("This prescription is signed, so it's final. A change is a new prescription."));
167
+ this.#entered = merged(this.#entered, edits);
168
+ // New free text for the drug drops a previous pick, and the lookup for the text before it.
169
+ let lookup = null;
170
+ if (edits.treatment?.name && !edits.treatment.id && !this.id) {
171
+ this.patch({ pick: null });
172
+ this.#lookup?.abort();
173
+ lookup = this.#lookup = new AbortController();
174
+ }
175
+ return this.run("saving", async () => {
176
+ if (lookup?.signal.aborted)
177
+ return { changes: this.changes }; // newer text came first: it looks up instead
178
+ if (this.signed)
179
+ throw refuse("This prescription is signed, so it's final. A change is a new prescription.");
180
+ if (!this.id)
181
+ return this.#beforeRecord(edits, lookup?.signal);
182
+ if (!Object.keys(edits).length)
183
+ return { changes: this.changes }; // queued to create, created by its turn
184
+ const outcome = kind === "sync"
185
+ ? await syncPrescription(this.#ctx.client, { id: this.id, ...edits })
186
+ : await updatePrescription(this.#ctx.client, this.id, edits);
187
+ return this.#settleStored(outcome);
188
+ }).then((result) => this.#takeDeclared(result));
189
+ }
190
+ /**
191
+ * A choice the server asked for. Which drug, before the record: that's the pick (created now if the patient is
192
+ * known). Anything else: sent again with the pick applied to what was entered.
193
+ */
194
+ choose(option) {
195
+ const path = option.path;
196
+ const isDrug = Boolean(path?.startsWith("treatment"));
197
+ const id = isDrug ? option.id : null;
198
+ if (id) {
199
+ const pick = { id, name: option.displayName || id, treatment: option.treatment };
200
+ // The pick is made: close the drug's choices now, not when the server answers.
201
+ const changes = {
202
+ ...this.changes,
203
+ unapplied: this.changes.unapplied.filter((c) => !c.key.startsWith("treatment")),
204
+ };
205
+ this.patch({ pick, changes });
206
+ this.#entered = { ...this.#entered, treatment: { id } };
207
+ if (!this.id)
208
+ return this.sync({});
209
+ return this.update({ treatment: { id } });
210
+ }
211
+ const next = withChoice(this.#entered, option);
212
+ const root = (path ?? "").split(".")[0];
213
+ const edits = root && root in next ? { [root]: next[root] } : next;
214
+ return this.id ? this.update(edits) : this.sync(edits);
215
+ }
216
+ /** One of `drafts`: this line continues it, with what was entered here applied to it. */
217
+ continueDraft(prescriptionId) {
218
+ const draft = this.snapshot.drafts?.find((d) => d.id === prescriptionId);
219
+ if (!draft)
220
+ return Promise.resolve({ changes: this.changes });
221
+ this.patch({ state: draft, drafts: null });
222
+ const { treatment, instructions, dispense, clinical } = this.#entered;
223
+ const edits = Object.fromEntries(Object.entries({ treatment, instructions, dispense, clinical }).filter(([, v]) => v !== undefined));
224
+ return Object.keys(edits).length ? this.update(edits) : Promise.resolve({ changes: this.changes });
225
+ }
226
+ /**
227
+ * The prescriber's approval. Waits for updates already sent, then signs what was stored — bound to its
228
+ * contentHash. Screening alerts don't stop it: signing is the prescriber's acknowledgement of
229
+ * what screening showed (network-api has no way to acknowledge an alert yet). Refused if
230
+ * the server's last answer left something open (a choice to make, a rejected field), or if an update in
231
+ * flight changed the screening result the prescriber saw (they review it first). A prescription marked changed-since-signing (INVALIDATED_SIGN) can be signed
232
+ * again: that's the prescriber approving what it says now. Sends only the signing, never content.
233
+ */
234
+ sign(message) {
235
+ const seen = this.state;
236
+ // Before its record, refused on the object (`error`), as a failed save is: a drug picked waits for its patient.
237
+ if (!seen)
238
+ return this.run("saving", async () => {
239
+ throw refuse(this.snapshot.pick && !this.#patientId
240
+ ? "A patient is required for signing"
241
+ : "There's nothing to sign yet: pick the drug first.");
242
+ });
243
+ return this.run("saving", async () => {
244
+ const current = this.state;
245
+ if (current.signing.state === "SIGNED")
246
+ return { changes: noChanges };
247
+ if (!classify(this.changes).settled)
248
+ throw refuse("The server left something open on this prescription (see `changes`). Resolve it, then sign.");
249
+ if (screening(current) !== screening(seen))
250
+ throw refuse("Screening changed since this was reviewed. Review it, then sign.");
251
+ // Only the signing, with the hash of what was stored and reviewed — never a hash fetched after the fact.
252
+ const result = this.#settle(await updatePrescription(this.#ctx.client, current.id, {
253
+ signing: { signedHash: current.signing.contentHash, message },
254
+ }));
255
+ if (!this.signed)
256
+ throw refuse("This changed since it was reviewed. Review it, then sign.");
257
+ return result;
258
+ });
259
+ }
260
+ /**
261
+ * The Photon Rx app's link to this record's flow (`/<flow>/<id>`); before the record, to a new one from the ids it
262
+ * hangs off (its patient, and its template or drug). `ph.url(this)`.
263
+ */
264
+ url() {
265
+ return this.#ctx.url(this);
266
+ }
267
+ /** The same, embeddable in an iframe; `ph.frame(this)`. */
268
+ frame() {
269
+ return this.#ctx.frame(this);
270
+ }
271
+ /** Read it again. */
272
+ reload() {
273
+ if (!this.id)
274
+ return Promise.resolve({ changes: this.changes });
275
+ return this.run("loading", async () => this.#settle(await getPrescription(this.#ctx.client, this.id)));
276
+ }
277
+ /** No record yet: look the drug up until it's clear, then create once the patient is known. */
278
+ async #beforeRecord(edits, signal) {
279
+ const pick = this.snapshot.pick;
280
+ const resolved = Boolean(pick || this.#entered.treatment?.id || this.#templateId);
281
+ if (!resolved) {
282
+ if (!edits.treatment || !this.#entered.treatment)
283
+ return { changes: this.changes };
284
+ const found = await this.#lookUp(this.#entered.treatment, signal);
285
+ if (!found)
286
+ return { changes: this.changes };
287
+ const changes = toChanges(found);
288
+ this.settle(null, changes);
289
+ // The server declared what the name is (it resolved it to a record): that's the pick. Without that,
290
+ // the prescriber picks — even when no choice came back.
291
+ const declared = changes.applied.find((c) => c.key === "treatment" && c.resolvedId);
292
+ if (!declared)
293
+ return { changes };
294
+ this.patch({
295
+ pick: { id: declared.resolvedId, name: this.#entered.treatment.name ?? declared.resolvedId, treatment: null },
296
+ });
297
+ if (!this.#patientId)
298
+ return { changes };
299
+ }
300
+ if (!this.#patientId) {
301
+ // A drug given by id, no patient yet: it's the line's drug — the pick, waiting for the patient. The lookup
302
+ // checks the id; network-api doesn't name it until there's a draft, so the name is the
303
+ // one given with it, or the id.
304
+ const given = this.#entered.treatment;
305
+ if (!pick && given?.id) {
306
+ const changes = toChanges(await this.#lookUp(given));
307
+ this.settle(null, changes);
308
+ const accepted = changes.applied.some((c) => c.key === "treatment");
309
+ if (accepted)
310
+ this.patch({ pick: { id: given.id, name: given.name ?? given.id, treatment: null } });
311
+ return { changes };
312
+ }
313
+ return { changes: this.changes };
314
+ }
315
+ return this.#create();
316
+ }
317
+ /**
318
+ * SyncPrescription without a patient: a drug lookup — it can never create anything. network-api also rejects
319
+ * the patient and every field it would have filled ("treatment.instructions", … — blocked by the missing
320
+ * patient); only the drug's own change answers it: its choices, or why nothing matched. (A template isn't looked
321
+ * up: network-api doesn't expand one without a patient.) null when newer text aborted it.
322
+ */
323
+ async #lookUp(treatment, signal) {
324
+ let outcome;
325
+ try {
326
+ outcome = await syncPrescription(this.#ctx.client, { treatment, templateId: this.#templateId }, signal);
327
+ }
328
+ catch (e) {
329
+ if (signal?.aborted)
330
+ return null;
331
+ throw e;
332
+ }
333
+ if (signal?.aborted)
334
+ return null;
335
+ if (outcome.kind !== "ok")
336
+ return { changes: [] };
337
+ return {
338
+ ...outcome.changes,
339
+ changes: outcome.changes.changes.filter((c) => c.status === "APPLIED" || c.key === "treatment"),
340
+ };
341
+ }
342
+ async #create() {
343
+ const pick = this.snapshot.pick;
344
+ const entered = this.#entered;
345
+ const outcome = await syncPrescription(this.#ctx.client, {
346
+ patient: { id: this.#patientId },
347
+ templateId: this.#templateId,
348
+ ...entered,
349
+ treatment: pick ? { id: pick.id } : entered.treatment,
350
+ });
351
+ if (outcome.kind === "ambiguous")
352
+ return this.#offerDrafts(outcome.candidates.map((c) => c.id));
353
+ const changes = toChanges(outcome.changes);
354
+ // A new line only takes a record once its drug is clear, and never a signed one or another line's:
355
+ // while the drug is still ambiguous, network-api hands back the patient's latest prescription — an old
356
+ // draft, one already signed and sent, or another line's (boson, 2026-09-29).
357
+ const drugStillOpen = classify(changes).needsChoice.some((c) => c.key.startsWith("treatment"));
358
+ const rx = outcome.prescription;
359
+ if (!rx || drugStillOpen || !this.#canTake(rx)) {
360
+ this.settle(null, changes);
361
+ return { changes };
362
+ }
363
+ this.settle(toPrescription(await storedCopy(this.#ctx.client, rx)), changes);
364
+ return { changes };
365
+ }
366
+ #canTake(rx) {
367
+ return rx.signing.state === "UNSIGNED" && !this.#isTaken(rx.id);
368
+ }
369
+ /**
370
+ * The patient already has several in-progress prescriptions and the server asks which this continues.
371
+ * Candidates carry no drug or signing state, so read each; offer only unsigned drafts of the same drug that
372
+ * no other line holds. network-api counts signed (even sent) ones as in progress.
373
+ */
374
+ async #offerDrafts(ids) {
375
+ const read = await Promise.all(ids.map((id) => getPrescription(this.#ctx.client, id)));
376
+ const open = read.flatMap((o) => (o.kind === "ok" && o.prescription ? [toPrescription(o.prescription)] : []));
377
+ const wanted = this.snapshot.pick ? { id: this.snapshot.pick.id } : this.#entered.treatment;
378
+ const sameDrug = (rx) => wanted?.id != null
379
+ ? rx.treatment.id === String(wanted.id)
380
+ : Boolean(wanted?.name && rx.treatment.name.toLowerCase().startsWith(wanted.name.trim().toLowerCase()));
381
+ const drafts = open.filter((rx) => this.#canTake(rx) && sameDrug(rx));
382
+ if (drafts.length) {
383
+ this.patch({ drafts });
384
+ return { changes: this.changes };
385
+ }
386
+ const names = [...new Set(open.map((rx) => rx.treatment.name))].join(", ");
387
+ // network-api won't start another prescription while ≥2 are open.
388
+ throw refuse(open.every((rx) => rx.signing.state === "UNSIGNED")
389
+ ? `This patient has ${open.length} unsent prescriptions (${names}). A new one can't be started until they're sent.`
390
+ : `Photon still counts ${open.length} of this patient's earlier prescriptions (${names}) as open, so a new one can't be started.`);
391
+ }
392
+ /** A choice the server declared (one option, an exact match) is taken without asking — once each. */
393
+ #takeDeclared(result) {
394
+ const option = declaredChoice(this.changes);
395
+ const key = option && optionKey(option);
396
+ if (!option || !key || this.#declared.has(key))
397
+ return result;
398
+ this.#declared.add(key);
399
+ return this.choose(option);
400
+ }
401
+ #settle(outcome) {
402
+ const changes = outcome.kind === "ok" ? toChanges(outcome.changes) : noChanges;
403
+ this.settle(outcome.kind === "ok" && outcome.prescription ? toPrescription(outcome.prescription) : null, changes);
404
+ return { changes };
405
+ }
406
+ /** After a sync or update: the stored copy, not the mutation's echo — its contentHash is what a signature must match. */
407
+ async #settleStored(outcome) {
408
+ const changes = outcome.kind === "ok" ? toChanges(outcome.changes) : noChanges;
409
+ const stored = outcome.kind === "ok" && outcome.prescription
410
+ ? toPrescription(await storedCopy(this.#ctx.client, outcome.prescription))
411
+ : null;
412
+ this.settle(stored, changes);
413
+ return { changes };
414
+ }
415
+ }
416
+ /** What screening found, comparable: a sign is refused when it changed after the prescriber saw it. */
417
+ const screening = (rx) => JSON.stringify(rx.screeningAlerts);
418
+ //# sourceMappingURL=prescription.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prescription.js","sourceRoot":"","sources":["../../src/photon/prescription.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,gBAAgB,EAChB,kBAAkB,GAInB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAwDxF,qFAAqF;AACrF,KAAK,UAAU,UAAU,CAAC,MAAqB,EAAE,EAA8B;IAC7E,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,eAAe,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;QAClD,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IA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OAA4B;QAC9C,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/E,MAAM,MAAM,GACV,OAAO,CAAC,IAAI,KAAK,IAAI,IAAI,OAAO,CAAC,YAAY;YAC3C,CAAC,CAAC,cAAc,CAAC,MAAM,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1E,CAAC,CAAC,IAAI,CAAC;QACX,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7B,OAAO,EAAE,OAAO,EAAE,CAAC;IACrB,CAAC;CACF;AAED,uGAAuG;AACvG,MAAM,SAAS,GAAG,CAAC,EAAsB,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC"}
@@ -0,0 +1,89 @@
1
+ import { PhotonError } from "./errors.ts";
2
+ /**
3
+ * The prescriber's sign-in, run by core in the browser: OAuth 2 authorization code with PKCE against the
4
+ * environment's Auth0 tenant — no SDK, no dependency (the browser's own crypto, fetch and storage).
5
+ *
6
+ * start() once, on load: finishes a sign-in coming back from Auth0 (only one this session started — a host's
7
+ * own `?code` is left alone), else renews a stored session, else signed out. Never redirects.
8
+ * signIn() from a click: redirects to Auth0 (its organization picker, or straight into `?organization=`).
9
+ * Inside an iframe, where Auth0's page won't load, it's a popup. `signInUrl()`: that page, to go to.
10
+ * signOut() forgets the session and ends Auth0's (`signOutUrl()`). The cards never offer it; an app may.
11
+ * token() the access token, renewed shortly before it expires — one renewal at a time.
12
+ *
13
+ * One session per Auth0 tenant and client per page (`sessionFor`): providers anywhere in the tree share it, and
14
+ * the code from a redirect is exchanged once. A live object: `subscribe` + `snapshot`.
15
+ *
16
+ * Where it's kept: the access token only in this page's memory. Across page loads, `localStorage` keeps the
17
+ * refresh token and who it's for — never the access token — so each load starts with a refresh. Auth0 rotates
18
+ * refresh tokens with reuse detection: a stolen one is revoked, with the whole chain, the first time either side
19
+ * uses a token the other already has. So the tabs of a site take turns (Web Locks) and each uses the newest one
20
+ * stored. No refresh token from Auth0: nothing is kept, and the session lasts as long as the page.
21
+ *
22
+ * Known risks: a script on the page can still read the refresh token (the posture chosen, Auth0's own for SPAs);
23
+ * a session ending mid-work swaps the cards for Sign in.
24
+ */
25
+ export type SessionStatus = "starting" | "signed-out" | "signing-in" | "signed-in" | "error";
26
+ export interface SessionUser {
27
+ name: string | null;
28
+ email: string | null;
29
+ /** The Photon organization the token is scoped to (`org_id`); null if the sign-in didn't pick one. */
30
+ organization: string | null;
31
+ }
32
+ export interface SessionSnapshot {
33
+ readonly status: SessionStatus;
34
+ readonly user: SessionUser | null;
35
+ readonly error: PhotonError | null;
36
+ }
37
+ /** Where `signIn` goes at Auth0. */
38
+ export interface SignInOptions {
39
+ /** The Photon organization to sign in to, past Auth0's picker. */
40
+ organization?: string;
41
+ /** An Auth0 connection (e.g. `"google-oauth2"`): straight to that identity provider, past Auth0's own page. */
42
+ connection?: string;
43
+ }
44
+ export interface SessionConfig {
45
+ /** The Auth0 tenant (`auth.<env>.health`). */
46
+ domain: string;
47
+ clientId: string;
48
+ /** The token audience network-api accepts. */
49
+ audience: string;
50
+ /** For tests: fetch, and how to leave the page. */
51
+ fetch?: typeof fetch;
52
+ navigate?: (url: string) => void;
53
+ openPopup?: (url: string) => Window | null;
54
+ }
55
+ export declare class Session {
56
+ #private;
57
+ constructor(config: SessionConfig);
58
+ get snapshot(): SessionSnapshot;
59
+ get status(): SessionStatus;
60
+ get user(): SessionUser | null;
61
+ subscribe: (listener: () => void) => (() => void);
62
+ /** Once per session: finish a sign-in that's coming back, else renew a stored one, else signed out. */
63
+ start(): Promise<void>;
64
+ /**
65
+ * Sign in — from a click. Leaves the page for Auth0 (its organization picker; `organization`, or the page's
66
+ * `?organization=`, goes straight in; `connection`, e.g. `"google-oauth2"`, goes straight to that identity provider,
67
+ * past Auth0's page) and comes back here. Inside an iframe: a popup, then signed in here.
68
+ */
69
+ signIn(options?: SignInOptions): Promise<void>;
70
+ /**
71
+ * Auth0's sign-in page for this session — to link to, or go to yourself. It's ready to come back to: the next
72
+ * `start()` on this page finishes the sign-in (PKCE: the verifier is kept for it, in this tab).
73
+ */
74
+ signInUrl(options?: SignInOptions): Promise<string>;
75
+ /** Auth0's sign-out page, coming back to `returnTo` (this site, unless said; Auth0 must allow it). */
76
+ signOutUrl(options?: {
77
+ returnTo?: string;
78
+ }): string;
79
+ /** Sign out: forget the session here, and end Auth0's (`signOutUrl`). Not something the cards offer. */
80
+ signOut(options?: {
81
+ returnTo?: string;
82
+ }): void;
83
+ /** The access token for network-api, renewed when it's about to expire. Signed out: `unauthorized`. */
84
+ token(): Promise<string>;
85
+ }
86
+ export declare function sessionFor(config: SessionConfig): Session;
87
+ /** A JWT's claims (not verified — read only for display and the org; network-api checks the token). */
88
+ export declare function claimsOf(jwt: string | undefined): Record<string, unknown>;
89
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/photon/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,aAAa,GAAG,UAAU,GAAG,YAAY,GAAG,YAAY,GAAG,WAAW,GAAG,OAAO,CAAC;AAE7F,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,sGAAsG;IACtG,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG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