@medplum/mock 0.9.6 → 0.9.9

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
- import { createReference, Operator, MedplumClient, badRequest, allOk, notFound, getStatus, parseSearchDefinition } from '@medplum/core';
1
+ import { createReference, Operator, evalFhirPath, MedplumClient, badRequest, allOk, notFound, getStatus, parseSearchDefinition } from '@medplum/core';
2
2
 
3
3
  const ExampleAccessPolicy = {
4
4
  resourceType: 'AccessPolicy',
@@ -155,6 +155,7 @@ const ExampleQuestionnaireResponse = {
155
155
  const HomerSimpson = {
156
156
  resourceType: 'Patient',
157
157
  id: '123',
158
+ gender: 'male',
158
159
  meta: {
159
160
  versionId: '2',
160
161
  lastUpdated: '2020-01-02T00:00:00.000Z',
@@ -404,6 +405,7 @@ const HomerObservation6 = {
404
405
  ],
405
406
  };
406
407
  const HomerSimpsonSpecimen = {
408
+ id: '123',
407
409
  resourceType: 'Specimen',
408
410
  subject: createReference(HomerSimpson),
409
411
  collection: {
@@ -6503,34 +6505,6 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6503
6505
  PERFORMANCE OF THIS SOFTWARE.
6504
6506
  ***************************************************************************** */
6505
6507
 
6506
- function __classPrivateFieldGet$1(receiver, state, kind, f) {
6507
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6508
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6509
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6510
- }
6511
-
6512
- function __classPrivateFieldSet$1(receiver, state, value, kind, f) {
6513
- if (kind === "m") throw new TypeError("Private method is not writable");
6514
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6515
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6516
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6517
- }
6518
-
6519
- /******************************************************************************
6520
- Copyright (c) Microsoft Corporation.
6521
-
6522
- Permission to use, copy, modify, and/or distribute this software for any
6523
- purpose with or without fee is hereby granted.
6524
-
6525
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
6526
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
6527
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
6528
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
6529
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
6530
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
6531
- PERFORMANCE OF THIS SOFTWARE.
6532
- ***************************************************************************** */
6533
-
6534
6508
  function __classPrivateFieldGet(receiver, state, kind, f) {
6535
6509
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6536
6510
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
@@ -6544,2772 +6518,212 @@ function __classPrivateFieldSet(receiver, state, value, kind, f) {
6544
6518
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6545
6519
  }
6546
6520
 
6547
- /**
6548
- * Ensures that the value is wrapped in an array.
6549
- * @param input The input as a an array or a value.
6550
- * @returns The input as an array.
6551
- */
6552
- function ensureArray(input) {
6553
- if (input === null || input === undefined) {
6554
- return [];
6555
- }
6556
- return Array.isArray(input) ? input : [input];
6557
- }
6558
- /**
6559
- * Applies a function to single value or an array of values.
6560
- * @param context The context which will be passed to the function.
6561
- * @param fn The function to apply.
6562
- * @returns The result of the function.
6563
- */
6564
- function applyMaybeArray(context, fn) {
6565
- if (context === undefined) {
6566
- return undefined;
6567
- }
6568
- if (Array.isArray(context)) {
6569
- return context
6570
- .map((e) => fn(e))
6571
- .filter((e) => !!e)
6572
- .flat();
6573
- }
6574
- else {
6575
- return fn(context);
6576
- }
6577
- }
6578
- /**
6579
- * Determines if the input is an empty array.
6580
- * @param obj Any value or array of values.
6581
- * @returns True if the input is an empty array.
6582
- */
6583
- function isEmptyArray(obj) {
6584
- return Array.isArray(obj) && obj.length === 0;
6585
- }
6586
- function isFalsy(obj) {
6587
- return !obj || isEmptyArray(obj);
6588
- }
6589
- /**
6590
- * Converts unknown object into a JavaScript boolean.
6591
- * Note that this is different than the FHIRPath "toBoolean",
6592
- * which has particular semantics around arrays, empty arrays, and type conversions.
6593
- * @param obj Any value or array of values.
6594
- * @returns The converted boolean value according to FHIRPath rules.
6595
- */
6596
- function toJsBoolean(obj) {
6597
- if (Array.isArray(obj)) {
6598
- return obj.length === 0 ? false : !!obj[0];
6521
+ var _MemoryRepository_resources, _MemoryRepository_history;
6522
+ class MemoryRepository {
6523
+ constructor() {
6524
+ _MemoryRepository_resources.set(this, void 0);
6525
+ _MemoryRepository_history.set(this, void 0);
6526
+ __classPrivateFieldSet(this, _MemoryRepository_resources, {}, "f");
6527
+ __classPrivateFieldSet(this, _MemoryRepository_history, {}, "f");
6599
6528
  }
6600
- return !!obj;
6601
- }
6602
- /**
6603
- * Removes duplicates in array using FHIRPath equality rules.
6604
- * @param arr The input array.
6605
- * @returns The result array with duplicates removed.
6606
- */
6607
- function removeDuplicates(arr) {
6608
- const result = [];
6609
- for (const i of arr) {
6610
- let found = false;
6611
- for (const j of result) {
6612
- if (fhirPathEquals(i, j)) {
6613
- found = true;
6614
- break;
6615
- }
6529
+ createResource(resource) {
6530
+ var _a;
6531
+ const result = resource;
6532
+ if (!result.id) {
6533
+ result.id = this.generateId();
6616
6534
  }
6617
- if (!found) {
6618
- result.push(i);
6535
+ if (!result.meta) {
6536
+ result.meta = {};
6619
6537
  }
6538
+ if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
6539
+ result.meta.versionId = this.generateId();
6540
+ }
6541
+ const { resourceType, id } = resource;
6542
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_resources, "f"))) {
6543
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType] = {};
6544
+ }
6545
+ if (!(resourceType in __classPrivateFieldGet(this, _MemoryRepository_history, "f"))) {
6546
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType] = {};
6547
+ }
6548
+ if (!(id in __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType])) {
6549
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id] = [];
6550
+ }
6551
+ __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
6552
+ __classPrivateFieldGet(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
6553
+ return result;
6620
6554
  }
6621
- return result;
6622
- }
6623
- /**
6624
- * Determines if two values are equal according to FHIRPath equality rules.
6625
- * @param x The first value.
6626
- * @param y The second value.
6627
- * @returns True if equal.
6628
- */
6629
- function fhirPathEquals(x, y) {
6630
- if (isFalsy(x) && isFalsy(y)) {
6631
- return true;
6632
- }
6633
- if (isEmptyArray(x) || isEmptyArray(y)) {
6634
- return [];
6635
- }
6636
- if (typeof x === 'number' && typeof y === 'number') {
6637
- return Math.abs(x - y) < 1e-8;
6638
- }
6639
- if (isQuantity(x) && isQuantity(y)) {
6640
- return isQuantityEquivalent(x, y);
6641
- }
6642
- if (Array.isArray(x) && Array.isArray(y)) {
6643
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6644
- }
6645
- if (typeof x === 'object' && typeof y === 'object') {
6646
- return deepEquals(x, y);
6647
- }
6648
- return x === y;
6649
- }
6650
- /**
6651
- * Determines if two values are equal according to FHIRPath equality rules.
6652
- * @param x The first value.
6653
- * @param y The second value.
6654
- * @returns True if equal.
6655
- */
6656
- function fhirPathEquivalent(x, y) {
6657
- if (isFalsy(x) && isFalsy(y)) {
6658
- return true;
6659
- }
6660
- if (isEmptyArray(x) || isEmptyArray(y)) {
6661
- // Note that this implies that if the collections have a different number of items to compare,
6662
- // or if one input is a value and the other is empty ({ }), the result will be false.
6663
- return false;
6664
- }
6665
- if (typeof x === 'number' && typeof y === 'number') {
6666
- // Use more generous threshold than equality
6667
- // Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand.
6668
- // Trailing zeroes after the decimal are ignored in determining precision.
6669
- return Math.abs(x - y) < 0.01;
6670
- }
6671
- if (isQuantity(x) && isQuantity(y)) {
6672
- return isQuantityEquivalent(x, y);
6555
+ readResource(resourceType, id) {
6556
+ var _a, _b;
6557
+ return (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id];
6673
6558
  }
6674
- if (Array.isArray(x) && Array.isArray(y)) {
6675
- // If both operands are collections with multiple items:
6676
- // 1) Each item must be equivalent
6677
- // 2) Comparison is not order dependent
6678
- x.sort();
6679
- y.sort();
6680
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
6559
+ readHistory(resourceType, id) {
6560
+ var _a, _b, _c;
6561
+ return {
6562
+ resourceType: 'Bundle',
6563
+ type: 'history',
6564
+ entry: ((_c = (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) !== null && _c !== void 0 ? _c : [])
6565
+ .sort((version1, version2) => { var _a, _b, _c; return -((_b = (_a = version1.meta) === null || _a === void 0 ? void 0 : _a.lastUpdated) === null || _b === void 0 ? void 0 : _b.localeCompare((_c = version2.meta) === null || _c === void 0 ? void 0 : _c.lastUpdated)); })
6566
+ .map((version) => ({ resource: version })),
6567
+ };
6681
6568
  }
6682
- if (typeof x === 'object' && typeof y === 'object') {
6683
- return deepEquals(x, y);
6569
+ readVersion(resourceType, id, versionId) {
6570
+ var _a, _b, _c;
6571
+ return (_c = (_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) === null || _c === void 0 ? void 0 : _c.find((v) => { var _a; return ((_a = v.meta) === null || _a === void 0 ? void 0 : _a.versionId) === versionId; });
6684
6572
  }
6685
- if (typeof x === 'string' && typeof y === 'string') {
6686
- // String: the strings must be the same, ignoring case and locale, and normalizing whitespace
6687
- // (see String Equivalence for more details).
6688
- return x.toLowerCase() === y.toLowerCase();
6573
+ search(searchRequest) {
6574
+ var _a;
6575
+ const { resourceType } = searchRequest;
6576
+ const resources = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
6577
+ const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
6578
+ return {
6579
+ resourceType: 'Bundle',
6580
+ type: 'searchset',
6581
+ entry: result.map((resource) => ({ resource })),
6582
+ total: result.length,
6583
+ };
6689
6584
  }
6690
- return x === y;
6691
- }
6692
- function fhirPathIs(value, desiredType) {
6693
- if (value === undefined || value === null) {
6694
- return false;
6585
+ deleteResource(resourceType, id) {
6586
+ var _a, _b;
6587
+ if ((_b = (_a = __classPrivateFieldGet(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) {
6588
+ delete __classPrivateFieldGet(this, _MemoryRepository_resources, "f")[resourceType][id];
6589
+ }
6695
6590
  }
6696
- switch (desiredType) {
6697
- case 'Boolean':
6698
- return typeof value === 'boolean';
6699
- case 'Decimal':
6700
- case 'Integer':
6701
- return typeof value === 'number';
6702
- case 'Date':
6703
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?/);
6704
- case 'DateTime':
6705
- return typeof value === 'string' && !!value.match(/^\d{4}(-\d{2}(-\d{2})?)?T/);
6706
- case 'Time':
6707
- return typeof value === 'string' && !!value.match(/^T\d/);
6708
- case 'Period':
6709
- return isPeriod(value);
6710
- case 'Quantity':
6711
- return isQuantity(value);
6712
- default:
6713
- return typeof value === 'object' && (value === null || value === void 0 ? void 0 : value.resourceType) === desiredType;
6591
+ generateId() {
6592
+ return Date.now().toString(36);
6714
6593
  }
6715
6594
  }
6595
+ _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
6716
6596
  /**
6717
- * Determines if the input is a Period object.
6718
- * This is heuristic based, as we do not have strong typing at runtime.
6719
- * @param input The input value.
6720
- * @returns True if the input is a period.
6721
- */
6722
- function isPeriod(input) {
6723
- return !!(input && typeof input === 'object' && 'start' in input);
6724
- }
6725
- /**
6726
- * Determines if the input is a Quantity object.
6727
- * This is heuristic based, as we do not have strong typing at runtime.
6728
- * @param input The input value.
6729
- * @returns True if the input is a quantity.
6730
- */
6731
- function isQuantity(input) {
6732
- return !!(input && typeof input === 'object' && 'value' in input && typeof input.value === 'number');
6733
- }
6734
- function isQuantityEquivalent(x, y) {
6735
- return (Math.abs(x.value - y.value) < 0.01 &&
6736
- (x.unit === y.unit || x.code === y.code || x.unit === y.code || x.code === y.unit));
6737
- }
6738
- /**
6739
- * Resource equality.
6740
- * Ignores meta.versionId and meta.lastUpdated.
6741
- * See: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/#4-deep-equality
6742
- * @param object1 The first object.
6743
- * @param object2 The second object.
6744
- * @returns True if the objects are equal.
6597
+ * Determines if the resource matches the search request.
6598
+ * @param resource The resource that was created or updated.
6599
+ * @param searchRequest The subscription criteria as a search request.
6600
+ * @returns True if the resource satisfies the search request.
6745
6601
  */
6746
- function deepEquals(object1, object2) {
6747
- const keys1 = Object.keys(object1);
6748
- const keys2 = Object.keys(object2);
6749
- if (keys1.length !== keys2.length) {
6602
+ function matchesSearchRequest(resource, searchRequest) {
6603
+ if (searchRequest.resourceType !== resource.resourceType) {
6750
6604
  return false;
6751
6605
  }
6752
- for (const key of keys1) {
6753
- const val1 = object1[key];
6754
- const val2 = object2[key];
6755
- if (isObject(val1) && isObject(val2)) {
6756
- if (!deepEquals(val1, val2)) {
6757
- return false;
6758
- }
6759
- }
6760
- else {
6761
- if (val1 !== val2) {
6606
+ if (searchRequest.filters) {
6607
+ for (const filter of searchRequest.filters) {
6608
+ if (!matchesSearchFilter(resource, filter)) {
6762
6609
  return false;
6763
6610
  }
6764
6611
  }
6765
6612
  }
6766
6613
  return true;
6767
6614
  }
6768
- function isObject(object) {
6769
- return object !== null && typeof object === 'object';
6770
- }
6771
6615
  /**
6772
- * Calculates the age in years from the birth date.
6773
- * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.
6774
- * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.
6775
- * @returns The age in years, months, and days.
6616
+ * Determines if the resource matches the search filter.
6617
+ * @param resource The resource that was created or updated.
6618
+ * @param filter One of the filters of a subscription criteria.
6619
+ * @returns True if the resource satisfies the search filter.
6776
6620
  */
6777
- function calculateAge(birthDateStr, endDateStr) {
6778
- const startDate = new Date(birthDateStr);
6779
- startDate.setUTCHours(0, 0, 0, 0);
6780
- const endDate = endDateStr ? new Date(endDateStr) : new Date();
6781
- endDate.setUTCHours(0, 0, 0, 0);
6782
- const startYear = startDate.getUTCFullYear();
6783
- const startMonth = startDate.getUTCMonth();
6784
- const startDay = startDate.getUTCDate();
6785
- const endYear = endDate.getUTCFullYear();
6786
- const endMonth = endDate.getUTCMonth();
6787
- const endDay = endDate.getUTCDate();
6788
- let years = endYear - startYear;
6789
- if (endMonth < startMonth || (endMonth === startMonth && endDay < startDay)) {
6790
- years--;
6791
- }
6792
- let months = endYear * 12 + endMonth - (startYear * 12 + startMonth);
6793
- if (endDay < startDay) {
6794
- months--;
6795
- }
6796
- const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
6797
- return { years, months, days };
6798
- }
6799
-
6800
- class FhirPathAtom {
6801
- constructor(original, child) {
6802
- this.original = original;
6803
- this.child = child;
6804
- }
6805
- eval(context) {
6806
- try {
6807
- const result = applyMaybeArray(context, (e) => this.child.eval(e));
6808
- if (Array.isArray(result)) {
6809
- return result.flat();
6810
- }
6811
- else if (result === undefined || result === null) {
6812
- return [];
6813
- }
6814
- else {
6815
- return [result];
6816
- }
6817
- }
6818
- catch (error) {
6819
- throw new Error(`FhirPathError on "${this.original}": ${error}`);
6621
+ function matchesSearchFilter(resource, filter) {
6622
+ for (const filterValue of filter.value.split(',')) {
6623
+ if (matchesSearchFilterValue(resource, filter, filterValue)) {
6624
+ return true;
6820
6625
  }
6821
6626
  }
6627
+ return false;
6822
6628
  }
6823
- class LiteralAtom {
6824
- constructor(value) {
6825
- this.value = value;
6826
- }
6827
- eval() {
6828
- return this.value;
6829
- }
6629
+ function matchesSearchFilterValue(resource, filter, filterValue) {
6630
+ const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
6631
+ const values = evalFhirPath(expression, resource);
6632
+ const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filterValue.toLowerCase()));
6633
+ return filter.operator === Operator.NOT_EQUALS ? !result : result;
6830
6634
  }
6831
- class SymbolAtom {
6832
- constructor(name) {
6833
- this.name = name;
6834
- }
6835
- eval(context) {
6836
- if (this.name === '$this') {
6837
- return context;
6838
- }
6839
- return applyMaybeArray(context, (e) => {
6840
- if (e && typeof e === 'object') {
6841
- if ('resourceType' in e && e.resourceType === this.name) {
6842
- return e;
6635
+
6636
+ class MockClient extends MedplumClient {
6637
+ constructor(clientOptions) {
6638
+ super({
6639
+ baseUrl: 'https://example.com/',
6640
+ clientId: 'my-client-id',
6641
+ fetch: (url, options) => {
6642
+ const method = options.method || 'GET';
6643
+ const path = url.replace('https://example.com/', '');
6644
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6645
+ console.log('MockClient', method, path);
6843
6646
  }
6844
- if (this.name in e) {
6845
- return e[this.name];
6647
+ const response = mockHandler(method, path, options);
6648
+ if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
6649
+ console.log('MockClient: not found', method, path);
6846
6650
  }
6847
- const propertyName = Object.keys(e).find((k) => k.startsWith(this.name));
6848
- if (propertyName) {
6849
- return e[propertyName];
6651
+ if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
6652
+ console.log('MockClient', JSON.stringify(response, null, 2));
6850
6653
  }
6851
- }
6852
- return undefined;
6654
+ return Promise.resolve({
6655
+ blob: () => Promise.resolve(response),
6656
+ json: () => Promise.resolve(response),
6657
+ });
6658
+ },
6853
6659
  });
6854
6660
  }
6855
- }
6856
- class EmptySetAtom {
6857
- eval() {
6858
- return [];
6859
- }
6860
- }
6861
- class UnaryOperatorAtom {
6862
- constructor(child, impl) {
6863
- this.child = child;
6864
- this.impl = impl;
6865
- }
6866
- eval(context) {
6867
- return this.impl(this.child.eval(context));
6868
- }
6869
- }
6870
- class AsAtom {
6871
- constructor(left, right) {
6872
- this.left = left;
6873
- this.right = right;
6661
+ clear() {
6662
+ super.clear();
6663
+ this.activeLoginOverride = undefined;
6874
6664
  }
6875
- eval(context) {
6876
- return this.left.eval(context);
6665
+ getProfile() {
6666
+ return {
6667
+ resourceType: 'Practitioner',
6668
+ id: '123',
6669
+ meta: {
6670
+ versionId: '456',
6671
+ },
6672
+ };
6877
6673
  }
6878
- }
6879
- class ArithemticOperatorAtom {
6880
- constructor(left, right, impl) {
6881
- this.left = left;
6882
- this.right = right;
6883
- this.impl = impl;
6674
+ setActiveLoginOverride(activeLoginOverride) {
6675
+ this.activeLoginOverride = activeLoginOverride;
6884
6676
  }
6885
- eval(context) {
6886
- const leftValue = this.left.eval(context);
6887
- const rightValue = this.right.eval(context);
6888
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6889
- return Object.assign(Object.assign({}, leftValue), { value: this.impl(leftValue.value, rightValue.value) });
6890
- }
6891
- else {
6892
- return this.impl(leftValue, rightValue);
6677
+ getActiveLogin() {
6678
+ if (this.activeLoginOverride !== undefined) {
6679
+ return this.activeLoginOverride;
6893
6680
  }
6681
+ return super.getActiveLogin();
6894
6682
  }
6895
- }
6896
- class ComparisonOperatorAtom {
6897
- constructor(left, right, impl) {
6898
- this.left = left;
6899
- this.right = right;
6900
- this.impl = impl;
6901
- }
6902
- eval(context) {
6903
- const leftValue = this.left.eval(context);
6904
- const rightValue = this.right.eval(context);
6905
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
6906
- return this.impl(leftValue.value, rightValue.value);
6907
- }
6908
- else {
6909
- return this.impl(leftValue, rightValue);
6683
+ createBinary(_data, filename, contentType) {
6684
+ if (filename.endsWith('.exe')) {
6685
+ return Promise.reject(badRequest('Invalid file type'));
6910
6686
  }
6687
+ return Promise.resolve({
6688
+ resourceType: 'Binary',
6689
+ title: filename,
6690
+ contentType,
6691
+ url: 'https://example.com/binary/123',
6692
+ });
6911
6693
  }
6912
6694
  }
6913
- class ConcatAtom {
6914
- constructor(left, right) {
6915
- this.left = left;
6916
- this.right = right;
6695
+ function mockHandler(method, path, options) {
6696
+ if (path.startsWith('admin/')) {
6697
+ return mockAdminHandler(method, path);
6917
6698
  }
6918
- eval(context) {
6919
- const leftValue = this.left.eval(context);
6920
- const rightValue = this.right.eval(context);
6921
- const result = [];
6922
- function add(value) {
6923
- if (value) {
6924
- if (Array.isArray(value)) {
6925
- result.push(...value);
6926
- }
6927
- else {
6928
- result.push(value);
6929
- }
6930
- }
6931
- }
6932
- add(leftValue);
6933
- add(rightValue);
6934
- if (result.length > 0 && result.every((e) => typeof e === 'string')) {
6935
- return result.join('');
6936
- }
6937
- return result;
6699
+ else if (path.startsWith('auth/')) {
6700
+ return mockAuthHandler(method, path, options);
6938
6701
  }
6939
- }
6940
- class ContainsAtom {
6941
- constructor(left, right) {
6942
- this.left = left;
6943
- this.right = right;
6702
+ else if (path.startsWith('fhir/R4')) {
6703
+ return mockFhirHandler(method, path, options);
6944
6704
  }
6945
- eval(context) {
6946
- const leftValue = this.left.eval(context);
6947
- const rightValue = this.right.eval(context);
6948
- return ensureArray(leftValue).includes(rightValue);
6705
+ else {
6706
+ return null;
6949
6707
  }
6950
6708
  }
6951
- class InAtom {
6952
- constructor(left, right) {
6953
- this.left = left;
6954
- this.right = right;
6955
- }
6956
- eval(context) {
6957
- const leftValue = this.left.eval(context);
6958
- const rightValue = this.right.eval(context);
6959
- return ensureArray(rightValue).includes(leftValue);
6709
+ function mockAdminHandler(_method, path) {
6710
+ if (path.startsWith('admin/projects/123')) {
6711
+ return {
6712
+ project: { id: '123', name: 'Project 123' },
6713
+ members: [
6714
+ { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
6715
+ { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
6716
+ { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
6717
+ ],
6718
+ };
6960
6719
  }
6720
+ return {
6721
+ ok: true,
6722
+ };
6961
6723
  }
6962
- class DotAtom {
6963
- constructor(left, right) {
6964
- this.left = left;
6965
- this.right = right;
6966
- }
6967
- eval(context) {
6968
- return this.right.eval(this.left.eval(context));
6969
- }
6970
- }
6971
- class UnionAtom {
6972
- constructor(left, right) {
6973
- this.left = left;
6974
- this.right = right;
6975
- }
6976
- eval(context) {
6977
- const leftResult = this.left.eval(context);
6978
- const rightResult = this.right.eval(context);
6979
- let resultArray;
6980
- if (leftResult !== undefined && rightResult !== undefined) {
6981
- resultArray = [leftResult, rightResult].flat();
6982
- }
6983
- else if (leftResult !== undefined) {
6984
- resultArray = ensureArray(leftResult);
6985
- }
6986
- else if (rightResult !== undefined) {
6987
- resultArray = ensureArray(rightResult);
6988
- }
6989
- else {
6990
- resultArray = [];
6991
- }
6992
- return removeDuplicates(resultArray);
6993
- }
6994
- }
6995
- class EqualsAtom {
6996
- constructor(left, right) {
6997
- this.left = left;
6998
- this.right = right;
6999
- }
7000
- eval(context) {
7001
- const leftValue = this.left.eval(context);
7002
- const rightValue = this.right.eval(context);
7003
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
7004
- return fhirPathEquals(leftValue.flat(), rightValue);
7005
- }
7006
- return applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
7007
- }
7008
- }
7009
- class NotEqualsAtom {
7010
- constructor(left, right) {
7011
- this.left = left;
7012
- this.right = right;
7013
- }
7014
- eval(context) {
7015
- const leftValue = this.left.eval(context);
7016
- const rightValue = this.right.eval(context);
7017
- let result;
7018
- if (Array.isArray(rightValue)) {
7019
- result = fhirPathEquals(leftValue, rightValue);
7020
- }
7021
- else {
7022
- result = applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
7023
- }
7024
- return !toJsBoolean(result);
7025
- }
7026
- }
7027
- class EquivalentAtom {
7028
- constructor(left, right) {
7029
- this.left = left;
7030
- this.right = right;
7031
- }
7032
- eval(context) {
7033
- const leftValue = this.left.eval(context);
7034
- const rightValue = this.right.eval(context);
7035
- if (Array.isArray(rightValue)) {
7036
- return fhirPathEquivalent(leftValue, rightValue);
7037
- }
7038
- return applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7039
- }
7040
- }
7041
- class NotEquivalentAtom {
7042
- constructor(left, right) {
7043
- this.left = left;
7044
- this.right = right;
7045
- }
7046
- eval(context) {
7047
- const leftValue = this.left.eval(context);
7048
- const rightValue = this.right.eval(context);
7049
- let result;
7050
- if (Array.isArray(rightValue)) {
7051
- result = fhirPathEquivalent(leftValue, rightValue);
7052
- }
7053
- else {
7054
- result = applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
7055
- }
7056
- return !toJsBoolean(result);
7057
- }
7058
- }
7059
- class IsAtom {
7060
- constructor(left, right) {
7061
- this.left = left;
7062
- this.right = right;
7063
- }
7064
- eval(context) {
7065
- const typeName = this.right.name;
7066
- return applyMaybeArray(this.left.eval(context), (e) => fhirPathIs(e, typeName));
7067
- }
7068
- }
7069
- /**
7070
- * 6.5.1. and
7071
- * Returns true if both operands evaluate to true, false if either operand evaluates to false, and the empty collection ({ }) otherwise.
7072
- */
7073
- class AndAtom {
7074
- constructor(left, right) {
7075
- this.left = left;
7076
- this.right = right;
7077
- }
7078
- eval(context) {
7079
- const leftValue = this.left.eval(context);
7080
- const rightValue = this.right.eval(context);
7081
- if (leftValue === true && rightValue === true) {
7082
- return true;
7083
- }
7084
- if (leftValue === false || rightValue === false) {
7085
- return false;
7086
- }
7087
- return [];
7088
- }
7089
- }
7090
- class OrAtom {
7091
- constructor(left, right) {
7092
- this.left = left;
7093
- this.right = right;
7094
- }
7095
- eval(context) {
7096
- const leftValue = this.left.eval(context);
7097
- if (toJsBoolean(leftValue)) {
7098
- return leftValue;
7099
- }
7100
- const rightValue = this.right.eval(context);
7101
- if (toJsBoolean(rightValue)) {
7102
- return rightValue;
7103
- }
7104
- return [];
7105
- }
7106
- }
7107
- /**
7108
- * 6.5.4. xor
7109
- * Returns true if exactly one of the operands evaluates to true,
7110
- * false if either both operands evaluate to true or both operands evaluate to false,
7111
- * and the empty collection ({ }) otherwise:
7112
- */
7113
- class XorAtom {
7114
- constructor(left, right) {
7115
- this.left = left;
7116
- this.right = right;
7117
- }
7118
- eval(context) {
7119
- const leftValue = this.left.eval(context);
7120
- const rightValue = this.right.eval(context);
7121
- if ((leftValue === true && rightValue !== true) || (leftValue !== true && rightValue === true)) {
7122
- return true;
7123
- }
7124
- if ((leftValue === true && rightValue === true) || (leftValue === false && rightValue === false)) {
7125
- return false;
7126
- }
7127
- return [];
7128
- }
7129
- }
7130
- class FunctionAtom {
7131
- constructor(name, args, impl) {
7132
- this.name = name;
7133
- this.args = args;
7134
- this.impl = impl;
7135
- }
7136
- eval(context) {
7137
- return this.impl(ensureArray(context), ...this.args);
7138
- }
7139
- }
7140
- class IndexerAtom {
7141
- constructor(left, expr) {
7142
- this.left = left;
7143
- this.expr = expr;
7144
- }
7145
- eval(context) {
7146
- const index = this.expr.eval(context);
7147
- if (typeof index !== 'number') {
7148
- throw new Error(`Invalid indexer expression: should return integer}`);
7149
- }
7150
- const leftResult = this.left.eval(context);
7151
- if (!(index in leftResult)) {
7152
- return [];
7153
- }
7154
- return leftResult[index];
7155
- }
7156
- }
7157
-
7158
- function parseDateString(str) {
7159
- if (str.startsWith('T')) {
7160
- // If a time string,
7161
- // then normalize to full length.
7162
- return str + 'T00:00:00.000Z'.substring(str.length);
7163
- }
7164
- if (str.length <= 10) {
7165
- // If a local date (i.e., "2021-01-01"),
7166
- // then return as-is.
7167
- return str;
7168
- }
7169
- try {
7170
- // Try to normalize to UTC
7171
- return new Date(str).toISOString();
7172
- }
7173
- catch (e) {
7174
- // Fallback to original input
7175
- // This happens on unsupported time formats such as "2021-01-01T12"
7176
- return str;
7177
- }
7178
- }
7179
-
7180
- /*
7181
- * Collection of FHIRPath
7182
- * See: https://hl7.org/fhirpath/#functions
7183
- */
7184
- /**
7185
- * Temporary placholder for unimplemented methods.
7186
- */
7187
- const stub = () => [];
7188
- /*
7189
- * 5.1 Existence
7190
- * See: https://hl7.org/fhirpath/#existence
7191
- */
7192
- /**
7193
- * Returns true if the input collection is empty ({ }) and false otherwise.
7194
- *
7195
- * See: https://hl7.org/fhirpath/#empty-boolean
7196
- *
7197
- * @param input The input collection.
7198
- * @returns True if the input collection is empty ({ }) and false otherwise.
7199
- */
7200
- function empty(input) {
7201
- return [input.length === 0];
7202
- }
7203
- /**
7204
- * Returns true if the collection has unknown elements, and false otherwise.
7205
- * This is the opposite of empty(), and as such is a shorthand for empty().not().
7206
- * If the input collection is empty ({ }), the result is false.
7207
- *
7208
- * The function can also take an optional criteria to be applied to the collection
7209
- * prior to the determination of the exists. In this case, the function is shorthand
7210
- * for where(criteria).exists().
7211
- *
7212
- * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
7213
- *
7214
- * @param input
7215
- * @param criteria
7216
- * @returns True if the collection has unknown elements, and false otherwise.
7217
- */
7218
- function exists(input, criteria) {
7219
- if (criteria) {
7220
- return [input.filter((e) => toJsBoolean(criteria.eval(e))).length > 0];
7221
- }
7222
- else {
7223
- return [input.length > 0];
7224
- }
7225
- }
7226
- /**
7227
- * Returns true if for every element in the input collection, criteria evaluates to true.
7228
- * Otherwise, the result is false.
7229
- *
7230
- * If the input collection is empty ({ }), the result is true.
7231
- *
7232
- * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
7233
- *
7234
- * @param input The input collection.
7235
- * @param criteria The evaluation criteria.
7236
- * @returns True if for every element in the input collection, criteria evaluates to true.
7237
- */
7238
- function all(input, criteria) {
7239
- return [input.every((e) => toJsBoolean(criteria.eval(e)))];
7240
- }
7241
- /**
7242
- * Takes a collection of Boolean values and returns true if all the items are true.
7243
- * If unknown items are false, the result is false.
7244
- * If the input is empty ({ }), the result is true.
7245
- *
7246
- * See: https://hl7.org/fhirpath/#alltrue-boolean
7247
- *
7248
- * @param input The input collection.
7249
- * @param criteria The evaluation criteria.
7250
- * @returns True if all the items are true.
7251
- */
7252
- function allTrue(input) {
7253
- for (const value of input) {
7254
- if (!value) {
7255
- return [false];
7256
- }
7257
- }
7258
- return [true];
7259
- }
7260
- /**
7261
- * Takes a collection of Boolean values and returns true if unknown of the items are true.
7262
- * If all the items are false, or if the input is empty ({ }), the result is false.
7263
- *
7264
- * See: https://hl7.org/fhirpath/#anytrue-boolean
7265
- *
7266
- * @param input The input collection.
7267
- * @param criteria The evaluation criteria.
7268
- * @returns True if unknown of the items are true.
7269
- */
7270
- function anyTrue(input) {
7271
- for (const value of input) {
7272
- if (value) {
7273
- return [true];
7274
- }
7275
- }
7276
- return [false];
7277
- }
7278
- /**
7279
- * Takes a collection of Boolean values and returns true if all the items are false.
7280
- * If unknown items are true, the result is false.
7281
- * If the input is empty ({ }), the result is true.
7282
- *
7283
- * See: https://hl7.org/fhirpath/#allfalse-boolean
7284
- *
7285
- * @param input The input collection.
7286
- * @param criteria The evaluation criteria.
7287
- * @returns True if all the items are false.
7288
- */
7289
- function allFalse(input) {
7290
- for (const value of input) {
7291
- if (value) {
7292
- return [false];
7293
- }
7294
- }
7295
- return [true];
7296
- }
7297
- /**
7298
- * Takes a collection of Boolean values and returns true if unknown of the items are false.
7299
- * If all the items are true, or if the input is empty ({ }), the result is false.
7300
- *
7301
- * See: https://hl7.org/fhirpath/#anyfalse-boolean
7302
- *
7303
- * @param input The input collection.
7304
- * @param criteria The evaluation criteria.
7305
- * @returns True if for every element in the input collection, criteria evaluates to true.
7306
- */
7307
- function anyFalse(input) {
7308
- for (const value of input) {
7309
- if (!value) {
7310
- return [true];
7311
- }
7312
- }
7313
- return [false];
7314
- }
7315
- /**
7316
- * Returns true if all items in the input collection are members of the collection passed
7317
- * as the other argument. Membership is determined using the = (Equals) (=) operation.
7318
- *
7319
- * Conceptually, this function is evaluated by testing each element in the input collection
7320
- * for membership in the other collection, with a default of true. This means that if the
7321
- * input collection is empty ({ }), the result is true, otherwise if the other collection
7322
- * is empty ({ }), the result is false.
7323
- *
7324
- * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
7325
- */
7326
- const subsetOf = stub;
7327
- /**
7328
- * Returns true if all items in the collection passed as the other argument are members of
7329
- * the input collection. Membership is determined using the = (Equals) (=) operation.
7330
- *
7331
- * Conceptually, this function is evaluated by testing each element in the other collection
7332
- * for membership in the input collection, with a default of true. This means that if the
7333
- * other collection is empty ({ }), the result is true, otherwise if the input collection
7334
- * is empty ({ }), the result is false.
7335
- *
7336
- * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
7337
- */
7338
- const supersetOf = stub;
7339
- /**
7340
- * Returns the integer count of the number of items in the input collection.
7341
- * Returns 0 when the input collection is empty.
7342
- *
7343
- * See: https://hl7.org/fhirpath/#count-integer
7344
- *
7345
- * @param input The input collection.
7346
- * @returns The integer count of the number of items in the input collection.
7347
- */
7348
- function count(input) {
7349
- return [input.length];
7350
- }
7351
- /**
7352
- * Returns a collection containing only the unique items in the input collection.
7353
- * To determine whether two items are the same, the = (Equals) (=) operator is used,
7354
- * as defined below.
7355
- *
7356
- * If the input collection is empty ({ }), the result is empty.
7357
- *
7358
- * Note that the order of elements in the input collection is not guaranteed to be
7359
- * preserved in the result.
7360
- *
7361
- * See: https://hl7.org/fhirpath/#distinct-collection
7362
- *
7363
- * @param input The input collection.
7364
- * @returns The integer count of the number of items in the input collection.
7365
- */
7366
- function distinct(input) {
7367
- return Array.from(new Set(input));
7368
- }
7369
- /**
7370
- * Returns true if all the items in the input collection are distinct.
7371
- * To determine whether two items are distinct, the = (Equals) (=) operator is used,
7372
- * as defined below.
7373
- *
7374
- * See: https://hl7.org/fhirpath/#isdistinct-boolean
7375
- *
7376
- * @param input The input collection.
7377
- * @returns The integer count of the number of items in the input collection.
7378
- */
7379
- function isDistinct(input) {
7380
- return [input.length === new Set(input).size];
7381
- }
7382
- /*
7383
- * 5.2 Filtering and projection
7384
- */
7385
- /**
7386
- * Returns a collection containing only those elements in the input collection
7387
- * for which the stated criteria expression evaluates to true.
7388
- * Elements for which the expression evaluates to false or empty ({ }) are not
7389
- * included in the result.
7390
- *
7391
- * If the input collection is empty ({ }), the result is empty.
7392
- *
7393
- * If the result of evaluating the condition is other than a single boolean value,
7394
- * the evaluation will end and signal an error to the calling environment,
7395
- * consistent with singleton evaluation of collections behavior.
7396
- *
7397
- * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
7398
- *
7399
- * @param input The input collection.
7400
- * @param condition The condition atom.
7401
- * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
7402
- */
7403
- function where(input, criteria) {
7404
- return input.filter((e) => toJsBoolean(criteria.eval(e)));
7405
- }
7406
- /**
7407
- * Evaluates the projection expression for each item in the input collection.
7408
- * The result of each evaluation is added to the output collection. If the
7409
- * evaluation results in a collection with multiple items, all items are added
7410
- * to the output collection (collections resulting from evaluation of projection
7411
- * are flattened). This means that if the evaluation for an element results in
7412
- * the empty collection ({ }), no element is added to the result, and that if
7413
- * the input collection is empty ({ }), the result is empty as well.
7414
- *
7415
- * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
7416
- */
7417
- function select(input, criteria) {
7418
- return ensureArray(input.map((e) => criteria.eval(e)).flat());
7419
- }
7420
- /**
7421
- * A version of select that will repeat the projection and add it to the output
7422
- * collection, as long as the projection yields new items (as determined by
7423
- * the = (Equals) (=) operator).
7424
- *
7425
- * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
7426
- */
7427
- const repeat = stub;
7428
- /**
7429
- * Returns a collection that contains all items in the input collection that
7430
- * are of the given type or a subclass thereof. If the input collection is
7431
- * empty ({ }), the result is empty. The type argument is an identifier that
7432
- * must resolve to the name of a type in a model
7433
- *
7434
- * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
7435
- */
7436
- const ofType = stub;
7437
- /*
7438
- * 5.3 Subsetting
7439
- */
7440
- /**
7441
- * Will return the single item in the input if there is just one item.
7442
- * If the input collection is empty ({ }), the result is empty.
7443
- * If there are multiple items, an error is signaled to the evaluation environment.
7444
- * This function is useful for ensuring that an error is returned if an assumption
7445
- * about cardinality is violated at run-time.
7446
- *
7447
- * See: https://hl7.org/fhirpath/#single-collection
7448
- *
7449
- * @param input The input collection.
7450
- * @returns The single item in the input if there is just one item.
7451
- */
7452
- function single(input) {
7453
- if (input.length > 1) {
7454
- throw new Error('Expected input length one for single()');
7455
- }
7456
- return input.length === 0 ? [] : input.slice(0, 1);
7457
- }
7458
- /**
7459
- * Returns a collection containing only the first item in the input collection.
7460
- * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
7461
- *
7462
- * See: https://hl7.org/fhirpath/#first-collection
7463
- *
7464
- * @param input The input collection.
7465
- * @returns A collection containing only the first item in the input collection.
7466
- */
7467
- function first(input) {
7468
- return input.length === 0 ? [] : [input[0]];
7469
- }
7470
- /**
7471
- * Returns a collection containing only the last item in the input collection.
7472
- * Will return an empty collection if the input collection has no items.
7473
- *
7474
- * See: https://hl7.org/fhirpath/#last-collection
7475
- *
7476
- * @param input The input collection.
7477
- * @returns A collection containing only the last item in the input collection.
7478
- */
7479
- function last(input) {
7480
- return input.length === 0 ? [] : [input[input.length - 1]];
7481
- }
7482
- /**
7483
- * Returns a collection containing all but the first item in the input collection.
7484
- * Will return an empty collection if the input collection has no items, or only one item.
7485
- *
7486
- * See: https://hl7.org/fhirpath/#tail-collection
7487
- *
7488
- * @param input The input collection.
7489
- * @returns A collection containing all but the first item in the input collection.
7490
- */
7491
- function tail(input) {
7492
- return input.length === 0 ? [] : input.slice(1, input.length);
7493
- }
7494
- /**
7495
- * Returns a collection containing all but the first num items in the input collection.
7496
- * Will return an empty collection if there are no items remaining after the
7497
- * indicated number of items have been skipped, or if the input collection is empty.
7498
- * If num is less than or equal to zero, the input collection is simply returned.
7499
- *
7500
- * See: https://hl7.org/fhirpath/#skipnum-integer-collection
7501
- *
7502
- * @param input The input collection.
7503
- * @returns A collection containing all but the first item in the input collection.
7504
- */
7505
- function skip(input, num) {
7506
- const numValue = num.eval(0);
7507
- if (typeof numValue !== 'number') {
7508
- throw new Error('Expected a number for skip(num)');
7509
- }
7510
- if (numValue >= input.length) {
7511
- return [];
7512
- }
7513
- if (numValue <= 0) {
7514
- return input;
7515
- }
7516
- return input.slice(numValue, input.length);
7517
- }
7518
- /**
7519
- * Returns a collection containing the first num items in the input collection,
7520
- * or less if there are less than num items.
7521
- * If num is less than or equal to 0, or if the input collection is empty ({ }),
7522
- * take returns an empty collection.
7523
- *
7524
- * See: https://hl7.org/fhirpath/#takenum-integer-collection
7525
- *
7526
- * @param input The input collection.
7527
- * @returns A collection containing the first num items in the input collection.
7528
- */
7529
- function take(input, num) {
7530
- const numValue = num.eval(0);
7531
- if (typeof numValue !== 'number') {
7532
- throw new Error('Expected a number for take(num)');
7533
- }
7534
- if (numValue >= input.length) {
7535
- return input;
7536
- }
7537
- if (numValue <= 0) {
7538
- return [];
7539
- }
7540
- return input.slice(0, numValue);
7541
- }
7542
- /**
7543
- * Returns the set of elements that are in both collections.
7544
- * Duplicate items will be eliminated by this function.
7545
- * Order of items is not guaranteed to be preserved in the result of this function.
7546
- *
7547
- * See: http://hl7.org/fhirpath/#intersectother-collection-collection
7548
- */
7549
- function intersect(input, other) {
7550
- if (!other) {
7551
- return input;
7552
- }
7553
- const otherArray = ensureArray(other.eval(0));
7554
- return removeDuplicates(input.filter((e) => otherArray.includes(e)));
7555
- }
7556
- /**
7557
- * Returns the set of elements that are not in the other collection.
7558
- * Duplicate items will not be eliminated by this function, and order will be preserved.
7559
- *
7560
- * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
7561
- *
7562
- * See: http://hl7.org/fhirpath/#excludeother-collection-collection
7563
- */
7564
- function exclude(input, other) {
7565
- if (!other) {
7566
- return input;
7567
- }
7568
- const otherArray = ensureArray(other.eval(0));
7569
- return input.filter((e) => !otherArray.includes(e));
7570
- }
7571
- /*
7572
- * 5.4. Combining
7573
- *
7574
- * See: https://hl7.org/fhirpath/#combining
7575
- */
7576
- /**
7577
- * Merge the two collections into a single collection,
7578
- * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
7579
- * There is no expectation of order in the resulting collection.
7580
- *
7581
- * In other words, this function returns the distinct list of elements from both inputs.
7582
- *
7583
- * See: http://hl7.org/fhirpath/#unionother-collection
7584
- */
7585
- function union(input, other) {
7586
- if (!other) {
7587
- return input;
7588
- }
7589
- return removeDuplicates([input, other.eval(0)].flat());
7590
- }
7591
- /**
7592
- * Merge the input and other collections into a single collection
7593
- * without eliminating duplicate values. Combining an empty collection
7594
- * with a non-empty collection will return the non-empty collection.
7595
- *
7596
- * There is no expectation of order in the resulting collection.
7597
- *
7598
- * See: http://hl7.org/fhirpath/#combineother-collection-collection
7599
- */
7600
- function combine(input, other) {
7601
- if (!other) {
7602
- return input;
7603
- }
7604
- return [input, other.eval(0)].flat();
7605
- }
7606
- /*
7607
- * 5.5. Conversion
7608
- *
7609
- * See: https://hl7.org/fhirpath/#conversion
7610
- */
7611
- /**
7612
- * The iif function in FHIRPath is an immediate if,
7613
- * also known as a conditional operator (such as C’s ? : operator).
7614
- *
7615
- * The criterion expression is expected to evaluate to a Boolean.
7616
- *
7617
- * If criterion is true, the function returns the value of the true-result argument.
7618
- *
7619
- * If criterion is false or an empty collection, the function returns otherwise-result,
7620
- * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
7621
- *
7622
- * Note that short-circuit behavior is expected in this function. In other words,
7623
- * true-result should only be evaluated if the criterion evaluates to true,
7624
- * and otherwise-result should only be evaluated otherwise. For implementations,
7625
- * this means delaying evaluation of the arguments.
7626
- *
7627
- * @param input
7628
- * @param criterion
7629
- * @param trueResult
7630
- * @param otherwiseResult
7631
- * @returns
7632
- */
7633
- function iif(input, criterion, trueResult, otherwiseResult) {
7634
- const evalResult = ensureArray(criterion.eval(input));
7635
- if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0] !== 'boolean')) {
7636
- throw new Error('Expected criterion to evaluate to a Boolean');
7637
- }
7638
- if (toJsBoolean(evalResult)) {
7639
- return ensureArray(trueResult.eval(input));
7640
- }
7641
- if (otherwiseResult) {
7642
- return ensureArray(otherwiseResult.eval(input));
7643
- }
7644
- return [];
7645
- }
7646
- /**
7647
- * Converts an input collection to a boolean.
7648
- *
7649
- * If the input collection contains a single item, this function will return a single boolean if:
7650
- * 1) the item is a Boolean
7651
- * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
7652
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7653
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7654
- *
7655
- * If the item is not one the above types, or the item is a String, Integer, or Decimal, but is not equal to one of the possible values convertible to a Boolean, the result is empty.
7656
- *
7657
- * See: https://hl7.org/fhirpath/#toboolean-boolean
7658
- *
7659
- * @param input
7660
- * @returns
7661
- */
7662
- function toBoolean(input) {
7663
- if (input.length === 0) {
7664
- return [];
7665
- }
7666
- const [value] = validateInput(input, 1);
7667
- if (typeof value === 'boolean') {
7668
- return [value];
7669
- }
7670
- if (typeof value === 'number') {
7671
- if (value === 0 || value === 1) {
7672
- return [!!value];
7673
- }
7674
- }
7675
- if (typeof value === 'string') {
7676
- const lowerStr = value.toLowerCase();
7677
- if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
7678
- return [true];
7679
- }
7680
- if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
7681
- return [false];
7682
- }
7683
- }
7684
- return [];
7685
- }
7686
- /**
7687
- * If the input collection contains a single item, this function will return true if:
7688
- * 1) the item is a Boolean
7689
- * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
7690
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
7691
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
7692
- *
7693
- * If the item is not one of the above types, or the item is a String, Integer, or Decimal, but is not equal to one of the possible values convertible to a Boolean, the result is false.
7694
- *
7695
- * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
7696
- *
7697
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7698
- *
7699
- * If the input collection is empty, the result is empty.
7700
- *
7701
- * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
7702
- *
7703
- * @param input
7704
- * @returns
7705
- */
7706
- function convertsToBoolean(input) {
7707
- if (input.length === 0) {
7708
- return [];
7709
- }
7710
- return [toBoolean(input).length === 1];
7711
- }
7712
- /**
7713
- * Returns the integer representation of the input.
7714
- *
7715
- * If the input collection contains a single item, this function will return a single integer if:
7716
- * 1) the item is an Integer
7717
- * 2) the item is a String and is convertible to an integer
7718
- * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
7719
- *
7720
- * If the item is not one the above types, the result is empty.
7721
- *
7722
- * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
7723
- *
7724
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7725
- *
7726
- * If the input collection is empty, the result is empty.
7727
- *
7728
- * See: https://hl7.org/fhirpath/#tointeger-integer
7729
- *
7730
- * @param input The input collection.
7731
- * @returns The string representation of the input.
7732
- */
7733
- function toInteger(input) {
7734
- if (input.length === 0) {
7735
- return [];
7736
- }
7737
- const [value] = validateInput(input, 1);
7738
- if (typeof value === 'number') {
7739
- return [value];
7740
- }
7741
- if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
7742
- return [parseInt(value, 10)];
7743
- }
7744
- if (typeof value === 'boolean') {
7745
- return [value ? 1 : 0];
7746
- }
7747
- return [];
7748
- }
7749
- /**
7750
- * Returns true if the input can be converted to string.
7751
- *
7752
- * If the input collection contains a single item, this function will return true if:
7753
- * 1) the item is an Integer
7754
- * 2) the item is a String and is convertible to an Integer
7755
- * 3) the item is a Boolean
7756
- * 4) If the item is not one of the above types, or the item is a String, but is not convertible to an Integer (using the regex format (\\+|-)?\d+), the result is false.
7757
- *
7758
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7759
- *
7760
- * If the input collection is empty, the result is empty.
7761
- *
7762
- * See: https://hl7.org/fhirpath/#convertstointeger-boolean
7763
- *
7764
- * @param input The input collection.
7765
- * @returns
7766
- */
7767
- function convertsToInteger(input) {
7768
- if (input.length === 0) {
7769
- return [];
7770
- }
7771
- return [toInteger(input).length === 1];
7772
- }
7773
- /**
7774
- * If the input collection contains a single item, this function will return a single date if:
7775
- * 1) the item is a Date
7776
- * 2) the item is a DateTime
7777
- * 3) the item is a String and is convertible to a Date
7778
- *
7779
- * If the item is not one of the above types, the result is empty.
7780
- *
7781
- * If the item is a String, but the string is not convertible to a Date (using the format YYYY-MM-DD), the result is empty.
7782
- *
7783
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7784
- *
7785
- * If the input collection is empty, the result is empty.
7786
- *
7787
- * See: https://hl7.org/fhirpath/#todate-date
7788
- */
7789
- function toDate(input) {
7790
- if (input.length === 0) {
7791
- return [];
7792
- }
7793
- const [value] = validateInput(input, 1);
7794
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7795
- return [parseDateString(value)];
7796
- }
7797
- return [];
7798
- }
7799
- /**
7800
- * If the input collection contains a single item, this function will return true if:
7801
- * 1) the item is a Date
7802
- * 2) the item is a DateTime
7803
- * 3) the item is a String and is convertible to a Date
7804
- *
7805
- * If the item is not one of the above types, or is not convertible to a Date (using the format YYYY-MM-DD), the result is false.
7806
- *
7807
- * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
7808
- *
7809
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7810
- *
7811
- * If the input collection is empty, the result is empty.
7812
- *
7813
- * See: https://hl7.org/fhirpath/#convertstodate-boolean
7814
- */
7815
- function convertsToDate(input) {
7816
- if (input.length === 0) {
7817
- return [];
7818
- }
7819
- return [toDate(input).length === 1];
7820
- }
7821
- /**
7822
- * If the input collection contains a single item, this function will return a single datetime if:
7823
- * 1) the item is a DateTime
7824
- * 2) the item is a Date, in which case the result is a DateTime with the year, month, and day of the Date, and the time components empty (not set to zero)
7825
- * 3) the item is a String and is convertible to a DateTime
7826
- *
7827
- * If the item is not one of the above types, the result is empty.
7828
- *
7829
- * If the item is a String, but the string is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is empty.
7830
- *
7831
- * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
7832
- *
7833
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7834
- *
7835
- * If the input collection is empty, the result is empty.
7836
-
7837
- * See: https://hl7.org/fhirpath/#todatetime-datetime
7838
- *
7839
- * @param input
7840
- * @returns
7841
- */
7842
- function toDateTime(input) {
7843
- if (input.length === 0) {
7844
- return [];
7845
- }
7846
- const [value] = validateInput(input, 1);
7847
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
7848
- return [parseDateString(value)];
7849
- }
7850
- return [];
7851
- }
7852
- /**
7853
- * If the input collection contains a single item, this function will return true if:
7854
- * 1) the item is a DateTime
7855
- * 2) the item is a Date
7856
- * 3) the item is a String and is convertible to a DateTime
7857
- *
7858
- * If the item is not one of the above types, or is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is false.
7859
- *
7860
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7861
- *
7862
- * If the input collection is empty, the result is empty.
7863
- *
7864
- * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
7865
- *
7866
- * @param input
7867
- * @returns
7868
- */
7869
- function convertsToDateTime(input) {
7870
- if (input.length === 0) {
7871
- return [];
7872
- }
7873
- return [toDateTime(input).length === 1];
7874
- }
7875
- /**
7876
- * If the input collection contains a single item, this function will return a single decimal if:
7877
- * 1) the item is an Integer or Decimal
7878
- * 2) the item is a String and is convertible to a Decimal
7879
- * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
7880
- * 4) If the item is not one of the above types, the result is empty.
7881
- *
7882
- * If the item is a String, but the string is not convertible to a Decimal (using the regex format (\\+|-)?\d+(\.\d+)?), the result is empty.
7883
- *
7884
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7885
- *
7886
- * If the input collection is empty, the result is empty.
7887
- *
7888
- * See: https://hl7.org/fhirpath/#decimal-conversion-functions
7889
- *
7890
- * @param input The input collection.
7891
- * @returns
7892
- */
7893
- function toDecimal(input) {
7894
- if (input.length === 0) {
7895
- return [];
7896
- }
7897
- const [value] = validateInput(input, 1);
7898
- if (typeof value === 'number') {
7899
- return [value];
7900
- }
7901
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
7902
- return [parseFloat(value)];
7903
- }
7904
- if (typeof value === 'boolean') {
7905
- return [value ? 1 : 0];
7906
- }
7907
- return [];
7908
- }
7909
- /**
7910
- * If the input collection contains a single item, this function will true if:
7911
- * 1) the item is an Integer or Decimal
7912
- * 2) the item is a String and is convertible to a Decimal
7913
- * 3) the item is a Boolean
7914
- *
7915
- * If the item is not one of the above types, or is not convertible to a Decimal (using the regex format (\\+|-)?\d+(\.\d+)?), the result is false.
7916
- *
7917
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7918
- *
7919
- * If the input collection is empty, the result is empty.
7920
-
7921
- * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
7922
- *
7923
- * @param input The input collection.
7924
- * @returns
7925
- */
7926
- function convertsToDecimal(input) {
7927
- if (input.length === 0) {
7928
- return [];
7929
- }
7930
- return [toDecimal(input).length === 1];
7931
- }
7932
- /**
7933
- * If the input collection contains a single item, this function will return a single quantity if:
7934
- * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
7935
- * 2) the item is a Quantity
7936
- * 3) the item is a String and is convertible to a Quantity
7937
- * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
7938
- *
7939
- * If the item is not one of the above types, the result is empty.
7940
- *
7941
- * See: https://hl7.org/fhirpath/#quantity-conversion-functions
7942
- *
7943
- * @param input The input collection.
7944
- * @returns
7945
- */
7946
- function toQuantity(input) {
7947
- if (input.length === 0) {
7948
- return [];
7949
- }
7950
- const [value] = validateInput(input, 1);
7951
- if (isQuantity(value)) {
7952
- return [value];
7953
- }
7954
- if (typeof value === 'number') {
7955
- return [{ value, unit: '1' }];
7956
- }
7957
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
7958
- return [{ value: parseFloat(value), unit: '1' }];
7959
- }
7960
- if (typeof value === 'boolean') {
7961
- return [{ value: value ? 1 : 0, unit: '1' }];
7962
- }
7963
- return [];
7964
- }
7965
- /**
7966
- * If the input collection contains a single item, this function will return true if:
7967
- * 1) the item is an Integer, Decimal, or Quantity
7968
- * 2) the item is a String that is convertible to a Quantity
7969
- * 3) the item is a Boolean
7970
- *
7971
- * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
7972
- *
7973
- * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
7974
- *
7975
- * then the result is false.
7976
- *
7977
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
7978
- *
7979
- * If the input collection is empty, the result is empty.
7980
- *
7981
- * If the unit argument is provided, it must be the string representation of a UCUM code (or a FHIRPath calendar duration keyword), and is used to determine whether the input quantity can be converted to the given unit, according to the unit conversion rules specified by UCUM. If the input quantity can be converted, the result is true, otherwise, the result is false.
7982
- *
7983
- * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
7984
- *
7985
- * @param input The input collection.
7986
- * @returns
7987
- */
7988
- function convertsToQuantity(input) {
7989
- if (input.length === 0) {
7990
- return [];
7991
- }
7992
- return [toQuantity(input).length === 1];
7993
- }
7994
- /**
7995
- * Returns the string representation of the input.
7996
- *
7997
- * If the input collection contains a single item, this function will return a single String if:
7998
- *
7999
- * 1) the item in the input collection is a String
8000
- * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
8001
- * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
8002
- *
8003
- * If the item is not one of the above types, the result is false.
8004
- *
8005
- * See: https://hl7.org/fhirpath/#tostring-string
8006
- *
8007
- * @param input The input collection.
8008
- * @returns The string representation of the input.
8009
- */
8010
- function toString(input) {
8011
- if (input.length === 0) {
8012
- return [];
8013
- }
8014
- const [value] = validateInput(input, 1);
8015
- if (value === null || value === undefined) {
8016
- return [];
8017
- }
8018
- if (isQuantity(value)) {
8019
- return [`${value.value} '${value.unit}'`];
8020
- }
8021
- return [value.toString()];
8022
- }
8023
- /**
8024
- * Returns true if the input can be converted to string.
8025
- *
8026
- * If the input collection contains a single item, this function will return true if:
8027
- * 1) the item is a String
8028
- * 2) the item is an Integer, Decimal, Date, Time, or DateTime
8029
- * 3) the item is a Boolean
8030
- * 4) the item is a Quantity
8031
- *
8032
- * If the item is not one of the above types, the result is false.
8033
- *
8034
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8035
- *
8036
- * If the input collection is empty, the result is empty.
8037
- *
8038
- * See: https://hl7.org/fhirpath/#tostring-string
8039
- *
8040
- * @param input The input collection.
8041
- * @returns
8042
- */
8043
- function convertsToString(input) {
8044
- if (input.length === 0) {
8045
- return [];
8046
- }
8047
- return [toString(input).length === 1];
8048
- }
8049
- /**
8050
- * If the input collection contains a single item, this function will return a single time if:
8051
- * 1) the item is a Time
8052
- * 2) the item is a String and is convertible to a Time
8053
- *
8054
- * If the item is not one of the above types, the result is empty.
8055
- *
8056
- * If the item is a String, but the string is not convertible to a Time (using the format hh:mm:ss.fff(+|-)hh:mm), the result is empty.
8057
- *
8058
- * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
8059
- *
8060
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8061
- *
8062
- * If the input collection is empty, the result is empty.
8063
- *
8064
- * See: https://hl7.org/fhirpath/#totime-time
8065
- *
8066
- * @param input
8067
- * @returns
8068
- */
8069
- function toTime(input) {
8070
- if (input.length === 0) {
8071
- return [];
8072
- }
8073
- const [value] = validateInput(input, 1);
8074
- if (typeof value === 'string') {
8075
- const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
8076
- if (match) {
8077
- return [parseDateString('T' + match[1])];
8078
- }
8079
- }
8080
- return [];
8081
- }
8082
- /**
8083
- * If the input collection contains a single item, this function will return true if:
8084
- * 1) the item is a Time
8085
- * 2) the item is a String and is convertible to a Time
8086
- *
8087
- * If the item is not one of the above types, or is not convertible to a Time (using the format hh:mm:ss.fff(+|-)hh:mm), the result is false.
8088
- *
8089
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8090
- *
8091
- * If the input collection is empty, the result is empty.
8092
- *
8093
- * See: https://hl7.org/fhirpath/#convertstotime-boolean
8094
- *
8095
- * @param input
8096
- * @returns
8097
- */
8098
- function convertsToTime(input) {
8099
- if (input.length === 0) {
8100
- return [];
8101
- }
8102
- return [toTime(input).length === 1];
8103
- }
8104
- /*
8105
- * 5.6. String Manipulation.
8106
- *
8107
- * See: https://hl7.org/fhirpath/#string-manipulation
8108
- */
8109
- /**
8110
- * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
8111
- *
8112
- * If substring is an empty string (''), the function returns 0.
8113
- *
8114
- * If the input or substring is empty ({ }), the result is empty ({ }).
8115
- *
8116
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8117
- *
8118
- * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
8119
- *
8120
- * @param input The input collection.
8121
- * @returns The index of the substring.
8122
- */
8123
- function indexOf(input, substringAtom) {
8124
- return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
8125
- }
8126
- /**
8127
- * Returns the part of the string starting at position start (zero-based). If length is given, will return at most length number of characters from the input string.
8128
- *
8129
- * If start lies outside the length of the string, the function returns empty ({ }). If there are less remaining characters in the string than indicated by length, the function returns just the remaining characters.
8130
- *
8131
- * If the input or start is empty, the result is empty.
8132
- *
8133
- * If an empty length is provided, the behavior is the same as if length had not been provided.
8134
- *
8135
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8136
- *
8137
- * @param input The input collection.
8138
- * @returns The index of the substring.
8139
- */
8140
- function substring(input, startAtom, lengthAtom) {
8141
- return applyStringFunc((str, start, length) => {
8142
- const startIndex = start;
8143
- const endIndex = length ? startIndex + length : str.length;
8144
- return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
8145
- }, input, startAtom, lengthAtom);
8146
- }
8147
- /**
8148
- *
8149
- * @param input The input collection.
8150
- * @returns The index of the substring.
8151
- */
8152
- function startsWith(input, prefixAtom) {
8153
- return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
8154
- }
8155
- /**
8156
- *
8157
- * @param input The input collection.
8158
- * @returns The index of the substring.
8159
- */
8160
- function endsWith(input, suffixAtom) {
8161
- return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
8162
- }
8163
- /**
8164
- *
8165
- * @param input The input collection.
8166
- * @returns The index of the substring.
8167
- */
8168
- function contains(input, substringAtom) {
8169
- return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
8170
- }
8171
- /**
8172
- *
8173
- * @param input The input collection.
8174
- * @returns The index of the substring.
8175
- */
8176
- function upper(input) {
8177
- return applyStringFunc((str) => str.toUpperCase(), input);
8178
- }
8179
- /**
8180
- *
8181
- * @param input The input collection.
8182
- * @returns The index of the substring.
8183
- */
8184
- function lower(input) {
8185
- return applyStringFunc((str) => str.toLowerCase(), input);
8186
- }
8187
- /**
8188
- *
8189
- * @param input The input collection.
8190
- * @returns The index of the substring.
8191
- */
8192
- function replace(input, patternAtom, substitionAtom) {
8193
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
8194
- }
8195
- /**
8196
- *
8197
- * @param input The input collection.
8198
- * @returns The index of the substring.
8199
- */
8200
- function matches(input, regexAtom) {
8201
- return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
8202
- }
8203
- /**
8204
- *
8205
- * @param input The input collection.
8206
- * @returns The index of the substring.
8207
- */
8208
- function replaceMatches(input, regexAtom, substitionAtom) {
8209
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
8210
- }
8211
- /**
8212
- *
8213
- * @param input The input collection.
8214
- * @returns The index of the substring.
8215
- */
8216
- function length(input) {
8217
- return applyStringFunc((str) => str.length, input);
8218
- }
8219
- /**
8220
- * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
8221
- *
8222
- * See: https://hl7.org/fhirpath/#tochars-collection
8223
- *
8224
- * @param input The input collection.
8225
- */
8226
- function toChars(input) {
8227
- return applyStringFunc((str) => (str ? str.split('') : undefined), input);
8228
- }
8229
- /*
8230
- * 5.7. Math
8231
- */
8232
- /**
8233
- * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
8234
- *
8235
- * If the input collection is empty, the result is empty.
8236
- *
8237
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8238
- *
8239
- * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
8240
- *
8241
- * @param input The input collection.
8242
- * @returns A collection containing the result.
8243
- */
8244
- function abs(input) {
8245
- return applyMathFunc(Math.abs, input);
8246
- }
8247
- /**
8248
- * Returns the first integer greater than or equal to the input.
8249
- *
8250
- * If the input collection is empty, the result is empty.
8251
- *
8252
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8253
- *
8254
- * See: https://hl7.org/fhirpath/#ceiling-integer
8255
- *
8256
- * @param input The input collection.
8257
- * @returns A collection containing the result.
8258
- */
8259
- function ceiling(input) {
8260
- return applyMathFunc(Math.ceil, input);
8261
- }
8262
- /**
8263
- * Returns e raised to the power of the input.
8264
- *
8265
- * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
8266
- *
8267
- * If the input collection is empty, the result is empty.
8268
- *
8269
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8270
- *
8271
- * See: https://hl7.org/fhirpath/#exp-decimal
8272
- *
8273
- * @param input The input collection.
8274
- * @returns A collection containing the result.
8275
- */
8276
- function exp(input) {
8277
- return applyMathFunc(Math.exp, input);
8278
- }
8279
- /**
8280
- * Returns the first integer less than or equal to the input.
8281
- *
8282
- * If the input collection is empty, the result is empty.
8283
- *
8284
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8285
- *
8286
- * See: https://hl7.org/fhirpath/#floor-integer
8287
- *
8288
- * @param input The input collection.
8289
- * @returns A collection containing the result.
8290
- */
8291
- function floor(input) {
8292
- return applyMathFunc(Math.floor, input);
8293
- }
8294
- /**
8295
- * Returns the natural logarithm of the input (i.e. the logarithm base e).
8296
- *
8297
- * When used with an Integer, it will be implicitly converted to a Decimal.
8298
- *
8299
- * If the input collection is empty, the result is empty.
8300
- *
8301
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8302
- *
8303
- * See: https://hl7.org/fhirpath/#ln-decimal
8304
- *
8305
- * @param input The input collection.
8306
- * @returns A collection containing the result.
8307
- */
8308
- function ln(input) {
8309
- return applyMathFunc(Math.log, input);
8310
- }
8311
- /**
8312
- * Returns the logarithm base base of the input number.
8313
- *
8314
- * When used with Integers, the arguments will be implicitly converted to Decimal.
8315
- *
8316
- * If base is empty, the result is empty.
8317
- *
8318
- * If the input collection is empty, the result is empty.
8319
- *
8320
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8321
- *
8322
- * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
8323
- *
8324
- * @param input The input collection.
8325
- * @returns A collection containing the result.
8326
- */
8327
- function log(input, baseAtom) {
8328
- return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
8329
- }
8330
- /**
8331
- * Raises a number to the exponent power. If this function is used with Integers, the result is an Integer. If the function is used with Decimals, the result is a Decimal. If the function is used with a mixture of Integer and Decimal, the Integer is implicitly converted to a Decimal and the result is a Decimal.
8332
- *
8333
- * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
8334
- *
8335
- * If the input is empty, or exponent is empty, the result is empty.
8336
- *
8337
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8338
- *
8339
- * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
8340
- *
8341
- * @param input The input collection.
8342
- * @returns A collection containing the result.
8343
- */
8344
- function power(input, expAtom) {
8345
- return applyMathFunc(Math.pow, input, expAtom);
8346
- }
8347
- /**
8348
- * Rounds the decimal to the nearest whole number using a traditional round (i.e. 0.5 or higher will round to 1). If specified, the precision argument determines the decimal place at which the rounding will occur. If not specified, the rounding will default to 0 decimal places.
8349
- *
8350
- * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
8351
- *
8352
- * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
8353
- *
8354
- * If the input collection is empty, the result is empty.
8355
- *
8356
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8357
- *
8358
- * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
8359
- *
8360
- * @param input The input collection.
8361
- * @returns A collection containing the result.
8362
- */
8363
- function round(input) {
8364
- return applyMathFunc(Math.round, input);
8365
- }
8366
- /**
8367
- * Returns the square root of the input number as a Decimal.
8368
- *
8369
- * If the square root cannot be represented (such as the square root of -1), the result is empty.
8370
- *
8371
- * If the input collection is empty, the result is empty.
8372
- *
8373
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8374
- *
8375
- * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
8376
- *
8377
- * See: https://hl7.org/fhirpath/#sqrt-decimal
8378
- *
8379
- * @param input The input collection.
8380
- * @returns A collection containing the result.
8381
- */
8382
- function sqrt(input) {
8383
- return applyMathFunc(Math.sqrt, input);
8384
- }
8385
- /**
8386
- * Returns the integer portion of the input.
8387
- *
8388
- * If the input collection is empty, the result is empty.
8389
- *
8390
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
8391
- *
8392
- * See: https://hl7.org/fhirpath/#truncate-integer
8393
- *
8394
- * @param input The input collection.
8395
- * @returns A collection containing the result.
8396
- */
8397
- function truncate(input) {
8398
- return applyMathFunc((x) => x | 0, input);
8399
- }
8400
- /*
8401
- * 5.8. Tree navigation
8402
- */
8403
- const children = stub;
8404
- const descendants = stub;
8405
- /*
8406
- * 5.9. Utility functions
8407
- */
8408
- /**
8409
- * Adds a String representation of the input collection to the diagnostic log,
8410
- * using the name argument as the name in the log. This log should be made available
8411
- * to the user in some appropriate fashion. Does not change the input, so returns
8412
- * the input collection as output.
8413
- *
8414
- * If the projection argument is used, the trace would log the result of evaluating
8415
- * the project expression on the input, but still return the input to the trace
8416
- * function unchanged.
8417
- *
8418
- * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
8419
- *
8420
- * @param input The input collection.
8421
- * @param nameAtom The log name.
8422
- */
8423
- function trace(input, nameAtom) {
8424
- console.log('trace', input, nameAtom);
8425
- return input;
8426
- }
8427
- /**
8428
- * Returns the current date and time, including timezone offset.
8429
- *
8430
- * See: https://hl7.org/fhirpath/#now-datetime
8431
- */
8432
- function now() {
8433
- return [new Date().toISOString()];
8434
- }
8435
- /**
8436
- * Returns the current time.
8437
- *
8438
- * See: https://hl7.org/fhirpath/#timeofday-time
8439
- */
8440
- function timeOfDay() {
8441
- return [new Date().toISOString().substring(11)];
8442
- }
8443
- /**
8444
- * Returns the current date.
8445
- *
8446
- * See: https://hl7.org/fhirpath/#today-date
8447
- */
8448
- function today() {
8449
- return [new Date().toISOString().substring(0, 10)];
8450
- }
8451
- /**
8452
- * Calculates the difference between two dates or date/times.
8453
- *
8454
- * This is not part of the official FHIRPath spec.
8455
- *
8456
- * IBM FHIR issue: https://github.com/IBM/FHIR/issues/1014
8457
- * IBM FHIR PR: https://github.com/IBM/FHIR/pull/1023
8458
- */
8459
- function between(context, startAtom, endAtom, unitsAtom) {
8460
- const startDate = toDateTime(ensureArray(startAtom.eval(context)));
8461
- if (startDate.length === 0) {
8462
- throw new Error('Invalid start date');
8463
- }
8464
- const endDate = toDateTime(ensureArray(endAtom.eval(context)));
8465
- if (endDate.length === 0) {
8466
- throw new Error('Invalid end date');
8467
- }
8468
- const unit = unitsAtom.eval(context);
8469
- if (unit !== 'years' && unit !== 'months' && unit !== 'days') {
8470
- throw new Error('Invalid units');
8471
- }
8472
- const age = calculateAge(startDate[0], endDate[0]);
8473
- return [{ value: age[unit], unit }];
8474
- }
8475
- /*
8476
- * 6.3 Types
8477
- */
8478
- /**
8479
- * The is() function is supported for backwards compatibility with previous
8480
- * implementations of FHIRPath. Just as with the is keyword, the type argument
8481
- * is an identifier that must resolve to the name of a type in a model.
8482
- *
8483
- * For implementations with compile-time typing, this requires special-case
8484
- * handling when processing the argument to treat it as a type specifier rather
8485
- * than an identifier expression:
8486
- *
8487
- * @param input
8488
- * @param typeAtom
8489
- * @returns
8490
- */
8491
- function is(input, typeAtom) {
8492
- const typeName = typeAtom.name;
8493
- return input.map((value) => fhirPathIs(value, typeName));
8494
- }
8495
- /*
8496
- * 6.5 Boolean logic
8497
- */
8498
- /**
8499
- * 6.5.3. not() : Boolean
8500
- *
8501
- * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
8502
- *
8503
- * @param input
8504
- * @returns
8505
- */
8506
- function not(input) {
8507
- return toBoolean(input).map((value) => !value);
8508
- }
8509
- /*
8510
- * Additional functions
8511
- * See: https://hl7.org/fhir/fhirpath.html#functions
8512
- */
8513
- /**
8514
- * For each item in the collection, if it is a string that is a uri (or canonical or url), locate the target of the reference, and add it to the resulting collection. If the item does not resolve to a resource, the item is ignored and nothing is added to the output collection.
8515
- * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
8516
- * @param input The input collection.
8517
- * @returns
8518
- */
8519
- function resolve(input) {
8520
- return input
8521
- .map((e) => {
8522
- let refStr;
8523
- if (typeof e === 'string') {
8524
- refStr = e;
8525
- }
8526
- else if (typeof e === 'object') {
8527
- const ref = e;
8528
- if (ref.resource) {
8529
- return ref.resource;
8530
- }
8531
- refStr = ref.reference;
8532
- }
8533
- if (!refStr) {
8534
- return undefined;
8535
- }
8536
- const [resourceType, id] = refStr.split('/');
8537
- return { resourceType, id };
8538
- })
8539
- .filter((e) => !!e);
8540
- }
8541
- /**
8542
- * The as operator can be used to treat a value as a specific type.
8543
- * @param context The context value.
8544
- * @returns The value as the specific type.
8545
- */
8546
- function as(context) {
8547
- return context;
8548
- }
8549
- /*
8550
- * 12. Formal Specifications
8551
- */
8552
- /**
8553
- * Returns the type of the input.
8554
- *
8555
- * 12.2. Model Information
8556
- *
8557
- * The model information returned by the reflection function type() is specified as an
8558
- * XML Schema document (xsd) and included in this specification at the following link:
8559
- * https://hl7.org/fhirpath/modelinfo.xsd
8560
- *
8561
- * See: https://hl7.org/fhirpath/#model-information
8562
- *
8563
- * @param input The input collection.
8564
- * @returns
8565
- */
8566
- function type(input) {
8567
- return input.map((value) => {
8568
- if (typeof value === 'boolean') {
8569
- return { namespace: 'System', name: 'Boolean' };
8570
- }
8571
- if (typeof value === 'number') {
8572
- return { namespace: 'System', name: 'Integer' };
8573
- }
8574
- if (value && typeof value === 'object' && 'resourceType' in value) {
8575
- return { namespace: 'FHIR', name: value.resourceType };
8576
- }
8577
- return null;
8578
- });
8579
- }
8580
- function conformsTo(input, systemAtom) {
8581
- const system = systemAtom.eval(undefined);
8582
- if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
8583
- throw new Error('Expected a StructureDefinition URL');
8584
- }
8585
- const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
8586
- return input.map((resource) => (resource === null || resource === void 0 ? void 0 : resource.resourceType) === expectedResourceType);
8587
- }
8588
- /*
8589
- * Helper utilities
8590
- */
8591
- function applyStringFunc(func, input, ...argsAtoms) {
8592
- if (input.length === 0) {
8593
- return [];
8594
- }
8595
- const [value] = validateInput(input, 1);
8596
- if (typeof value !== 'string') {
8597
- throw new Error('String function cannot be called with non-string');
8598
- }
8599
- const result = func(value, ...argsAtoms.map((atom) => atom && atom.eval(value)));
8600
- return result === undefined ? [] : [result];
8601
- }
8602
- function applyMathFunc(func, input, ...argsAtoms) {
8603
- if (input.length === 0) {
8604
- return [];
8605
- }
8606
- const [value] = validateInput(input, 1);
8607
- const quantity = isQuantity(value);
8608
- const numberInput = quantity ? value.value : value;
8609
- if (typeof numberInput !== 'number') {
8610
- throw new Error('Math function cannot be called with non-number');
8611
- }
8612
- const result = func(numberInput, ...argsAtoms.map((atom) => atom.eval(undefined)));
8613
- return quantity ? [Object.assign(Object.assign({}, value), { value: result })] : [result];
8614
- }
8615
- function validateInput(input, count) {
8616
- if (input.length !== count) {
8617
- throw new Error(`Expected ${count} arguments`);
8618
- }
8619
- return input;
8620
- }
8621
-
8622
- var functions = /*#__PURE__*/Object.freeze({
8623
- __proto__: null,
8624
- empty: empty,
8625
- exists: exists,
8626
- all: all,
8627
- allTrue: allTrue,
8628
- anyTrue: anyTrue,
8629
- allFalse: allFalse,
8630
- anyFalse: anyFalse,
8631
- subsetOf: subsetOf,
8632
- supersetOf: supersetOf,
8633
- count: count,
8634
- distinct: distinct,
8635
- isDistinct: isDistinct,
8636
- where: where,
8637
- select: select,
8638
- repeat: repeat,
8639
- ofType: ofType,
8640
- single: single,
8641
- first: first,
8642
- last: last,
8643
- tail: tail,
8644
- skip: skip,
8645
- take: take,
8646
- intersect: intersect,
8647
- exclude: exclude,
8648
- union: union,
8649
- combine: combine,
8650
- iif: iif,
8651
- toBoolean: toBoolean,
8652
- convertsToBoolean: convertsToBoolean,
8653
- toInteger: toInteger,
8654
- convertsToInteger: convertsToInteger,
8655
- toDate: toDate,
8656
- convertsToDate: convertsToDate,
8657
- toDateTime: toDateTime,
8658
- convertsToDateTime: convertsToDateTime,
8659
- toDecimal: toDecimal,
8660
- convertsToDecimal: convertsToDecimal,
8661
- toQuantity: toQuantity,
8662
- convertsToQuantity: convertsToQuantity,
8663
- toString: toString,
8664
- convertsToString: convertsToString,
8665
- toTime: toTime,
8666
- convertsToTime: convertsToTime,
8667
- indexOf: indexOf,
8668
- substring: substring,
8669
- startsWith: startsWith,
8670
- endsWith: endsWith,
8671
- contains: contains,
8672
- upper: upper,
8673
- lower: lower,
8674
- replace: replace,
8675
- matches: matches,
8676
- replaceMatches: replaceMatches,
8677
- length: length,
8678
- toChars: toChars,
8679
- abs: abs,
8680
- ceiling: ceiling,
8681
- exp: exp,
8682
- floor: floor,
8683
- ln: ln,
8684
- log: log,
8685
- power: power,
8686
- round: round,
8687
- sqrt: sqrt,
8688
- truncate: truncate,
8689
- children: children,
8690
- descendants: descendants,
8691
- trace: trace,
8692
- now: now,
8693
- timeOfDay: timeOfDay,
8694
- today: today,
8695
- between: between,
8696
- is: is,
8697
- not: not,
8698
- resolve: resolve,
8699
- as: as,
8700
- type: type,
8701
- conformsTo: conformsTo
8702
- });
8703
-
8704
- var _Tokenizer_instances, _Tokenizer_str, _Tokenizer_pos, _Tokenizer_peekToken, _Tokenizer_consumeToken, _Tokenizer_consumeWhitespace, _Tokenizer_consumeMultiLineComment, _Tokenizer_consumeSingleLineComment, _Tokenizer_consumeString, _Tokenizer_consumeBacktickSymbol, _Tokenizer_consumeDateTime, _Tokenizer_consumeNumber, _Tokenizer_consumeSymbol, _Tokenizer_consumeOperator, _Tokenizer_consumeWhile, _Tokenizer_curr, _Tokenizer_prev, _Tokenizer_peek;
8705
- function tokenize(str) {
8706
- return new Tokenizer(str).tokenize();
8707
- }
8708
- const STANDARD_UNITS = [
8709
- 'year',
8710
- 'years',
8711
- 'month',
8712
- 'months',
8713
- 'week',
8714
- 'weeks',
8715
- 'day',
8716
- 'days',
8717
- 'hour',
8718
- 'hours',
8719
- 'minute',
8720
- 'minutes',
8721
- 'second',
8722
- 'seconds',
8723
- 'millisecond',
8724
- 'milliseconds',
8725
- ];
8726
- const TWO_CHAR_OPERATORS = ['!=', '!~', '<=', '>=', '{}'];
8727
- class Tokenizer {
8728
- constructor(str) {
8729
- _Tokenizer_instances.add(this);
8730
- _Tokenizer_str.set(this, void 0);
8731
- _Tokenizer_pos.set(this, void 0);
8732
- __classPrivateFieldSet(this, _Tokenizer_str, str, "f");
8733
- __classPrivateFieldSet(this, _Tokenizer_pos, 0, "f");
8734
- }
8735
- tokenize() {
8736
- const result = [];
8737
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length) {
8738
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8739
- if (token) {
8740
- result.push(token);
8741
- }
8742
- }
8743
- return result;
8744
- }
8745
- }
8746
- _Tokenizer_str = new WeakMap(), _Tokenizer_pos = new WeakMap(), _Tokenizer_instances = new WeakSet(), _Tokenizer_peekToken = function _Tokenizer_peekToken() {
8747
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8748
- const token = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8749
- __classPrivateFieldSet(this, _Tokenizer_pos, start, "f");
8750
- return token;
8751
- }, _Tokenizer_consumeToken = function _Tokenizer_consumeToken() {
8752
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhitespace).call(this);
8753
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8754
- if (!c) {
8755
- return undefined;
8756
- }
8757
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8758
- if (c === '/' && next === '*') {
8759
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeMultiLineComment).call(this);
8760
- }
8761
- if (c === '/' && next === '/') {
8762
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSingleLineComment).call(this);
8763
- }
8764
- if (c === "'") {
8765
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeString).call(this);
8766
- }
8767
- if (c === '`') {
8768
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeBacktickSymbol).call(this);
8769
- }
8770
- if (c === '@') {
8771
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeDateTime).call(this);
8772
- }
8773
- if (c.match(/\d/)) {
8774
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeNumber).call(this);
8775
- }
8776
- if (c.match(/\w/)) {
8777
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8778
- }
8779
- if (c === '$' && next.match(/\w/)) {
8780
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeSymbol).call(this);
8781
- }
8782
- return __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeOperator).call(this);
8783
- }, _Tokenizer_consumeWhitespace = function _Tokenizer_consumeWhitespace() {
8784
- return buildToken('Whitespace', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\s/)));
8785
- }, _Tokenizer_consumeMultiLineComment = function _Tokenizer_consumeMultiLineComment() {
8786
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8787
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '*' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this) !== '/');
8788
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8789
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8790
- }, _Tokenizer_consumeSingleLineComment = function _Tokenizer_consumeSingleLineComment() {
8791
- return buildToken('Comment', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '\n'));
8792
- }, _Tokenizer_consumeString = function _Tokenizer_consumeString() {
8793
- var _a, _b;
8794
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8795
- const result = buildToken('String', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_prev).call(this) === '\\' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== "'"));
8796
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8797
- return result;
8798
- }, _Tokenizer_consumeBacktickSymbol = function _Tokenizer_consumeBacktickSymbol() {
8799
- var _a, _b;
8800
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8801
- const result = buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) !== '`'));
8802
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8803
- return result;
8804
- }, _Tokenizer_consumeDateTime = function _Tokenizer_consumeDateTime() {
8805
- var _a, _b, _c, _d, _e;
8806
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8807
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8808
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d-]/));
8809
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'T') {
8810
- __classPrivateFieldSet(this, _Tokenizer_pos, (_b = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _b++, _b), "f");
8811
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8812
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8813
- __classPrivateFieldSet(this, _Tokenizer_pos, (_c = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _c++, _c), "f");
8814
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d]/));
8815
- }
8816
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === 'Z') {
8817
- __classPrivateFieldSet(this, _Tokenizer_pos, (_d = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _d++, _d), "f");
8818
- }
8819
- else if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '+' || __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '-') {
8820
- __classPrivateFieldSet(this, _Tokenizer_pos, (_e = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _e++, _e), "f");
8821
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[\d:]/));
8822
- }
8823
- }
8824
- return buildToken('DateTime', __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start + 1, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8825
- }, _Tokenizer_consumeNumber = function _Tokenizer_consumeNumber() {
8826
- var _a;
8827
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8828
- let id = 'Number';
8829
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8830
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === '.' && __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this).match(/\d/)) {
8831
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8832
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/\d/));
8833
- }
8834
- if (__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this) === ' ') {
8835
- if (isUnitToken(__classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peekToken).call(this))) {
8836
- id = 'Quantity';
8837
- __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeToken).call(this);
8838
- }
8839
- }
8840
- return buildToken(id, __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f")));
8841
- }, _Tokenizer_consumeSymbol = function _Tokenizer_consumeSymbol() {
8842
- return buildToken('Symbol', __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_consumeWhile).call(this, () => __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this).match(/[$\w]/)));
8843
- }, _Tokenizer_consumeOperator = function _Tokenizer_consumeOperator() {
8844
- var _a;
8845
- const c = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_curr).call(this);
8846
- const next = __classPrivateFieldGet(this, _Tokenizer_instances, "m", _Tokenizer_peek).call(this);
8847
- const twoCharOp = c + next;
8848
- if (TWO_CHAR_OPERATORS.includes(twoCharOp)) {
8849
- __classPrivateFieldSet(this, _Tokenizer_pos, __classPrivateFieldGet(this, _Tokenizer_pos, "f") + 2, "f");
8850
- return buildToken(twoCharOp, twoCharOp);
8851
- }
8852
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8853
- return buildToken(c, c);
8854
- }, _Tokenizer_consumeWhile = function _Tokenizer_consumeWhile(condition) {
8855
- var _a;
8856
- const start = __classPrivateFieldGet(this, _Tokenizer_pos, "f");
8857
- while (__classPrivateFieldGet(this, _Tokenizer_pos, "f") < __classPrivateFieldGet(this, _Tokenizer_str, "f").length && condition()) {
8858
- __classPrivateFieldSet(this, _Tokenizer_pos, (_a = __classPrivateFieldGet(this, _Tokenizer_pos, "f"), _a++, _a), "f");
8859
- }
8860
- return __classPrivateFieldGet(this, _Tokenizer_str, "f").substring(start, __classPrivateFieldGet(this, _Tokenizer_pos, "f"));
8861
- }, _Tokenizer_curr = function _Tokenizer_curr() {
8862
- return __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f")];
8863
- }, _Tokenizer_prev = function _Tokenizer_prev() {
8864
- var _a;
8865
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") - 1]) !== null && _a !== void 0 ? _a : '';
8866
- }, _Tokenizer_peek = function _Tokenizer_peek() {
8867
- var _a;
8868
- return (_a = __classPrivateFieldGet(this, _Tokenizer_str, "f")[__classPrivateFieldGet(this, _Tokenizer_pos, "f") + 1]) !== null && _a !== void 0 ? _a : '';
8869
- };
8870
- function buildToken(id, value) {
8871
- return { id, value };
8872
- }
8873
- function isUnitToken(token) {
8874
- if (token) {
8875
- if (token.id === 'String') {
8876
- return true;
8877
- }
8878
- if (token.id === 'Symbol' && STANDARD_UNITS.includes(token.value)) {
8879
- return true;
8880
- }
8881
- }
8882
- return false;
8883
- }
8884
-
8885
- var _ParserBuilder_prefixParselets, _ParserBuilder_infixParselets, _Parser_instances, _Parser_tokens, _Parser_prefixParselets, _Parser_infixParselets, _Parser_getPrecedence, _Parser_consume, _Parser_look;
8886
- class ParserBuilder {
8887
- constructor() {
8888
- _ParserBuilder_prefixParselets.set(this, {});
8889
- _ParserBuilder_infixParselets.set(this, {});
8890
- }
8891
- registerInfix(tokenType, parselet) {
8892
- __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f")[tokenType] = parselet;
8893
- return this;
8894
- }
8895
- registerPrefix(tokenType, parselet) {
8896
- __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f")[tokenType] = parselet;
8897
- return this;
8898
- }
8899
- prefix(tokenType, precedence, builder) {
8900
- return this.registerPrefix(tokenType, {
8901
- parse(parser, token) {
8902
- const right = parser.consumeAndParse(precedence);
8903
- return builder(token, right);
8904
- },
8905
- });
8906
- }
8907
- infixLeft(tokenType, precedence, builder) {
8908
- return this.registerInfix(tokenType, {
8909
- parse(parser, left, token) {
8910
- const right = parser.consumeAndParse(precedence);
8911
- return builder(left, token, right);
8912
- },
8913
- precedence,
8914
- });
8915
- }
8916
- construct(input) {
8917
- return new Parser(tokenize(input), __classPrivateFieldGet(this, _ParserBuilder_prefixParselets, "f"), __classPrivateFieldGet(this, _ParserBuilder_infixParselets, "f"));
8918
- }
8919
- }
8920
- _ParserBuilder_prefixParselets = new WeakMap(), _ParserBuilder_infixParselets = new WeakMap();
8921
- class Parser {
8922
- constructor(tokens, prefixParselets, infixParselets) {
8923
- _Parser_instances.add(this);
8924
- _Parser_tokens.set(this, void 0);
8925
- _Parser_prefixParselets.set(this, void 0);
8926
- _Parser_infixParselets.set(this, void 0);
8927
- __classPrivateFieldSet(this, _Parser_tokens, tokens, "f");
8928
- __classPrivateFieldSet(this, _Parser_prefixParselets, prefixParselets, "f");
8929
- __classPrivateFieldSet(this, _Parser_infixParselets, infixParselets, "f");
8930
- }
8931
- match(expected) {
8932
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8933
- if ((token === null || token === void 0 ? void 0 : token.id) !== expected) {
8934
- return false;
8935
- }
8936
- __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8937
- return true;
8938
- }
8939
- consumeAndParse(precedence = 100 /* MaximumPrecedence */) {
8940
- const token = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8941
- const prefix = __classPrivateFieldGet(this, _Parser_prefixParselets, "f")[token.id];
8942
- if (!prefix) {
8943
- throw Error(`Parse error at ${token.value}. No matching prefix parselet.`);
8944
- }
8945
- let left = prefix.parse(this, token);
8946
- while (precedence > __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_getPrecedence).call(this)) {
8947
- const next = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_consume).call(this);
8948
- const infix = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[next.id];
8949
- left = infix.parse(this, left, next);
8950
- }
8951
- return left;
8952
- }
8953
- }
8954
- _Parser_tokens = new WeakMap(), _Parser_prefixParselets = new WeakMap(), _Parser_infixParselets = new WeakMap(), _Parser_instances = new WeakSet(), _Parser_getPrecedence = function _Parser_getPrecedence() {
8955
- const nextToken = __classPrivateFieldGet(this, _Parser_instances, "m", _Parser_look).call(this);
8956
- if (!nextToken) {
8957
- return 100 /* MaximumPrecedence */;
8958
- }
8959
- const parser = __classPrivateFieldGet(this, _Parser_infixParselets, "f")[nextToken.id];
8960
- if (parser) {
8961
- return parser.precedence;
8962
- }
8963
- return 100 /* MaximumPrecedence */;
8964
- }, _Parser_consume = function _Parser_consume() {
8965
- if (!__classPrivateFieldGet(this, _Parser_tokens, "f").length) {
8966
- throw Error('Cant consume unknown more tokens.');
8967
- }
8968
- return __classPrivateFieldGet(this, _Parser_tokens, "f").shift();
8969
- }, _Parser_look = function _Parser_look() {
8970
- return __classPrivateFieldGet(this, _Parser_tokens, "f").length > 0 ? __classPrivateFieldGet(this, _Parser_tokens, "f")[0] : undefined;
8971
- };
8972
- const PARENTHESES_PARSELET = {
8973
- parse(parser) {
8974
- const expr = parser.consumeAndParse();
8975
- if (!parser.match(')')) {
8976
- throw new Error('Parse error: expected `)`');
8977
- }
8978
- return expr;
8979
- },
8980
- };
8981
- const INDEXER_PARSELET = {
8982
- parse(parser, left) {
8983
- const expr = parser.consumeAndParse();
8984
- if (!parser.match(']')) {
8985
- throw new Error('Parse error: expected `]`');
8986
- }
8987
- return new IndexerAtom(left, expr);
8988
- },
8989
- precedence: 2 /* Indexer */,
8990
- };
8991
- const FUNCTION_CALL_PARSELET = {
8992
- parse(parser, left) {
8993
- if (!(left instanceof SymbolAtom)) {
8994
- throw new Error('Unexpected parentheses');
8995
- }
8996
- if (!(left.name in functions)) {
8997
- throw new Error('Unrecognized function: ' + left.name);
8998
- }
8999
- const args = [];
9000
- while (!parser.match(')')) {
9001
- args.push(parser.consumeAndParse());
9002
- parser.match(',');
9003
- }
9004
- return new FunctionAtom(left.name, args, functions[left.name]);
9005
- },
9006
- precedence: 0 /* FunctionCall */,
9007
- };
9008
- function parseQuantity(str) {
9009
- const parts = str.split(' ');
9010
- const value = parseFloat(parts[0]);
9011
- let unit = parts[1];
9012
- if (unit && unit.startsWith("'") && unit.endsWith("'")) {
9013
- unit = unit.substring(1, unit.length - 1);
9014
- }
9015
- else {
9016
- unit = '{' + unit + '}';
9017
- }
9018
- return { value, unit };
9019
- }
9020
- const parserBuilder = new ParserBuilder()
9021
- .registerPrefix('String', {
9022
- parse: (_, token) => new LiteralAtom(token.value),
9023
- })
9024
- .registerPrefix('DateTime', {
9025
- parse: (_, token) => new LiteralAtom(parseDateString(token.value)),
9026
- })
9027
- .registerPrefix('Quantity', {
9028
- parse: (_, token) => new LiteralAtom(parseQuantity(token.value)),
9029
- })
9030
- .registerPrefix('Number', {
9031
- parse: (_, token) => new LiteralAtom(parseFloat(token.value)),
9032
- })
9033
- .registerPrefix('Symbol', {
9034
- parse: (_, token) => {
9035
- if (token.value === 'false') {
9036
- return new LiteralAtom(false);
9037
- }
9038
- if (token.value === 'true') {
9039
- return new LiteralAtom(true);
9040
- }
9041
- return new SymbolAtom(token.value);
9042
- },
9043
- })
9044
- .registerPrefix('{}', { parse: () => new EmptySetAtom() })
9045
- .registerPrefix('(', PARENTHESES_PARSELET)
9046
- .registerInfix('[', INDEXER_PARSELET)
9047
- .registerInfix('(', FUNCTION_CALL_PARSELET)
9048
- .prefix('+', 3 /* UnaryAdd */, (_, right) => new UnaryOperatorAtom(right, (x) => x))
9049
- .prefix('-', 3 /* UnarySubtract */, (_, right) => new ArithemticOperatorAtom(right, right, (_, y) => -y))
9050
- .infixLeft('.', 1 /* Dot */, (left, _, right) => new DotAtom(left, right))
9051
- .infixLeft('/', 4 /* Divide */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x / y))
9052
- .infixLeft('*', 4 /* Multiply */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x * y))
9053
- .infixLeft('+', 5 /* Add */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x + y))
9054
- .infixLeft('-', 5 /* Subtract */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x - y))
9055
- .infixLeft('|', 7 /* Union */, (left, _, right) => new UnionAtom(left, right))
9056
- .infixLeft('=', 9 /* Equals */, (left, _, right) => new EqualsAtom(left, right))
9057
- .infixLeft('!=', 9 /* Equals */, (left, _, right) => new NotEqualsAtom(left, right))
9058
- .infixLeft('~', 9 /* Equivalent */, (left, _, right) => new EquivalentAtom(left, right))
9059
- .infixLeft('!~', 9 /* NotEquivalent */, (left, _, right) => new NotEquivalentAtom(left, right))
9060
- .infixLeft('<', 8 /* LessThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x < y))
9061
- .infixLeft('<=', 8 /* LessThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x <= y))
9062
- .infixLeft('>', 8 /* GreaterThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x > y))
9063
- .infixLeft('>=', 8 /* GreaterThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x >= y))
9064
- .infixLeft('&', 5 /* Ampersand */, (left, _, right) => new ConcatAtom(left, right))
9065
- .infixLeft('Symbol', 6 /* Is */, (left, symbol, right) => {
9066
- switch (symbol.value) {
9067
- case 'and':
9068
- return new AndAtom(left, right);
9069
- case 'as':
9070
- return new AsAtom(left, right);
9071
- case 'contains':
9072
- return new ContainsAtom(left, right);
9073
- case 'div':
9074
- return new ArithemticOperatorAtom(left, right, (x, y) => (x / y) | 0);
9075
- case 'in':
9076
- return new InAtom(left, right);
9077
- case 'is':
9078
- return new IsAtom(left, right);
9079
- case 'mod':
9080
- return new ArithemticOperatorAtom(left, right, (x, y) => x % y);
9081
- case 'or':
9082
- return new OrAtom(left, right);
9083
- case 'xor':
9084
- return new XorAtom(left, right);
9085
- default:
9086
- throw new Error('Cannot use ' + symbol.value + ' as infix operator');
9087
- }
9088
- });
9089
- /**
9090
- * Parses a FHIRPath expression into an AST.
9091
- * The result can be used to evaluate the expression against a resource or other object.
9092
- * This method is useful if you know that you will evaluate the same expression many times
9093
- * against different resources.
9094
- * @param input The FHIRPath expression to parse.
9095
- * @returns The AST representing the expression.
9096
- */
9097
- function parseFhirPath(input) {
9098
- try {
9099
- return new FhirPathAtom(input, parserBuilder.construct(input).consumeAndParse());
9100
- }
9101
- catch (error) {
9102
- throw new Error(`FhirPathError on "${input}": ${error}`);
9103
- }
9104
- }
9105
- /**
9106
- * Evaluates a FHIRPath expression against a resource or other object.
9107
- * @param input The FHIRPath expression to parse.
9108
- * @param context The resource or object to evaluate the expression against.
9109
- * @returns The result of the FHIRPath expression against the resource or object.
9110
- */
9111
- function evalFhirPath(input, context) {
9112
- return parseFhirPath(input).eval(context);
9113
- }
9114
-
9115
- var _MemoryRepository_resources, _MemoryRepository_history;
9116
- class MemoryRepository {
9117
- constructor() {
9118
- _MemoryRepository_resources.set(this, void 0);
9119
- _MemoryRepository_history.set(this, void 0);
9120
- __classPrivateFieldSet$1(this, _MemoryRepository_resources, {}, "f");
9121
- __classPrivateFieldSet$1(this, _MemoryRepository_history, {}, "f");
9122
- }
9123
- createResource(resource) {
9124
- var _a;
9125
- const result = resource;
9126
- if (!result.id) {
9127
- result.id = this.generateId();
9128
- }
9129
- if (!result.meta) {
9130
- result.meta = {};
9131
- }
9132
- if (!((_a = result.meta) === null || _a === void 0 ? void 0 : _a.versionId)) {
9133
- result.meta.versionId = this.generateId();
9134
- }
9135
- const { resourceType, id } = resource;
9136
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f"))) {
9137
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType] = {};
9138
- }
9139
- if (!(resourceType in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f"))) {
9140
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType] = {};
9141
- }
9142
- if (!(id in __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType])) {
9143
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id] = [];
9144
- }
9145
- __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id] = resource;
9146
- __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")[resourceType][id].push(result);
9147
- return result;
9148
- }
9149
- readResource(resourceType, id) {
9150
- var _a, _b;
9151
- return (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id];
9152
- }
9153
- readHistory(resourceType, id) {
9154
- var _a, _b, _c;
9155
- return {
9156
- resourceType: 'Bundle',
9157
- type: 'history',
9158
- entry: ((_c = (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) !== null && _c !== void 0 ? _c : [])
9159
- .sort((version1, version2) => { var _a, _b, _c; return -((_b = (_a = version1.meta) === null || _a === void 0 ? void 0 : _a.lastUpdated) === null || _b === void 0 ? void 0 : _b.localeCompare((_c = version2.meta) === null || _c === void 0 ? void 0 : _c.lastUpdated)); })
9160
- .map((version) => ({ resource: version })),
9161
- };
9162
- }
9163
- readVersion(resourceType, id, versionId) {
9164
- var _a, _b, _c;
9165
- return (_c = (_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_history, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) === null || _c === void 0 ? void 0 : _c.find((v) => { var _a; return ((_a = v.meta) === null || _a === void 0 ? void 0 : _a.versionId) === versionId; });
9166
- }
9167
- search(searchRequest) {
9168
- var _a;
9169
- const { resourceType } = searchRequest;
9170
- const resources = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType]) !== null && _a !== void 0 ? _a : {};
9171
- const result = Object.values(resources).filter((resource) => matchesSearchRequest(resource, searchRequest));
9172
- return {
9173
- resourceType: 'Bundle',
9174
- type: 'searchset',
9175
- entry: result.map((resource) => ({ resource })),
9176
- total: result.length,
9177
- };
9178
- }
9179
- deleteResource(resourceType, id) {
9180
- var _a, _b;
9181
- if ((_b = (_a = __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")) === null || _a === void 0 ? void 0 : _a[resourceType]) === null || _b === void 0 ? void 0 : _b[id]) {
9182
- delete __classPrivateFieldGet$1(this, _MemoryRepository_resources, "f")[resourceType][id];
9183
- }
9184
- }
9185
- generateId() {
9186
- return Date.now().toString(36);
9187
- }
9188
- }
9189
- _MemoryRepository_resources = new WeakMap(), _MemoryRepository_history = new WeakMap();
9190
- /**
9191
- * Determines if the resource matches the search request.
9192
- * @param resource The resource that was created or updated.
9193
- * @param searchRequest The subscription criteria as a search request.
9194
- * @returns True if the resource satisfies the search request.
9195
- */
9196
- function matchesSearchRequest(resource, searchRequest) {
9197
- if (searchRequest.resourceType !== resource.resourceType) {
9198
- return false;
9199
- }
9200
- if (searchRequest.filters) {
9201
- for (const filter of searchRequest.filters) {
9202
- if (!matchesSearchFilter(resource, filter)) {
9203
- return false;
9204
- }
9205
- }
9206
- }
9207
- return true;
9208
- }
9209
- /**
9210
- * Determines if the resource matches the search filter.
9211
- * @param resource The resource that was created or updated.
9212
- * @param filter One of the filters of a subscription criteria.
9213
- * @returns True if the resource satisfies the search filter.
9214
- */
9215
- function matchesSearchFilter(resource, filter) {
9216
- const expression = filter.code.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
9217
- const values = evalFhirPath(expression, resource);
9218
- const result = values.some((value) => JSON.stringify(value).toLowerCase().includes(filter.value.toLowerCase()));
9219
- return filter.operator === Operator.NOT_EQUALS ? !result : result;
9220
- }
9221
-
9222
- class MockClient extends MedplumClient {
9223
- constructor(clientOptions) {
9224
- super({
9225
- baseUrl: 'https://example.com/',
9226
- clientId: 'my-client-id',
9227
- fetch: (url, options) => {
9228
- const method = options.method || 'GET';
9229
- const path = url.replace('https://example.com/', '');
9230
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9231
- console.log('MockClient', method, path);
9232
- }
9233
- const response = mockHandler(method, path, options);
9234
- if ((clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) && !response) {
9235
- console.log('MockClient: not found', method, path);
9236
- }
9237
- if (clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.debug) {
9238
- console.log('MockClient', JSON.stringify(response, null, 2));
9239
- }
9240
- return Promise.resolve({
9241
- blob: () => Promise.resolve(response),
9242
- json: () => Promise.resolve(response),
9243
- });
9244
- },
9245
- });
9246
- }
9247
- clear() {
9248
- super.clear();
9249
- this.activeLoginOverride = undefined;
9250
- }
9251
- getProfile() {
9252
- return {
9253
- resourceType: 'Practitioner',
9254
- id: '123',
9255
- meta: {
9256
- versionId: '456',
9257
- },
9258
- };
9259
- }
9260
- setActiveLoginOverride(activeLoginOverride) {
9261
- this.activeLoginOverride = activeLoginOverride;
9262
- }
9263
- getActiveLogin() {
9264
- if (this.activeLoginOverride !== undefined) {
9265
- return this.activeLoginOverride;
9266
- }
9267
- return super.getActiveLogin();
9268
- }
9269
- createBinary(_data, filename, contentType) {
9270
- if (filename.endsWith('.exe')) {
9271
- return Promise.reject(badRequest('Invalid file type'));
9272
- }
9273
- return Promise.resolve({
9274
- resourceType: 'Binary',
9275
- title: filename,
9276
- contentType,
9277
- url: 'https://example.com/binary/123',
9278
- });
9279
- }
9280
- }
9281
- function mockHandler(method, path, options) {
9282
- if (path.startsWith('admin/')) {
9283
- return mockAdminHandler(method, path);
9284
- }
9285
- else if (path.startsWith('auth/')) {
9286
- return mockAuthHandler(method, path, options);
9287
- }
9288
- else if (path.startsWith('fhir/R4')) {
9289
- return mockFhirHandler(method, path, options);
9290
- }
9291
- else {
9292
- return null;
9293
- }
9294
- }
9295
- function mockAdminHandler(_method, path) {
9296
- if (path.startsWith('admin/projects/123')) {
9297
- return {
9298
- project: { id: '123', name: 'Project 123' },
9299
- members: [
9300
- { id: '123', profile: { reference: 'Practitioner/123', display: 'Alice Smith' }, role: 'owner' },
9301
- { id: '888', profile: { reference: 'ClientApplication/123', display: 'Test Client' }, role: 'client' },
9302
- { id: '999', profile: { reference: 'Bot/123', display: 'Test Bot' }, role: 'bot' },
9303
- ],
9304
- };
9305
- }
9306
- return {
9307
- ok: true,
9308
- };
9309
- }
9310
- function mockAuthHandler(method, path, options) {
9311
- if (path.startsWith('auth/changepassword')) {
9312
- return mockChangePasswordHandler(method, path, options);
6724
+ function mockAuthHandler(method, path, options) {
6725
+ if (path.startsWith('auth/changepassword')) {
6726
+ return mockChangePasswordHandler(method, path, options);
9313
6727
  }
9314
6728
  if (path.startsWith('auth/login')) {
9315
6729
  return mockLoginHandler(method, path, options);
@@ -9466,19 +6880,22 @@ function mockFhirHandler(method, url, options) {
9466
6880
  const match = /fhir\/R4\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?\/?([^/]+)?/.exec(path);
9467
6881
  const resourceType = match === null || match === void 0 ? void 0 : match[1];
9468
6882
  const id = match === null || match === void 0 ? void 0 : match[2];
9469
- const history = match === null || match === void 0 ? void 0 : match[3];
6883
+ const operation = match === null || match === void 0 ? void 0 : match[3];
9470
6884
  const versionId = match === null || match === void 0 ? void 0 : match[4];
9471
- if (path.startsWith('fhir/R4/ValueSet/%24expand')) {
6885
+ if (path.startsWith('fhir/R4/ValueSet/$expand')) {
9472
6886
  return exampleValueSet;
9473
6887
  }
9474
- else if (path === 'fhir/R4/%24graphql') {
6888
+ else if (path === 'fhir/R4/$graphql') {
9475
6889
  return mockFhirGraphqlHandler(method, path, options);
9476
6890
  }
9477
6891
  else if (path === 'not-found' || id === 'not-found') {
9478
6892
  return notFound;
9479
6893
  }
9480
6894
  else if (method === 'POST') {
9481
- if (resourceType) {
6895
+ if (resourceType && id && operation) {
6896
+ return {};
6897
+ }
6898
+ else if (resourceType) {
9482
6899
  return mockRepo.createResource(JSON.parse(options.body));
9483
6900
  }
9484
6901
  else {
@@ -9489,7 +6906,7 @@ function mockFhirHandler(method, url, options) {
9489
6906
  if (resourceType && id && versionId) {
9490
6907
  return mockRepo.readVersion(resourceType, id, versionId);
9491
6908
  }
9492
- else if (resourceType && id && history) {
6909
+ else if (resourceType && id && operation === '_history') {
9493
6910
  return mockRepo.readHistory(resourceType, id);
9494
6911
  }
9495
6912
  else if (resourceType && id) {