@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.
- package/README.md +150 -5
- package/dist/analytics/lifecycleEvents.d.ts +32 -0
- package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
- package/dist/analytics/lifecycleEvents.js +75 -0
- package/dist/analytics/lifecycleEvents.js.map +1 -0
- package/dist/analytics/track.d.ts +39 -0
- package/dist/analytics/track.d.ts.map +1 -0
- package/dist/analytics/track.js +91 -0
- package/dist/analytics/track.js.map +1 -0
- package/dist/api/changes/applyOption.d.ts +4 -1
- package/dist/api/changes/applyOption.d.ts.map +1 -1
- package/dist/api/changes/applyOption.js +23 -2
- package/dist/api/changes/applyOption.js.map +1 -1
- package/dist/api/client.d.ts +6 -1
- package/dist/api/client.d.ts.map +1 -1
- package/dist/api/client.js +47 -33
- package/dist/api/client.js.map +1 -1
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.d.ts.map +1 -1
- package/dist/api/index.js +2 -0
- package/dist/api/index.js.map +1 -1
- package/dist/api/me.d.ts +37 -0
- package/dist/api/me.d.ts.map +1 -0
- package/dist/api/me.js +6 -0
- package/dist/api/me.js.map +1 -0
- package/dist/api/orders.d.ts +1047 -0
- package/dist/api/orders.d.ts.map +1 -0
- package/dist/api/orders.js +7 -0
- package/dist/api/orders.js.map +1 -0
- package/dist/api/patient.d.ts +5 -2
- package/dist/api/patient.d.ts.map +1 -1
- package/dist/api/patient.js +1 -1
- package/dist/api/patient.js.map +1 -1
- package/dist/api/prescription.d.ts +7 -1
- package/dist/api/prescription.d.ts.map +1 -1
- package/dist/api/prescription.js +10 -1
- package/dist/api/prescription.js.map +1 -1
- package/dist/gql/gql.d.ts +11 -3
- package/dist/gql/gql.d.ts.map +1 -1
- package/dist/gql/gql.js +5 -3
- package/dist/gql/gql.js.map +1 -1
- package/dist/gql/graphql.d.ts +10507 -1563
- package/dist/gql/graphql.d.ts.map +1 -1
- package/dist/gql/graphql.js +2984 -435
- package/dist/gql/graphql.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/meta/version.d.ts +2 -0
- package/dist/meta/version.d.ts.map +1 -0
- package/dist/meta/version.js +2 -0
- package/dist/meta/version.js.map +1 -0
- package/dist/photon/auth.d.ts +9 -5
- package/dist/photon/auth.d.ts.map +1 -1
- package/dist/photon/auth.js +2 -6
- package/dist/photon/auth.js.map +1 -1
- package/dist/photon/choices.d.ts +1 -1
- package/dist/photon/choices.js +2 -2
- package/dist/photon/choices.js.map +1 -1
- package/dist/photon/environments.d.ts +2 -1
- package/dist/photon/environments.d.ts.map +1 -1
- package/dist/photon/environments.js +2 -1
- package/dist/photon/environments.js.map +1 -1
- package/dist/photon/index.d.ts +6 -3
- package/dist/photon/index.d.ts.map +1 -1
- package/dist/photon/index.js +2 -1
- package/dist/photon/index.js.map +1 -1
- package/dist/photon/machine.d.ts +28 -0
- package/dist/photon/machine.d.ts.map +1 -0
- package/dist/photon/machine.js +53 -0
- package/dist/photon/machine.js.map +1 -0
- package/dist/photon/map.d.ts +6 -2
- package/dist/photon/map.d.ts.map +1 -1
- package/dist/photon/map.js +133 -33
- package/dist/photon/map.js.map +1 -1
- package/dist/photon/order.d.ts +24 -5
- package/dist/photon/order.d.ts.map +1 -1
- package/dist/photon/order.js +85 -23
- package/dist/photon/order.js.map +1 -1
- package/dist/photon/orders.d.ts +5 -0
- package/dist/photon/orders.d.ts.map +1 -0
- package/dist/photon/orders.js +39 -0
- package/dist/photon/orders.js.map +1 -0
- package/dist/photon/patient.d.ts +8 -6
- package/dist/photon/patient.d.ts.map +1 -1
- package/dist/photon/patient.js +61 -30
- package/dist/photon/patient.js.map +1 -1
- package/dist/photon/photon.d.ts +39 -1
- package/dist/photon/photon.d.ts.map +1 -1
- package/dist/photon/photon.js +85 -5
- package/dist/photon/photon.js.map +1 -1
- package/dist/photon/prescription.d.ts +17 -4
- package/dist/photon/prescription.d.ts.map +1 -1
- package/dist/photon/prescription.js +48 -11
- package/dist/photon/prescription.js.map +1 -1
- package/dist/photon/session.d.ts +16 -10
- package/dist/photon/session.d.ts.map +1 -1
- package/dist/photon/session.js +26 -11
- package/dist/photon/session.js.map +1 -1
- package/dist/photon/types.d.ts +278 -46
- package/dist/photon/types.d.ts.map +1 -1
- package/dist/test-utils/msw.d.ts +2 -2
- package/dist/test-utils/msw.d.ts.map +1 -1
- package/dist/test-utils/msw.js +5 -5
- package/dist/test-utils/msw.js.map +1 -1
- package/dist/testing/{scriptedClient.d.ts → fakeNetworkApiClient.d.ts} +5 -4
- package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
- package/dist/testing/{scriptedClient.js → fakeNetworkApiClient.js} +8 -4
- package/dist/testing/fakeNetworkApiClient.js.map +1 -0
- package/dist/testing/fixtures.d.ts +1047 -0
- package/dist/testing/fixtures.d.ts.map +1 -1
- package/dist/testing/fixtures.js +47 -13
- package/dist/testing/fixtures.js.map +1 -1
- package/dist/testing.d.ts +4 -4
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +4 -4
- package/dist/testing.js.map +1 -1
- package/package.json +2 -2
- package/src/analytics/lifecycleEvents.test.ts +437 -0
- package/src/analytics/lifecycleEvents.ts +172 -0
- package/src/analytics/track.test.ts +231 -0
- package/src/analytics/track.ts +129 -0
- package/src/api/changes/applyOption.ts +25 -2
- package/src/api/client.ts +71 -46
- package/src/api/index.ts +2 -0
- package/src/api/me.ts +7 -0
- package/src/api/orders.ts +8 -0
- package/src/api/patient.ts +11 -2
- package/src/api/prescription.ts +18 -0
- package/src/gql/gql.ts +21 -9
- package/src/gql/graphql.ts +4280 -597
- package/src/index.ts +1 -1
- package/src/meta/version.test.ts +10 -0
- package/src/meta/version.ts +1 -0
- package/src/operations/fragments.graphql +166 -20
- package/src/operations/me.graphql +38 -0
- package/src/operations/orders.graphql +35 -0
- package/src/operations/patient.graphql +29 -3
- package/src/operations/prescription.graphql +20 -0
- package/src/photon/auth.ts +9 -10
- package/src/photon/choices.ts +2 -2
- package/src/photon/environments.ts +3 -1
- package/src/photon/index.ts +17 -2
- package/src/photon/machine.ts +90 -0
- package/src/photon/map.ts +151 -35
- package/src/photon/order.test.ts +142 -0
- package/src/photon/order.ts +99 -24
- package/src/photon/orders.ts +42 -0
- package/src/photon/patient.ts +73 -33
- package/src/photon/photon.ts +139 -6
- package/src/photon/prescription.ts +71 -12
- package/src/photon/session.ts +39 -16
- package/src/photon/types.ts +280 -26
- package/src/test-utils/msw.ts +16 -5
- package/src/testing/{scriptedClient.ts → fakeNetworkApiClient.ts} +8 -4
- package/src/testing/fixtures.ts +55 -13
- package/src/testing.ts +6 -3
- package/dist/testing/scriptedClient.d.ts.map +0 -1
- package/dist/testing/scriptedClient.js.map +0 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { AnalyticsProperties } from "./track.ts";
|
|
2
|
+
import type { OrderRecord, PatientRecord, PrescriptionRecord, ScreeningAlert } from "../photon/types.ts";
|
|
3
|
+
|
|
4
|
+
export type LifecycleEventName =
|
|
5
|
+
| "Patient Created"
|
|
6
|
+
| "Patient Updated"
|
|
7
|
+
| "Draft Prescription Added"
|
|
8
|
+
| "Draft Prescription Deleted"
|
|
9
|
+
| "Screening Alert Acknowledged"
|
|
10
|
+
| "Screening Alert Canceled"
|
|
11
|
+
| "Prescription Signed"
|
|
12
|
+
| "Order Sent";
|
|
13
|
+
|
|
14
|
+
export type DraftPrescriptionSource = "form" | "template_prefill" | "prescription_id_prefill";
|
|
15
|
+
|
|
16
|
+
export type PatientForLifecycleAnalytics = Pick<PatientRecord, "id" | "demographic" | "contact" | "preferredPharmacy">;
|
|
17
|
+
|
|
18
|
+
export type DraftPrescriptionForLifecycleAnalytics = Pick<
|
|
19
|
+
PrescriptionRecord,
|
|
20
|
+
"id" | "treatment" | "dispense" | "instructions"
|
|
21
|
+
> & {
|
|
22
|
+
clinical: { notes: string | null } | null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type PrescriptionForLifecycleAnalytics = Pick<PrescriptionRecord, "id">;
|
|
26
|
+
|
|
27
|
+
export type SignedPrescriptionForLifecycleAnalytics = PrescriptionForLifecycleAnalytics & {
|
|
28
|
+
screeningAlerts?: readonly unknown[] | null;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type OrderForLifecycleAnalytics = Pick<OrderRecord, "id"> & {
|
|
32
|
+
prescriptions: readonly PrescriptionForLifecycleAnalytics[];
|
|
33
|
+
pharmacy: Pick<NonNullable<OrderRecord["pharmacy"]>, "fulfillmentType"> | null;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export interface LifecycleAnalytics {
|
|
37
|
+
patientCreated(patient: PatientForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
|
|
38
|
+
patientUpdated(patient: PatientForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
|
|
39
|
+
draftPrescriptionAdded(
|
|
40
|
+
prescription: DraftPrescriptionForLifecycleAnalytics,
|
|
41
|
+
source: DraftPrescriptionSource,
|
|
42
|
+
properties?: AnalyticsProperties,
|
|
43
|
+
): Promise<void>;
|
|
44
|
+
draftPrescriptionDeleted(prescriptionId: string, properties?: AnalyticsProperties): Promise<void>;
|
|
45
|
+
screeningAlertAcknowledged(
|
|
46
|
+
alerts: readonly ScreeningAlert[],
|
|
47
|
+
buttonText: string,
|
|
48
|
+
properties?: AnalyticsProperties,
|
|
49
|
+
): Promise<void>;
|
|
50
|
+
screeningAlertCanceled(
|
|
51
|
+
alerts: readonly ScreeningAlert[],
|
|
52
|
+
buttonText: string,
|
|
53
|
+
properties?: AnalyticsProperties,
|
|
54
|
+
): Promise<void>;
|
|
55
|
+
prescriptionSigned(
|
|
56
|
+
prescription: SignedPrescriptionForLifecycleAnalytics,
|
|
57
|
+
properties?: AnalyticsProperties,
|
|
58
|
+
): Promise<void>;
|
|
59
|
+
orderSent(order: OrderForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type Track = (event: string, properties?: AnalyticsProperties) => Promise<void>;
|
|
63
|
+
|
|
64
|
+
const SEND_TO_PATIENT = "SEND_TO_PATIENT";
|
|
65
|
+
|
|
66
|
+
export function lifecycleAnalyticsSentWith(track: Track): LifecycleAnalytics {
|
|
67
|
+
const sendCtaClicked = (
|
|
68
|
+
event: LifecycleEventName,
|
|
69
|
+
derivedProperties: AnalyticsProperties,
|
|
70
|
+
callerProperties: AnalyticsProperties = {},
|
|
71
|
+
) => track(event, { ...callerProperties, category: "ctaClicked", ...derivedProperties });
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
patientCreated: (patient, properties) => sendCtaClicked("Patient Created", patientProperties(patient), properties),
|
|
75
|
+
patientUpdated: (patient, properties) => sendCtaClicked("Patient Updated", patientProperties(patient), properties),
|
|
76
|
+
draftPrescriptionAdded: (prescription, source, properties) =>
|
|
77
|
+
sendCtaClicked(
|
|
78
|
+
"Draft Prescription Added",
|
|
79
|
+
{
|
|
80
|
+
prescriptionId: prescription.id,
|
|
81
|
+
draftPrescriptionSource: source,
|
|
82
|
+
...prescriptionFormSnapshot(prescription),
|
|
83
|
+
},
|
|
84
|
+
properties,
|
|
85
|
+
),
|
|
86
|
+
draftPrescriptionDeleted: (prescriptionId, properties) =>
|
|
87
|
+
sendCtaClicked("Draft Prescription Deleted", { prescriptionId }, properties),
|
|
88
|
+
screeningAlertAcknowledged: (alerts, buttonText, properties) =>
|
|
89
|
+
sendCtaClicked("Screening Alert Acknowledged", { screeningAlertCount: alerts.length, buttonText }, properties),
|
|
90
|
+
screeningAlertCanceled: (alerts, buttonText, properties) =>
|
|
91
|
+
sendCtaClicked("Screening Alert Canceled", { screeningAlertCount: alerts.length, buttonText }, properties),
|
|
92
|
+
prescriptionSigned: (prescription, properties) =>
|
|
93
|
+
sendCtaClicked(
|
|
94
|
+
"Prescription Signed",
|
|
95
|
+
{ prescriptionId: prescription.id, ...screeningAlertsAcknowledgedBySigning(prescription) },
|
|
96
|
+
properties,
|
|
97
|
+
),
|
|
98
|
+
orderSent: (order, properties) =>
|
|
99
|
+
sendCtaClicked(
|
|
100
|
+
"Order Sent",
|
|
101
|
+
{
|
|
102
|
+
orderId: order.id,
|
|
103
|
+
prescriptionCount: order.prescriptions.length,
|
|
104
|
+
prescriptionIds: order.prescriptions.map((prescription) => prescription.id),
|
|
105
|
+
fulfillmentType: fulfillmentTypeOf(order),
|
|
106
|
+
},
|
|
107
|
+
properties,
|
|
108
|
+
),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function patientProperties(patient: PatientForLifecycleAnalytics): AnalyticsProperties {
|
|
113
|
+
return { patientId: patient.id, ...patientFormSnapshot(patient) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function screeningAlertsAcknowledgedBySigning(
|
|
117
|
+
prescription: SignedPrescriptionForLifecycleAnalytics,
|
|
118
|
+
): AnalyticsProperties {
|
|
119
|
+
return prescription.screeningAlerts ? { screeningAlertCount: prescription.screeningAlerts.length } : {};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function fulfillmentTypeOf(order: OrderForLifecycleAnalytics): string | null {
|
|
123
|
+
if (!order.pharmacy) return SEND_TO_PATIENT;
|
|
124
|
+
const offeredTypes = order.pharmacy.fulfillmentType ?? [];
|
|
125
|
+
return offeredTypes.length === 1 ? offeredTypes[0]! : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function patientFormSnapshot(patient: PatientForLifecycleAnalytics): AnalyticsProperties {
|
|
129
|
+
const { demographic, contact, preferredPharmacy } = patient;
|
|
130
|
+
return completedFieldSnapshot({
|
|
131
|
+
firstName: demographic?.name.first,
|
|
132
|
+
lastName: demographic?.name.last,
|
|
133
|
+
dateOfBirth: demographic?.dateOfBirth,
|
|
134
|
+
phone: contact?.phone,
|
|
135
|
+
sex: demographic?.sex,
|
|
136
|
+
gender: demographic?.gender,
|
|
137
|
+
email: contact?.email,
|
|
138
|
+
address_street1: contact?.address?.street1,
|
|
139
|
+
address_street2: contact?.address?.street2,
|
|
140
|
+
address_city: contact?.address?.city,
|
|
141
|
+
address_state: contact?.address?.state,
|
|
142
|
+
address_zip: contact?.address?.postalCode,
|
|
143
|
+
preferredPharmacy,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function prescriptionFormSnapshot(prescription: DraftPrescriptionForLifecycleAnalytics): AnalyticsProperties {
|
|
148
|
+
const { treatment, dispense, instructions, clinical } = prescription;
|
|
149
|
+
return completedFieldSnapshot({
|
|
150
|
+
treatment,
|
|
151
|
+
dispenseQuantity: dispense?.quantity,
|
|
152
|
+
dispenseUnit: dispense?.unit,
|
|
153
|
+
daysSupply: dispense?.daysSupply,
|
|
154
|
+
refills: dispense?.refillsAllowed,
|
|
155
|
+
instructions,
|
|
156
|
+
notes: clinical?.notes,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function completedFieldSnapshot(valuesByFieldName: Record<string, unknown>): AnalyticsProperties {
|
|
161
|
+
return Object.fromEntries(
|
|
162
|
+
Object.entries(valuesByFieldName).map(([fieldName, value]) => [snapshotPropertyName(fieldName), isFilled(value)]),
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function snapshotPropertyName(fieldName: string): string {
|
|
167
|
+
return `snap_${fieldName.replace(/([A-Z])/g, "_$1").toLowerCase()}`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isFilled(value: unknown): boolean {
|
|
171
|
+
return value !== undefined && value !== null && value !== "" && value !== false;
|
|
172
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { clientVersion, environmentUrls, photon } from "../index.ts";
|
|
3
|
+
import { MAX_LIST_LENGTH, MAX_PROPERTY_LENGTH } from "./track.ts";
|
|
4
|
+
import { fakeNetworkApiClient, photonOver } from "../testing.ts";
|
|
5
|
+
|
|
6
|
+
// ph.analytics.track: one event to analytics-api as the signed-in prescriber. Never rejects, never PHI.
|
|
7
|
+
|
|
8
|
+
const jwt = (claims: Record<string, unknown>) => `x.${btoa(JSON.stringify(claims)).replace(/=+$/, "")}.y`;
|
|
9
|
+
const providerCaller = (userId: string) => ({
|
|
10
|
+
me: {
|
|
11
|
+
__typename: "User",
|
|
12
|
+
id: userId,
|
|
13
|
+
name: { first: "Ada", last: "Lovelace" },
|
|
14
|
+
organization: { __typename: "Organization", id: "org_1", name: "Acme Clinic" },
|
|
15
|
+
permissions: [],
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const photonWithAnalytics = (
|
|
20
|
+
handlers: Parameters<typeof fakeNetworkApiClient>[0] = { Me: () => providerCaller("usr_1") },
|
|
21
|
+
token: () => Promise<string> = async () => jwt({ sub: "auth0|1", org_id: "org_1" }),
|
|
22
|
+
) => {
|
|
23
|
+
const network = fakeNetworkApiClient(handlers);
|
|
24
|
+
const ph = photonOver(network.client, environmentUrls("boson"), {
|
|
25
|
+
analytics: { url: "https://analytics-api.boson.health", token, clientName: "photon-mcp" },
|
|
26
|
+
});
|
|
27
|
+
return { ph, analytics: ph.analytics!, names: network.names };
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
let fetchSpy: ReturnType<typeof vi.fn>;
|
|
31
|
+
const sent = () =>
|
|
32
|
+
fetchSpy.mock.calls.map(([url, init]) => ({
|
|
33
|
+
url: url as string,
|
|
34
|
+
init: init as RequestInit,
|
|
35
|
+
body: JSON.parse((init as RequestInit).body as string) as {
|
|
36
|
+
event: string;
|
|
37
|
+
userId: string;
|
|
38
|
+
properties: Record<string, unknown>;
|
|
39
|
+
},
|
|
40
|
+
}));
|
|
41
|
+
const events = () => sent().map(({ body }) => body.event);
|
|
42
|
+
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
fetchSpy = vi.fn(async () => new Response(JSON.stringify({ status: "ok" })));
|
|
45
|
+
vi.stubGlobal("fetch", fetchSpy);
|
|
46
|
+
});
|
|
47
|
+
afterEach(() => {
|
|
48
|
+
vi.useRealTimers();
|
|
49
|
+
vi.unstubAllGlobals();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("ph.analytics.track", () => {
|
|
53
|
+
it("POSTs the event to analytics-api with the prescriber's token, as their usr_ id", async () => {
|
|
54
|
+
vi.useFakeTimers({ now: new Date("2026-11-04T12:00:00.000Z"), toFake: ["Date"] });
|
|
55
|
+
const { analytics } = photonWithAnalytics();
|
|
56
|
+
await analytics.track("Patient Created", { patientId: "pat_1", integration: "mcp" });
|
|
57
|
+
const { url, init, body } = sent()[0]!;
|
|
58
|
+
expect(url).toBe("https://analytics-api.boson.health/event");
|
|
59
|
+
expect(init).toMatchObject({
|
|
60
|
+
method: "POST",
|
|
61
|
+
keepalive: true,
|
|
62
|
+
headers: {
|
|
63
|
+
"content-type": "application/json",
|
|
64
|
+
"x-photon-auth-token": jwt({ sub: "auth0|1", org_id: "org_1" }),
|
|
65
|
+
"x-photon-auth-token-type": "auth0",
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
expect(body).toEqual({
|
|
69
|
+
event: "Patient Created",
|
|
70
|
+
userId: "usr_1",
|
|
71
|
+
properties: {
|
|
72
|
+
providerId: "usr_1",
|
|
73
|
+
orgId: "org_1",
|
|
74
|
+
environment: "boson",
|
|
75
|
+
clientName: "photon-mcp",
|
|
76
|
+
clientVersion,
|
|
77
|
+
timestamp: "2026-11-04T12:00:00.000Z",
|
|
78
|
+
patientId: "pat_1",
|
|
79
|
+
integration: "mcp",
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("lets the caller set timestamp and its own properties, never providerId, orgId or environment", async () => {
|
|
85
|
+
const { analytics } = photonWithAnalytics();
|
|
86
|
+
await analytics.track("Order Sent", {
|
|
87
|
+
timestamp: "2026-01-01T00:00:00.000Z",
|
|
88
|
+
clientName: "host",
|
|
89
|
+
providerId: "usr_forged",
|
|
90
|
+
orgId: "org_forged",
|
|
91
|
+
environment: "photon",
|
|
92
|
+
});
|
|
93
|
+
expect(sent()[0]!.body.properties).toMatchObject({
|
|
94
|
+
timestamp: "2026-01-01T00:00:00.000Z",
|
|
95
|
+
clientName: "host",
|
|
96
|
+
providerId: "usr_1",
|
|
97
|
+
orgId: "org_1",
|
|
98
|
+
environment: "boson",
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("asks network-api who the caller is once per signed-in user", async () => {
|
|
103
|
+
let sub = "auth0|1";
|
|
104
|
+
const { analytics, names } = photonWithAnalytics(
|
|
105
|
+
{ Me: () => providerCaller(sub === "auth0|1" ? "usr_1" : "usr_2") },
|
|
106
|
+
async () => jwt({ sub, org_id: "org_1" }),
|
|
107
|
+
);
|
|
108
|
+
await Promise.all([analytics.track("Event A"), analytics.track("Event B")]);
|
|
109
|
+
sub = "auth0|2";
|
|
110
|
+
await analytics.track("Event C");
|
|
111
|
+
expect(sent().map(({ body }) => [body.event, body.userId, body.properties.providerId])).toEqual([
|
|
112
|
+
["Event A", "usr_1", "usr_1"],
|
|
113
|
+
["Event B", "usr_1", "usr_1"],
|
|
114
|
+
["Event C", "usr_2", "usr_2"],
|
|
115
|
+
]);
|
|
116
|
+
expect(names()).toEqual(["Me", "Me"]);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("drops the event, and asks again next time, when network-api can't say who the caller is", async () => {
|
|
120
|
+
let fail = true;
|
|
121
|
+
const { analytics } = photonWithAnalytics({
|
|
122
|
+
Me: () => {
|
|
123
|
+
if (fail) throw new Error("unreachable");
|
|
124
|
+
return providerCaller("usr_1");
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
await expect(analytics.track("Event A")).resolves.toBeUndefined();
|
|
128
|
+
expect(fetchSpy).not.toHaveBeenCalled();
|
|
129
|
+
fail = false;
|
|
130
|
+
await analytics.track("Event B");
|
|
131
|
+
expect(events()).toEqual(["Event B"]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("sends nothing for a caller that isn't a prescriber, or a token without a subject", async () => {
|
|
135
|
+
const patient = photonWithAnalytics({
|
|
136
|
+
Me: () => ({ me: { __typename: "Patient", id: "pat_1", name: { first: "Paige", last: "Turner" } } }),
|
|
137
|
+
});
|
|
138
|
+
await patient.analytics.track("Event A");
|
|
139
|
+
const noSub = photonWithAnalytics(undefined, async () => "not-a-jwt");
|
|
140
|
+
await noSub.analytics.track("Event A");
|
|
141
|
+
expect(fetchSpy).not.toHaveBeenCalled();
|
|
142
|
+
expect(noSub.names()).toEqual([]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("never rejects: a failed token, network-api or analytics-api changes nothing for the caller", async () => {
|
|
146
|
+
await expect(
|
|
147
|
+
photonWithAnalytics(undefined, async () => Promise.reject(new Error("no token"))).analytics.track("Event A"),
|
|
148
|
+
).resolves.toBeUndefined();
|
|
149
|
+
fetchSpy.mockRejectedValueOnce(new TypeError("fetch failed"));
|
|
150
|
+
await expect(photonWithAnalytics().analytics.track("Event A")).resolves.toBeUndefined();
|
|
151
|
+
fetchSpy.mockResolvedValueOnce(new Response("nope", { status: 500 }));
|
|
152
|
+
await expect(photonWithAnalytics().analytics.track("Event A")).resolves.toBeUndefined();
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
describe("guards: mistakes are dropped, not sent", () => {
|
|
156
|
+
it.each([
|
|
157
|
+
["a name that isn't Title Case", "patient created", {}],
|
|
158
|
+
["a name with digits", "Event 1", {}],
|
|
159
|
+
["an object value", "Event A", { patient: { name: "Paige" } }],
|
|
160
|
+
["a list holding a non-string", "Event A", { ids: ["rx_1", 2] }],
|
|
161
|
+
["a list holding an object", "Event A", { ids: [{ id: "rx_1" }] }],
|
|
162
|
+
["a list with a string longer than the limit", "Event A", { ids: ["x".repeat(MAX_PROPERTY_LENGTH + 1)] }],
|
|
163
|
+
[
|
|
164
|
+
"a list longer than the limit",
|
|
165
|
+
"Event A",
|
|
166
|
+
{ ids: Array.from({ length: MAX_LIST_LENGTH + 1 }, (_, i) => `rx_${i}`) },
|
|
167
|
+
],
|
|
168
|
+
["a string longer than the limit", "Event A", { note: "x".repeat(MAX_PROPERTY_LENGTH + 1) }],
|
|
169
|
+
])("%s", async (_why, event, properties) => {
|
|
170
|
+
const { analytics, names } = photonWithAnalytics();
|
|
171
|
+
await analytics.track(event, properties as never);
|
|
172
|
+
expect(fetchSpy).not.toHaveBeenCalled();
|
|
173
|
+
expect(names()).toEqual([]);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("ids, enums, counts, booleans, nulls and a string at the limit pass", async () => {
|
|
177
|
+
const { analytics } = photonWithAnalytics();
|
|
178
|
+
await analytics.track("Prescribe Workflow Viewed", {
|
|
179
|
+
orderId: "ord_1",
|
|
180
|
+
host: "chatgpt",
|
|
181
|
+
count: 2,
|
|
182
|
+
locked: false,
|
|
183
|
+
sessionId: null,
|
|
184
|
+
tag: "x".repeat(MAX_PROPERTY_LENGTH),
|
|
185
|
+
prescriptionIds: Array.from({ length: MAX_LIST_LENGTH }, (_, i) => `rx_${i}`),
|
|
186
|
+
none: [],
|
|
187
|
+
});
|
|
188
|
+
expect(events()).toEqual(["Prescribe Workflow Viewed"]);
|
|
189
|
+
expect(sent()[0]!.body.properties.prescriptionIds).toHaveLength(MAX_LIST_LENGTH);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
describe("integration: which surface sent it", () => {
|
|
195
|
+
const getToken = async () => jwt({ sub: "auth0|1", org_id: "org_1" });
|
|
196
|
+
const me = async () => new Response(JSON.stringify({ data: providerCaller("usr_1") }));
|
|
197
|
+
|
|
198
|
+
it('an MCP connector\'s instance tags every event integration: "mcp", without the caller saying so', async () => {
|
|
199
|
+
const ph = photon({ environment: "boson", auth: { getToken }, source: "MCP_CONNECTOR", fetch: me });
|
|
200
|
+
expect(ph.analytics?.integration).toBe("mcp");
|
|
201
|
+
await ph.analytics!.track("Patient Created", { patientId: "pat_1" });
|
|
202
|
+
await ph.analytics!.track("Order Sent", { orderId: "ord_1" });
|
|
203
|
+
expect(sent().map(({ body }) => body.properties.integration)).toEqual(["mcp", "mcp"]);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("other instances add none, and an event's own integration wins (React's cards send theirs)", async () => {
|
|
207
|
+
const host = photon({ environment: "boson", auth: { getToken }, source: "EMBEDDABLE_COMPONENT", fetch: me });
|
|
208
|
+
expect(host.analytics?.integration).toBeNull();
|
|
209
|
+
await host.analytics!.track("Event A");
|
|
210
|
+
await host.analytics!.track("Event B", { integration: "react" });
|
|
211
|
+
expect(sent().map(({ body }) => body.properties.integration)).toEqual([undefined, "react"]);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe("photon({ disableAnalytics })", () => {
|
|
216
|
+
const getToken = async () => jwt({ sub: "auth0|1", org_id: "org_1" });
|
|
217
|
+
|
|
218
|
+
it("analytics is on unless it's turned off", () => {
|
|
219
|
+
expect(photon({ environment: "boson", auth: { getToken } }).analytics?.track).toBeTypeOf("function");
|
|
220
|
+
expect(photon({ environment: "boson", auth: { getToken }, disableAnalytics: false }).analytics).not.toBeNull();
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("disableAnalytics: no ph.analytics, nothing sent — and the instance works as before", async () => {
|
|
224
|
+
const network = vi.fn(async () => new Response(JSON.stringify({ data: { ping: "pong" } })));
|
|
225
|
+
const ph = photon({ environment: "boson", auth: { getToken }, disableAnalytics: true, fetch: network });
|
|
226
|
+
expect(ph.analytics).toBeNull();
|
|
227
|
+
await ph.ping().catch(() => {});
|
|
228
|
+
expect(network).toHaveBeenCalled();
|
|
229
|
+
expect(fetchSpy).not.toHaveBeenCalled();
|
|
230
|
+
});
|
|
231
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { clientVersion } from "../meta/version.ts";
|
|
2
|
+
import type { EnvironmentUrls } from "../photon/environments.ts";
|
|
3
|
+
import { lifecycleAnalyticsSentWith, type LifecycleAnalytics } from "./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
|
+
}
|
|
@@ -91,13 +91,36 @@ export function applyOption<T>(input: T, option: ApplicableOption): T {
|
|
|
91
91
|
return applyAt(input, optionPath(option), parseOptionValue(option.value));
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Fields beside a locator that describe the entry rather than find it, so a pick keeps them. A medication
|
|
96
|
+
* history entry's `status` is required (MedicationHistoryEntryInput), so dropping it fails the write.
|
|
97
|
+
*/
|
|
98
|
+
const KEPT_BESIDE_LOCATOR = new Set(["status"]);
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Put a picked value at its path in the input. A locator (`….id`) replaces its siblings (the typed name and
|
|
102
|
+
* any search criteria, such as a pharmacy's `near`) but keeps the fields in KEPT_BESIDE_LOCATOR.
|
|
103
|
+
*/
|
|
95
104
|
export function applyAt<T>(input: T, path: string, value: unknown): T {
|
|
96
105
|
const segments = path.split(".").filter(Boolean);
|
|
97
106
|
const last = segments.at(-1)!;
|
|
98
107
|
if (segments.length > 1 && LOCATORS.has(last)) {
|
|
99
108
|
const parentPath = segments.slice(0, -1).join(".");
|
|
100
|
-
|
|
109
|
+
const parent = valueAt(input, segments.slice(0, -1));
|
|
110
|
+
const kept =
|
|
111
|
+
parent && typeof parent === "object" && !Array.isArray(parent)
|
|
112
|
+
? Object.fromEntries(Object.entries(parent).filter(([key]) => KEPT_BESIDE_LOCATOR.has(key)))
|
|
113
|
+
: {};
|
|
114
|
+
return setAtPath(input, parentPath, { ...kept, [last]: value });
|
|
101
115
|
}
|
|
102
116
|
return setAtPath(input, path, value);
|
|
103
117
|
}
|
|
118
|
+
|
|
119
|
+
function valueAt(input: unknown, segments: string[]): unknown {
|
|
120
|
+
let node = input;
|
|
121
|
+
for (const segment of segments) {
|
|
122
|
+
if (!node || typeof node !== "object") return undefined;
|
|
123
|
+
node = (node as Record<string, unknown>)[segment];
|
|
124
|
+
}
|
|
125
|
+
return node;
|
|
126
|
+
}
|