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