@medplum/mock 0.9.6 → 0.9.7

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