@medplum/core 0.5.2 → 0.9.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.
package/dist/cjs/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.medplum = global.medplum || {}, global.medplum.core = {})));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- /*! *****************************************************************************
7
+ /******************************************************************************
8
8
  Copyright (c) Microsoft Corporation.
9
9
 
10
10
  Permission to use, copy, modify, and/or distribute this software for any
@@ -173,6 +173,7 @@
173
173
  * @return Human friendly display string.
174
174
  */
175
175
  function getDisplayString(resource) {
176
+ var _a, _b;
176
177
  if (isProfileResource(resource)) {
177
178
  const profileName = getProfileResourceDisplayString(resource);
178
179
  if (profileName) {
@@ -185,6 +186,11 @@
185
186
  return deviceName;
186
187
  }
187
188
  }
189
+ if (resource.resourceType === 'Observation') {
190
+ if ('code' in resource && ((_a = resource.code) === null || _a === void 0 ? void 0 : _a.text)) {
191
+ return (_b = resource.code) === null || _b === void 0 ? void 0 : _b.text;
192
+ }
193
+ }
188
194
  if (resource.resourceType === 'User') {
189
195
  if (resource.email) {
190
196
  return resource.email;
@@ -229,12 +235,25 @@
229
235
  const photos = resource.photo;
230
236
  if (photos) {
231
237
  for (const photo of photos) {
232
- if (photo.url && photo.contentType && photo.contentType.startsWith('image/')) {
233
- return photo.url;
238
+ const url = getPhotoImageSrc(photo);
239
+ if (url) {
240
+ return url;
234
241
  }
235
242
  }
236
243
  }
237
244
  }
245
+ if (resource.resourceType === 'Bot' && resource.photo) {
246
+ const url = getPhotoImageSrc(resource.photo);
247
+ if (url) {
248
+ return url;
249
+ }
250
+ }
251
+ return undefined;
252
+ }
253
+ function getPhotoImageSrc(photo) {
254
+ if (photo.url && photo.contentType && photo.contentType.startsWith('image/')) {
255
+ return photo.url;
256
+ }
238
257
  return undefined;
239
258
  }
240
259
  /**
@@ -247,6 +266,96 @@
247
266
  function getDateProperty(date) {
248
267
  return date ? new Date(date) : undefined;
249
268
  }
269
+ /**
270
+ * Calculates the age in years from the birth date.
271
+ * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.
272
+ * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.
273
+ * @returns The age in years, months, and days.
274
+ */
275
+ function calculateAge(birthDateStr, endDateStr) {
276
+ const startDate = new Date(birthDateStr);
277
+ startDate.setUTCHours(0, 0, 0, 0);
278
+ const endDate = endDateStr ? new Date(endDateStr) : new Date();
279
+ endDate.setUTCHours(0, 0, 0, 0);
280
+ const startYear = startDate.getUTCFullYear();
281
+ const startMonth = startDate.getUTCMonth();
282
+ const startDay = startDate.getUTCDate();
283
+ const endYear = endDate.getUTCFullYear();
284
+ const endMonth = endDate.getUTCMonth();
285
+ const endDay = endDate.getUTCDate();
286
+ let years = endYear - startYear;
287
+ if (endMonth < startMonth || (endMonth === startMonth && endDay < startDay)) {
288
+ years--;
289
+ }
290
+ let months = endYear * 12 + endMonth - (startYear * 12 + startMonth);
291
+ if (endDay < startDay) {
292
+ months--;
293
+ }
294
+ const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
295
+ return { years, months, days };
296
+ }
297
+ /**
298
+ * Calculates the age string for display using the age appropriate units.
299
+ * If the age is greater than or equal to 2 years, then the age is displayed in years.
300
+ * If the age is greater than or equal to 1 month, then the age is displayed in months.
301
+ * Otherwise, the age is displayed in days.
302
+ * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.
303
+ * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.
304
+ * @returns The age string.
305
+ */
306
+ function calculateAgeString(birthDateStr, endDateStr) {
307
+ const { years, months, days } = calculateAge(birthDateStr, endDateStr);
308
+ if (years >= 2) {
309
+ return years.toString().padStart(3, '0') + 'Y';
310
+ }
311
+ else if (months >= 1) {
312
+ return months.toString().padStart(3, '0') + 'M';
313
+ }
314
+ else {
315
+ return days.toString().padStart(3, '0') + 'D';
316
+ }
317
+ }
318
+ /**
319
+ * Returns all questionnaire answers as a map by link ID.
320
+ * @param response The questionnaire response resource.
321
+ * @returns Questionnaire answers mapped by link ID.
322
+ */
323
+ function getQuestionnaireAnswers(response) {
324
+ const result = {};
325
+ buildQuestionnaireAnswerItems(response.item, result);
326
+ return result;
327
+ }
328
+ /**
329
+ * Recursively builds the questionnaire answer items map.
330
+ * @param item The current questionnaire response item.
331
+ * @param result The cumulative result map.
332
+ */
333
+ function buildQuestionnaireAnswerItems(items, result) {
334
+ if (items) {
335
+ for (const item of items) {
336
+ if (item.linkId && item.answer && item.answer.length > 0) {
337
+ result[item.linkId] = item.answer[0];
338
+ }
339
+ buildQuestionnaireAnswerItems(item.item, result);
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Returns an extension value by extension URLs.
345
+ * @param resource The base resource.
346
+ * @param urls Array of extension URLs. Each entry represents a nested extension.
347
+ * @returns The extension value if found; undefined otherwise.
348
+ */
349
+ function getExtensionValue(resource, ...urls) {
350
+ var _a;
351
+ // Let curr be the current resource or extension. Extensions can be nested.
352
+ let curr = resource;
353
+ // For each of the urls, try to find a matching nested extension.
354
+ for (let i = 0; i < urls.length && curr; i++) {
355
+ curr = (_a = curr === null || curr === void 0 ? void 0 : curr.extension) === null || _a === void 0 ? void 0 : _a.find((e) => e.url === urls[i]);
356
+ }
357
+ return curr === null || curr === void 0 ? void 0 : curr.valueString;
358
+ }
250
359
  /**
251
360
  * FHIR JSON stringify.
252
361
  * Removes properties with empty string values.
@@ -267,7 +376,15 @@
267
376
  * @param {*} v Property value.
268
377
  */
269
378
  function stringifyReplacer(k, v) {
270
- return isEmpty(v) ? undefined : v;
379
+ return !isArrayKey(k) && isEmpty(v) ? undefined : v;
380
+ }
381
+ /**
382
+ * Returns true if the key is an array key.
383
+ * @param k The property key.
384
+ * @returns True if the key is an array key.
385
+ */
386
+ function isArrayKey(k) {
387
+ return !!k.match(/\d+$/);
271
388
  }
272
389
  /**
273
390
  * Returns true if the value is empty (null, undefined, empty string, or empty object).
@@ -284,39 +401,78 @@
284
401
  /**
285
402
  * Resource equality.
286
403
  * Ignores meta.versionId and meta.lastUpdated.
287
- * See: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#4-deep-equality
288
404
  * @param object1 The first object.
289
405
  * @param object2 The second object.
290
406
  * @returns True if the objects are equal.
291
407
  */
292
408
  function deepEquals(object1, object2, path) {
293
- let keys1 = Object.keys(object1);
294
- let keys2 = Object.keys(object2);
295
- if (path === 'meta') {
296
- keys1 = keys1.filter((k) => k !== 'versionId' && k !== 'lastUpdated' && k !== 'author');
297
- keys2 = keys2.filter((k) => k !== 'versionId' && k !== 'lastUpdated' && k !== 'author');
409
+ if (object1 === object2) {
410
+ return true;
411
+ }
412
+ if (isEmpty(object1) && isEmpty(object2)) {
413
+ return true;
414
+ }
415
+ if (isEmpty(object1) || isEmpty(object2)) {
416
+ return false;
417
+ }
418
+ if (Array.isArray(object1) && Array.isArray(object2)) {
419
+ return deepEqualsArray(object1, object2);
420
+ }
421
+ if (Array.isArray(object1) || Array.isArray(object2)) {
422
+ return false;
298
423
  }
299
- if (keys1.length !== keys2.length) {
424
+ if (isObject(object1) && isObject(object2)) {
425
+ return deepEqualsObject(object1, object2, path);
426
+ }
427
+ if (isObject(object1) || isObject(object2)) {
428
+ return false;
429
+ }
430
+ return false;
431
+ }
432
+ function deepEqualsArray(array1, array2) {
433
+ if (array1.length !== array2.length) {
300
434
  return false;
301
435
  }
302
- for (const key of keys1) {
436
+ for (let i = 0; i < array1.length; i++) {
437
+ if (!deepEquals(array1[i], array2[i])) {
438
+ return false;
439
+ }
440
+ }
441
+ return true;
442
+ }
443
+ function deepEqualsObject(object1, object2, path) {
444
+ const keySet = new Set();
445
+ Object.keys(object1).forEach((k) => keySet.add(k));
446
+ Object.keys(object2).forEach((k) => keySet.add(k));
447
+ if (path === 'meta') {
448
+ keySet.delete('versionId');
449
+ keySet.delete('lastUpdated');
450
+ keySet.delete('author');
451
+ }
452
+ for (const key of keySet) {
303
453
  const val1 = object1[key];
304
454
  const val2 = object2[key];
305
- if (isObject(val1) && isObject(val2)) {
306
- if (!deepEquals(val1, val2, key)) {
307
- return false;
308
- }
309
- }
310
- else {
311
- if (val1 !== val2) {
312
- return false;
313
- }
455
+ if (!deepEquals(val1, val2, key)) {
456
+ return false;
314
457
  }
315
458
  }
316
459
  return true;
317
460
  }
318
- function isObject(object) {
319
- return object !== null && typeof object === 'object';
461
+ /**
462
+ * Returns true if the input is an object.
463
+ * @param object The candidate object.
464
+ * @returns True if the input is a non-null non-undefined object.
465
+ */
466
+ function isObject(obj) {
467
+ return obj !== null && typeof obj === 'object';
468
+ }
469
+ /**
470
+ * Returns true if the input array is an array of strings.
471
+ * @param arr Input array.
472
+ * @returns True if the input array is an array of strings.
473
+ */
474
+ function isStringArray(arr) {
475
+ return arr.every((e) => typeof e === 'string');
320
476
  }
321
477
  // Precompute hex octets
322
478
  // See: https://stackoverflow.com/a/55200387
@@ -420,7 +576,7 @@
420
576
  */
421
577
  function decodePayload(payload) {
422
578
  const cleanedPayload = payload.replace(/-/g, '+').replace(/_/g, '/');
423
- const decodedPayload = window.atob(cleanedPayload);
579
+ const decodedPayload = decodeBase64(cleanedPayload);
424
580
  const uriEncodedPayload = Array.from(decodedPayload).reduce((acc, char) => {
425
581
  const uriEncodedChar = ('00' + char.charCodeAt(0).toString(16)).slice(-2);
426
582
  return `${acc}%${uriEncodedChar}`;
@@ -428,6 +584,15 @@
428
584
  const jsonPayload = decodeURIComponent(uriEncodedPayload);
429
585
  return JSON.parse(jsonPayload);
430
586
  }
587
+ function decodeBase64(data) {
588
+ if (typeof window !== 'undefined') {
589
+ return window.atob(data);
590
+ }
591
+ if (typeof Buffer !== 'undefined') {
592
+ return Buffer.from(data, 'base64').toString('binary');
593
+ }
594
+ throw new Error('Unable to decode base64');
595
+ }
431
596
  /**
432
597
  * Parses the JWT payload.
433
598
  * @param token JWT token
@@ -586,6 +751,7 @@
586
751
  }
587
752
  }
588
753
 
754
+ const DEFAULT_SEARCH_COUNT = 20;
589
755
  /**
590
756
  * Search operators.
591
757
  * These operators represent "modifiers" and "prefixes" in FHIR search.
@@ -640,10 +806,11 @@
640
806
  *
641
807
  * See the FHIR search spec: http://hl7.org/fhir/r4/search.html
642
808
  *
643
- * @param location The URL to parse.
809
+ * @param url The URL to parse.
644
810
  * @returns Parsed search definition.
645
811
  */
646
- function parseSearchDefinition(location) {
812
+ function parseSearchDefinition(url) {
813
+ const location = new URL(url, 'https://example.com/');
647
814
  const resourceType = location.pathname
648
815
  .replace(/(^\/)|(\/$)/g, '') // Remove leading and trailing slashes
649
816
  .split('/')
@@ -652,15 +819,15 @@
652
819
  let filters = undefined;
653
820
  let sortRules = undefined;
654
821
  let fields = undefined;
655
- let page = undefined;
822
+ let offset = undefined;
656
823
  let count = undefined;
657
824
  let total = undefined;
658
825
  params.forEach((value, key) => {
659
826
  if (key === '_fields') {
660
827
  fields = value.split(',');
661
828
  }
662
- else if (key === '_page') {
663
- page = parseInt(value);
829
+ else if (key === '_offset') {
830
+ offset = parseInt(value);
664
831
  }
665
832
  else if (key === '_count') {
666
833
  count = parseInt(value);
@@ -681,7 +848,7 @@
681
848
  resourceType,
682
849
  filters,
683
850
  fields,
684
- page,
851
+ offset,
685
852
  count,
686
853
  total,
687
854
  sortRules,
@@ -757,13 +924,13 @@
757
924
  if (definition.sortRules && definition.sortRules.length > 0) {
758
925
  params.push(formatSortRules(definition.sortRules));
759
926
  }
760
- if (definition.page && definition.page > 0) {
761
- params.push('_page=' + definition.page);
927
+ if (definition.offset !== undefined) {
928
+ params.push('_offset=' + definition.offset);
762
929
  }
763
- if (definition.count && definition.count > 0) {
930
+ if (definition.count !== undefined) {
764
931
  params.push('_count=' + definition.count);
765
932
  }
766
- if (definition.total) {
933
+ if (definition.total !== undefined) {
767
934
  params.push('_total=' + encodeURIComponent(definition.total));
768
935
  }
769
936
  if (params.length === 0) {
@@ -1072,13 +1239,61 @@
1072
1239
 
1073
1240
  // PKCE auth ased on:
1074
1241
  // https://aws.amazon.com/blogs/security/how-to-add-authentication-single-page-web-application-with-amazon-cognito-oauth2-implementation/
1075
- var _MedplumClient_instances, _MedplumClient_fetch, _MedplumClient_storage, _MedplumClient_schema, _MedplumClient_resourceCache, _MedplumClient_baseUrl, _MedplumClient_clientId, _MedplumClient_authorizeUrl, _MedplumClient_tokenUrl, _MedplumClient_logoutUrl, _MedplumClient_onUnauthenticated, _MedplumClient_accessToken, _MedplumClient_refreshToken, _MedplumClient_refreshPromise, _MedplumClient_profilePromise, _MedplumClient_profile, _MedplumClient_config, _MedplumClient_addLogin, _MedplumClient_refreshProfile, _MedplumClient_request, _MedplumClient_buildFetchOptions, _MedplumClient_handleUnauthenticated, _MedplumClient_startPkce, _MedplumClient_requestAuthorization, _MedplumClient_refresh, _MedplumClient_fetchTokens, _MedplumClient_verifyTokens, _MedplumClient_setupStorageListener;
1242
+ var _MedplumClient_instances, _MedplumClient_fetch, _MedplumClient_storage, _MedplumClient_schema, _MedplumClient_resourceCache, _MedplumClient_baseUrl, _MedplumClient_clientId, _MedplumClient_authorizeUrl, _MedplumClient_tokenUrl, _MedplumClient_logoutUrl, _MedplumClient_onUnauthenticated, _MedplumClient_accessToken, _MedplumClient_refreshToken, _MedplumClient_refreshPromise, _MedplumClient_profilePromise, _MedplumClient_profile, _MedplumClient_config, _MedplumClient_addLogin, _MedplumClient_refreshProfile, _MedplumClient_request, _MedplumClient_addFetchOptionsDefaults, _MedplumClient_setRequestContentType, _MedplumClient_setRequestBody, _MedplumClient_handleUnauthenticated, _MedplumClient_startPkce, _MedplumClient_requestAuthorization, _MedplumClient_refresh, _MedplumClient_fetchTokens, _MedplumClient_verifyTokens, _MedplumClient_setupStorageListener;
1076
1243
  const DEFAULT_BASE_URL = 'https://api.medplum.com/';
1077
1244
  const DEFAULT_SCOPE = 'launch/patient openid fhirUser offline_access user/*.*';
1078
1245
  const DEFAULT_RESOURCE_CACHE_SIZE = 1000;
1079
1246
  const JSON_CONTENT_TYPE = 'application/json';
1080
1247
  const FHIR_CONTENT_TYPE = 'application/fhir+json';
1081
1248
  const PATCH_CONTENT_TYPE = 'application/json-patch+json';
1249
+ /**
1250
+ * The MedplumClient class provides a client for the Medplum FHIR server.
1251
+ *
1252
+ * The client can be used in the browser, in a NodeJS application, or in a Medplum Bot.
1253
+ *
1254
+ * The client provides helpful methods for common operations such as:
1255
+ * 1) Authenticating
1256
+ * 2) Creating resources
1257
+ * 2) Reading resources
1258
+ * 3) Updating resources
1259
+ * 5) Deleting resources
1260
+ * 6) Searching
1261
+ * 7) Making GraphQL queries
1262
+ *
1263
+ * Here is a quick example of how to use the client:
1264
+ *
1265
+ * ```typescript
1266
+ * import { MedplumClient } from '@medplum/core';
1267
+ * const medplum = new MedplumClient();
1268
+ * ```
1269
+ *
1270
+ * Create a `Patient`:
1271
+ *
1272
+ * ```typescript
1273
+ * const patient = await medplum.createResource({
1274
+ * resourceType: 'Patient',
1275
+ * name: [{
1276
+ * given: ['Alice'],
1277
+ * family: 'Smith'
1278
+ * }]
1279
+ * });
1280
+ * ```
1281
+ *
1282
+ * Read a `Patient` by ID:
1283
+ *
1284
+ * ```typescript
1285
+ * const patient = await medplum.readResource('Patient', '123');
1286
+ * console.log(patient.name[0].given[0]);
1287
+ * ```
1288
+ *
1289
+ * Search for a `Patient` by name:
1290
+ *
1291
+ * ```typescript
1292
+ * const bundle = await medplum.search('Patient?name=Alice');
1293
+ * console.log(bundle.total);
1294
+ * ```
1295
+ *
1296
+ */
1082
1297
  class MedplumClient extends EventTarget {
1083
1298
  constructor(options) {
1084
1299
  var _a;
@@ -1138,17 +1353,94 @@
1138
1353
  __classPrivateFieldSet(this, _MedplumClient_config, undefined, "f");
1139
1354
  this.dispatchEvent({ type: 'change' });
1140
1355
  }
1141
- get(url) {
1142
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'GET', url);
1356
+ /**
1357
+ * Makes an HTTP GET request to the specified URL.
1358
+ *
1359
+ * This is a lower level method for custom requests.
1360
+ * For common operations, we recommend using higher level methods
1361
+ * such as `readResource()`, `search()`, etc.
1362
+ *
1363
+ * @param url The target URL.
1364
+ * @param options Optional fetch options.
1365
+ * @returns Promise to the response content.
1366
+ */
1367
+ get(url, options = {}) {
1368
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'GET', url, options);
1143
1369
  }
1144
- post(url, body, contentType) {
1145
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'POST', url, contentType, body);
1370
+ /**
1371
+ * Makes an HTTP POST request to the specified URL.
1372
+ *
1373
+ * This is a lower level method for custom requests.
1374
+ * For common operations, we recommend using higher level methods
1375
+ * such as `createResource()`.
1376
+ *
1377
+ * @param url The target URL.
1378
+ * @param body The content body. Strings and `File` objects are passed directly. Other objects are converted to JSON.
1379
+ * @param contentType The content type to be included in the "Content-Type" header.
1380
+ * @param options Optional fetch options.
1381
+ * @returns Promise to the response content.
1382
+ */
1383
+ post(url, body, contentType, options = {}) {
1384
+ if (body) {
1385
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, body);
1386
+ }
1387
+ if (contentType) {
1388
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1389
+ }
1390
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'POST', url, options);
1391
+ }
1392
+ /**
1393
+ * Makes an HTTP PUT request to the specified URL.
1394
+ *
1395
+ * This is a lower level method for custom requests.
1396
+ * For common operations, we recommend using higher level methods
1397
+ * such as `updateResource()`.
1398
+ *
1399
+ * @param url The target URL.
1400
+ * @param body The content body. Strings and `File` objects are passed directly. Other objects are converted to JSON.
1401
+ * @param contentType The content type to be included in the "Content-Type" header.
1402
+ * @param options Optional fetch options.
1403
+ * @returns Promise to the response content.
1404
+ */
1405
+ put(url, body, contentType, options = {}) {
1406
+ if (body) {
1407
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, body);
1408
+ }
1409
+ if (contentType) {
1410
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1411
+ }
1412
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PUT', url, options);
1146
1413
  }
1147
- put(url, body, contentType) {
1148
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PUT', url, contentType, body);
1414
+ /**
1415
+ * Makes an HTTP PATCH request to the specified URL.
1416
+ *
1417
+ * This is a lower level method for custom requests.
1418
+ * For common operations, we recommend using higher level methods
1419
+ * such as `patchResource()`.
1420
+ *
1421
+ * @param url The target URL.
1422
+ * @param operations Array of JSONPatch operations.
1423
+ * @param options Optional fetch options.
1424
+ * @returns Promise to the response content.
1425
+ */
1426
+ patch(url, operations, options = {}) {
1427
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, operations);
1428
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, PATCH_CONTENT_TYPE);
1429
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PATCH', url, options);
1149
1430
  }
1150
- delete(url) {
1151
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'DELETE', url);
1431
+ /**
1432
+ * Makes an HTTP DELETE request to the specified URL.
1433
+ *
1434
+ * This is a lower level method for custom requests.
1435
+ * For common operations, we recommend using higher level methods
1436
+ * such as `deleteResource()`.
1437
+ *
1438
+ * @param url The target URL.
1439
+ * @param options Optional fetch options.
1440
+ * @returns Promise to the response content.
1441
+ */
1442
+ delete(url, options = {}) {
1443
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'DELETE', url, options);
1152
1444
  }
1153
1445
  /**
1154
1446
  * Tries to register a new user.
@@ -1239,11 +1531,114 @@
1239
1531
  }
1240
1532
  /**
1241
1533
  * Sends a FHIR search request.
1242
- * @param search The search query.
1534
+ *
1535
+ * Example using a FHIR search string:
1536
+ *
1537
+ * ```typescript
1538
+ * const bundle = await client.search('Patient?name=Alice');
1539
+ * console.log(bundle);
1540
+ * ```
1541
+ *
1542
+ * Example using a structured search:
1543
+ *
1544
+ * ```typescript
1545
+ * const bundle = await client.search({
1546
+ * resourceType: 'Patient',
1547
+ * filters: [{
1548
+ * code: 'name',
1549
+ * operator: 'eq',
1550
+ * value: 'Alice',
1551
+ * }]
1552
+ * });
1553
+ * console.log(bundle);
1554
+ * ```
1555
+ *
1556
+ * The return value is a FHIR bundle:
1557
+ *
1558
+ * ```json
1559
+ * {
1560
+ * "resourceType": "Bundle",
1561
+ * "type": "searchest",
1562
+ * "total": 1,
1563
+ * "entry": [
1564
+ * {
1565
+ * "resource": {
1566
+ * "resourceType": "Patient",
1567
+ * "name": [
1568
+ * {
1569
+ * "given": [
1570
+ * "George"
1571
+ * ],
1572
+ * "family": "Washington"
1573
+ * }
1574
+ * ],
1575
+ * }
1576
+ * }
1577
+ * ]
1578
+ * }
1579
+ * ```
1580
+ *
1581
+ * See FHIR search for full details: https://www.hl7.org/fhir/search.html
1582
+ *
1583
+ * @param query The search query as either a string or a structured search object.
1243
1584
  * @returns Promise to the search result bundle.
1244
1585
  */
1245
- search(search) {
1246
- return this.get(this.fhirUrl(search.resourceType) + formatSearchQuery(search));
1586
+ search(query, options = {}) {
1587
+ return this.get(typeof query === 'string' ? 'fhir/R4/' + query : this.fhirUrl(query.resourceType) + formatSearchQuery(query), options);
1588
+ }
1589
+ /**
1590
+ * Sends a FHIR search request for a single resource.
1591
+ *
1592
+ * This is a convenience method for `search()` that returns the first resource rather than a `Bundle`.
1593
+ *
1594
+ * Example using a FHIR search string:
1595
+ *
1596
+ * ```typescript
1597
+ * const patient = await client.searchOne('Patient?identifier=123');
1598
+ * console.log(patient);
1599
+ * ```
1600
+ *
1601
+ * The return value is the resource, if available; otherwise, undefined.
1602
+ *
1603
+ * See FHIR search for full details: https://www.hl7.org/fhir/search.html
1604
+ *
1605
+ * @param query The search query as either a string or a structured search object.
1606
+ * @returns Promise to the search result bundle.
1607
+ */
1608
+ searchOne(query, options = {}) {
1609
+ var _a, _b;
1610
+ return __awaiter(this, void 0, void 0, function* () {
1611
+ const search = typeof query === 'string' ? parseSearchDefinition(query) : query;
1612
+ search.count = 1;
1613
+ const bundle = yield this.search(search, options);
1614
+ return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.resource;
1615
+ });
1616
+ }
1617
+ /**
1618
+ * Sends a FHIR search request for an array of resources.
1619
+ *
1620
+ * This is a convenience method for `search()` that returns the resources as an array rather than a `Bundle`.
1621
+ *
1622
+ * Example using a FHIR search string:
1623
+ *
1624
+ * ```typescript
1625
+ * const patients = await client.searchResources('Patient?name=Alice');
1626
+ * console.log(patients);
1627
+ * ```
1628
+ *
1629
+ * The return value is an array of resources.
1630
+ *
1631
+ * See FHIR search for full details: https://www.hl7.org/fhir/search.html
1632
+ *
1633
+ * @param query The search query as either a string or a structured search object.
1634
+ * @returns Promise to the search result bundle.
1635
+ */
1636
+ searchResources(query, options = {}) {
1637
+ var _a, _b;
1638
+ return __awaiter(this, void 0, void 0, function* () {
1639
+ const bundle = yield this.search(query, options);
1640
+ return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.map((entry) => entry.resource)) !== null && _b !== void 0 ? _b : [];
1641
+ });
1247
1642
  }
1248
1643
  /**
1249
1644
  * Searches a ValueSet resource using the "expand" operation.
@@ -1252,10 +1647,10 @@
1252
1647
  * @param filter The search string.
1253
1648
  * @returns Promise to expanded ValueSet.
1254
1649
  */
1255
- searchValueSet(system, filter) {
1650
+ searchValueSet(system, filter, options = {}) {
1256
1651
  return this.get(this.fhirUrl('ValueSet', '$expand') +
1257
1652
  `?url=${encodeURIComponent(system)}` +
1258
- `&filter=${encodeURIComponent(filter)}`);
1653
+ `&filter=${encodeURIComponent(filter)}`, options);
1259
1654
  }
1260
1655
  /**
1261
1656
  * Returns a cached resource if it is available.
@@ -1283,7 +1678,23 @@
1283
1678
  }
1284
1679
  return undefined;
1285
1680
  }
1286
- read(resourceType, id) {
1681
+ /**
1682
+ * Reads a resource by resource type and ID.
1683
+ *
1684
+ * Example:
1685
+ *
1686
+ * ```typescript
1687
+ * const patient = await medplum.readResource('Patient', '123');
1688
+ * console.log(patient);
1689
+ * ```
1690
+ *
1691
+ * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1692
+ *
1693
+ * @param resourceType The FHIR resource type.
1694
+ * @param id The resource ID.
1695
+ * @returns The resource if available; undefined otherwise.
1696
+ */
1697
+ readResource(resourceType, id) {
1287
1698
  const cacheKey = resourceType + '/' + id;
1288
1699
  const promise = this.get(this.fhirUrl(resourceType, id)).then((resource) => {
1289
1700
  __classPrivateFieldGet(this, _MedplumClient_resourceCache, "f").set(cacheKey, resource);
@@ -1292,18 +1703,74 @@
1292
1703
  __classPrivateFieldGet(this, _MedplumClient_resourceCache, "f").set(cacheKey, promise);
1293
1704
  return promise;
1294
1705
  }
1706
+ /**
1707
+ * Reads a resource by resource type and ID using the in-memory resource cache.
1708
+ *
1709
+ * If the resource is not available in the cache, it will be read from the server.
1710
+ *
1711
+ * Example:
1712
+ *
1713
+ * ```typescript
1714
+ * const patient = await medplum.readCached('Patient', '123');
1715
+ * console.log(patient);
1716
+ * ```
1717
+ *
1718
+ * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1719
+ *
1720
+ * @param resourceType The FHIR resource type.
1721
+ * @param id The resource ID.
1722
+ * @returns The resource if available; undefined otherwise.
1723
+ */
1295
1724
  readCached(resourceType, id) {
1296
1725
  const cached = __classPrivateFieldGet(this, _MedplumClient_resourceCache, "f").get(resourceType + '/' + id);
1297
- return cached ? Promise.resolve(cached) : this.read(resourceType, id);
1726
+ return cached ? Promise.resolve(cached) : this.readResource(resourceType, id);
1298
1727
  }
1728
+ /**
1729
+ * Reads a resource by `Reference`.
1730
+ *
1731
+ * This is a convenience method for `readResource()` that accepts a `Reference` object.
1732
+ *
1733
+ * Example:
1734
+ *
1735
+ * ```typescript
1736
+ * const serviceRequest = await medplum.readResource('ServiceRequest', '123');
1737
+ * const patient = await medplum.readReference(serviceRequest.subject);
1738
+ * console.log(patient);
1739
+ * ```
1740
+ *
1741
+ * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1742
+ *
1743
+ * @param reference The FHIR reference object.
1744
+ * @returns The resource if available; undefined otherwise.
1745
+ */
1299
1746
  readReference(reference) {
1300
1747
  const refString = reference === null || reference === void 0 ? void 0 : reference.reference;
1301
1748
  if (!refString) {
1302
1749
  return Promise.reject('Missing reference');
1303
1750
  }
1304
1751
  const [resourceType, id] = refString.split('/');
1305
- return this.read(resourceType, id);
1752
+ return this.readResource(resourceType, id);
1306
1753
  }
1754
+ /**
1755
+ * Reads a resource by `Reference` using the in-memory resource cache.
1756
+ *
1757
+ * This is a convenience method for `readResource()` that accepts a `Reference` object.
1758
+ *
1759
+ * If the resource is not available in the cache, it will be read from the server.
1760
+ *
1761
+ * Example:
1762
+ *
1763
+ * ```typescript
1764
+ * const serviceRequest = await medplum.readResource('ServiceRequest', '123');
1765
+ * const patient = await medplum.readCachedReference(serviceRequest.subject);
1766
+ * console.log(patient);
1767
+ * ```
1768
+ *
1769
+ * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1770
+ *
1771
+ * @param reference The FHIR reference object.
1772
+ * @returns The resource if available; undefined otherwise.
1773
+ */
1307
1774
  readCachedReference(reference) {
1308
1775
  const refString = reference === null || reference === void 0 ? void 0 : reference.reference;
1309
1776
  if (!refString) {
@@ -1372,38 +1839,181 @@
1372
1839
  return __classPrivateFieldGet(this, _MedplumClient_schema, "f");
1373
1840
  });
1374
1841
  }
1842
+ /**
1843
+ * Reads resource history by resource type and ID.
1844
+ *
1845
+ * The return value is a bundle of all versions of the resource.
1846
+ *
1847
+ * Example:
1848
+ *
1849
+ * ```typescript
1850
+ * const history = await medplum.readHistory('Patient', '123');
1851
+ * console.log(history);
1852
+ * ```
1853
+ *
1854
+ * See the FHIR "history" operation for full details: https://www.hl7.org/fhir/http.html#history
1855
+ *
1856
+ * @param resourceType The FHIR resource type.
1857
+ * @param id The resource ID.
1858
+ * @returns The resource if available; undefined otherwise.
1859
+ */
1375
1860
  readHistory(resourceType, id) {
1376
1861
  return this.get(this.fhirUrl(resourceType, id, '_history'));
1377
1862
  }
1863
+ /**
1864
+ * Reads a specific version of a resource by resource type, ID, and version ID.
1865
+ *
1866
+ * Example:
1867
+ *
1868
+ * ```typescript
1869
+ * const version = await medplum.readVersion('Patient', '123', '456');
1870
+ * console.log(version);
1871
+ * ```
1872
+ *
1873
+ * See the FHIR "vread" operation for full details: https://www.hl7.org/fhir/http.html#vread
1874
+ *
1875
+ * @param resourceType The FHIR resource type.
1876
+ * @param id The resource ID.
1877
+ * @returns The resource if available; undefined otherwise.
1878
+ */
1879
+ readVersion(resourceType, id, vid) {
1880
+ return this.get(this.fhirUrl(resourceType, id, '_history', vid));
1881
+ }
1378
1882
  readPatientEverything(id) {
1379
1883
  return this.get(this.fhirUrl('Patient', id, '$everything'));
1380
1884
  }
1381
- create(resource) {
1885
+ /**
1886
+ * Creates a new FHIR resource.
1887
+ *
1888
+ * The return value is the newly created resource, including the ID and meta.
1889
+ *
1890
+ * Example:
1891
+ *
1892
+ * ```typescript
1893
+ * const result = await medplum.createResource({
1894
+ * resourceType: 'Patient',
1895
+ * name: [{
1896
+ * family: 'Smith',
1897
+ * given: ['John']
1898
+ * }]
1899
+ * });
1900
+ * console.log(result.id);
1901
+ * ```
1902
+ *
1903
+ * See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create
1904
+ *
1905
+ * @param resource The FHIR resource to create.
1906
+ * @returns The result of the create operation.
1907
+ */
1908
+ createResource(resource) {
1382
1909
  if (!resource.resourceType) {
1383
- throw new Error('Missing resourceType');
1910
+ return Promise.reject('Missing resourceType');
1384
1911
  }
1385
1912
  return this.post(this.fhirUrl(resource.resourceType), resource);
1386
1913
  }
1914
+ /**
1915
+ * Creates a FHIR `Binary` resource with the provided data content.
1916
+ *
1917
+ * The return value is the newly created resource, including the ID and meta.
1918
+ *
1919
+ * The `data` parameter can be a string or a `File` object.
1920
+ *
1921
+ * A `File` object often comes from a `<input type="file">` element.
1922
+ *
1923
+ * Example:
1924
+ *
1925
+ * ```typescript
1926
+ * const result = await medplum.createBinary(myFile, 'test.jpg', 'image/jpeg');
1927
+ * console.log(result.id);
1928
+ * ```
1929
+ *
1930
+ * See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create
1931
+ *
1932
+ * @param resource The FHIR resource to create.
1933
+ * @returns The result of the create operation.
1934
+ */
1387
1935
  createBinary(data, filename, contentType) {
1388
1936
  return this.post(this.fhirUrl('Binary') + '?_filename=' + encodeURIComponent(filename), data, contentType);
1389
1937
  }
1390
- update(resource) {
1938
+ /**
1939
+ * Updates a FHIR resource.
1940
+ *
1941
+ * The return value is the updated resource, including the ID and meta.
1942
+ *
1943
+ * Example:
1944
+ *
1945
+ * ```typescript
1946
+ * const result = await medplum.updateResource({
1947
+ * resourceType: 'Patient',
1948
+ * id: '123',
1949
+ * name: [{
1950
+ * family: 'Smith',
1951
+ * given: ['John']
1952
+ * }]
1953
+ * });
1954
+ * console.log(result.meta.versionId);
1955
+ * ```
1956
+ *
1957
+ * See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#update
1958
+ *
1959
+ * @param resource The FHIR resource to update.
1960
+ * @returns The result of the update operation.
1961
+ */
1962
+ updateResource(resource) {
1391
1963
  if (!resource.resourceType) {
1392
- throw new Error('Missing resourceType');
1964
+ return Promise.reject('Missing resourceType');
1393
1965
  }
1394
1966
  if (!resource.id) {
1395
- throw new Error('Missing id');
1967
+ return Promise.reject('Missing id');
1396
1968
  }
1397
1969
  return this.put(this.fhirUrl(resource.resourceType, resource.id), resource);
1398
1970
  }
1399
- patch(resourceType, id, operations) {
1400
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PATCH', this.fhirUrl(resourceType, id), PATCH_CONTENT_TYPE, operations);
1971
+ /**
1972
+ * Updates a FHIR resource using JSONPatch operations.
1973
+ *
1974
+ * The return value is the updated resource, including the ID and meta.
1975
+ *
1976
+ * Example:
1977
+ *
1978
+ * ```typescript
1979
+ * const result = await medplum.patchResource('Patient', '123', [
1980
+ * {op: 'replace', path: '/name/0/family', value: 'Smith'},
1981
+ * ]);
1982
+ * console.log(result.meta.versionId);
1983
+ * ```
1984
+ *
1985
+ * See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#patch
1986
+ *
1987
+ * See the JSONPatch specification for full details: https://tools.ietf.org/html/rfc6902
1988
+ *
1989
+ * @param resourceType The FHIR resource type.
1990
+ * @param id The resource ID.
1991
+ * @param operations The JSONPatch operations.
1992
+ * @returns The result of the patch operations.
1993
+ */
1994
+ patchResource(resourceType, id, operations) {
1995
+ return this.patch(this.fhirUrl(resourceType, id), operations);
1401
1996
  }
1997
+ /**
1998
+ * Deletes a FHIR resource by resource type and ID.
1999
+ *
2000
+ * Example:
2001
+ *
2002
+ * ```typescript
2003
+ * await medplum.deleteResource('Patient', '123');
2004
+ * ```
2005
+ *
2006
+ * See the FHIR "delete" operation for full details: https://www.hl7.org/fhir/http.html#delete
2007
+ *
2008
+ * @param resourceType The FHIR resource type.
2009
+ * @param id The resource ID.
2010
+ * @returns The result of the delete operation.
2011
+ */
1402
2012
  deleteResource(resourceType, id) {
1403
2013
  return this.delete(this.fhirUrl(resourceType, id));
1404
2014
  }
1405
- graphql(query) {
1406
- return this.post(this.fhirUrl('$graphql'), { query }, JSON_CONTENT_TYPE);
2015
+ graphql(query, options) {
2016
+ return this.post(this.fhirUrl('$graphql'), { query }, JSON_CONTENT_TYPE, options);
1407
2017
  }
1408
2018
  getActiveLogin() {
1409
2019
  return __classPrivateFieldGet(this, _MedplumClient_storage, "f").getObject('activeLogin');
@@ -1421,6 +2031,12 @@
1421
2031
  yield __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_refreshProfile).call(this);
1422
2032
  });
1423
2033
  }
2034
+ setAccessToken(accessToken) {
2035
+ __classPrivateFieldSet(this, _MedplumClient_accessToken, accessToken, "f");
2036
+ __classPrivateFieldSet(this, _MedplumClient_refreshToken, undefined, "f");
2037
+ __classPrivateFieldSet(this, _MedplumClient_profile, undefined, "f");
2038
+ __classPrivateFieldSet(this, _MedplumClient_config, undefined, "f");
2039
+ }
1424
2040
  getLogins() {
1425
2041
  var _a;
1426
2042
  return (_a = __classPrivateFieldGet(this, _MedplumClient_storage, "f").getObject('logins')) !== null && _a !== void 0 ? _a : [];
@@ -1447,12 +2063,12 @@
1447
2063
  * @param url The URL to request.
1448
2064
  * @returns Promise to the response body as a blob.
1449
2065
  */
1450
- download(url) {
2066
+ download(url, options = {}) {
1451
2067
  return __awaiter(this, void 0, void 0, function* () {
1452
2068
  if (__classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f")) {
1453
2069
  yield __classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f");
1454
2070
  }
1455
- const options = __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_buildFetchOptions).call(this, 'GET');
2071
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_addFetchOptionsDefaults).call(this, options);
1456
2072
  const response = yield __classPrivateFieldGet(this, _MedplumClient_fetch, "f").call(this, url, options);
1457
2073
  return response.blob();
1458
2074
  });
@@ -1466,12 +2082,12 @@
1466
2082
  const pkceState = __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('pkceState');
1467
2083
  if (!pkceState) {
1468
2084
  this.clear();
1469
- throw new Error('Invalid PCKE state');
2085
+ return Promise.reject('Invalid PCKE state');
1470
2086
  }
1471
2087
  const codeVerifier = __classPrivateFieldGet(this, _MedplumClient_storage, "f").getString('codeVerifier');
1472
2088
  if (!codeVerifier) {
1473
2089
  this.clear();
1474
- throw new Error('Invalid PCKE code verifier');
2090
+ return Promise.reject('Invalid PCKE code verifier');
1475
2091
  }
1476
2092
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, 'grant_type=authorization_code' +
1477
2093
  (__classPrivateFieldGet(this, _MedplumClient_clientId, "f") ? '&client_id=' + encodeURIComponent(__classPrivateFieldGet(this, _MedplumClient_clientId, "f")) : '') +
@@ -1482,6 +2098,15 @@
1482
2098
  '&code=' +
1483
2099
  encodeURIComponent(code));
1484
2100
  }
2101
+ clientCredentials(clientId, clientSecret) {
2102
+ return __awaiter(this, void 0, void 0, function* () {
2103
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_fetchTokens).call(this, 'grant_type=client_credentials' +
2104
+ '&client_id=' +
2105
+ encodeURIComponent(clientId) +
2106
+ '&client_secret=' +
2107
+ encodeURIComponent(clientSecret));
2108
+ });
2109
+ }
1485
2110
  }
1486
2111
  _MedplumClient_fetch = new WeakMap(), _MedplumClient_storage = new WeakMap(), _MedplumClient_schema = new WeakMap(), _MedplumClient_resourceCache = new WeakMap(), _MedplumClient_baseUrl = new WeakMap(), _MedplumClient_clientId = new WeakMap(), _MedplumClient_authorizeUrl = new WeakMap(), _MedplumClient_tokenUrl = new WeakMap(), _MedplumClient_logoutUrl = new WeakMap(), _MedplumClient_onUnauthenticated = new WeakMap(), _MedplumClient_accessToken = new WeakMap(), _MedplumClient_refreshToken = new WeakMap(), _MedplumClient_refreshPromise = new WeakMap(), _MedplumClient_profilePromise = new WeakMap(), _MedplumClient_profile = new WeakMap(), _MedplumClient_config = new WeakMap(), _MedplumClient_instances = new WeakSet(), _MedplumClient_addLogin = function _MedplumClient_addLogin(newLogin) {
1487
2112
  const logins = this.getLogins().filter((login) => { var _a, _b; return ((_a = login.profile) === null || _a === void 0 ? void 0 : _a.reference) !== ((_b = newLogin.profile) === null || _b === void 0 ? void 0 : _b.reference); });
@@ -1502,7 +2127,7 @@
1502
2127
  }), "f");
1503
2128
  return __classPrivateFieldGet(this, _MedplumClient_profilePromise, "f");
1504
2129
  });
1505
- }, _MedplumClient_request = function _MedplumClient_request(method, url, contentType, body) {
2130
+ }, _MedplumClient_request = function _MedplumClient_request(method, url, options = {}) {
1506
2131
  return __awaiter(this, void 0, void 0, function* () {
1507
2132
  if (__classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f")) {
1508
2133
  yield __classPrivateFieldGet(this, _MedplumClient_refreshPromise, "f");
@@ -1510,48 +2135,57 @@
1510
2135
  if (!url.startsWith('http')) {
1511
2136
  url = __classPrivateFieldGet(this, _MedplumClient_baseUrl, "f") + url;
1512
2137
  }
1513
- const options = __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_buildFetchOptions).call(this, method, contentType, body);
2138
+ options.method = method;
2139
+ __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_addFetchOptionsDefaults).call(this, options);
1514
2140
  const response = yield __classPrivateFieldGet(this, _MedplumClient_fetch, "f").call(this, url, options);
1515
2141
  if (response.status === 401) {
1516
2142
  // Refresh and try again
1517
- return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_handleUnauthenticated).call(this, method, url, contentType, body);
2143
+ return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_handleUnauthenticated).call(this, method, url, options);
1518
2144
  }
1519
2145
  if (response.status === 204 || response.status === 304) {
1520
2146
  // No content or change
1521
2147
  return undefined;
1522
2148
  }
1523
2149
  const obj = yield response.json();
1524
- if (obj.resourceType === 'OperationOutcome' && !isOk(obj)) {
2150
+ if ((obj === null || obj === void 0 ? void 0 : obj.resourceType) === 'OperationOutcome' && !isOk(obj)) {
1525
2151
  return Promise.reject(obj);
1526
2152
  }
1527
2153
  return obj;
1528
2154
  });
1529
- }, _MedplumClient_buildFetchOptions = function _MedplumClient_buildFetchOptions(method, contentType, body) {
1530
- const headers = {
1531
- 'Content-Type': contentType || FHIR_CONTENT_TYPE,
1532
- };
2155
+ }, _MedplumClient_addFetchOptionsDefaults = function _MedplumClient_addFetchOptionsDefaults(options) {
2156
+ if (!options.headers) {
2157
+ options.headers = {};
2158
+ }
2159
+ const headers = options.headers;
2160
+ if (!headers['Content-Type']) {
2161
+ headers['Content-Type'] = FHIR_CONTENT_TYPE;
2162
+ }
1533
2163
  if (__classPrivateFieldGet(this, _MedplumClient_accessToken, "f")) {
1534
2164
  headers['Authorization'] = 'Bearer ' + __classPrivateFieldGet(this, _MedplumClient_accessToken, "f");
1535
2165
  }
1536
- const options = {
1537
- method: method,
1538
- cache: 'no-cache',
1539
- credentials: 'include',
1540
- headers,
1541
- };
1542
- if (body) {
1543
- if (typeof body === 'string' || (typeof File !== 'undefined' && body instanceof File)) {
1544
- options.body = body;
1545
- }
1546
- else {
1547
- options.body = stringify(body);
1548
- }
2166
+ if (!options.cache) {
2167
+ options.cache = 'no-cache';
2168
+ }
2169
+ if (!options.credentials) {
2170
+ options.credentials = 'include';
2171
+ }
2172
+ }, _MedplumClient_setRequestContentType = function _MedplumClient_setRequestContentType(options, contentType) {
2173
+ if (!options.headers) {
2174
+ options.headers = {};
2175
+ }
2176
+ const headers = options.headers;
2177
+ headers['Content-Type'] = contentType;
2178
+ }, _MedplumClient_setRequestBody = function _MedplumClient_setRequestBody(options, data) {
2179
+ if (typeof data === 'string' || (typeof File !== 'undefined' && data instanceof File)) {
2180
+ options.body = data;
1549
2181
  }
1550
- return options;
1551
- }, _MedplumClient_handleUnauthenticated = function _MedplumClient_handleUnauthenticated(method, url, contentType, body) {
2182
+ else if (data) {
2183
+ options.body = stringify(data);
2184
+ }
2185
+ }, _MedplumClient_handleUnauthenticated = function _MedplumClient_handleUnauthenticated(method, url, options) {
1552
2186
  return __awaiter(this, void 0, void 0, function* () {
1553
2187
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_refresh).call(this)
1554
- .then(() => __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, method, url, contentType, body))
2188
+ .then(() => __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, method, url, options))
1555
2189
  .catch((error) => {
1556
2190
  this.clear();
1557
2191
  if (__classPrivateFieldGet(this, _MedplumClient_onUnauthenticated, "f")) {
@@ -1573,7 +2207,7 @@
1573
2207
  }, _MedplumClient_requestAuthorization = function _MedplumClient_requestAuthorization() {
1574
2208
  return __awaiter(this, void 0, void 0, function* () {
1575
2209
  if (!__classPrivateFieldGet(this, _MedplumClient_authorizeUrl, "f")) {
1576
- throw new Error('Missing authorize URL');
2210
+ return Promise.reject('Missing authorize URL');
1577
2211
  }
1578
2212
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_startPkce).call(this);
1579
2213
  window.location.assign(__classPrivateFieldGet(this, _MedplumClient_authorizeUrl, "f") +
@@ -1668,6 +2302,316 @@
1668
2302
  return window.location.protocol + '//' + window.location.host + '/';
1669
2303
  }
1670
2304
 
2305
+ const SEGMENT_SEPARATOR = '\r';
2306
+ const FIELD_SEPARATOR = '|';
2307
+ const COMPONENT_SEPARATOR = '^';
2308
+ /**
2309
+ * The Hl7Message class represents one HL7 message.
2310
+ * A message is a collection of segments.
2311
+ * Note that we do not strictly parse messages, and only use default delimeters.
2312
+ */
2313
+ class Hl7Message {
2314
+ constructor(segments) {
2315
+ this.segments = segments;
2316
+ }
2317
+ get(index) {
2318
+ if (typeof index === 'number') {
2319
+ return this.segments[index];
2320
+ }
2321
+ return this.segments.find((s) => s.name === index);
2322
+ }
2323
+ getAll(name) {
2324
+ return this.segments.filter((s) => s.name === name);
2325
+ }
2326
+ toString() {
2327
+ return this.segments.map((s) => s.toString()).join(SEGMENT_SEPARATOR);
2328
+ }
2329
+ buildAck() {
2330
+ var _a, _b, _c, _d, _e, _f;
2331
+ const now = new Date();
2332
+ const msh = this.get('MSH');
2333
+ const sendingApp = ((_a = msh === null || msh === void 0 ? void 0 : msh.get(2)) === null || _a === void 0 ? void 0 : _a.toString()) || '';
2334
+ const sendingFacility = ((_b = msh === null || msh === void 0 ? void 0 : msh.get(3)) === null || _b === void 0 ? void 0 : _b.toString()) || '';
2335
+ const receivingApp = ((_c = msh === null || msh === void 0 ? void 0 : msh.get(4)) === null || _c === void 0 ? void 0 : _c.toString()) || '';
2336
+ const receivingFacility = ((_d = msh === null || msh === void 0 ? void 0 : msh.get(5)) === null || _d === void 0 ? void 0 : _d.toString()) || '';
2337
+ const controlId = ((_e = msh === null || msh === void 0 ? void 0 : msh.get(9)) === null || _e === void 0 ? void 0 : _e.toString()) || '';
2338
+ const versionId = ((_f = msh === null || msh === void 0 ? void 0 : msh.get(12)) === null || _f === void 0 ? void 0 : _f.toString()) || '2.5.1';
2339
+ return new Hl7Message([
2340
+ new Hl7Segment([
2341
+ 'MSH',
2342
+ '^~\\&',
2343
+ receivingApp,
2344
+ receivingFacility,
2345
+ sendingApp,
2346
+ sendingFacility,
2347
+ now.toISOString(),
2348
+ '',
2349
+ 'ACK',
2350
+ now.getTime().toString(),
2351
+ 'P',
2352
+ versionId,
2353
+ ]),
2354
+ new Hl7Segment(['MSA', 'AA', controlId, 'OK']),
2355
+ ]);
2356
+ }
2357
+ static parse(text) {
2358
+ if (!text.startsWith('MSH|^~\\&')) {
2359
+ const err = new Error('Invalid HL7 message');
2360
+ err.type = 'entity.parse.failed';
2361
+ throw err;
2362
+ }
2363
+ return new Hl7Message(text.split(/[\r\n]+/).map((line) => Hl7Segment.parse(line)));
2364
+ }
2365
+ }
2366
+ /**
2367
+ * The Hl7Segment class represents one HL7 segment.
2368
+ * A segment is a collection of fields.
2369
+ * The name field is the first field.
2370
+ * Note that we do not strictly parse messages, and only use default delimeters.
2371
+ */
2372
+ class Hl7Segment {
2373
+ constructor(fields) {
2374
+ if (isStringArray(fields)) {
2375
+ this.fields = fields.map((f) => Hl7Field.parse(f));
2376
+ }
2377
+ else {
2378
+ this.fields = fields;
2379
+ }
2380
+ this.name = this.fields[0].components[0];
2381
+ }
2382
+ get(index) {
2383
+ return this.fields[index];
2384
+ }
2385
+ toString() {
2386
+ return this.fields.map((f) => f.toString()).join(FIELD_SEPARATOR);
2387
+ }
2388
+ static parse(text) {
2389
+ return new Hl7Segment(text.split(FIELD_SEPARATOR).map((f) => Hl7Field.parse(f)));
2390
+ }
2391
+ }
2392
+ /**
2393
+ * The Hl7Field class represents one HL7 field.
2394
+ * A field is a collection of components.
2395
+ * Note that we do not strictly parse messages, and only use default delimeters.
2396
+ */
2397
+ class Hl7Field {
2398
+ constructor(components) {
2399
+ this.components = components;
2400
+ }
2401
+ get(index) {
2402
+ return this.components[index];
2403
+ }
2404
+ toString() {
2405
+ return this.components.join(COMPONENT_SEPARATOR);
2406
+ }
2407
+ static parse(text) {
2408
+ return new Hl7Field(text.split(COMPONENT_SEPARATOR));
2409
+ }
2410
+ }
2411
+
2412
+ var _LegacyRepositoryClient_client;
2413
+ /**
2414
+ * The LegacyRepositoryClient is a supplementary API client that matches the legacy "Repository" API.
2415
+ * The "Repository" API is deprecated and will be removed in a future release.
2416
+ * This LegacyRepositoryClient is also deprecated and will be removed in a future release.
2417
+ * @deprecated
2418
+ */
2419
+ class LegacyRepositoryClient {
2420
+ constructor(client) {
2421
+ _LegacyRepositoryClient_client.set(this, void 0);
2422
+ __classPrivateFieldSet(this, _LegacyRepositoryClient_client, client, "f");
2423
+ }
2424
+ /**
2425
+ * Creates a resource.
2426
+ *
2427
+ * See: https://www.hl7.org/fhir/http.html#create
2428
+ *
2429
+ * @param resource The resource to create.
2430
+ * @returns Operation outcome and the new resource.
2431
+ * @deprecated
2432
+ */
2433
+ createResource(resource) {
2434
+ return __awaiter(this, void 0, void 0, function* () {
2435
+ try {
2436
+ const result = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").createResource(resource);
2437
+ return [created, result];
2438
+ }
2439
+ catch (error) {
2440
+ return [error, undefined];
2441
+ }
2442
+ });
2443
+ }
2444
+ /**
2445
+ * Returns a resource.
2446
+ *
2447
+ * See: https://www.hl7.org/fhir/http.html#read
2448
+ *
2449
+ * @param resourceType The FHIR resource type.
2450
+ * @param id The FHIR resource ID.
2451
+ * @returns Operation outcome and a resource.
2452
+ * @deprecated
2453
+ */
2454
+ readResource(resourceType, id) {
2455
+ return __awaiter(this, void 0, void 0, function* () {
2456
+ try {
2457
+ const resource = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").readResource(resourceType, id);
2458
+ return [allOk, resource];
2459
+ }
2460
+ catch (error) {
2461
+ return [error, undefined];
2462
+ }
2463
+ });
2464
+ }
2465
+ /**
2466
+ * Returns a resource by FHIR reference.
2467
+ *
2468
+ * See: https://www.hl7.org/fhir/http.html#read
2469
+ *
2470
+ * @param reference The FHIR reference.
2471
+ * @returns Operation outcome and a resource.
2472
+ * @deprecated
2473
+ */
2474
+ readReference(reference) {
2475
+ return __awaiter(this, void 0, void 0, function* () {
2476
+ try {
2477
+ const resource = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").readReference(reference);
2478
+ return [allOk, resource];
2479
+ }
2480
+ catch (error) {
2481
+ return [error, undefined];
2482
+ }
2483
+ });
2484
+ }
2485
+ /**
2486
+ * Returns resource history.
2487
+ *
2488
+ * See: https://www.hl7.org/fhir/http.html#history
2489
+ *
2490
+ * @param resourceType The FHIR resource type.
2491
+ * @param id The FHIR resource ID.
2492
+ * @returns Operation outcome and a history bundle.
2493
+ * @deprecated
2494
+ */
2495
+ readHistory(resourceType, id) {
2496
+ return __awaiter(this, void 0, void 0, function* () {
2497
+ try {
2498
+ const resource = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").readHistory(resourceType, id);
2499
+ return [allOk, resource];
2500
+ }
2501
+ catch (error) {
2502
+ return [error, undefined];
2503
+ }
2504
+ });
2505
+ }
2506
+ /**
2507
+ * Returns a resource version.
2508
+ *
2509
+ * See: https://www.hl7.org/fhir/http.html#vread
2510
+ *
2511
+ * @param resourceType The FHIR resource type.
2512
+ * @param id The FHIR resource ID.
2513
+ * @param vid The version ID.
2514
+ * @returns Operation outcome and a resource.
2515
+ * @deprecated
2516
+ */
2517
+ readVersion(resourceType, id, vid) {
2518
+ return __awaiter(this, void 0, void 0, function* () {
2519
+ try {
2520
+ const resource = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").readVersion(resourceType, id, vid);
2521
+ return [allOk, resource];
2522
+ }
2523
+ catch (error) {
2524
+ return [error, undefined];
2525
+ }
2526
+ });
2527
+ }
2528
+ /**
2529
+ * Updates a resource.
2530
+ *
2531
+ * See: https://www.hl7.org/fhir/http.html#update
2532
+ *
2533
+ * @param resource The resource to update.
2534
+ * @returns Operation outcome and the updated resource.
2535
+ * @deprecated
2536
+ */
2537
+ updateResource(resource) {
2538
+ return __awaiter(this, void 0, void 0, function* () {
2539
+ try {
2540
+ const updated = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").updateResource(resource);
2541
+ return [allOk, updated];
2542
+ }
2543
+ catch (error) {
2544
+ return [error, undefined];
2545
+ }
2546
+ });
2547
+ }
2548
+ /**
2549
+ * Deletes a resource.
2550
+ *
2551
+ * See: https://www.hl7.org/fhir/http.html#delete
2552
+ *
2553
+ * @param resourceType The FHIR resource type.
2554
+ * @param id The resource ID.
2555
+ * @returns Operation outcome.
2556
+ * @deprecated
2557
+ */
2558
+ deleteResource(resourceType, id) {
2559
+ return __awaiter(this, void 0, void 0, function* () {
2560
+ try {
2561
+ yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").deleteResource(resourceType, id);
2562
+ return [allOk, undefined];
2563
+ }
2564
+ catch (error) {
2565
+ return [error, undefined];
2566
+ }
2567
+ });
2568
+ }
2569
+ /**
2570
+ * Patches a resource.
2571
+ *
2572
+ * See: https://www.hl7.org/fhir/http.html#patch
2573
+ *
2574
+ * @param resourceType The FHIR resource type.
2575
+ * @param id The resource ID.
2576
+ * @param patch Array of JSONPatch operations.
2577
+ * @returns Operation outcome and the resource.
2578
+ * @deprecated
2579
+ */
2580
+ patchResource(resourceType, id, patch) {
2581
+ return __awaiter(this, void 0, void 0, function* () {
2582
+ try {
2583
+ const resource = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").patchResource(resourceType, id, patch);
2584
+ return [allOk, resource];
2585
+ }
2586
+ catch (error) {
2587
+ return [error, undefined];
2588
+ }
2589
+ });
2590
+ }
2591
+ /**
2592
+ * Searches for resources.
2593
+ *
2594
+ * See: https://www.hl7.org/fhir/http.html#search
2595
+ *
2596
+ * @param searchRequest The search request.
2597
+ * @returns The search result bundle.
2598
+ * @deprecated
2599
+ */
2600
+ search(query) {
2601
+ return __awaiter(this, void 0, void 0, function* () {
2602
+ const searchRequest = typeof query === 'string' ? parseSearchDefinition(query) : query;
2603
+ try {
2604
+ const bundle = yield __classPrivateFieldGet(this, _LegacyRepositoryClient_client, "f").search(searchRequest);
2605
+ return [allOk, bundle];
2606
+ }
2607
+ catch (error) {
2608
+ return [error, undefined];
2609
+ }
2610
+ });
2611
+ }
2612
+ }
2613
+ _LegacyRepositoryClient_client = new WeakMap();
2614
+
1671
2615
  exports.SearchParameterType = void 0;
1672
2616
  (function (SearchParameterType) {
1673
2617
  SearchParameterType["BOOLEAN"] = "BOOLEAN";
@@ -1794,8 +2738,16 @@
1794
2738
  return result;
1795
2739
  }
1796
2740
 
2741
+ exports.COMPONENT_SEPARATOR = COMPONENT_SEPARATOR;
2742
+ exports.DEFAULT_SEARCH_COUNT = DEFAULT_SEARCH_COUNT;
2743
+ exports.FIELD_SEPARATOR = FIELD_SEPARATOR;
2744
+ exports.Hl7Field = Hl7Field;
2745
+ exports.Hl7Message = Hl7Message;
2746
+ exports.Hl7Segment = Hl7Segment;
2747
+ exports.LegacyRepositoryClient = LegacyRepositoryClient;
1797
2748
  exports.MedplumClient = MedplumClient;
1798
2749
  exports.OperationOutcomeError = OperationOutcomeError;
2750
+ exports.SEGMENT_SEPARATOR = SEGMENT_SEPARATOR;
1799
2751
  exports.accessDenied = accessDenied;
1800
2752
  exports.allOk = allOk;
1801
2753
  exports.arrayBufferToBase64 = arrayBufferToBase64;
@@ -1803,6 +2755,8 @@
1803
2755
  exports.assertOk = assertOk;
1804
2756
  exports.badRequest = badRequest;
1805
2757
  exports.buildTypeName = buildTypeName;
2758
+ exports.calculateAge = calculateAge;
2759
+ exports.calculateAgeString = calculateAgeString;
1806
2760
  exports.capitalize = capitalize;
1807
2761
  exports.createReference = createReference;
1808
2762
  exports.createSchema = createSchema;
@@ -1817,8 +2771,10 @@
1817
2771
  exports.getDateProperty = getDateProperty;
1818
2772
  exports.getDisplayString = getDisplayString;
1819
2773
  exports.getExpressionForResourceType = getExpressionForResourceType;
2774
+ exports.getExtensionValue = getExtensionValue;
1820
2775
  exports.getImageSrc = getImageSrc;
1821
2776
  exports.getPropertyDisplayName = getPropertyDisplayName;
2777
+ exports.getQuestionnaireAnswers = getQuestionnaireAnswers;
1822
2778
  exports.getReferenceString = getReferenceString;
1823
2779
  exports.getSearchParameterDetails = getSearchParameterDetails;
1824
2780
  exports.getStatus = getStatus;
@@ -1828,8 +2784,10 @@
1828
2784
  exports.isGone = isGone;
1829
2785
  exports.isLowerCase = isLowerCase;
1830
2786
  exports.isNotFound = isNotFound;
2787
+ exports.isObject = isObject;
1831
2788
  exports.isOk = isOk;
1832
2789
  exports.isProfileResource = isProfileResource;
2790
+ exports.isStringArray = isStringArray;
1833
2791
  exports.notFound = notFound;
1834
2792
  exports.notModified = notModified;
1835
2793
  exports.parseSearchDefinition = parseSearchDefinition;