@esushealth/sdk 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,286 @@
1
+ import { patientPortalResources } from "./integration-contract.js";
2
+ import { queryPath, readResource, readSearchResult, validSegment } from "./fhir.js";
3
+ import { createTransport, EsusError, integrationOrigin, record } from "./transport.js";
4
+ function invalid(response, operation) {
5
+ throw new EsusError(`Esus returned an invalid ${operation} response`, response.status, response.headers.get("x-request-id"));
6
+ }
7
+ function validLifetime(value) {
8
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
9
+ }
10
+ function confirmed({ body, response }, operation) {
11
+ if (record(body)?.success !== true)
12
+ invalid(response, operation);
13
+ }
14
+ function noContent({ response }, operation) {
15
+ if (response.status !== 204)
16
+ invalid(response, operation);
17
+ }
18
+ function codesFrom({ body, response }) {
19
+ const recoveryCodes = record(body)?.recoveryCodes;
20
+ if (!Array.isArray(recoveryCodes) || !recoveryCodes.every((code) => typeof code === "string")) {
21
+ return invalid(response, "MFA recovery codes");
22
+ }
23
+ return { recoveryCodes };
24
+ }
25
+ function challengeFrom({ body, response }) {
26
+ const options = record(body);
27
+ if (typeof options?.challenge !== "string" || !options.challenge)
28
+ return invalid(response, "passkey options");
29
+ return options;
30
+ }
31
+ function passkeyFrom(body, response) {
32
+ const passkey = record(body);
33
+ if (typeof passkey?.id !== "string" || typeof passkey.backedUp !== "boolean")
34
+ return invalid(response, "passkey");
35
+ return passkey;
36
+ }
37
+ function sessionFrom({ body, response }) {
38
+ const token = record(body);
39
+ if (typeof token?.accessToken !== "string" || !token.accessToken ||
40
+ typeof token.refreshToken !== "string" || !token.refreshToken ||
41
+ token.tokenType !== "Bearer" || !validLifetime(token.expiresIn))
42
+ return invalid(response, "session");
43
+ return {
44
+ accessToken: token.accessToken, refreshToken: token.refreshToken, expiresIn: token.expiresIn, tokenType: token.tokenType,
45
+ };
46
+ }
47
+ function loginFrom(reply) {
48
+ const challenge = record(reply.body);
49
+ if (challenge?.mfaRequired !== true)
50
+ return sessionFrom(reply);
51
+ if (typeof challenge.mfaToken !== "string" || !challenge.mfaToken || !validLifetime(challenge.expiresIn)) {
52
+ return invalid(reply.response, "MFA challenge");
53
+ }
54
+ return { mfaRequired: true, mfaToken: challenge.mfaToken, expiresIn: challenge.expiresIn };
55
+ }
56
+ function validRole(value) {
57
+ const role = record(value);
58
+ return typeof role?.name === "string" && typeof role.isStaff === "boolean" && Array.isArray(role.permissions) &&
59
+ role.permissions.every((value) => {
60
+ const permission = record(value);
61
+ return typeof permission?.resource === "string" && typeof permission.action === "string";
62
+ });
63
+ }
64
+ function userFrom({ body, response }) {
65
+ const user = record(body);
66
+ if (typeof user?.id !== "string" || typeof user.email !== "string" ||
67
+ typeof user.isActive !== "boolean" || typeof user.emailVerified !== "boolean" || typeof user.createdAt !== "string" ||
68
+ !["firstName", "lastName", "avatarUrl", "patientId", "practitionerId", "lastLoginAt"].every((field) => user[field] === null || typeof user[field] === "string") || !Array.isArray(user.roles) || !user.roles.every(validRole))
69
+ return invalid(response, "app user");
70
+ return user;
71
+ }
72
+ /** Server-side client. The host application owns token persistence and refresh coordination. */
73
+ export function createAppSessionClient(options) {
74
+ if (!options.appId.trim())
75
+ throw new TypeError("Esus appId is required");
76
+ const request = createTransport(options, { "x-app-id": options.appId });
77
+ function call(path, options, body, accessToken, method = body ? "POST" : "GET") {
78
+ const headers = new Headers();
79
+ if (options.userAgent)
80
+ headers.set("user-agent", options.userAgent);
81
+ if (options.turnstileToken)
82
+ headers.set("cf-turnstile-token", options.turnstileToken);
83
+ if (accessToken)
84
+ headers.set("authorization", `Bearer ${accessToken}`);
85
+ if (body)
86
+ headers.set("content-type", "application/json");
87
+ if (method !== "GET") {
88
+ headers.set("x-requested-with", "XMLHttpRequest");
89
+ }
90
+ return request(`/v1/auth/${path}`, {
91
+ method, headers, body: body ? JSON.stringify(body) : undefined, signal: options.signal,
92
+ });
93
+ }
94
+ return {
95
+ async verifyInvitation(token, options = {}) {
96
+ if (!validSegment(token))
97
+ throw new TypeError("Invalid Esus invitation token");
98
+ const { body, response } = await call(`user-invite/${token}`, options);
99
+ const invitation = record(body);
100
+ if (typeof invitation?.email !== "string" || typeof invitation.expiresAt !== "string" ||
101
+ typeof invitation.hasHealthRecord !== "boolean" || typeof invitation.hasProfessionalRole !== "boolean") {
102
+ return invalid(response, "app invitation");
103
+ }
104
+ return {
105
+ email: invitation.email,
106
+ expiresAt: invitation.expiresAt,
107
+ hasHealthRecord: invitation.hasHealthRecord,
108
+ hasProfessionalRole: invitation.hasProfessionalRole,
109
+ };
110
+ },
111
+ async signUp(input, options = {}) {
112
+ const { body, response } = await call("signup", options, input);
113
+ const user = record(body);
114
+ if (typeof user?.appUserId !== "string" || typeof user.emailVerificationRequired !== "boolean") {
115
+ return invalid(response, "signup");
116
+ }
117
+ return { appUserId: user.appUserId, emailVerificationRequired: user.emailVerificationRequired };
118
+ },
119
+ async requestEmailCode(input, options = {}) {
120
+ const { body, response } = await call("otp/request", options, input);
121
+ const message = record(body)?.message;
122
+ if (typeof message !== "string")
123
+ return invalid(response, "email code request");
124
+ return { message };
125
+ },
126
+ async verifyEmail(input, options = {}) {
127
+ const result = await call("email/verify", options, input);
128
+ confirmed(result, "email verification");
129
+ const userId = record(result.body)?.userId;
130
+ if (typeof userId !== "string")
131
+ return invalid(result.response, "email verification");
132
+ return { userId };
133
+ },
134
+ async confirmPasswordReset(input, options = {}) {
135
+ confirmed(await call("password/reset/confirm", options, input), "password reset");
136
+ },
137
+ async requestEmailChange(accessToken, input, options = {}) {
138
+ confirmed(await call("email/change", options, input, accessToken), "email change request");
139
+ },
140
+ async confirmEmailChange(accessToken, code, options = {}) {
141
+ confirmed(await call("email/change/verify", options, { code }, accessToken), "email change confirmation");
142
+ },
143
+ async signInWithPassword(credentials, options = {}) {
144
+ return loginFrom(await call("login", options, credentials));
145
+ },
146
+ googleSignInUrl(returnTo) {
147
+ const callback = new URL(returnTo);
148
+ integrationOrigin(callback.origin);
149
+ if (callback.username || callback.password || callback.hash)
150
+ throw new TypeError("Invalid Google sign-in callback URL");
151
+ const start = new URL("/v1/auth/google/start", options.url);
152
+ start.searchParams.set("app_id", options.appId);
153
+ start.searchParams.set("next", callback.href);
154
+ return start;
155
+ },
156
+ async exchangeGoogleCode(code, options = {}) {
157
+ return loginFrom(await call("google/exchange", options, { code }));
158
+ },
159
+ async verifyMfa(challenge, options = {}) {
160
+ return sessionFrom(await call("mfa/verify", options, challenge));
161
+ },
162
+ mfa: {
163
+ async status(accessToken, options = {}) {
164
+ const { body, response } = await call("mfa/status", options, undefined, accessToken);
165
+ const status = record(body);
166
+ if (typeof status?.enabled !== "boolean" || typeof status.recoveryCodesRemaining !== "number")
167
+ return invalid(response, "MFA status");
168
+ return { enabled: status.enabled, recoveryCodesRemaining: status.recoveryCodesRemaining };
169
+ },
170
+ async setup(accessToken, input, options = {}) {
171
+ const { body, response } = await call("mfa/setup", options, input, accessToken);
172
+ const setup = record(body);
173
+ if (typeof setup?.secret !== "string" || typeof setup.otpauthUri !== "string")
174
+ return invalid(response, "MFA setup");
175
+ return { secret: setup.secret, otpauthUri: setup.otpauthUri };
176
+ },
177
+ async enable(accessToken, input, options = {}) {
178
+ return codesFrom(await call("mfa/enable", options, input, accessToken));
179
+ },
180
+ async disable(accessToken, input, options = {}) {
181
+ confirmed(await call("mfa/disable", options, input, accessToken), "MFA disable");
182
+ },
183
+ async regenerateRecoveryCodes(accessToken, input, options = {}) {
184
+ return codesFrom(await call("mfa/recovery-codes/regenerate", options, input, accessToken));
185
+ },
186
+ },
187
+ passkeys: {
188
+ async startLogin(input = {}, options = {}) {
189
+ return challengeFrom(await call("webauthn/login/options", options, input));
190
+ },
191
+ async completeLogin(input, options = {}) {
192
+ return sessionFrom(await call("webauthn/login/verify", options, input));
193
+ },
194
+ async startRegistration(accessToken, input, options = {}) {
195
+ return challengeFrom(await call("me/webauthn/register/options", options, input, accessToken));
196
+ },
197
+ async completeRegistration(accessToken, input, options = {}) {
198
+ const { body, response } = await call("me/webauthn/register/verify", options, input, accessToken);
199
+ return passkeyFrom(body, response);
200
+ },
201
+ async list(accessToken, options = {}) {
202
+ const { body, response } = await call("me/webauthn/credentials", options, undefined, accessToken);
203
+ const credentials = record(body)?.credentials;
204
+ if (!Array.isArray(credentials))
205
+ return invalid(response, "passkey list");
206
+ return credentials.map((entry) => passkeyFrom(entry, response));
207
+ },
208
+ async remove(accessToken, id, options = {}) {
209
+ if (!validSegment(id))
210
+ throw new TypeError("Invalid Esus passkey ID");
211
+ noContent(await call(`me/webauthn/credentials/${id}`, options, undefined, accessToken, "DELETE"), "passkey removal");
212
+ },
213
+ },
214
+ async refreshSession(refreshToken, options = {}) {
215
+ return sessionFrom(await call("refresh", options, { refreshToken }));
216
+ },
217
+ async getUser(accessToken, options = {}) {
218
+ return userFrom(await call("me", options, undefined, accessToken));
219
+ },
220
+ async updateUser(accessToken, input, options = {}) {
221
+ return userFrom(await call("me", options, input, accessToken, "PATCH"));
222
+ },
223
+ async changePassword(accessToken, input, options = {}) {
224
+ confirmed(await call("password/change", options, input, accessToken), "password change");
225
+ },
226
+ async deleteAccount(accessToken, proof, options = {}) {
227
+ noContent(await call("me", options, proof, accessToken, "DELETE"), "account deletion");
228
+ },
229
+ async requestAccountDeletionCode(accessToken, options = {}) {
230
+ confirmed(await call("me/deletion-code", options, undefined, accessToken, "POST"), "account deletion code");
231
+ },
232
+ async listSessions(accessToken, options = {}) {
233
+ const { body, response } = await call("sessions", options, undefined, accessToken);
234
+ const page = record(body);
235
+ if (!Array.isArray(page?.sessions) || typeof page.total !== "number")
236
+ return invalid(response, "session list");
237
+ return page;
238
+ },
239
+ async revokeSession(accessToken, sessionId, options = {}) {
240
+ if (!validSegment(sessionId))
241
+ throw new TypeError("Invalid Esus session ID");
242
+ noContent(await call(`sessions/${sessionId}`, options, undefined, accessToken, "DELETE"), "session revocation");
243
+ },
244
+ async revokeAllSessions(accessToken, options = {}) {
245
+ noContent(await call("sessions", options, undefined, accessToken, "DELETE"), "session revocation");
246
+ },
247
+ records: {
248
+ async profile(accessToken, options = {}) {
249
+ const { body, response } = await call("profile", options, undefined, accessToken);
250
+ const profile = record(body);
251
+ switch (profile?.kind) {
252
+ case "none":
253
+ if (profile.resource !== null)
254
+ return invalid(response, "linked profile");
255
+ return { kind: "none", resource: null };
256
+ case "patient":
257
+ return { kind: "patient", resource: readResource("Patient", profile.resource, response) };
258
+ case "practitioner":
259
+ return { kind: "practitioner", resource: readResource("Practitioner", profile.resource, response) };
260
+ default:
261
+ return invalid(response, "linked profile");
262
+ }
263
+ },
264
+ async read(accessToken, kind, options = {}) {
265
+ if (kind !== "Patient" && kind !== "Practitioner")
266
+ throw new TypeError("Unknown linked resource");
267
+ const { body, response } = await call(kind, options, undefined, accessToken);
268
+ return { resource: readResource(kind, body, response), etag: response.headers.get("etag") };
269
+ },
270
+ async search(accessToken, kind, filters, options = {}) {
271
+ if (!patientPortalResources.includes(kind))
272
+ throw new TypeError("Unknown patient portal resource");
273
+ const { body, response } = await call(queryPath(`me/${kind}`, filters ?? {}), options, undefined, accessToken);
274
+ return readSearchResult(kind, body, response);
275
+ },
276
+ async revokeConsent(accessToken, id, options = {}) {
277
+ if (!validSegment(id))
278
+ throw new TypeError("Invalid Esus consent ID");
279
+ confirmed(await call(`me/consent/${id}/revoke`, options, undefined, accessToken, "POST"), "consent revocation");
280
+ },
281
+ },
282
+ async signOut(session, options = {}) {
283
+ confirmed(await call("logout", options, { refreshToken: session.refreshToken }, session.accessToken), "logout");
284
+ },
285
+ };
286
+ }
@@ -0,0 +1,279 @@
1
+ import { type IntegrationInputs, type IntegrationQueries } from "./integration-contract.js";
2
+ import { type RequestOptions, type Transport } from "./transport.js";
3
+ export declare function clinicalWorkflows(request: Transport): {
4
+ queue: {
5
+ checkIn: (body: IntegrationInputs["POST /queue/check-in"], options?: RequestOptions) => Promise<{
6
+ readonly id: string;
7
+ readonly organizationId: string;
8
+ readonly patientId: string;
9
+ readonly appointmentId: string | null;
10
+ readonly locationId: string | null;
11
+ readonly practitionerId: string | null;
12
+ readonly status: string;
13
+ readonly priority: number;
14
+ readonly queueNumber: number | null;
15
+ readonly checkedInAt: string;
16
+ readonly calledAt: string | null;
17
+ readonly startedAt: string | null;
18
+ readonly completedAt: string | null;
19
+ readonly note: string | null;
20
+ readonly createdAt: string;
21
+ readonly updatedAt: string;
22
+ }>;
23
+ waiting: (query?: IntegrationQueries["GET /queue/waiting"], options?: RequestOptions) => Promise<readonly {
24
+ readonly id: string;
25
+ readonly organizationId: string;
26
+ readonly patientId: string;
27
+ readonly appointmentId: string | null;
28
+ readonly locationId: string | null;
29
+ readonly practitionerId: string | null;
30
+ readonly status: string;
31
+ readonly priority: number;
32
+ readonly queueNumber: number | null;
33
+ readonly checkedInAt: string;
34
+ readonly calledAt: string | null;
35
+ readonly startedAt: string | null;
36
+ readonly completedAt: string | null;
37
+ readonly note: string | null;
38
+ readonly createdAt: string;
39
+ readonly updatedAt: string;
40
+ }[]>;
41
+ callNext: (body?: IntegrationInputs["POST /queue/call-next"], options?: RequestOptions) => Promise<{
42
+ readonly id: string;
43
+ readonly organizationId: string;
44
+ readonly patientId: string;
45
+ readonly appointmentId: string | null;
46
+ readonly locationId: string | null;
47
+ readonly practitionerId: string | null;
48
+ readonly status: string;
49
+ readonly priority: number;
50
+ readonly queueNumber: number | null;
51
+ readonly checkedInAt: string;
52
+ readonly calledAt: string | null;
53
+ readonly startedAt: string | null;
54
+ readonly completedAt: string | null;
55
+ readonly note: string | null;
56
+ readonly createdAt: string;
57
+ readonly updatedAt: string;
58
+ }>;
59
+ start: (id: string, options?: RequestOptions) => Promise<{
60
+ readonly id: string;
61
+ readonly organizationId: string;
62
+ readonly patientId: string;
63
+ readonly appointmentId: string | null;
64
+ readonly locationId: string | null;
65
+ readonly practitionerId: string | null;
66
+ readonly status: string;
67
+ readonly priority: number;
68
+ readonly queueNumber: number | null;
69
+ readonly checkedInAt: string;
70
+ readonly calledAt: string | null;
71
+ readonly startedAt: string | null;
72
+ readonly completedAt: string | null;
73
+ readonly note: string | null;
74
+ readonly createdAt: string;
75
+ readonly updatedAt: string;
76
+ }>;
77
+ complete: (id: string, options?: RequestOptions) => Promise<{
78
+ readonly id: string;
79
+ readonly organizationId: string;
80
+ readonly patientId: string;
81
+ readonly appointmentId: string | null;
82
+ readonly locationId: string | null;
83
+ readonly practitionerId: string | null;
84
+ readonly status: string;
85
+ readonly priority: number;
86
+ readonly queueNumber: number | null;
87
+ readonly checkedInAt: string;
88
+ readonly calledAt: string | null;
89
+ readonly startedAt: string | null;
90
+ readonly completedAt: string | null;
91
+ readonly note: string | null;
92
+ readonly createdAt: string;
93
+ readonly updatedAt: string;
94
+ }>;
95
+ noShow: (id: string, options?: RequestOptions) => Promise<{
96
+ readonly id: string;
97
+ readonly organizationId: string;
98
+ readonly patientId: string;
99
+ readonly appointmentId: string | null;
100
+ readonly locationId: string | null;
101
+ readonly practitionerId: string | null;
102
+ readonly status: string;
103
+ readonly priority: number;
104
+ readonly queueNumber: number | null;
105
+ readonly checkedInAt: string;
106
+ readonly calledAt: string | null;
107
+ readonly startedAt: string | null;
108
+ readonly completedAt: string | null;
109
+ readonly note: string | null;
110
+ readonly createdAt: string;
111
+ readonly updatedAt: string;
112
+ }>;
113
+ board: (query?: IntegrationQueries["GET /queue/board"], options?: RequestOptions) => Promise<{
114
+ readonly waiting: ReadonlyArray<{
115
+ readonly "id": string;
116
+ readonly "organizationId": string;
117
+ readonly "patientId": string;
118
+ readonly "appointmentId": string | null;
119
+ readonly "locationId": string | null;
120
+ readonly "practitionerId": string | null;
121
+ readonly "status": string;
122
+ readonly "priority": number;
123
+ readonly "queueNumber": number | null;
124
+ readonly "checkedInAt": string;
125
+ readonly "calledAt": string | null;
126
+ readonly "startedAt": string | null;
127
+ readonly "completedAt": string | null;
128
+ readonly "note": string | null;
129
+ readonly "createdAt": string;
130
+ readonly "updatedAt": string;
131
+ }>;
132
+ readonly called: ReadonlyArray<{
133
+ readonly "id": string;
134
+ readonly "organizationId": string;
135
+ readonly "patientId": string;
136
+ readonly "appointmentId": string | null;
137
+ readonly "locationId": string | null;
138
+ readonly "practitionerId": string | null;
139
+ readonly "status": string;
140
+ readonly "priority": number;
141
+ readonly "queueNumber": number | null;
142
+ readonly "checkedInAt": string;
143
+ readonly "calledAt": string | null;
144
+ readonly "startedAt": string | null;
145
+ readonly "completedAt": string | null;
146
+ readonly "note": string | null;
147
+ readonly "createdAt": string;
148
+ readonly "updatedAt": string;
149
+ }>;
150
+ readonly inProgress: ReadonlyArray<{
151
+ readonly "id": string;
152
+ readonly "organizationId": string;
153
+ readonly "patientId": string;
154
+ readonly "appointmentId": string | null;
155
+ readonly "locationId": string | null;
156
+ readonly "practitionerId": string | null;
157
+ readonly "status": string;
158
+ readonly "priority": number;
159
+ readonly "queueNumber": number | null;
160
+ readonly "checkedInAt": string;
161
+ readonly "calledAt": string | null;
162
+ readonly "startedAt": string | null;
163
+ readonly "completedAt": string | null;
164
+ readonly "note": string | null;
165
+ readonly "createdAt": string;
166
+ readonly "updatedAt": string;
167
+ }>;
168
+ readonly completed: ReadonlyArray<{
169
+ readonly "id": string;
170
+ readonly "organizationId": string;
171
+ readonly "patientId": string;
172
+ readonly "appointmentId": string | null;
173
+ readonly "locationId": string | null;
174
+ readonly "practitionerId": string | null;
175
+ readonly "status": string;
176
+ readonly "priority": number;
177
+ readonly "queueNumber": number | null;
178
+ readonly "checkedInAt": string;
179
+ readonly "calledAt": string | null;
180
+ readonly "startedAt": string | null;
181
+ readonly "completedAt": string | null;
182
+ readonly "note": string | null;
183
+ readonly "createdAt": string;
184
+ readonly "updatedAt": string;
185
+ }>;
186
+ }>;
187
+ stats: (query?: IntegrationQueries["GET /queue/stats"], options?: RequestOptions) => Promise<readonly {
188
+ readonly status: string;
189
+ readonly count: number;
190
+ readonly avgWaitMinutes: number | null;
191
+ }[]>;
192
+ };
193
+ pharmacy: {
194
+ stock: (query?: IntegrationQueries["GET /pharmacy/stock"], options?: RequestOptions) => Promise<readonly {
195
+ readonly id: string;
196
+ readonly organizationId: string;
197
+ readonly medicationId: string;
198
+ readonly locationId: string;
199
+ readonly quantity: string | number;
200
+ readonly minQuantity: number | null;
201
+ readonly maxQuantity: number | null;
202
+ readonly lotNumber: string | null;
203
+ readonly expirationDate: string | null;
204
+ readonly lastRestockedAt: string | null;
205
+ readonly createdAt: string;
206
+ readonly updatedAt: string;
207
+ }[]>;
208
+ restock: (body: IntegrationInputs["POST /pharmacy/restock"], options?: RequestOptions) => Promise<{
209
+ readonly id: string;
210
+ readonly organizationId: string;
211
+ readonly medicationId: string;
212
+ readonly locationId: string;
213
+ readonly quantity: string | number;
214
+ readonly minQuantity: number | null;
215
+ readonly maxQuantity: number | null;
216
+ readonly lotNumber: string | null;
217
+ readonly expirationDate: string | null;
218
+ readonly lastRestockedAt: string | null;
219
+ readonly createdAt: string;
220
+ readonly updatedAt: string;
221
+ }>;
222
+ dispense: (body: IntegrationInputs["POST /pharmacy/dispense"], options?: RequestOptions) => Promise<{
223
+ readonly id: string;
224
+ readonly organizationId: string;
225
+ readonly medicationId: string;
226
+ readonly locationId: string;
227
+ readonly quantity: string | number;
228
+ readonly minQuantity: number | null;
229
+ readonly maxQuantity: number | null;
230
+ readonly lotNumber: string | null;
231
+ readonly expirationDate: string | null;
232
+ readonly lastRestockedAt: string | null;
233
+ readonly createdAt: string;
234
+ readonly updatedAt: string;
235
+ }>;
236
+ adjust: (body: IntegrationInputs["POST /pharmacy/adjust"], options?: RequestOptions) => Promise<{
237
+ readonly id: string;
238
+ readonly organizationId: string;
239
+ readonly medicationId: string;
240
+ readonly locationId: string;
241
+ readonly quantity: string | number;
242
+ readonly minQuantity: number | null;
243
+ readonly maxQuantity: number | null;
244
+ readonly lotNumber: string | null;
245
+ readonly expirationDate: string | null;
246
+ readonly lastRestockedAt: string | null;
247
+ readonly createdAt: string;
248
+ readonly updatedAt: string;
249
+ }>;
250
+ lowStock: (query?: IntegrationQueries["GET /pharmacy/low-stock"], options?: RequestOptions) => Promise<readonly {
251
+ readonly id: string;
252
+ readonly organizationId: string;
253
+ readonly medicationId: string;
254
+ readonly locationId: string;
255
+ readonly quantity: string | number;
256
+ readonly minQuantity: number | null;
257
+ readonly maxQuantity: number | null;
258
+ readonly lotNumber: string | null;
259
+ readonly expirationDate: string | null;
260
+ readonly lastRestockedAt: string | null;
261
+ readonly createdAt: string;
262
+ readonly updatedAt: string;
263
+ }[]>;
264
+ expiring: (query?: IntegrationQueries["GET /pharmacy/expiring"], options?: RequestOptions) => Promise<readonly {
265
+ readonly id: string;
266
+ readonly organizationId: string;
267
+ readonly medicationId: string;
268
+ readonly locationId: string;
269
+ readonly quantity: string | number;
270
+ readonly minQuantity: number | null;
271
+ readonly maxQuantity: number | null;
272
+ readonly lotNumber: string | null;
273
+ readonly expirationDate: string | null;
274
+ readonly lastRestockedAt: string | null;
275
+ readonly createdAt: string;
276
+ readonly updatedAt: string;
277
+ }[]>;
278
+ };
279
+ };
@@ -0,0 +1,43 @@
1
+ import { queryPath, validSegment } from "./fhir.js";
2
+ import { clinicalWorkflowStatuses } from "./integration-contract.js";
3
+ import { EsusError } from "./transport.js";
4
+ export function clinicalWorkflows(request) {
5
+ async function call(route, { id, query, body, signal }) {
6
+ const separator = route.indexOf(" ");
7
+ const method = route.slice(0, separator);
8
+ let path = route.slice(separator + 1);
9
+ if (path.includes(":id")) {
10
+ if (!validSegment(id))
11
+ throw new TypeError("Invalid queue entry ID");
12
+ path = path.replace(":id", id);
13
+ }
14
+ const result = await request(query ? queryPath(path, query) : path, {
15
+ method, signal,
16
+ ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
17
+ });
18
+ if (result.response.status !== clinicalWorkflowStatuses[route] || result.body === null || typeof result.body !== "object") {
19
+ throw new EsusError("Esus returned an invalid workflow response", result.response.status, result.response.headers.get("x-request-id"));
20
+ }
21
+ return result.body;
22
+ }
23
+ return {
24
+ queue: {
25
+ checkIn: (body, options) => call("POST /queue/check-in", { ...options, body }),
26
+ waiting: (query, options) => call("GET /queue/waiting", { ...options, query }),
27
+ callNext: (body = {}, options) => call("POST /queue/call-next", { ...options, body }),
28
+ start: (id, options) => call("POST /queue/:id/start", { ...options, id }),
29
+ complete: (id, options) => call("POST /queue/:id/complete", { ...options, id }),
30
+ noShow: (id, options) => call("POST /queue/:id/no-show", { ...options, id }),
31
+ board: (query, options) => call("GET /queue/board", { ...options, query }),
32
+ stats: (query, options) => call("GET /queue/stats", { ...options, query }),
33
+ },
34
+ pharmacy: {
35
+ stock: (query, options) => call("GET /pharmacy/stock", { ...options, query }),
36
+ restock: (body, options) => call("POST /pharmacy/restock", { ...options, body }),
37
+ dispense: (body, options) => call("POST /pharmacy/dispense", { ...options, body }),
38
+ adjust: (body, options) => call("POST /pharmacy/adjust", { ...options, body }),
39
+ lowStock: (query, options) => call("GET /pharmacy/low-stock", { ...options, query }),
40
+ expiring: (query, options) => call("GET /pharmacy/expiring", { ...options, query }),
41
+ },
42
+ };
43
+ }
@@ -0,0 +1,24 @@
1
+ import type { createServiceClient } from "./server.js";
2
+ import { type RequestOptions } from "./transport.js";
3
+ export declare const integrationCapabilities: readonly ["account-email", "app-sessions", "clinical-workflows", "files", "organization", "public-status", "tenant-apps", "webhooks"];
4
+ export type IntegrationCapability = typeof integrationCapabilities[number];
5
+ export type CapabilityCheck = {
6
+ capability: IntegrationCapability;
7
+ status: "missing" | "configured" | "verified" | "denied" | "failed";
8
+ detail: string;
9
+ };
10
+ type Service = ReturnType<typeof createServiceClient>;
11
+ type Diagnostics = RequestOptions & {
12
+ url: string;
13
+ capabilities: readonly IntegrationCapability[];
14
+ service?: Service;
15
+ settings: {
16
+ emailAppId?: string;
17
+ sessionAppId?: string;
18
+ webhookAppId?: string;
19
+ webhookSecret?: boolean;
20
+ testFileId?: string;
21
+ };
22
+ };
23
+ export declare function diagnoseCapabilities({ url, capabilities, service, settings, signal }: Diagnostics): Promise<CapabilityCheck[]>;
24
+ export {};