@photonhealth/client 2.0.0-rc.1 → 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 (152) hide show
  1. package/README.md +150 -5
  2. package/dist/analytics/lifecycleEvents.d.ts +29 -0
  3. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  4. package/dist/analytics/lifecycleEvents.js +72 -0
  5. package/dist/analytics/lifecycleEvents.js.map +1 -0
  6. package/dist/api/client.d.ts +6 -1
  7. package/dist/api/client.d.ts.map +1 -1
  8. package/dist/api/client.js +47 -33
  9. package/dist/api/client.js.map +1 -1
  10. package/dist/api/index.d.ts +2 -0
  11. package/dist/api/index.d.ts.map +1 -1
  12. package/dist/api/index.js +2 -0
  13. package/dist/api/index.js.map +1 -1
  14. package/dist/api/me.d.ts +37 -0
  15. package/dist/api/me.d.ts.map +1 -0
  16. package/dist/api/me.js +6 -0
  17. package/dist/api/me.js.map +1 -0
  18. package/dist/api/orders.d.ts +1047 -0
  19. package/dist/api/orders.d.ts.map +1 -0
  20. package/dist/api/orders.js +7 -0
  21. package/dist/api/orders.js.map +1 -0
  22. package/dist/api/patient.d.ts +5 -2
  23. package/dist/api/patient.d.ts.map +1 -1
  24. package/dist/api/patient.js +1 -1
  25. package/dist/api/patient.js.map +1 -1
  26. package/dist/api/prescription.d.ts +7 -1
  27. package/dist/api/prescription.d.ts.map +1 -1
  28. package/dist/api/prescription.js +10 -1
  29. package/dist/api/prescription.js.map +1 -1
  30. package/dist/gql/gql.d.ts +11 -3
  31. package/dist/gql/gql.d.ts.map +1 -1
  32. package/dist/gql/gql.js +5 -3
  33. package/dist/gql/gql.js.map +1 -1
  34. package/dist/gql/graphql.d.ts +10507 -1563
  35. package/dist/gql/graphql.d.ts.map +1 -1
  36. package/dist/gql/graphql.js +2984 -435
  37. package/dist/gql/graphql.js.map +1 -1
  38. package/dist/index.d.ts +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/meta/version.d.ts +2 -0
  41. package/dist/meta/version.d.ts.map +1 -0
  42. package/dist/meta/version.js +2 -0
  43. package/dist/meta/version.js.map +1 -0
  44. package/dist/photon/analytics.d.ts +39 -0
  45. package/dist/photon/analytics.d.ts.map +1 -0
  46. package/dist/photon/analytics.js +91 -0
  47. package/dist/photon/analytics.js.map +1 -0
  48. package/dist/photon/auth.d.ts +9 -5
  49. package/dist/photon/auth.d.ts.map +1 -1
  50. package/dist/photon/auth.js +2 -6
  51. package/dist/photon/auth.js.map +1 -1
  52. package/dist/photon/choices.d.ts +1 -1
  53. package/dist/photon/choices.js +2 -2
  54. package/dist/photon/choices.js.map +1 -1
  55. package/dist/photon/environments.d.ts +2 -1
  56. package/dist/photon/environments.d.ts.map +1 -1
  57. package/dist/photon/environments.js +2 -1
  58. package/dist/photon/environments.js.map +1 -1
  59. package/dist/photon/index.d.ts +6 -3
  60. package/dist/photon/index.d.ts.map +1 -1
  61. package/dist/photon/index.js +2 -1
  62. package/dist/photon/index.js.map +1 -1
  63. package/dist/photon/machine.d.ts +28 -0
  64. package/dist/photon/machine.d.ts.map +1 -0
  65. package/dist/photon/machine.js +53 -0
  66. package/dist/photon/machine.js.map +1 -0
  67. package/dist/photon/map.d.ts +6 -2
  68. package/dist/photon/map.d.ts.map +1 -1
  69. package/dist/photon/map.js +133 -33
  70. package/dist/photon/map.js.map +1 -1
  71. package/dist/photon/order.d.ts +21 -1
  72. package/dist/photon/order.d.ts.map +1 -1
  73. package/dist/photon/order.js +79 -12
  74. package/dist/photon/order.js.map +1 -1
  75. package/dist/photon/orders.d.ts +5 -0
  76. package/dist/photon/orders.d.ts.map +1 -0
  77. package/dist/photon/orders.js +39 -0
  78. package/dist/photon/orders.js.map +1 -0
  79. package/dist/photon/patient.d.ts +8 -6
  80. package/dist/photon/patient.d.ts.map +1 -1
  81. package/dist/photon/patient.js +61 -30
  82. package/dist/photon/patient.js.map +1 -1
  83. package/dist/photon/photon.d.ts +39 -1
  84. package/dist/photon/photon.d.ts.map +1 -1
  85. package/dist/photon/photon.js +85 -5
  86. package/dist/photon/photon.js.map +1 -1
  87. package/dist/photon/prescription.d.ts +17 -4
  88. package/dist/photon/prescription.d.ts.map +1 -1
  89. package/dist/photon/prescription.js +48 -11
  90. package/dist/photon/prescription.js.map +1 -1
  91. package/dist/photon/session.d.ts +15 -10
  92. package/dist/photon/session.d.ts.map +1 -1
  93. package/dist/photon/session.js +5 -3
  94. package/dist/photon/session.js.map +1 -1
  95. package/dist/photon/types.d.ts +278 -46
  96. package/dist/photon/types.d.ts.map +1 -1
  97. package/dist/test-utils/msw.d.ts +2 -2
  98. package/dist/test-utils/msw.d.ts.map +1 -1
  99. package/dist/test-utils/msw.js +5 -5
  100. package/dist/test-utils/msw.js.map +1 -1
  101. package/dist/testing/{scriptedClient.d.ts → fakeNetworkApiClient.d.ts} +5 -4
  102. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  103. package/dist/testing/{scriptedClient.js → fakeNetworkApiClient.js} +8 -4
  104. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  105. package/dist/testing/fixtures.d.ts +1047 -0
  106. package/dist/testing/fixtures.d.ts.map +1 -1
  107. package/dist/testing/fixtures.js +47 -13
  108. package/dist/testing/fixtures.js.map +1 -1
  109. package/dist/testing.d.ts +4 -4
  110. package/dist/testing.d.ts.map +1 -1
  111. package/dist/testing.js +4 -4
  112. package/dist/testing.js.map +1 -1
  113. package/package.json +2 -2
  114. package/src/analytics/lifecycleEvents.test.ts +417 -0
  115. package/src/analytics/lifecycleEvents.ts +155 -0
  116. package/src/api/client.ts +71 -46
  117. package/src/api/index.ts +2 -0
  118. package/src/api/me.ts +7 -0
  119. package/src/api/orders.ts +8 -0
  120. package/src/api/patient.ts +11 -2
  121. package/src/api/prescription.ts +18 -0
  122. package/src/gql/gql.ts +21 -9
  123. package/src/gql/graphql.ts +4280 -597
  124. package/src/index.ts +1 -1
  125. package/src/meta/version.test.ts +10 -0
  126. package/src/meta/version.ts +1 -0
  127. package/src/operations/fragments.graphql +166 -20
  128. package/src/operations/me.graphql +38 -0
  129. package/src/operations/orders.graphql +35 -0
  130. package/src/operations/patient.graphql +29 -3
  131. package/src/operations/prescription.graphql +20 -0
  132. package/src/photon/analytics.ts +129 -0
  133. package/src/photon/auth.ts +9 -10
  134. package/src/photon/choices.ts +2 -2
  135. package/src/photon/environments.ts +3 -1
  136. package/src/photon/index.ts +16 -2
  137. package/src/photon/machine.ts +90 -0
  138. package/src/photon/map.ts +151 -35
  139. package/src/photon/order.test.ts +142 -0
  140. package/src/photon/order.ts +92 -12
  141. package/src/photon/orders.ts +42 -0
  142. package/src/photon/patient.ts +73 -33
  143. package/src/photon/photon.ts +139 -6
  144. package/src/photon/prescription.ts +71 -12
  145. package/src/photon/session.ts +18 -9
  146. package/src/photon/types.ts +280 -26
  147. package/src/test-utils/msw.ts +16 -5
  148. package/src/testing/{scriptedClient.ts → fakeNetworkApiClient.ts} +8 -4
  149. package/src/testing/fixtures.ts +55 -13
  150. package/src/testing.ts +6 -3
  151. package/dist/testing/scriptedClient.d.ts.map +0 -1
  152. package/dist/testing/scriptedClient.js.map +0 -1
package/src/index.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * network-api's three upsert mutations — patient, prescription, order — one call each, returning live
9
9
  * objects (state you can subscribe to; methods that await the web calls) with the workflow rules
10
- * inside. See docs/CORE.md.
10
+ * inside. See the package README.
11
11
  *
12
12
  * This is the whole public surface. The GraphQL layer (api/, gql/) is internal.
13
13
  */
@@ -0,0 +1,10 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { describe, expect, it } from "vitest";
3
+ import { clientVersion } from "../index.ts";
4
+
5
+ describe("clientVersion", () => {
6
+ it("is package.json's version: bump both together", () => {
7
+ const manifest = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
8
+ expect(clientVersion).toBe(manifest.version);
9
+ });
10
+ });
@@ -0,0 +1 @@
1
+ export const clientVersion: string = "0.14.5";
@@ -18,7 +18,6 @@ fragment TreatmentFields on Treatment {
18
18
  strength
19
19
  medicationType
20
20
  schedule
21
- recommendedDispenseUnits
22
21
  }
23
22
 
24
23
  fragment ChoiceFields on Choice {
@@ -32,11 +31,19 @@ fragment ChoiceFields on Choice {
32
31
  type
33
32
  label
34
33
  confidence
34
+ value {
35
+ displayValue
36
+ value
37
+ unit
38
+ }
35
39
  }
36
40
  entity {
37
41
  __typename
38
42
  ... on Treatment {
39
43
  ...TreatmentFields
44
+ templates {
45
+ ...PrescriptionTemplateFields
46
+ }
40
47
  }
41
48
  ... on Pharmacy {
42
49
  ...PharmacyFields
@@ -46,23 +53,44 @@ fragment ChoiceFields on Choice {
46
53
 
47
54
  fragment PharmacyOfferFields on PharmacyOffer {
48
55
  source
56
+ prescriptionId
57
+ priceType
49
58
  isPromoted
50
59
  attributeTags {
51
60
  kind
52
61
  label
53
62
  }
54
- priceSummary {
55
- priceType
56
- totalAmount
57
- totalRetailAmount
58
- totalSavings
63
+ price {
64
+ amount
65
+ retailAmount
66
+ promotions {
67
+ type
68
+ baseAmount
69
+ amountSaved
70
+ }
59
71
  }
60
- prescriptionDeliveryEstimates {
61
- prescriptionId
72
+ deliveryEstimate {
62
73
  deliveryPromise
63
74
  deliveryPromiseRangeStart
64
75
  deliveryPromiseRangeEnd
65
76
  }
77
+ redemptionState
78
+ redemptionMethods {
79
+ ...RedemptionMethodFields
80
+ }
81
+ }
82
+
83
+ fragment RedemptionMethodFields on RedemptionMethod {
84
+ __typename
85
+ ... on PharmacyDiscountCard {
86
+ id
87
+ prescriptionId
88
+ bin
89
+ pcn
90
+ group
91
+ memberId
92
+ externalUrl
93
+ }
66
94
  }
67
95
 
68
96
  fragment ChangeFields on Change {
@@ -103,6 +131,24 @@ fragment OperationErrorFields on OperationError {
103
131
  fragment PharmacyFields on Pharmacy {
104
132
  id
105
133
  name
134
+ logo
135
+ phone
136
+ hours {
137
+ openFrom
138
+ openUntil
139
+ dayOfWeek
140
+ is24Hr
141
+ timezone
142
+ }
143
+ isOpen
144
+ nextEvents {
145
+ open {
146
+ ...PharmacyEventFields
147
+ }
148
+ close {
149
+ ...PharmacyEventFields
150
+ }
151
+ }
106
152
  address {
107
153
  street1
108
154
  street2
@@ -118,6 +164,42 @@ fragment PharmacyFields on Pharmacy {
118
164
  }
119
165
  }
120
166
 
167
+ fragment PharmacyEventFields on PharmacyEvent {
168
+ __typename
169
+ ... on PharmacyOpenEvent {
170
+ type
171
+ datetime
172
+ }
173
+ ... on PharmacyCloseEvent {
174
+ type
175
+ datetime
176
+ }
177
+ ... on PharmacyOpen24HrEvent {
178
+ type
179
+ }
180
+ }
181
+
182
+ fragment OrganizationFields on Organization {
183
+ id
184
+ name
185
+ customer {
186
+ __typename
187
+ ... on Customer {
188
+ id
189
+ name
190
+ }
191
+ }
192
+ settings {
193
+ brandColor
194
+ brandLogo
195
+ priorAuthorizationExceptionMessage
196
+ patientUx {
197
+ enablePatientRerouting
198
+ enableAutomatedOps
199
+ }
200
+ }
201
+ }
202
+
121
203
  fragment PatientDemographicFields on PatientDemographic {
122
204
  name {
123
205
  first
@@ -127,6 +209,9 @@ fragment PatientDemographicFields on PatientDemographic {
127
209
  dateOfBirth
128
210
  sex
129
211
  gender
212
+ }
213
+
214
+ fragment PatientContactFields on PatientContact {
130
215
  email
131
216
  phone
132
217
  address {
@@ -137,6 +222,16 @@ fragment PatientDemographicFields on PatientDemographic {
137
222
  postalCode
138
223
  country
139
224
  }
225
+ }
226
+
227
+ fragment PatientFields on Patient {
228
+ id
229
+ demographic {
230
+ ...PatientDemographicFields
231
+ }
232
+ contact {
233
+ ...PatientContactFields
234
+ }
140
235
  benefits {
141
236
  status
142
237
  entries {
@@ -150,13 +245,6 @@ fragment PatientDemographicFields on PatientDemographic {
150
245
  preferredPharmacy {
151
246
  ...PharmacyFields
152
247
  }
153
- }
154
-
155
- fragment PatientFields on Patient {
156
- id
157
- demographic {
158
- ...PatientDemographicFields
159
- }
160
248
  clinical {
161
249
  allergies {
162
250
  status
@@ -213,6 +301,24 @@ fragment ScreeningAlertFields on ScreeningAlert {
213
301
 
214
302
  fragment PrescriptionFields on Prescription {
215
303
  id
304
+ prescriber {
305
+ id
306
+ name {
307
+ first
308
+ middle
309
+ last
310
+ }
311
+ }
312
+ fulfillment {
313
+ state
314
+ pharmacyEstimatedReadyAt
315
+ exceptions {
316
+ id
317
+ type
318
+ message
319
+ createdAt
320
+ }
321
+ }
216
322
  templateId
217
323
  patient {
218
324
  id
@@ -250,6 +356,17 @@ fragment PrescriptionFields on Prescription {
250
356
  fragment OrderFields on Order {
251
357
  id
252
358
  state
359
+ offers {
360
+ atPharmacy {
361
+ ...PharmacyOfferFields
362
+ }
363
+ }
364
+ organization {
365
+ __typename
366
+ ... on Organization {
367
+ ...OrganizationFields
368
+ }
369
+ }
253
370
  patient {
254
371
  ...PatientRecordFields
255
372
  }
@@ -262,11 +379,40 @@ fragment OrderFields on Order {
262
379
  pharmacy {
263
380
  ...PharmacyFields
264
381
  }
265
- exceptions {
266
- id
267
- type
268
- message
269
- createdAt
382
+ fulfillment {
383
+ state
384
+ history {
385
+ pharmacy {
386
+ ...PharmacyFields
387
+ }
388
+ selector
389
+ reason
390
+ createdAt
391
+ }
392
+ routability {
393
+ allowed
394
+ reason
395
+ }
396
+ exceptions {
397
+ id
398
+ type
399
+ message
400
+ createdAt
401
+ }
402
+ }
403
+ }
404
+
405
+ fragment PrescriptionTemplateFields on PrescriptionTemplate {
406
+ id
407
+ source
408
+ name
409
+ instructions
410
+ dispense {
411
+ quantity
412
+ unit
413
+ daysSupply
414
+ refillsAllowed
415
+ dispenseAsWritten
270
416
  }
271
417
  }
272
418
 
@@ -0,0 +1,38 @@
1
+ query Me {
2
+ me {
3
+ __typename
4
+ ... on User {
5
+ id
6
+ name {
7
+ first
8
+ last
9
+ }
10
+ organization {
11
+ __typename
12
+ ... on Organization {
13
+ id
14
+ name
15
+ }
16
+ }
17
+ permissions
18
+ }
19
+ ... on Patient {
20
+ id
21
+ name {
22
+ first
23
+ last
24
+ }
25
+ }
26
+ ... on Machine {
27
+ organization {
28
+ __typename
29
+ ... on Organization {
30
+ id
31
+ name
32
+ }
33
+ }
34
+ permissions
35
+ }
36
+ ...OperationErrorFields
37
+ }
38
+ }
@@ -0,0 +1,35 @@
1
+ # Read-only order snapshots and pharmacy choices. A sole match is still a choice;
2
+ # selecting it remains an explicit UpdateOrder mutation.
3
+ query Orders(
4
+ $filter: OrdersFilterInput
5
+ $limit: Int
6
+ $pharmacy: PharmacyReferenceInput
7
+ $page: PageInput
8
+ $includePharmacies: Boolean!
9
+ ) {
10
+ orders(filter: $filter, limit: $limit) {
11
+ __typename
12
+ ... on OrdersPayload {
13
+ orders {
14
+ ...OrderFields
15
+ routablePharmacies(pharmacy: $pharmacy, page: $page) @include(if: $includePharmacies) {
16
+ options {
17
+ ...ChoiceFields
18
+ }
19
+ totalCount
20
+ nextOffset
21
+ }
22
+ }
23
+ }
24
+ ... on AmbiguousPatientMatch {
25
+ reason
26
+ candidates {
27
+ id
28
+ firstName
29
+ lastName
30
+ dateOfBirth
31
+ }
32
+ }
33
+ ...OperationErrorFields
34
+ }
35
+ }
@@ -14,23 +14,49 @@ mutation GetPatient($id: ID!, $metadata: RequestMetadata!) {
14
14
  mutation SyncPatient(
15
15
  $id: ID
16
16
  $demographic: PatientDemographicInput
17
+ $contact: PatientContactInput
17
18
  $clinical: PatientClinicalInput
19
+ $benefits: BenefitsPatch
20
+ $preferredPharmacy: PharmacyReferenceInput
18
21
  $metadata: RequestMetadata!
19
22
  ) {
20
- patient(patient: { id: $id, demographic: $demographic, clinical: $clinical }, metadata: $metadata) {
23
+ patient(
24
+ patient: {
25
+ id: $id
26
+ demographic: $demographic
27
+ contact: $contact
28
+ clinical: $clinical
29
+ benefits: $benefits
30
+ preferredPharmacy: $preferredPharmacy
31
+ }
32
+ metadata: $metadata
33
+ ) {
21
34
  ...PatientResultFields
22
35
  }
23
36
  }
24
37
 
25
- # Demographics (incl. benefits) and/or clinical patches (allergies — `none: true` for NKDA —
38
+ # Demographics, contact, benefits, preferred pharmacy and/or clinical patches (allergies — `none: true` for NKDA —
26
39
  # medications, diagnoses, notes).
27
40
  mutation UpdatePatient(
28
41
  $id: ID!
29
42
  $demographic: PatientDemographicInput
43
+ $contact: PatientContactInput
30
44
  $clinical: PatientClinicalInput
45
+ $benefits: BenefitsPatch
46
+ $preferredPharmacy: PharmacyReferenceInput
31
47
  $metadata: RequestMetadata!
32
48
  ) {
33
- patient(patient: { id: $id, demographic: $demographic, clinical: $clinical }, metadata: $metadata) {
49
+ patient(
50
+ patient: {
51
+ id: $id
52
+ demographic: $demographic
53
+ contact: $contact
54
+ clinical: $clinical
55
+ benefits: $benefits
56
+ preferredPharmacy: $preferredPharmacy
57
+ }
58
+ metadata: $metadata
59
+ ) {
34
60
  ...PatientResultFields
35
61
  }
36
62
  }
@@ -8,6 +8,8 @@
8
8
  # Update that one prescription (by id): only the fields sent change — or sign it: `signing.signedHash`
9
9
  # = the contentHash the prescriber reviewed. Signing can't be combined with content edits.
10
10
  # Screening runs on every call; every response carries signing.contentHash.
11
+ # Templates: like Get (id only, nothing changes), but selects only its treatment's templates — their Medi-Span
12
+ # sig lookup runs only when asked for, not on every save.
11
13
 
12
14
  mutation GetPrescription($id: ID!, $metadata: RequestMetadata!) {
13
15
  prescription(prescription: { id: $id }, metadata: $metadata) {
@@ -15,6 +17,24 @@ mutation GetPrescription($id: ID!, $metadata: RequestMetadata!) {
15
17
  }
16
18
  }
17
19
 
20
+ mutation GetPrescriptionTemplates($id: ID!, $metadata: RequestMetadata!) {
21
+ prescription(prescription: { id: $id }, metadata: $metadata) {
22
+ __typename
23
+ ... on PrescriptionPayload {
24
+ prescription {
25
+ treatment {
26
+ templates {
27
+ ...PrescriptionTemplateFields
28
+ }
29
+ }
30
+ }
31
+ }
32
+ ... on OperationError {
33
+ ...OperationErrorFields
34
+ }
35
+ }
36
+ }
37
+
18
38
  mutation SyncPrescription(
19
39
  $id: ID
20
40
  $externalId: String
@@ -0,0 +1,129 @@
1
+ import { clientVersion } from "../meta/version.ts";
2
+ import type { EnvironmentUrls } from "./environments.ts";
3
+ import { lifecycleAnalyticsSentWith, type LifecycleAnalytics } from "../analytics/lifecycleEvents.ts";
4
+
5
+ /**
6
+ * An event's properties: ids, enums, booleans, counts, durations, timestamps, and lists of ids (an order's
7
+ * prescriptions). Never PHI, never a value typed.
8
+ */
9
+ export type AnalyticsProperties = Record<string, string | number | boolean | null | string[]>;
10
+
11
+ /** Where an instance's events go: analytics-api and the token to send them with. */
12
+ export interface AnalyticsTarget {
13
+ readonly url: string;
14
+ token(): Promise<string>;
15
+ readonly clientName: string | null;
16
+ /**
17
+ * Which Photon surface the events come from (`"mcp"`), when the instance knows: every event carries it as
18
+ * `integration`, unless the event's properties set their own (React's cards send `"react"`).
19
+ */
20
+ readonly integration?: string | null;
21
+ }
22
+
23
+ /** `ph.analytics`: send prescribing events to Photon's analytics, as the signed-in prescriber. */
24
+ export interface Analytics extends AnalyticsTarget, LifecycleAnalytics {
25
+ /**
26
+ * Sends one event as the signed-in prescriber, with `providerId`, `orgId`, `environment`, `clientName`,
27
+ * `clientVersion`, `timestamp` and, when the instance knows it, `integration` added. Never rejects, and never throws: it resolves once the event is sent, or
28
+ * once it's dropped — no prescriber behind the token, network-api can't say who it is, analytics-api fails, or the
29
+ * event breaks the guards (a Title Case name; string, number, boolean or null values, or lists of at most
30
+ * {@link MAX_LIST_LENGTH} strings; strings of at most {@link MAX_PROPERTY_LENGTH} characters). The guards catch mistakes, not abuse: analytics-api checks only the token.
31
+ */
32
+ track(event: string, properties?: AnalyticsProperties): Promise<void>;
33
+ }
34
+
35
+ export const MAX_PROPERTY_LENGTH = 128;
36
+ export const MAX_LIST_LENGTH = 50;
37
+ const TITLE_CASE = /^[A-Z][A-Za-z]*( [A-Z][A-Za-z]*)*$/;
38
+
39
+ interface Instance {
40
+ environment: EnvironmentUrls | null;
41
+ /** The instance's caller's `usr_` id, or null when it isn't a prescriber. Throws when network-api can't say. */
42
+ providerId(): Promise<string | null>;
43
+ }
44
+
45
+ export function analyticsFor(target: AnalyticsTarget, instance: Instance): Analytics {
46
+ const providerIdsBySub = new Map<string, Promise<string | null>>();
47
+ const providerIdFor = (sub: string) => {
48
+ let providerId = providerIdsBySub.get(sub);
49
+ if (!providerId) {
50
+ providerId = instance.providerId();
51
+ providerId.catch(() => providerIdsBySub.delete(sub)); // ask again next time
52
+ providerIdsBySub.set(sub, providerId);
53
+ }
54
+ return providerId;
55
+ };
56
+
57
+ const track: Analytics["track"] = async (event, properties = {}) => {
58
+ try {
59
+ if (!wellFormed(event, properties)) return;
60
+ const timestamp = new Date().toISOString();
61
+ const token = await target.token();
62
+ const claims = unverifiedJwtClaims(token);
63
+ if (typeof claims.sub !== "string") return;
64
+ const providerId = await providerIdFor(claims.sub);
65
+ if (!providerId) return;
66
+ const orgId = typeof claims.org_id === "string" ? claims.org_id : null;
67
+ await fetch(`${target.url}/event`, {
68
+ method: "POST",
69
+ headers: {
70
+ "content-type": "application/json",
71
+ "x-photon-auth-token": token,
72
+ "x-photon-auth-token-type": "auth0", // analytics-api returns 400 without it
73
+ },
74
+ body: JSON.stringify({
75
+ event,
76
+ userId: providerId,
77
+ properties: {
78
+ clientName: target.clientName,
79
+ clientVersion,
80
+ timestamp,
81
+ ...(target.integration ? { integration: target.integration } : {}),
82
+ ...properties,
83
+ // Who and where come from the instance, never the caller.
84
+ providerId,
85
+ orgId,
86
+ environment: instance.environment?.name ?? null,
87
+ },
88
+ }),
89
+ keepalive: true,
90
+ });
91
+ } catch {
92
+ // never block the prescriber
93
+ }
94
+ };
95
+
96
+ return {
97
+ url: target.url,
98
+ token: () => target.token(),
99
+ clientName: target.clientName,
100
+ integration: target.integration ?? null,
101
+ track,
102
+ ...lifecycleAnalyticsSentWith(track),
103
+ };
104
+ }
105
+
106
+ function wellFormed(event: string, properties: AnalyticsProperties): boolean {
107
+ if (typeof event !== "string" || !TITLE_CASE.test(event)) return false;
108
+ if (!properties || typeof properties !== "object") return false;
109
+ const shortString = (value: unknown) => typeof value === "string" && value.length <= MAX_PROPERTY_LENGTH;
110
+ return Object.values(properties).every(
111
+ (value) =>
112
+ value === null ||
113
+ value === undefined ||
114
+ typeof value === "number" ||
115
+ typeof value === "boolean" ||
116
+ shortString(value) ||
117
+ (Array.isArray(value) && value.length <= MAX_LIST_LENGTH && value.every(shortString)),
118
+ );
119
+ }
120
+
121
+ function unverifiedJwtClaims(jwt: string): Record<string, unknown> {
122
+ try {
123
+ const payload = jwt.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/");
124
+ const bytes = Uint8Array.from(atob(payload), (c) => c.charCodeAt(0));
125
+ return JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;
126
+ } catch {
127
+ return {};
128
+ }
129
+ }
@@ -5,10 +5,9 @@ import { PhotonError } from "./errors.ts";
5
5
  *
6
6
  * SPA `{ clientId }` — core signs the prescriber in itself, in the browser (session.ts): `ph.session`.
7
7
  * SPA `{ getToken }` — the host signs in (e.g. its own Auth0 SDK) and supplies the org-scoped token.
8
- * M2M `{ clientId, clientSecret, organizationId }` — a backend's own credentials. Core will run the
9
- * client-credentials grant, cache the token until shortly before it expires, share one refresh
10
- * between concurrent calls and retry once on a 401. Not built yet (Photon-Health/prescribe#18): the shape is
11
- * fixed now so it doesn't change later. Servers only: `photon()` refuses a secret in a browser.
8
+ * M2M `{ clientId, clientSecret, organizationId }` — a backend's own credentials (machine.ts): core runs the
9
+ * client-credentials grant, keeps the token until shortly before it expires, shares one request between
10
+ * concurrent calls and retries once on a 401. Servers only: `photon()` refuses a secret in a browser.
12
11
  */
13
12
  export type PhotonAuth =
14
13
  | { getToken: () => Promise<string> }
@@ -18,6 +17,12 @@ export type PhotonAuth =
18
17
  /** Core's own browser sign-in: a client id alone. */
19
18
  export const signsIn = (auth: PhotonAuth): auth is { clientId: string } => "clientId" in auth && !hasSecret(auth);
20
19
 
20
+ /** A backend's own credentials (M2M). */
21
+ export const isMachine = (
22
+ auth: PhotonAuth,
23
+ ): auth is { clientId: string; clientSecret: string; organizationId: string } =>
24
+ "clientId" in auth && "clientSecret" in auth;
25
+
21
26
  /** A client secret, in any shape it's given (M2M). */
22
27
  export const hasSecret = (auth: object): boolean => "clientSecret" in auth || "client_secret" in auth;
23
28
 
@@ -39,12 +44,6 @@ export function refuseSecretInBrowser(auth: object): void {
39
44
  );
40
45
  }
41
46
 
42
- export function tokenSource(auth: PhotonAuth): () => Promise<string> {
43
- if ("getToken" in auth) return auth.getToken;
44
- refuseSecretInBrowser(auth);
45
- throw new PhotonError("invalid", "Client-credentials (M2M) auth isn't supported yet — pass { getToken }.");
46
- }
47
-
48
47
  /**
49
48
  * How links from an instance sign in (`FlowLink.auth`): an embed signs the prescriber in with the host's own
50
49
  * client — `{ clientId }`'s — and any link opens in the instance's organization, when it has one. An M2M client
@@ -66,13 +66,13 @@ export const optionKey = (option: ChangeOption) => `${option.path}=${JSON.string
66
66
 
67
67
  /**
68
68
  * Does the server want a mailing address for this patient? network-api says so either as an unapplied
69
- * change under demographic.address (patient upserts) or in an error ("patient … has no address", at
69
+ * change under contact.address (patient upserts) or in an error ("patient … has no address", at
70
70
  * submit). Ask for one only when it does — a phone is often enough.
71
71
  */
72
72
  export function asksForAddress(changes?: Changes | null, message?: string | null): boolean {
73
73
  const fromChanges = (changes?.unapplied ?? []).some(
74
74
  (c) =>
75
- c.key.startsWith("demographic.address") ||
75
+ c.key.startsWith("contact.address") ||
76
76
  (c.category === "MISSING_INPUT" && /address/i.test(`${c.label} ${c.reason ?? ""}`)),
77
77
  );
78
78
  return fromChanges || /\baddress\b/i.test(message ?? "");
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Photon environments, in code. Every URL is inferred from the environment name —
3
3
  * `<service>.<env>.health` — so there's nothing to configure per deploy, in a browser or on a server.
4
- * Mirrors Photon-Health/mcp src/config.ts. tau is locally running services; it signs in through
4
+ * tau is locally running services; it signs in through
5
5
  * boson's Auth0 tenant.
6
6
  */
7
7
 
@@ -21,6 +21,7 @@ export interface EnvironmentUrls {
21
21
  * `rx.new` in production, `rx.<env>.health` otherwise; tau's is the local dev server (`npm run dev:tau`).
22
22
  */
23
23
  appUrl: string;
24
+ analyticsApiUrl: string;
24
25
  }
25
26
 
26
27
  /** Environments without their own Auth0 tenant. Local services (tau) sign in through boson's. */
@@ -43,5 +44,6 @@ export function environmentUrls(name: PhotonEnvironment): EnvironmentUrls {
43
44
  auth0Domain: `auth.${authEnv}.health`,
44
45
  auth0Audience: `https://api.${authEnv}.health`,
45
46
  appUrl: APP_URL[name] ?? `https://rx.${name}.health`,
47
+ analyticsApiUrl: `${scheme(name)}://analytics-api.${name}.health`,
46
48
  };
47
49
  }