@medplum/core 0.9.7 → 0.9.8

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
@@ -55,9 +55,17 @@
55
55
  __classPrivateFieldSet(this, _LRUCache_max, max, "f");
56
56
  __classPrivateFieldSet(this, _LRUCache_cache, new Map(), "f");
57
57
  }
58
+ /**
59
+ * Deletes all values from the cache.
60
+ */
58
61
  clear() {
59
62
  __classPrivateFieldGet(this, _LRUCache_cache, "f").clear();
60
63
  }
64
+ /**
65
+ * Returns the value for the given key.
66
+ * @param key The key to retrieve.
67
+ * @returns The value if found; undefined otherwise.
68
+ */
61
69
  get(key) {
62
70
  const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key);
63
71
  if (item) {
@@ -66,6 +74,11 @@
66
74
  }
67
75
  return item;
68
76
  }
77
+ /**
78
+ * Sets the value for the given key.
79
+ * @param key The key to set.
80
+ * @param val The value to set.
81
+ */
69
82
  set(key, val) {
70
83
  if (__classPrivateFieldGet(this, _LRUCache_cache, "f").has(key)) {
71
84
  __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key);
@@ -75,9 +88,20 @@
75
88
  }
76
89
  __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, val);
77
90
  }
91
+ /**
92
+ * Deletes the value for the given key.
93
+ * @param key The key to delete.
94
+ */
78
95
  delete(key) {
79
96
  __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key);
80
97
  }
98
+ /**
99
+ * Returns the list of all keys in the cache.
100
+ * @returns The array of keys in the cache.
101
+ */
102
+ keys() {
103
+ return __classPrivateFieldGet(this, _LRUCache_cache, "f").keys();
104
+ }
81
105
  }
82
106
  _LRUCache_max = new WeakMap(), _LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_first = function _LRUCache_first() {
83
107
  // This works because the Map class maintains ordered keys.
@@ -786,6 +810,91 @@
786
810
  }
787
811
  }
788
812
 
813
+ /*
814
+ * This file attempts a unified "generatePdf" function that works both client-side and server-side.
815
+ * On client-side, it checks for a global "pdfMake" variable.
816
+ * On server-side, it dynamically loads "pdfmake" from the node_modules.
817
+ */
818
+ function generatePdf(docDefinition, tableLayouts, fonts) {
819
+ return __awaiter(this, void 0, void 0, function* () {
820
+ // Setup sane defaults
821
+ // See: https://pdfmake.github.io/docs/0.1/document-definition-object/styling/
822
+ docDefinition.pageSize = docDefinition.pageSize || 'LETTER';
823
+ docDefinition.pageMargins = docDefinition.pageMargins || [60, 60, 60, 60];
824
+ docDefinition.pageOrientation = docDefinition.pageOrientation || 'portrait';
825
+ docDefinition.defaultStyle = docDefinition.defaultStyle || {};
826
+ docDefinition.defaultStyle.font = docDefinition.defaultStyle.font || 'Helvetica';
827
+ docDefinition.defaultStyle.fontSize = docDefinition.defaultStyle.fontSize || 11;
828
+ docDefinition.defaultStyle.lineHeight = docDefinition.defaultStyle.lineHeight || 2.0;
829
+ if (typeof pdfMake === 'undefined') {
830
+ return generatePdfServerSide(docDefinition, tableLayouts, fonts);
831
+ }
832
+ else {
833
+ return generatePdfClientSide(docDefinition, tableLayouts, fonts);
834
+ }
835
+ });
836
+ }
837
+ function generatePdfServerSide(docDefinition, tableLayouts, fonts) {
838
+ return __awaiter(this, void 0, void 0, function* () {
839
+ if (!fonts) {
840
+ fonts = {
841
+ Helvetica: {
842
+ normal: 'Helvetica',
843
+ bold: 'Helvetica-Bold',
844
+ italics: 'Helvetica-Oblique',
845
+ bolditalics: 'Helvetica-BoldOblique',
846
+ },
847
+ Roboto: {
848
+ normal: 'https://static.medplum.com/fonts/Roboto-Regular.ttf',
849
+ bold: 'https://static.medplum.com/fonts/Roboto-Medium.ttf',
850
+ italics: 'https://static.medplum.com/fonts/Roboto-Italic.ttf',
851
+ bolditalics: 'https://static.medplum.com/fonts/Roboto-MediumItalic.ttf',
852
+ },
853
+ Avenir: {
854
+ normal: 'https://static.medplum.com/fonts/avenir.ttf',
855
+ },
856
+ };
857
+ }
858
+ return new Promise((resolve, reject) => {
859
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
860
+ const PdfPrinter = require('pdfmake');
861
+ const printer = new PdfPrinter(fonts);
862
+ const pdfDoc = printer.createPdfKitDocument(docDefinition, { tableLayouts });
863
+ const chunks = [];
864
+ pdfDoc.on('data', (chunk) => chunks.push(chunk));
865
+ pdfDoc.on('end', () => resolve(Buffer.concat(chunks)));
866
+ pdfDoc.on('error', reject);
867
+ pdfDoc.end();
868
+ });
869
+ });
870
+ }
871
+ function generatePdfClientSide(docDefinition, tableLayouts, fonts) {
872
+ return __awaiter(this, void 0, void 0, function* () {
873
+ if (!fonts) {
874
+ fonts = {
875
+ Helvetica: {
876
+ normal: 'https://static.medplum.com/fonts/Helvetica.ttf',
877
+ bold: 'https://static.medplum.com/fonts/Helvetica-bold.ttf',
878
+ italics: 'https://static.medplum.com/fonts/Helvetica-italic.ttf',
879
+ bolditalics: 'https://static.medplum.com/fonts/Helvetica-bold-italic.ttf',
880
+ },
881
+ Roboto: {
882
+ normal: 'https://static.medplum.com/fonts/Roboto-Regular.ttf',
883
+ bold: 'https://static.medplum.com/fonts/Roboto-Medium.ttf',
884
+ italics: 'https://static.medplum.com/fonts/Roboto-Italic.ttf',
885
+ bolditalics: 'https://static.medplum.com/fonts/Roboto-MediumItalic.ttf',
886
+ },
887
+ Avenir: {
888
+ normal: 'https://static.medplum.com/fonts/avenir.ttf',
889
+ },
890
+ };
891
+ }
892
+ return new Promise((resolve) => {
893
+ pdfMake.createPdf(docDefinition, tableLayouts, fonts).getBlob(resolve);
894
+ });
895
+ });
896
+ }
897
+
789
898
  var _ReadablePromise_suspender, _ReadablePromise_status, _ReadablePromise_response, _ReadablePromise_error, _a;
790
899
  /**
791
900
  * The ReadablePromise class wraps a request promise suitable for React Suspense.
@@ -1472,6 +1581,26 @@
1472
1581
  __classPrivateFieldSet(this, _MedplumClient_config, undefined, "f");
1473
1582
  this.dispatchEvent({ type: 'change' });
1474
1583
  }
1584
+ /**
1585
+ * Invalidates any cached values or cached requests for the given URL.
1586
+ * @param url The URL to invalidate.
1587
+ */
1588
+ invalidateUrl(url) {
1589
+ url = url.toString();
1590
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1591
+ }
1592
+ /**
1593
+ * Invalidates all cached search results or cached requests for the given resourceType.
1594
+ * @param resourceType The resource type to invalidate.
1595
+ */
1596
+ invalidateSearches(resourceType) {
1597
+ const url = 'fhir/R4/' + resourceType;
1598
+ for (const key of __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").keys()) {
1599
+ if (key.endsWith(url) || key.includes(url + '?')) {
1600
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(key);
1601
+ }
1602
+ }
1603
+ }
1475
1604
  /**
1476
1605
  * Makes an HTTP GET request to the specified URL.
1477
1606
  *
@@ -1516,7 +1645,7 @@
1516
1645
  if (contentType) {
1517
1646
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1518
1647
  }
1519
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1648
+ this.invalidateUrl(url);
1520
1649
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'POST', url, options);
1521
1650
  }
1522
1651
  /**
@@ -1540,7 +1669,7 @@
1540
1669
  if (contentType) {
1541
1670
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, contentType);
1542
1671
  }
1543
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1672
+ this.invalidateUrl(url);
1544
1673
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PUT', url, options);
1545
1674
  }
1546
1675
  /**
@@ -1559,7 +1688,7 @@
1559
1688
  url = url.toString();
1560
1689
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestBody).call(this, options, operations);
1561
1690
  __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_setRequestContentType).call(this, options, PATCH_CONTENT_TYPE);
1562
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1691
+ this.invalidateUrl(url);
1563
1692
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'PATCH', url, options);
1564
1693
  }
1565
1694
  /**
@@ -1575,7 +1704,7 @@
1575
1704
  */
1576
1705
  delete(url, options = {}) {
1577
1706
  url = url.toString();
1578
- __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").delete(url);
1707
+ this.invalidateUrl(url);
1579
1708
  return __classPrivateFieldGet(this, _MedplumClient_instances, "m", _MedplumClient_request).call(this, 'DELETE', url, options);
1580
1709
  }
1581
1710
  /**
@@ -1653,6 +1782,19 @@
1653
1782
  fhirUrl(...path) {
1654
1783
  return new URL(__classPrivateFieldGet(this, _MedplumClient_baseUrl, "f") + 'fhir/R4/' + path.join('/'));
1655
1784
  }
1785
+ /**
1786
+ * Builds a FHIR search URL from a search query or structured query object.
1787
+ * @param query The FHIR search query or structured query object.
1788
+ * @returns The well-formed FHIR URL.
1789
+ */
1790
+ fhirSearchUrl(query) {
1791
+ if (typeof query === 'string') {
1792
+ return this.fhirUrl(query);
1793
+ }
1794
+ const url = this.fhirUrl(query.resourceType);
1795
+ url.search = formatSearchQuery(query);
1796
+ return url;
1797
+ }
1656
1798
  /**
1657
1799
  * Sends a FHIR search request.
1658
1800
  *
@@ -1708,7 +1850,7 @@
1708
1850
  * @returns Promise to the search result bundle.
1709
1851
  */
1710
1852
  search(query, options = {}) {
1711
- return this.get(typeof query === 'string' ? 'fhir/R4/' + query : this.fhirUrl(query.resourceType) + formatSearchQuery(query), options);
1853
+ return this.get(this.fhirSearchUrl(query), options);
1712
1854
  }
1713
1855
  /**
1714
1856
  * Sends a FHIR search request for a single resource.
@@ -1732,7 +1874,16 @@
1732
1874
  searchOne(query, options = {}) {
1733
1875
  const search = typeof query === 'string' ? parseSearchDefinition(query) : query;
1734
1876
  search.count = 1;
1735
- return new ReadablePromise(this.search(search, options).then((bundle) => { var _a, _b; return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.resource; }));
1877
+ const cacheKey = this.fhirSearchUrl(query).toString() + '-searchOne';
1878
+ if (!(options === null || options === void 0 ? void 0 : options.cache)) {
1879
+ const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(cacheKey);
1880
+ if (cached) {
1881
+ return cached;
1882
+ }
1883
+ }
1884
+ const promise = new ReadablePromise(this.search(search, options).then((b) => { var _a, _b; return (_b = (_a = b.entry) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.resource; }));
1885
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").set(cacheKey, promise);
1886
+ return promise;
1736
1887
  }
1737
1888
  /**
1738
1889
  * Sends a FHIR search request for an array of resources.
@@ -1754,7 +1905,16 @@
1754
1905
  * @returns Promise to the search result bundle.
1755
1906
  */
1756
1907
  searchResources(query, options = {}) {
1757
- return new ReadablePromise(this.search(query, options).then((bundle) => { var _a, _b; return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.map((entry) => entry.resource)) !== null && _b !== void 0 ? _b : []; }));
1908
+ const cacheKey = this.fhirSearchUrl(query).toString() + '-searchResources';
1909
+ if (!(options === null || options === void 0 ? void 0 : options.cache)) {
1910
+ const cached = __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").get(cacheKey);
1911
+ if (cached) {
1912
+ return cached;
1913
+ }
1914
+ }
1915
+ const promise = new ReadablePromise(this.search(query, options).then((b) => { var _a, _b; return (_b = (_a = b.entry) === null || _a === void 0 ? void 0 : _a.map((e) => e.resource)) !== null && _b !== void 0 ? _b : []; }));
1916
+ __classPrivateFieldGet(this, _MedplumClient_requestCache, "f").set(cacheKey, promise);
1917
+ return promise;
1758
1918
  }
1759
1919
  /**
1760
1920
  * Searches a ValueSet resource using the "expand" operation.
@@ -1809,27 +1969,6 @@
1809
1969
  readResource(resourceType, id) {
1810
1970
  return this.get(this.fhirUrl(resourceType, id));
1811
1971
  }
1812
- /**
1813
- * Reads a resource by resource type and ID using the in-memory resource cache.
1814
- *
1815
- * If the resource is not available in the cache, it will be read from the server.
1816
- *
1817
- * Example:
1818
- *
1819
- * ```typescript
1820
- * const patient = await medplum.readCached('Patient', '123');
1821
- * console.log(patient);
1822
- * ```
1823
- *
1824
- * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1825
- *
1826
- * @param resourceType The FHIR resource type.
1827
- * @param id The resource ID.
1828
- * @returns The resource if available; undefined otherwise.
1829
- */
1830
- readCached(resourceType, id) {
1831
- return this.get(this.fhirUrl(resourceType, id));
1832
- }
1833
1972
  /**
1834
1973
  * Reads a resource by `Reference`.
1835
1974
  *
@@ -1856,34 +1995,6 @@
1856
1995
  const [resourceType, id] = refString.split('/');
1857
1996
  return this.readResource(resourceType, id);
1858
1997
  }
1859
- /**
1860
- * Reads a resource by `Reference` using the in-memory resource cache.
1861
- *
1862
- * This is a convenience method for `readResource()` that accepts a `Reference` object.
1863
- *
1864
- * If the resource is not available in the cache, it will be read from the server.
1865
- *
1866
- * Example:
1867
- *
1868
- * ```typescript
1869
- * const serviceRequest = await medplum.readResource('ServiceRequest', '123');
1870
- * const patient = await medplum.readCachedReference(serviceRequest.subject);
1871
- * console.log(patient);
1872
- * ```
1873
- *
1874
- * See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read
1875
- *
1876
- * @param reference The FHIR reference object.
1877
- * @returns The resource if available; undefined otherwise.
1878
- */
1879
- readCachedReference(reference) {
1880
- const refString = reference === null || reference === void 0 ? void 0 : reference.reference;
1881
- if (!refString) {
1882
- return new ReadablePromise(Promise.reject(new Error('Missing reference')));
1883
- }
1884
- const [resourceType, id] = refString.split('/');
1885
- return this.readCached(resourceType, id);
1886
- }
1887
1998
  /**
1888
1999
  * Returns a cached schema for a resource type.
1889
2000
  * If the schema is not cached, returns undefined.
@@ -2014,6 +2125,7 @@
2014
2125
  if (!resource.resourceType) {
2015
2126
  throw new Error('Missing resourceType');
2016
2127
  }
2128
+ this.invalidateSearches(resource.resourceType);
2017
2129
  return this.post(this.fhirUrl(resource.resourceType), resource);
2018
2130
  }
2019
2131
  /**
@@ -2108,15 +2220,14 @@
2108
2220
  *
2109
2221
  * See the pdfmake document definition for full details: https://pdfmake.github.io/docs/0.1/document-definition-object/
2110
2222
  *
2111
- * @param docDefinition The FHIR resource to create.
2223
+ * @param docDefinition The PDF document definition.
2112
2224
  * @returns The result of the create operation.
2113
2225
  */
2114
- createPdf(docDefinition, filename) {
2115
- const url = this.fhirUrl('Binary', '$pdf');
2116
- if (filename) {
2117
- url.searchParams.set('_filename', filename);
2118
- }
2119
- return this.post(url, docDefinition, 'application/json');
2226
+ createPdf(docDefinition, filename, tableLayouts, fonts) {
2227
+ return __awaiter(this, void 0, void 0, function* () {
2228
+ const blob = yield generatePdf(docDefinition, tableLayouts, fonts);
2229
+ return this.createBinary(blob, filename, 'application/pdf');
2230
+ });
2120
2231
  }
2121
2232
  /**
2122
2233
  * Creates a FHIR `Communication` resource with the provided data content.
@@ -2183,6 +2294,7 @@
2183
2294
  if (!resource.id) {
2184
2295
  throw new Error('Missing id');
2185
2296
  }
2297
+ this.invalidateSearches(resource.resourceType);
2186
2298
  return this.put(this.fhirUrl(resource.resourceType, resource.id), resource);
2187
2299
  }
2188
2300
  /**
@@ -2209,6 +2321,7 @@
2209
2321
  * @returns The result of the patch operations.
2210
2322
  */
2211
2323
  patchResource(resourceType, id, operations) {
2324
+ this.invalidateSearches(resourceType);
2212
2325
  return this.patch(this.fhirUrl(resourceType, id), operations);
2213
2326
  }
2214
2327
  /**
@@ -2227,6 +2340,7 @@
2227
2340
  * @returns The result of the delete operation.
2228
2341
  */
2229
2342
  deleteResource(resourceType, id) {
2343
+ this.invalidateSearches(resourceType);
2230
2344
  return this.delete(this.fhirUrl(resourceType, id));
2231
2345
  }
2232
2346
  /**
@@ -2442,7 +2556,10 @@
2442
2556
  const headers = options.headers;
2443
2557
  headers['Content-Type'] = contentType;
2444
2558
  }, _MedplumClient_setRequestBody = function _MedplumClient_setRequestBody(options, data) {
2445
- if (typeof data === 'string' || (typeof File !== 'undefined' && data instanceof File)) {
2559
+ if (typeof data === 'string' ||
2560
+ (typeof Blob !== 'undefined' && data instanceof Blob) ||
2561
+ (typeof Buffer !== 'undefined' && data instanceof Buffer) ||
2562
+ (typeof File !== 'undefined' && data instanceof File)) {
2446
2563
  options.body = data;
2447
2564
  }
2448
2565
  else if (data) {
@@ -2557,47 +2674,38 @@
2557
2674
  }
2558
2675
 
2559
2676
  /**
2560
- * Ensures that the value is wrapped in an array.
2561
- * @param input The input as a an array or a value.
2562
- * @returns The input as an array.
2677
+ * Returns a single element array with a typed boolean value.
2678
+ * @param value The primitive boolean value.
2679
+ * @returns Single element array with a typed boolean value.
2563
2680
  */
2564
- function ensureArray(input) {
2565
- if (input === null || input === undefined) {
2566
- return [];
2567
- }
2568
- return Array.isArray(input) ? input : [input];
2681
+ function booleanToTypedValue(value) {
2682
+ return [{ type: exports.PropertyType.boolean, value }];
2569
2683
  }
2570
2684
  /**
2571
- * Applies a function to single value or an array of values.
2572
- * @param context The context which will be passed to the function.
2573
- * @param fn The function to apply.
2574
- * @returns The result of the function.
2685
+ * Returns a "best guess" TypedValue for a given value.
2686
+ * @param value The unknown value to check.
2687
+ * @returns A "best guess" TypedValue for the given value.
2575
2688
  */
2576
- function applyMaybeArray(context, fn) {
2577
- if (context === undefined) {
2578
- return undefined;
2689
+ function toTypedValue(value) {
2690
+ if (Number.isSafeInteger(value)) {
2691
+ return { type: exports.PropertyType.integer, value };
2579
2692
  }
2580
- if (Array.isArray(context)) {
2581
- return context
2582
- .map((e) => fn(e))
2583
- .filter((e) => !!e)
2584
- .flat();
2693
+ else if (typeof value === 'number') {
2694
+ return { type: exports.PropertyType.decimal, value };
2695
+ }
2696
+ else if (typeof value === 'boolean') {
2697
+ return { type: exports.PropertyType.boolean, value };
2698
+ }
2699
+ else if (typeof value === 'string') {
2700
+ return { type: exports.PropertyType.string, value };
2701
+ }
2702
+ else if (isQuantity(value)) {
2703
+ return { type: exports.PropertyType.Quantity, value };
2585
2704
  }
2586
2705
  else {
2587
- return fn(context);
2706
+ return { type: exports.PropertyType.BackboneElement, value };
2588
2707
  }
2589
2708
  }
2590
- /**
2591
- * Determines if the input is an empty array.
2592
- * @param obj Any value or array of values.
2593
- * @returns True if the input is an empty array.
2594
- */
2595
- function isEmptyArray(obj) {
2596
- return Array.isArray(obj) && obj.length === 0;
2597
- }
2598
- function isFalsy(obj) {
2599
- return !obj || isEmptyArray(obj);
2600
- }
2601
2709
  /**
2602
2710
  * Converts unknown object into a JavaScript boolean.
2603
2711
  * Note that this is different than the FHIRPath "toBoolean",
@@ -2606,10 +2714,7 @@
2606
2714
  * @returns The converted boolean value according to FHIRPath rules.
2607
2715
  */
2608
2716
  function toJsBoolean(obj) {
2609
- if (Array.isArray(obj)) {
2610
- return obj.length === 0 ? false : !!obj[0];
2611
- }
2612
- return !!obj;
2717
+ return obj.length === 0 ? false : !!obj[0].value;
2613
2718
  }
2614
2719
  /**
2615
2720
  * Removes duplicates in array using FHIRPath equality rules.
@@ -2621,7 +2726,7 @@
2621
2726
  for (const i of arr) {
2622
2727
  let found = false;
2623
2728
  for (const j of result) {
2624
- if (fhirPathEquals(i, j)) {
2729
+ if (toJsBoolean(fhirPathEquals(i, j))) {
2625
2730
  found = true;
2626
2731
  break;
2627
2732
  }
@@ -2632,6 +2737,29 @@
2632
2737
  }
2633
2738
  return result;
2634
2739
  }
2740
+ /**
2741
+ * Returns a negated FHIRPath boolean expression.
2742
+ * @param input The input array.
2743
+ * @returns The negated type value array.
2744
+ */
2745
+ function fhirPathNot(input) {
2746
+ return booleanToTypedValue(!toJsBoolean(input));
2747
+ }
2748
+ /**
2749
+ * Determines if two arrays are equal according to FHIRPath equality rules.
2750
+ * @param x The first array.
2751
+ * @param y The second array.
2752
+ * @returns FHIRPath true if the arrays are equal.
2753
+ */
2754
+ function fhirPathArrayEquals(x, y) {
2755
+ if (x.length === 0 || y.length === 0) {
2756
+ return [];
2757
+ }
2758
+ if (x.length !== y.length) {
2759
+ return booleanToTypedValue(false);
2760
+ }
2761
+ return booleanToTypedValue(x.every((val, index) => toJsBoolean(fhirPathEquals(val, y[index]))));
2762
+ }
2635
2763
  /**
2636
2764
  * Determines if two values are equal according to FHIRPath equality rules.
2637
2765
  * @param x The first value.
@@ -2639,69 +2767,89 @@
2639
2767
  * @returns True if equal.
2640
2768
  */
2641
2769
  function fhirPathEquals(x, y) {
2642
- if (isFalsy(x) && isFalsy(y)) {
2643
- return true;
2644
- }
2645
- if (isEmptyArray(x) || isEmptyArray(y)) {
2646
- return [];
2770
+ const xValue = x.value;
2771
+ const yValue = y.value;
2772
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2773
+ return booleanToTypedValue(Math.abs(xValue - yValue) < 1e-8);
2647
2774
  }
2648
- if (typeof x === 'number' && typeof y === 'number') {
2649
- return Math.abs(x - y) < 1e-8;
2775
+ if (isQuantity(xValue) && isQuantity(yValue)) {
2776
+ return booleanToTypedValue(isQuantityEquivalent(xValue, yValue));
2650
2777
  }
2651
- if (isQuantity(x) && isQuantity(y)) {
2652
- return isQuantityEquivalent(x, y);
2778
+ if (typeof xValue === 'object' && typeof yValue === 'object') {
2779
+ return booleanToTypedValue(deepEquals(x, y));
2653
2780
  }
2654
- if (Array.isArray(x) && Array.isArray(y)) {
2655
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
2781
+ return booleanToTypedValue(xValue === yValue);
2782
+ }
2783
+ /**
2784
+ * Determines if two arrays are equivalent according to FHIRPath equality rules.
2785
+ * @param x The first array.
2786
+ * @param y The second array.
2787
+ * @returns FHIRPath true if the arrays are equivalent.
2788
+ */
2789
+ function fhirPathArrayEquivalent(x, y) {
2790
+ if (x.length === 0 && y.length === 0) {
2791
+ return booleanToTypedValue(true);
2656
2792
  }
2657
- if (typeof x === 'object' && typeof y === 'object') {
2658
- return deepEquals(x, y);
2793
+ if (x.length !== y.length) {
2794
+ return booleanToTypedValue(false);
2659
2795
  }
2660
- return x === y;
2796
+ x.sort(fhirPathEquivalentCompare);
2797
+ y.sort(fhirPathEquivalentCompare);
2798
+ return booleanToTypedValue(x.every((val, index) => toJsBoolean(fhirPathEquivalent(val, y[index]))));
2661
2799
  }
2662
2800
  /**
2663
- * Determines if two values are equal according to FHIRPath equality rules.
2801
+ * Determines if two values are equivalent according to FHIRPath equality rules.
2664
2802
  * @param x The first value.
2665
2803
  * @param y The second value.
2666
- * @returns True if equal.
2804
+ * @returns True if equivalent.
2667
2805
  */
2668
2806
  function fhirPathEquivalent(x, y) {
2669
- if (isFalsy(x) && isFalsy(y)) {
2670
- return true;
2671
- }
2672
- if (isEmptyArray(x) || isEmptyArray(y)) {
2673
- // Note that this implies that if the collections have a different number of items to compare,
2674
- // or if one input is a value and the other is empty ({ }), the result will be false.
2675
- return false;
2676
- }
2677
- if (typeof x === 'number' && typeof y === 'number') {
2807
+ const xValue = x.value;
2808
+ const yValue = y.value;
2809
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2678
2810
  // Use more generous threshold than equality
2679
2811
  // Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand.
2680
2812
  // Trailing zeroes after the decimal are ignored in determining precision.
2681
- return Math.abs(x - y) < 0.01;
2682
- }
2683
- if (isQuantity(x) && isQuantity(y)) {
2684
- return isQuantityEquivalent(x, y);
2813
+ return booleanToTypedValue(Math.abs(xValue - yValue) < 0.01);
2685
2814
  }
2686
- if (Array.isArray(x) && Array.isArray(y)) {
2687
- // If both operands are collections with multiple items:
2688
- // 1) Each item must be equivalent
2689
- // 2) Comparison is not order dependent
2690
- x.sort();
2691
- y.sort();
2692
- return x.length === y.length && x.every((val, index) => fhirPathEquals(val, y[index]));
2815
+ if (isQuantity(xValue) && isQuantity(yValue)) {
2816
+ return booleanToTypedValue(isQuantityEquivalent(xValue, yValue));
2693
2817
  }
2694
- if (typeof x === 'object' && typeof y === 'object') {
2695
- return deepEquals(x, y);
2818
+ if (typeof xValue === 'object' && typeof yValue === 'object') {
2819
+ return booleanToTypedValue(deepEquals(xValue, yValue));
2696
2820
  }
2697
- if (typeof x === 'string' && typeof y === 'string') {
2821
+ if (typeof xValue === 'string' && typeof yValue === 'string') {
2698
2822
  // String: the strings must be the same, ignoring case and locale, and normalizing whitespace
2699
2823
  // (see String Equivalence for more details).
2700
- return x.toLowerCase() === y.toLowerCase();
2824
+ return booleanToTypedValue(xValue.toLowerCase() === yValue.toLowerCase());
2825
+ }
2826
+ return booleanToTypedValue(xValue === yValue);
2827
+ }
2828
+ /**
2829
+ * Returns the sort order of two values for FHIRPath array equivalence.
2830
+ * @param x The first value.
2831
+ * @param y The second value.
2832
+ * @returns The sort order of the values.
2833
+ */
2834
+ function fhirPathEquivalentCompare(x, y) {
2835
+ const xValue = x.value;
2836
+ const yValue = y.value;
2837
+ if (typeof xValue === 'number' && typeof yValue === 'number') {
2838
+ return xValue - yValue;
2701
2839
  }
2702
- return x === y;
2840
+ if (typeof xValue === 'string' && typeof yValue === 'string') {
2841
+ return xValue.localeCompare(yValue);
2842
+ }
2843
+ return 0;
2703
2844
  }
2704
- function fhirPathIs(value, desiredType) {
2845
+ /**
2846
+ * Determines if the typed value is the desired type.
2847
+ * @param typedValue The typed value to check.
2848
+ * @param desiredType The desired type name.
2849
+ * @returns True if the typed value is of the desired type.
2850
+ */
2851
+ function fhirPathIs(typedValue, desiredType) {
2852
+ const { value } = typedValue;
2705
2853
  if (value === undefined || value === null) {
2706
2854
  return false;
2707
2855
  }
@@ -2781,6 +2929,7 @@
2781
2929
  return object !== null && typeof object === 'object';
2782
2930
  }
2783
2931
 
2932
+ var _SymbolAtom_instances, _SymbolAtom_evalValue;
2784
2933
  class FhirPathAtom {
2785
2934
  constructor(original, child) {
2786
2935
  this.original = original;
@@ -2788,15 +2937,11 @@
2788
2937
  }
2789
2938
  eval(context) {
2790
2939
  try {
2791
- const result = applyMaybeArray(context, (e) => this.child.eval(e));
2792
- if (Array.isArray(result)) {
2793
- return result.flat();
2794
- }
2795
- else if (result === undefined || result === null) {
2796
- return [];
2940
+ if (context.length > 0) {
2941
+ return context.map((e) => this.child.eval([e])).flat();
2797
2942
  }
2798
2943
  else {
2799
- return [result];
2944
+ return this.child.eval(context);
2800
2945
  }
2801
2946
  }
2802
2947
  catch (error) {
@@ -2809,34 +2954,53 @@
2809
2954
  this.value = value;
2810
2955
  }
2811
2956
  eval() {
2812
- return this.value;
2957
+ return [this.value];
2813
2958
  }
2814
2959
  }
2815
2960
  class SymbolAtom {
2816
2961
  constructor(name) {
2817
2962
  this.name = name;
2963
+ _SymbolAtom_instances.add(this);
2818
2964
  }
2819
2965
  eval(context) {
2820
2966
  if (this.name === '$this') {
2821
2967
  return context;
2822
2968
  }
2823
- return applyMaybeArray(context, (e) => {
2824
- if (e && typeof e === 'object') {
2825
- if ('resourceType' in e && e.resourceType === this.name) {
2826
- return e;
2827
- }
2828
- if (this.name in e) {
2829
- return e[this.name];
2830
- }
2831
- const propertyName = Object.keys(e).find((k) => k.startsWith(this.name));
2832
- if (propertyName) {
2833
- return e[propertyName];
2834
- }
2835
- }
2836
- return undefined;
2837
- });
2969
+ return context
2970
+ .map((e) => __classPrivateFieldGet(this, _SymbolAtom_instances, "m", _SymbolAtom_evalValue).call(this, e))
2971
+ .flat()
2972
+ .filter((e) => (e === null || e === void 0 ? void 0 : e.value) !== undefined);
2838
2973
  }
2839
2974
  }
2975
+ _SymbolAtom_instances = new WeakSet(), _SymbolAtom_evalValue = function _SymbolAtom_evalValue(typedValue) {
2976
+ const input = typedValue.value;
2977
+ if (!input || typeof input !== 'object') {
2978
+ return undefined;
2979
+ }
2980
+ if ('resourceType' in input && input.resourceType === this.name) {
2981
+ return typedValue;
2982
+ }
2983
+ let result = undefined;
2984
+ if (this.name in input) {
2985
+ result = input[this.name];
2986
+ }
2987
+ else {
2988
+ const propertyName = Object.keys(input).find((k) => k.startsWith(this.name));
2989
+ if (propertyName) {
2990
+ result = input[propertyName];
2991
+ }
2992
+ }
2993
+ if (result === undefined) {
2994
+ return undefined;
2995
+ }
2996
+ // TODO: Get the PropertyType from the choice of type
2997
+ if (Array.isArray(result)) {
2998
+ return result.map(toTypedValue);
2999
+ }
3000
+ else {
3001
+ return [toTypedValue(result)];
3002
+ }
3003
+ };
2840
3004
  class EmptySetAtom {
2841
3005
  eval() {
2842
3006
  return [];
@@ -2867,30 +3031,27 @@
2867
3031
  this.impl = impl;
2868
3032
  }
2869
3033
  eval(context) {
2870
- const leftValue = this.left.eval(context);
2871
- const rightValue = this.right.eval(context);
2872
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
2873
- return Object.assign(Object.assign({}, leftValue), { value: this.impl(leftValue.value, rightValue.value) });
3034
+ const leftEvalResult = this.left.eval(context);
3035
+ if (leftEvalResult.length !== 1) {
3036
+ return [];
2874
3037
  }
2875
- else {
2876
- return this.impl(leftValue, rightValue);
3038
+ const rightEvalResult = this.right.eval(context);
3039
+ if (rightEvalResult.length !== 1) {
3040
+ return [];
2877
3041
  }
2878
- }
2879
- }
2880
- class ComparisonOperatorAtom {
2881
- constructor(left, right, impl) {
2882
- this.left = left;
2883
- this.right = right;
2884
- this.impl = impl;
2885
- }
2886
- eval(context) {
2887
- const leftValue = this.left.eval(context);
2888
- const rightValue = this.right.eval(context);
2889
- if (isQuantity(leftValue) && isQuantity(rightValue)) {
2890
- return this.impl(leftValue.value, rightValue.value);
3042
+ const leftValue = leftEvalResult[0].value;
3043
+ const rightValue = rightEvalResult[0].value;
3044
+ const leftNumber = isQuantity(leftValue) ? leftValue.value : leftValue;
3045
+ const rightNumber = isQuantity(rightValue) ? rightValue.value : rightValue;
3046
+ const result = this.impl(leftNumber, rightNumber);
3047
+ if (typeof result === 'boolean') {
3048
+ return booleanToTypedValue(result);
3049
+ }
3050
+ else if (isQuantity(leftValue)) {
3051
+ return [{ type: exports.PropertyType.Quantity, value: Object.assign(Object.assign({}, leftValue), { value: result }) }];
2891
3052
  }
2892
3053
  else {
2893
- return this.impl(leftValue, rightValue);
3054
+ return [toTypedValue(result)];
2894
3055
  }
2895
3056
  }
2896
3057
  }
@@ -2902,21 +3063,9 @@
2902
3063
  eval(context) {
2903
3064
  const leftValue = this.left.eval(context);
2904
3065
  const rightValue = this.right.eval(context);
2905
- const result = [];
2906
- function add(value) {
2907
- if (value) {
2908
- if (Array.isArray(value)) {
2909
- result.push(...value);
2910
- }
2911
- else {
2912
- result.push(value);
2913
- }
2914
- }
2915
- }
2916
- add(leftValue);
2917
- add(rightValue);
2918
- if (result.length > 0 && result.every((e) => typeof e === 'string')) {
2919
- return result.join('');
3066
+ const result = [...leftValue, ...rightValue];
3067
+ if (result.length > 0 && result.every((e) => typeof e.value === 'string')) {
3068
+ return [{ type: exports.PropertyType.string, value: result.map((e) => e.value).join('') }];
2920
3069
  }
2921
3070
  return result;
2922
3071
  }
@@ -2929,7 +3078,7 @@
2929
3078
  eval(context) {
2930
3079
  const leftValue = this.left.eval(context);
2931
3080
  const rightValue = this.right.eval(context);
2932
- return ensureArray(leftValue).includes(rightValue);
3081
+ return booleanToTypedValue(leftValue.some((e) => e.value === rightValue[0].value));
2933
3082
  }
2934
3083
  }
2935
3084
  class InAtom {
@@ -2940,7 +3089,7 @@
2940
3089
  eval(context) {
2941
3090
  const leftValue = this.left.eval(context);
2942
3091
  const rightValue = this.right.eval(context);
2943
- return ensureArray(rightValue).includes(leftValue);
3092
+ return booleanToTypedValue(rightValue.some((e) => e.value === leftValue[0].value));
2944
3093
  }
2945
3094
  }
2946
3095
  class DotAtom {
@@ -2960,20 +3109,7 @@
2960
3109
  eval(context) {
2961
3110
  const leftResult = this.left.eval(context);
2962
3111
  const rightResult = this.right.eval(context);
2963
- let resultArray;
2964
- if (leftResult !== undefined && rightResult !== undefined) {
2965
- resultArray = [leftResult, rightResult].flat();
2966
- }
2967
- else if (leftResult !== undefined) {
2968
- resultArray = ensureArray(leftResult);
2969
- }
2970
- else if (rightResult !== undefined) {
2971
- resultArray = ensureArray(rightResult);
2972
- }
2973
- else {
2974
- resultArray = [];
2975
- }
2976
- return removeDuplicates(resultArray);
3112
+ return removeDuplicates([...leftResult, ...rightResult]);
2977
3113
  }
2978
3114
  }
2979
3115
  class EqualsAtom {
@@ -2984,10 +3120,7 @@
2984
3120
  eval(context) {
2985
3121
  const leftValue = this.left.eval(context);
2986
3122
  const rightValue = this.right.eval(context);
2987
- if (Array.isArray(leftValue) && Array.isArray(rightValue)) {
2988
- return fhirPathEquals(leftValue.flat(), rightValue);
2989
- }
2990
- return applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
3123
+ return fhirPathArrayEquals(leftValue, rightValue);
2991
3124
  }
2992
3125
  }
2993
3126
  class NotEqualsAtom {
@@ -2998,14 +3131,7 @@
2998
3131
  eval(context) {
2999
3132
  const leftValue = this.left.eval(context);
3000
3133
  const rightValue = this.right.eval(context);
3001
- let result;
3002
- if (Array.isArray(rightValue)) {
3003
- result = fhirPathEquals(leftValue, rightValue);
3004
- }
3005
- else {
3006
- result = applyMaybeArray(leftValue, (e) => fhirPathEquals(e, rightValue));
3007
- }
3008
- return !toJsBoolean(result);
3134
+ return fhirPathNot(fhirPathArrayEquals(leftValue, rightValue));
3009
3135
  }
3010
3136
  }
3011
3137
  class EquivalentAtom {
@@ -3016,10 +3142,7 @@
3016
3142
  eval(context) {
3017
3143
  const leftValue = this.left.eval(context);
3018
3144
  const rightValue = this.right.eval(context);
3019
- if (Array.isArray(rightValue)) {
3020
- return fhirPathEquivalent(leftValue, rightValue);
3021
- }
3022
- return applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
3145
+ return fhirPathArrayEquivalent(leftValue, rightValue);
3023
3146
  }
3024
3147
  }
3025
3148
  class NotEquivalentAtom {
@@ -3030,14 +3153,7 @@
3030
3153
  eval(context) {
3031
3154
  const leftValue = this.left.eval(context);
3032
3155
  const rightValue = this.right.eval(context);
3033
- let result;
3034
- if (Array.isArray(rightValue)) {
3035
- result = fhirPathEquivalent(leftValue, rightValue);
3036
- }
3037
- else {
3038
- result = applyMaybeArray(leftValue, (e) => fhirPathEquivalent(e, rightValue));
3039
- }
3040
- return !toJsBoolean(result);
3156
+ return fhirPathNot(fhirPathArrayEquivalent(leftValue, rightValue));
3041
3157
  }
3042
3158
  }
3043
3159
  class IsAtom {
@@ -3046,8 +3162,12 @@
3046
3162
  this.right = right;
3047
3163
  }
3048
3164
  eval(context) {
3165
+ const leftValue = this.left.eval(context);
3166
+ if (leftValue.length !== 1) {
3167
+ return [];
3168
+ }
3049
3169
  const typeName = this.right.name;
3050
- return applyMaybeArray(this.left.eval(context), (e) => fhirPathIs(e, typeName));
3170
+ return booleanToTypedValue(fhirPathIs(leftValue[0], typeName));
3051
3171
  }
3052
3172
  }
3053
3173
  /**
@@ -3060,13 +3180,14 @@
3060
3180
  this.right = right;
3061
3181
  }
3062
3182
  eval(context) {
3183
+ var _a, _b, _c, _d;
3063
3184
  const leftValue = this.left.eval(context);
3064
3185
  const rightValue = this.right.eval(context);
3065
- if (leftValue === true && rightValue === true) {
3066
- return true;
3186
+ if (((_a = leftValue[0]) === null || _a === void 0 ? void 0 : _a.value) === true && ((_b = rightValue[0]) === null || _b === void 0 ? void 0 : _b.value) === true) {
3187
+ return booleanToTypedValue(true);
3067
3188
  }
3068
- if (leftValue === false || rightValue === false) {
3069
- return false;
3189
+ if (((_c = leftValue[0]) === null || _c === void 0 ? void 0 : _c.value) === false || ((_d = rightValue[0]) === null || _d === void 0 ? void 0 : _d.value) === false) {
3190
+ return booleanToTypedValue(false);
3070
3191
  }
3071
3192
  return [];
3072
3193
  }
@@ -3100,13 +3221,18 @@
3100
3221
  this.right = right;
3101
3222
  }
3102
3223
  eval(context) {
3103
- const leftValue = this.left.eval(context);
3104
- const rightValue = this.right.eval(context);
3224
+ const leftResult = this.left.eval(context);
3225
+ const rightResult = this.right.eval(context);
3226
+ if (leftResult.length === 0 && rightResult.length === 0) {
3227
+ return [];
3228
+ }
3229
+ const leftValue = leftResult.length === 0 ? null : leftResult[0].value;
3230
+ const rightValue = rightResult.length === 0 ? null : rightResult[0].value;
3105
3231
  if ((leftValue === true && rightValue !== true) || (leftValue !== true && rightValue === true)) {
3106
- return true;
3232
+ return booleanToTypedValue(true);
3107
3233
  }
3108
3234
  if ((leftValue === true && rightValue === true) || (leftValue === false && rightValue === false)) {
3109
- return false;
3235
+ return booleanToTypedValue(false);
3110
3236
  }
3111
3237
  return [];
3112
3238
  }
@@ -3118,7 +3244,7 @@
3118
3244
  this.impl = impl;
3119
3245
  }
3120
3246
  eval(context) {
3121
- return this.impl(ensureArray(context), ...this.args);
3247
+ return this.impl(context, ...this.args);
3122
3248
  }
3123
3249
  }
3124
3250
  class IndexerAtom {
@@ -3127,7 +3253,11 @@
3127
3253
  this.expr = expr;
3128
3254
  }
3129
3255
  eval(context) {
3130
- const index = this.expr.eval(context);
3256
+ const evalResult = this.expr.eval(context);
3257
+ if (evalResult.length !== 1) {
3258
+ return [];
3259
+ }
3260
+ const index = evalResult[0].value;
3131
3261
  if (typeof index !== 'number') {
3132
3262
  throw new Error(`Invalid indexer expression: should return integer}`);
3133
3263
  }
@@ -3135,7 +3265,7 @@
3135
3265
  if (!(index in leftResult)) {
3136
3266
  return [];
3137
3267
  }
3138
- return leftResult[index];
3268
+ return [leftResult[index]];
3139
3269
  }
3140
3270
  }
3141
3271
 
@@ -3161,1414 +3291,1453 @@
3161
3291
  }
3162
3292
  }
3163
3293
 
3164
- /*
3165
- * Collection of FHIRPath
3166
- * See: https://hl7.org/fhirpath/#functions
3167
- */
3168
3294
  /**
3169
3295
  * Temporary placholder for unimplemented methods.
3170
3296
  */
3171
3297
  const stub = () => [];
3172
- /*
3173
- * 5.1 Existence
3174
- * See: https://hl7.org/fhirpath/#existence
3175
- */
3176
- /**
3177
- * Returns true if the input collection is empty ({ }) and false otherwise.
3178
- *
3179
- * See: https://hl7.org/fhirpath/#empty-boolean
3180
- *
3181
- * @param input The input collection.
3182
- * @returns True if the input collection is empty ({ }) and false otherwise.
3183
- */
3184
- function empty(input) {
3185
- return [input.length === 0];
3186
- }
3187
- /**
3188
- * Returns true if the collection has unknown elements, and false otherwise.
3189
- * This is the opposite of empty(), and as such is a shorthand for empty().not().
3190
- * If the input collection is empty ({ }), the result is false.
3191
- *
3192
- * The function can also take an optional criteria to be applied to the collection
3193
- * prior to the determination of the exists. In this case, the function is shorthand
3194
- * for where(criteria).exists().
3195
- *
3196
- * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
3197
- *
3198
- * @param input
3199
- * @param criteria
3200
- * @returns True if the collection has unknown elements, and false otherwise.
3201
- */
3202
- function exists(input, criteria) {
3203
- if (criteria) {
3204
- return [input.filter((e) => toJsBoolean(criteria.eval(e))).length > 0];
3205
- }
3206
- else {
3207
- return [input.length > 0];
3208
- }
3209
- }
3210
- /**
3211
- * Returns true if for every element in the input collection, criteria evaluates to true.
3212
- * Otherwise, the result is false.
3213
- *
3214
- * If the input collection is empty ({ }), the result is true.
3215
- *
3216
- * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
3217
- *
3218
- * @param input The input collection.
3219
- * @param criteria The evaluation criteria.
3220
- * @returns True if for every element in the input collection, criteria evaluates to true.
3221
- */
3222
- function all(input, criteria) {
3223
- return [input.every((e) => toJsBoolean(criteria.eval(e)))];
3224
- }
3225
- /**
3226
- * Takes a collection of Boolean values and returns true if all the items are true.
3227
- * If unknown items are false, the result is false.
3228
- * If the input is empty ({ }), the result is true.
3229
- *
3230
- * See: https://hl7.org/fhirpath/#alltrue-boolean
3231
- *
3232
- * @param input The input collection.
3233
- * @param criteria The evaluation criteria.
3234
- * @returns True if all the items are true.
3235
- */
3236
- function allTrue(input) {
3237
- for (const value of input) {
3238
- if (!value) {
3239
- return [false];
3240
- }
3241
- }
3242
- return [true];
3243
- }
3244
- /**
3245
- * Takes a collection of Boolean values and returns true if unknown of the items are true.
3246
- * If all the items are false, or if the input is empty ({ }), the result is false.
3247
- *
3248
- * See: https://hl7.org/fhirpath/#anytrue-boolean
3249
- *
3250
- * @param input The input collection.
3251
- * @param criteria The evaluation criteria.
3252
- * @returns True if unknown of the items are true.
3253
- */
3254
- function anyTrue(input) {
3255
- for (const value of input) {
3256
- if (value) {
3257
- return [true];
3298
+ const functions = {
3299
+ /*
3300
+ * 5.1 Existence
3301
+ * See: https://hl7.org/fhirpath/#existence
3302
+ */
3303
+ /**
3304
+ * Returns true if the input collection is empty ({ }) and false otherwise.
3305
+ *
3306
+ * See: https://hl7.org/fhirpath/#empty-boolean
3307
+ *
3308
+ * @param input The input collection.
3309
+ * @returns True if the input collection is empty ({ }) and false otherwise.
3310
+ */
3311
+ empty: (input) => {
3312
+ return booleanToTypedValue(input.length === 0);
3313
+ },
3314
+ /**
3315
+ * Returns true if the collection has unknown elements, and false otherwise.
3316
+ * This is the opposite of empty(), and as such is a shorthand for empty().not().
3317
+ * If the input collection is empty ({ }), the result is false.
3318
+ *
3319
+ * The function can also take an optional criteria to be applied to the collection
3320
+ * prior to the determination of the exists. In this case, the function is shorthand
3321
+ * for where(criteria).exists().
3322
+ *
3323
+ * See: https://hl7.org/fhirpath/#existscriteria-expression-boolean
3324
+ *
3325
+ * @param input
3326
+ * @param criteria
3327
+ * @returns True if the collection has unknown elements, and false otherwise.
3328
+ */
3329
+ exists: (input, criteria) => {
3330
+ if (criteria) {
3331
+ return booleanToTypedValue(input.filter((e) => toJsBoolean(criteria.eval([e]))).length > 0);
3258
3332
  }
3259
- }
3260
- return [false];
3261
- }
3262
- /**
3263
- * Takes a collection of Boolean values and returns true if all the items are false.
3264
- * If unknown items are true, the result is false.
3265
- * If the input is empty ({ }), the result is true.
3266
- *
3267
- * See: https://hl7.org/fhirpath/#allfalse-boolean
3268
- *
3269
- * @param input The input collection.
3270
- * @param criteria The evaluation criteria.
3271
- * @returns True if all the items are false.
3272
- */
3273
- function allFalse(input) {
3274
- for (const value of input) {
3275
- if (value) {
3276
- return [false];
3333
+ else {
3334
+ return booleanToTypedValue(input.length > 0);
3277
3335
  }
3278
- }
3279
- return [true];
3280
- }
3281
- /**
3282
- * Takes a collection of Boolean values and returns true if unknown of the items are false.
3283
- * If all the items are true, or if the input is empty ({ }), the result is false.
3284
- *
3285
- * See: https://hl7.org/fhirpath/#anyfalse-boolean
3286
- *
3287
- * @param input The input collection.
3288
- * @param criteria The evaluation criteria.
3289
- * @returns True if for every element in the input collection, criteria evaluates to true.
3290
- */
3291
- function anyFalse(input) {
3292
- for (const value of input) {
3293
- if (!value) {
3294
- return [true];
3336
+ },
3337
+ /**
3338
+ * Returns true if for every element in the input collection, criteria evaluates to true.
3339
+ * Otherwise, the result is false.
3340
+ *
3341
+ * If the input collection is empty ({ }), the result is true.
3342
+ *
3343
+ * See: https://hl7.org/fhirpath/#allcriteria-expression-boolean
3344
+ *
3345
+ * @param input The input collection.
3346
+ * @param criteria The evaluation criteria.
3347
+ * @returns True if for every element in the input collection, criteria evaluates to true.
3348
+ */
3349
+ all: (input, criteria) => {
3350
+ return booleanToTypedValue(input.every((e) => toJsBoolean(criteria.eval([e]))));
3351
+ },
3352
+ /**
3353
+ * Takes a collection of Boolean values and returns true if all the items are true.
3354
+ * If unknown items are false, the result is false.
3355
+ * If the input is empty ({ }), the result is true.
3356
+ *
3357
+ * See: https://hl7.org/fhirpath/#alltrue-boolean
3358
+ *
3359
+ * @param input The input collection.
3360
+ * @param criteria The evaluation criteria.
3361
+ * @returns True if all the items are true.
3362
+ */
3363
+ allTrue: (input) => {
3364
+ for (const value of input) {
3365
+ if (!value.value) {
3366
+ return booleanToTypedValue(false);
3367
+ }
3295
3368
  }
3296
- }
3297
- return [false];
3298
- }
3299
- /**
3300
- * Returns true if all items in the input collection are members of the collection passed
3301
- * as the other argument. Membership is determined using the = (Equals) (=) operation.
3302
- *
3303
- * Conceptually, this function is evaluated by testing each element in the input collection
3304
- * for membership in the other collection, with a default of true. This means that if the
3305
- * input collection is empty ({ }), the result is true, otherwise if the other collection
3306
- * is empty ({ }), the result is false.
3307
- *
3308
- * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
3309
- */
3310
- const subsetOf = stub;
3311
- /**
3312
- * Returns true if all items in the collection passed as the other argument are members of
3313
- * the input collection. Membership is determined using the = (Equals) (=) operation.
3314
- *
3315
- * Conceptually, this function is evaluated by testing each element in the other collection
3316
- * for membership in the input collection, with a default of true. This means that if the
3317
- * other collection is empty ({ }), the result is true, otherwise if the input collection
3318
- * is empty ({ }), the result is false.
3319
- *
3320
- * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
3321
- */
3322
- const supersetOf = stub;
3323
- /**
3324
- * Returns the integer count of the number of items in the input collection.
3325
- * Returns 0 when the input collection is empty.
3326
- *
3327
- * See: https://hl7.org/fhirpath/#count-integer
3328
- *
3329
- * @param input The input collection.
3330
- * @returns The integer count of the number of items in the input collection.
3331
- */
3332
- function count(input) {
3333
- return [input.length];
3334
- }
3335
- /**
3336
- * Returns a collection containing only the unique items in the input collection.
3337
- * To determine whether two items are the same, the = (Equals) (=) operator is used,
3338
- * as defined below.
3339
- *
3340
- * If the input collection is empty ({ }), the result is empty.
3341
- *
3342
- * Note that the order of elements in the input collection is not guaranteed to be
3343
- * preserved in the result.
3344
- *
3345
- * See: https://hl7.org/fhirpath/#distinct-collection
3346
- *
3347
- * @param input The input collection.
3348
- * @returns The integer count of the number of items in the input collection.
3349
- */
3350
- function distinct(input) {
3351
- return Array.from(new Set(input));
3352
- }
3353
- /**
3354
- * Returns true if all the items in the input collection are distinct.
3355
- * To determine whether two items are distinct, the = (Equals) (=) operator is used,
3356
- * as defined below.
3357
- *
3358
- * See: https://hl7.org/fhirpath/#isdistinct-boolean
3359
- *
3360
- * @param input The input collection.
3361
- * @returns The integer count of the number of items in the input collection.
3362
- */
3363
- function isDistinct(input) {
3364
- return [input.length === new Set(input).size];
3365
- }
3366
- /*
3367
- * 5.2 Filtering and projection
3368
- */
3369
- /**
3370
- * Returns a collection containing only those elements in the input collection
3371
- * for which the stated criteria expression evaluates to true.
3372
- * Elements for which the expression evaluates to false or empty ({ }) are not
3373
- * included in the result.
3374
- *
3375
- * If the input collection is empty ({ }), the result is empty.
3376
- *
3377
- * If the result of evaluating the condition is other than a single boolean value,
3378
- * the evaluation will end and signal an error to the calling environment,
3379
- * consistent with singleton evaluation of collections behavior.
3380
- *
3381
- * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
3382
- *
3383
- * @param input The input collection.
3384
- * @param condition The condition atom.
3385
- * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
3386
- */
3387
- function where(input, criteria) {
3388
- return input.filter((e) => toJsBoolean(criteria.eval(e)));
3389
- }
3390
- /**
3391
- * Evaluates the projection expression for each item in the input collection.
3392
- * The result of each evaluation is added to the output collection. If the
3393
- * evaluation results in a collection with multiple items, all items are added
3394
- * to the output collection (collections resulting from evaluation of projection
3395
- * are flattened). This means that if the evaluation for an element results in
3396
- * the empty collection ({ }), no element is added to the result, and that if
3397
- * the input collection is empty ({ }), the result is empty as well.
3398
- *
3399
- * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
3400
- */
3401
- function select(input, criteria) {
3402
- return ensureArray(input.map((e) => criteria.eval(e)).flat());
3403
- }
3404
- /**
3405
- * A version of select that will repeat the projection and add it to the output
3406
- * collection, as long as the projection yields new items (as determined by
3407
- * the = (Equals) (=) operator).
3408
- *
3409
- * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
3410
- */
3411
- const repeat = stub;
3412
- /**
3413
- * Returns a collection that contains all items in the input collection that
3414
- * are of the given type or a subclass thereof. If the input collection is
3415
- * empty ({ }), the result is empty. The type argument is an identifier that
3416
- * must resolve to the name of a type in a model
3417
- *
3418
- * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
3419
- */
3420
- const ofType = stub;
3421
- /*
3422
- * 5.3 Subsetting
3423
- */
3424
- /**
3425
- * Will return the single item in the input if there is just one item.
3426
- * If the input collection is empty ({ }), the result is empty.
3427
- * If there are multiple items, an error is signaled to the evaluation environment.
3428
- * This function is useful for ensuring that an error is returned if an assumption
3429
- * about cardinality is violated at run-time.
3430
- *
3431
- * See: https://hl7.org/fhirpath/#single-collection
3432
- *
3433
- * @param input The input collection.
3434
- * @returns The single item in the input if there is just one item.
3435
- */
3436
- function single(input) {
3437
- if (input.length > 1) {
3438
- throw new Error('Expected input length one for single()');
3439
- }
3440
- return input.length === 0 ? [] : input.slice(0, 1);
3441
- }
3442
- /**
3443
- * Returns a collection containing only the first item in the input collection.
3444
- * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
3445
- *
3446
- * See: https://hl7.org/fhirpath/#first-collection
3447
- *
3448
- * @param input The input collection.
3449
- * @returns A collection containing only the first item in the input collection.
3450
- */
3451
- function first(input) {
3452
- return input.length === 0 ? [] : [input[0]];
3453
- }
3454
- /**
3455
- * Returns a collection containing only the last item in the input collection.
3456
- * Will return an empty collection if the input collection has no items.
3457
- *
3458
- * See: https://hl7.org/fhirpath/#last-collection
3459
- *
3460
- * @param input The input collection.
3461
- * @returns A collection containing only the last item in the input collection.
3462
- */
3463
- function last(input) {
3464
- return input.length === 0 ? [] : [input[input.length - 1]];
3465
- }
3466
- /**
3467
- * Returns a collection containing all but the first item in the input collection.
3468
- * Will return an empty collection if the input collection has no items, or only one item.
3469
- *
3470
- * See: https://hl7.org/fhirpath/#tail-collection
3471
- *
3472
- * @param input The input collection.
3473
- * @returns A collection containing all but the first item in the input collection.
3474
- */
3475
- function tail(input) {
3476
- return input.length === 0 ? [] : input.slice(1, input.length);
3477
- }
3478
- /**
3479
- * Returns a collection containing all but the first num items in the input collection.
3480
- * Will return an empty collection if there are no items remaining after the
3481
- * indicated number of items have been skipped, or if the input collection is empty.
3482
- * If num is less than or equal to zero, the input collection is simply returned.
3483
- *
3484
- * See: https://hl7.org/fhirpath/#skipnum-integer-collection
3485
- *
3486
- * @param input The input collection.
3487
- * @returns A collection containing all but the first item in the input collection.
3488
- */
3489
- function skip(input, num) {
3490
- const numValue = num.eval(0);
3491
- if (typeof numValue !== 'number') {
3492
- throw new Error('Expected a number for skip(num)');
3493
- }
3494
- if (numValue >= input.length) {
3495
- return [];
3496
- }
3497
- if (numValue <= 0) {
3498
- return input;
3499
- }
3500
- return input.slice(numValue, input.length);
3501
- }
3502
- /**
3503
- * Returns a collection containing the first num items in the input collection,
3504
- * or less if there are less than num items.
3505
- * If num is less than or equal to 0, or if the input collection is empty ({ }),
3506
- * take returns an empty collection.
3507
- *
3508
- * See: https://hl7.org/fhirpath/#takenum-integer-collection
3509
- *
3510
- * @param input The input collection.
3511
- * @returns A collection containing the first num items in the input collection.
3512
- */
3513
- function take(input, num) {
3514
- const numValue = num.eval(0);
3515
- if (typeof numValue !== 'number') {
3516
- throw new Error('Expected a number for take(num)');
3517
- }
3518
- if (numValue >= input.length) {
3519
- return input;
3520
- }
3521
- if (numValue <= 0) {
3522
- return [];
3523
- }
3524
- return input.slice(0, numValue);
3525
- }
3526
- /**
3527
- * Returns the set of elements that are in both collections.
3528
- * Duplicate items will be eliminated by this function.
3529
- * Order of items is not guaranteed to be preserved in the result of this function.
3530
- *
3531
- * See: http://hl7.org/fhirpath/#intersectother-collection-collection
3532
- */
3533
- function intersect(input, other) {
3534
- if (!other) {
3535
- return input;
3536
- }
3537
- const otherArray = ensureArray(other.eval(0));
3538
- return removeDuplicates(input.filter((e) => otherArray.includes(e)));
3539
- }
3540
- /**
3541
- * Returns the set of elements that are not in the other collection.
3542
- * Duplicate items will not be eliminated by this function, and order will be preserved.
3543
- *
3544
- * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
3545
- *
3546
- * See: http://hl7.org/fhirpath/#excludeother-collection-collection
3547
- */
3548
- function exclude(input, other) {
3549
- if (!other) {
3550
- return input;
3551
- }
3552
- const otherArray = ensureArray(other.eval(0));
3553
- return input.filter((e) => !otherArray.includes(e));
3554
- }
3555
- /*
3556
- * 5.4. Combining
3557
- *
3558
- * See: https://hl7.org/fhirpath/#combining
3559
- */
3560
- /**
3561
- * Merge the two collections into a single collection,
3562
- * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
3563
- * There is no expectation of order in the resulting collection.
3564
- *
3565
- * In other words, this function returns the distinct list of elements from both inputs.
3566
- *
3567
- * See: http://hl7.org/fhirpath/#unionother-collection
3568
- */
3569
- function union(input, other) {
3570
- if (!other) {
3571
- return input;
3572
- }
3573
- return removeDuplicates([input, other.eval(0)].flat());
3574
- }
3575
- /**
3576
- * Merge the input and other collections into a single collection
3577
- * without eliminating duplicate values. Combining an empty collection
3578
- * with a non-empty collection will return the non-empty collection.
3579
- *
3580
- * There is no expectation of order in the resulting collection.
3581
- *
3582
- * See: http://hl7.org/fhirpath/#combineother-collection-collection
3583
- */
3584
- function combine(input, other) {
3585
- if (!other) {
3586
- return input;
3587
- }
3588
- return [input, other.eval(0)].flat();
3589
- }
3590
- /*
3591
- * 5.5. Conversion
3592
- *
3593
- * See: https://hl7.org/fhirpath/#conversion
3594
- */
3595
- /**
3596
- * The iif function in FHIRPath is an immediate if,
3597
- * also known as a conditional operator (such as C’s ? : operator).
3598
- *
3599
- * The criterion expression is expected to evaluate to a Boolean.
3600
- *
3601
- * If criterion is true, the function returns the value of the true-result argument.
3602
- *
3603
- * If criterion is false or an empty collection, the function returns otherwise-result,
3604
- * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
3605
- *
3606
- * Note that short-circuit behavior is expected in this function. In other words,
3607
- * true-result should only be evaluated if the criterion evaluates to true,
3608
- * and otherwise-result should only be evaluated otherwise. For implementations,
3609
- * this means delaying evaluation of the arguments.
3610
- *
3611
- * @param input
3612
- * @param criterion
3613
- * @param trueResult
3614
- * @param otherwiseResult
3615
- * @returns
3616
- */
3617
- function iif(input, criterion, trueResult, otherwiseResult) {
3618
- const evalResult = ensureArray(criterion.eval(input));
3619
- if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0] !== 'boolean')) {
3620
- throw new Error('Expected criterion to evaluate to a Boolean');
3621
- }
3622
- if (toJsBoolean(evalResult)) {
3623
- return ensureArray(trueResult.eval(input));
3624
- }
3625
- if (otherwiseResult) {
3626
- return ensureArray(otherwiseResult.eval(input));
3627
- }
3628
- return [];
3629
- }
3630
- /**
3631
- * Converts an input collection to a boolean.
3632
- *
3633
- * If the input collection contains a single item, this function will return a single boolean if:
3634
- * 1) the item is a Boolean
3635
- * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
3636
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3637
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3638
- *
3639
- * 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.
3640
- *
3641
- * See: https://hl7.org/fhirpath/#toboolean-boolean
3642
- *
3643
- * @param input
3644
- * @returns
3645
- */
3646
- function toBoolean(input) {
3647
- if (input.length === 0) {
3648
- return [];
3649
- }
3650
- const [value] = validateInput(input, 1);
3651
- if (typeof value === 'boolean') {
3652
- return [value];
3653
- }
3654
- if (typeof value === 'number') {
3655
- if (value === 0 || value === 1) {
3656
- return [!!value];
3369
+ return booleanToTypedValue(true);
3370
+ },
3371
+ /**
3372
+ * Takes a collection of Boolean values and returns true if unknown of the items are true.
3373
+ * If all the items are false, or if the input is empty ({ }), the result is false.
3374
+ *
3375
+ * See: https://hl7.org/fhirpath/#anytrue-boolean
3376
+ *
3377
+ * @param input The input collection.
3378
+ * @param criteria The evaluation criteria.
3379
+ * @returns True if unknown of the items are true.
3380
+ */
3381
+ anyTrue: (input) => {
3382
+ for (const value of input) {
3383
+ if (value.value) {
3384
+ return booleanToTypedValue(true);
3385
+ }
3657
3386
  }
3658
- }
3659
- if (typeof value === 'string') {
3660
- const lowerStr = value.toLowerCase();
3661
- if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
3662
- return [true];
3387
+ return booleanToTypedValue(false);
3388
+ },
3389
+ /**
3390
+ * Takes a collection of Boolean values and returns true if all the items are false.
3391
+ * If unknown items are true, the result is false.
3392
+ * If the input is empty ({ }), the result is true.
3393
+ *
3394
+ * See: https://hl7.org/fhirpath/#allfalse-boolean
3395
+ *
3396
+ * @param input The input collection.
3397
+ * @param criteria The evaluation criteria.
3398
+ * @returns True if all the items are false.
3399
+ */
3400
+ allFalse: (input) => {
3401
+ for (const value of input) {
3402
+ if (value.value) {
3403
+ return booleanToTypedValue(false);
3404
+ }
3663
3405
  }
3664
- if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
3665
- return [false];
3406
+ return booleanToTypedValue(true);
3407
+ },
3408
+ /**
3409
+ * Takes a collection of Boolean values and returns true if unknown of the items are false.
3410
+ * If all the items are true, or if the input is empty ({ }), the result is false.
3411
+ *
3412
+ * See: https://hl7.org/fhirpath/#anyfalse-boolean
3413
+ *
3414
+ * @param input The input collection.
3415
+ * @param criteria The evaluation criteria.
3416
+ * @returns True if for every element in the input collection, criteria evaluates to true.
3417
+ */
3418
+ anyFalse: (input) => {
3419
+ for (const value of input) {
3420
+ if (!value.value) {
3421
+ return booleanToTypedValue(true);
3422
+ }
3423
+ }
3424
+ return booleanToTypedValue(false);
3425
+ },
3426
+ /**
3427
+ * Returns true if all items in the input collection are members of the collection passed
3428
+ * as the other argument. Membership is determined using the = (Equals) (=) operation.
3429
+ *
3430
+ * Conceptually, this function is evaluated by testing each element in the input collection
3431
+ * for membership in the other collection, with a default of true. This means that if the
3432
+ * input collection is empty ({ }), the result is true, otherwise if the other collection
3433
+ * is empty ({ }), the result is false.
3434
+ *
3435
+ * See: http://hl7.org/fhirpath/#subsetofother-collection-boolean
3436
+ */
3437
+ subsetOf: stub,
3438
+ /**
3439
+ * Returns true if all items in the collection passed as the other argument are members of
3440
+ * the input collection. Membership is determined using the = (Equals) (=) operation.
3441
+ *
3442
+ * Conceptually, this function is evaluated by testing each element in the other collection
3443
+ * for membership in the input collection, with a default of true. This means that if the
3444
+ * other collection is empty ({ }), the result is true, otherwise if the input collection
3445
+ * is empty ({ }), the result is false.
3446
+ *
3447
+ * See: http://hl7.org/fhirpath/#supersetofother-collection-boolean
3448
+ */
3449
+ supersetOf: stub,
3450
+ /**
3451
+ * Returns the integer count of the number of items in the input collection.
3452
+ * Returns 0 when the input collection is empty.
3453
+ *
3454
+ * See: https://hl7.org/fhirpath/#count-integer
3455
+ *
3456
+ * @param input The input collection.
3457
+ * @returns The integer count of the number of items in the input collection.
3458
+ */
3459
+ count: (input) => {
3460
+ return [{ type: exports.PropertyType.integer, value: input.length }];
3461
+ },
3462
+ /**
3463
+ * Returns a collection containing only the unique items in the input collection.
3464
+ * To determine whether two items are the same, the = (Equals) (=) operator is used,
3465
+ * as defined below.
3466
+ *
3467
+ * If the input collection is empty ({ }), the result is empty.
3468
+ *
3469
+ * Note that the order of elements in the input collection is not guaranteed to be
3470
+ * preserved in the result.
3471
+ *
3472
+ * See: https://hl7.org/fhirpath/#distinct-collection
3473
+ *
3474
+ * @param input The input collection.
3475
+ * @returns The integer count of the number of items in the input collection.
3476
+ */
3477
+ distinct: (input) => {
3478
+ const result = [];
3479
+ for (const value of input) {
3480
+ if (!result.some((e) => e.value === value.value)) {
3481
+ result.push(value);
3482
+ }
3483
+ }
3484
+ return result;
3485
+ },
3486
+ /**
3487
+ * Returns true if all the items in the input collection are distinct.
3488
+ * To determine whether two items are distinct, the = (Equals) (=) operator is used,
3489
+ * as defined below.
3490
+ *
3491
+ * See: https://hl7.org/fhirpath/#isdistinct-boolean
3492
+ *
3493
+ * @param input The input collection.
3494
+ * @returns The integer count of the number of items in the input collection.
3495
+ */
3496
+ isDistinct: (input) => {
3497
+ return booleanToTypedValue(input.length === functions.distinct(input).length);
3498
+ },
3499
+ /*
3500
+ * 5.2 Filtering and projection
3501
+ */
3502
+ /**
3503
+ * Returns a collection containing only those elements in the input collection
3504
+ * for which the stated criteria expression evaluates to true.
3505
+ * Elements for which the expression evaluates to false or empty ({ }) are not
3506
+ * included in the result.
3507
+ *
3508
+ * If the input collection is empty ({ }), the result is empty.
3509
+ *
3510
+ * If the result of evaluating the condition is other than a single boolean value,
3511
+ * the evaluation will end and signal an error to the calling environment,
3512
+ * consistent with singleton evaluation of collections behavior.
3513
+ *
3514
+ * See: https://hl7.org/fhirpath/#wherecriteria-expression-collection
3515
+ *
3516
+ * @param input The input collection.
3517
+ * @param condition The condition atom.
3518
+ * @returns A collection containing only those elements in the input collection for which the stated criteria expression evaluates to true.
3519
+ */
3520
+ where: (input, criteria) => {
3521
+ return input.filter((e) => toJsBoolean(criteria.eval([e])));
3522
+ },
3523
+ /**
3524
+ * Evaluates the projection expression for each item in the input collection.
3525
+ * The result of each evaluation is added to the output collection. If the
3526
+ * evaluation results in a collection with multiple items, all items are added
3527
+ * to the output collection (collections resulting from evaluation of projection
3528
+ * are flattened). This means that if the evaluation for an element results in
3529
+ * the empty collection ({ }), no element is added to the result, and that if
3530
+ * the input collection is empty ({ }), the result is empty as well.
3531
+ *
3532
+ * See: http://hl7.org/fhirpath/#selectprojection-expression-collection
3533
+ */
3534
+ select: (input, criteria) => {
3535
+ return input.map((e) => criteria.eval([e])).flat();
3536
+ },
3537
+ /**
3538
+ * A version of select that will repeat the projection and add it to the output
3539
+ * collection, as long as the projection yields new items (as determined by
3540
+ * the = (Equals) (=) operator).
3541
+ *
3542
+ * See: http://hl7.org/fhirpath/#repeatprojection-expression-collection
3543
+ */
3544
+ repeat: stub,
3545
+ /**
3546
+ * Returns a collection that contains all items in the input collection that
3547
+ * are of the given type or a subclass thereof. If the input collection is
3548
+ * empty ({ }), the result is empty. The type argument is an identifier that
3549
+ * must resolve to the name of a type in a model
3550
+ *
3551
+ * See: http://hl7.org/fhirpath/#oftypetype-type-specifier-collection
3552
+ */
3553
+ ofType: stub,
3554
+ /*
3555
+ * 5.3 Subsetting
3556
+ */
3557
+ /**
3558
+ * Will return the single item in the input if there is just one item.
3559
+ * If the input collection is empty ({ }), the result is empty.
3560
+ * If there are multiple items, an error is signaled to the evaluation environment.
3561
+ * This function is useful for ensuring that an error is returned if an assumption
3562
+ * about cardinality is violated at run-time.
3563
+ *
3564
+ * See: https://hl7.org/fhirpath/#single-collection
3565
+ *
3566
+ * @param input The input collection.
3567
+ * @returns The single item in the input if there is just one item.
3568
+ */
3569
+ single: (input) => {
3570
+ if (input.length > 1) {
3571
+ throw new Error('Expected input length one for single()');
3572
+ }
3573
+ return input.length === 0 ? [] : input.slice(0, 1);
3574
+ },
3575
+ /**
3576
+ * Returns a collection containing only the first item in the input collection.
3577
+ * This function is equivalent to item[0], so it will return an empty collection if the input collection has no items.
3578
+ *
3579
+ * See: https://hl7.org/fhirpath/#first-collection
3580
+ *
3581
+ * @param input The input collection.
3582
+ * @returns A collection containing only the first item in the input collection.
3583
+ */
3584
+ first: (input) => {
3585
+ return input.length === 0 ? [] : input.slice(0, 1);
3586
+ },
3587
+ /**
3588
+ * Returns a collection containing only the last item in the input collection.
3589
+ * Will return an empty collection if the input collection has no items.
3590
+ *
3591
+ * See: https://hl7.org/fhirpath/#last-collection
3592
+ *
3593
+ * @param input The input collection.
3594
+ * @returns A collection containing only the last item in the input collection.
3595
+ */
3596
+ last: (input) => {
3597
+ return input.length === 0 ? [] : input.slice(input.length - 1, input.length);
3598
+ },
3599
+ /**
3600
+ * Returns a collection containing all but the first item in the input collection.
3601
+ * Will return an empty collection if the input collection has no items, or only one item.
3602
+ *
3603
+ * See: https://hl7.org/fhirpath/#tail-collection
3604
+ *
3605
+ * @param input The input collection.
3606
+ * @returns A collection containing all but the first item in the input collection.
3607
+ */
3608
+ tail: (input) => {
3609
+ return input.length === 0 ? [] : input.slice(1, input.length);
3610
+ },
3611
+ /**
3612
+ * Returns a collection containing all but the first num items in the input collection.
3613
+ * Will return an empty collection if there are no items remaining after the
3614
+ * indicated number of items have been skipped, or if the input collection is empty.
3615
+ * If num is less than or equal to zero, the input collection is simply returned.
3616
+ *
3617
+ * See: https://hl7.org/fhirpath/#skipnum-integer-collection
3618
+ *
3619
+ * @param input The input collection.
3620
+ * @returns A collection containing all but the first item in the input collection.
3621
+ */
3622
+ skip: (input, num) => {
3623
+ var _a;
3624
+ const numValue = (_a = num.eval([])[0]) === null || _a === void 0 ? void 0 : _a.value;
3625
+ if (typeof numValue !== 'number') {
3626
+ throw new Error('Expected a number for skip(num)');
3627
+ }
3628
+ if (numValue >= input.length) {
3629
+ return [];
3630
+ }
3631
+ if (numValue <= 0) {
3632
+ return input;
3633
+ }
3634
+ return input.slice(numValue, input.length);
3635
+ },
3636
+ /**
3637
+ * Returns a collection containing the first num items in the input collection,
3638
+ * or less if there are less than num items.
3639
+ * If num is less than or equal to 0, or if the input collection is empty ({ }),
3640
+ * take returns an empty collection.
3641
+ *
3642
+ * See: https://hl7.org/fhirpath/#takenum-integer-collection
3643
+ *
3644
+ * @param input The input collection.
3645
+ * @returns A collection containing the first num items in the input collection.
3646
+ */
3647
+ take: (input, num) => {
3648
+ var _a;
3649
+ const numValue = (_a = num.eval([])[0]) === null || _a === void 0 ? void 0 : _a.value;
3650
+ if (typeof numValue !== 'number') {
3651
+ throw new Error('Expected a number for take(num)');
3652
+ }
3653
+ if (numValue >= input.length) {
3654
+ return input;
3655
+ }
3656
+ if (numValue <= 0) {
3657
+ return [];
3658
+ }
3659
+ return input.slice(0, numValue);
3660
+ },
3661
+ /**
3662
+ * Returns the set of elements that are in both collections.
3663
+ * Duplicate items will be eliminated by this function.
3664
+ * Order of items is not guaranteed to be preserved in the result of this function.
3665
+ *
3666
+ * See: http://hl7.org/fhirpath/#intersectother-collection-collection
3667
+ */
3668
+ intersect: (input, other) => {
3669
+ if (!other) {
3670
+ return input;
3671
+ }
3672
+ const otherArray = other.eval([]);
3673
+ const result = [];
3674
+ for (const value of input) {
3675
+ if (!result.some((e) => e.value === value.value) && otherArray.some((e) => e.value === value.value)) {
3676
+ result.push(value);
3677
+ }
3678
+ }
3679
+ return result;
3680
+ },
3681
+ /**
3682
+ * Returns the set of elements that are not in the other collection.
3683
+ * Duplicate items will not be eliminated by this function, and order will be preserved.
3684
+ *
3685
+ * e.g. (1 | 2 | 3).exclude(2) returns (1 | 3).
3686
+ *
3687
+ * See: http://hl7.org/fhirpath/#excludeother-collection-collection
3688
+ */
3689
+ exclude: (input, other) => {
3690
+ if (!other) {
3691
+ return input;
3692
+ }
3693
+ const otherArray = other.eval([]);
3694
+ const result = [];
3695
+ for (const value of input) {
3696
+ if (!otherArray.some((e) => e.value === value.value)) {
3697
+ result.push(value);
3698
+ }
3699
+ }
3700
+ return result;
3701
+ },
3702
+ /*
3703
+ * 5.4. Combining
3704
+ *
3705
+ * See: https://hl7.org/fhirpath/#combining
3706
+ */
3707
+ /**
3708
+ * Merge the two collections into a single collection,
3709
+ * eliminating unknown duplicate values (using = (Equals) (=) to determine equality).
3710
+ * There is no expectation of order in the resulting collection.
3711
+ *
3712
+ * In other words, this function returns the distinct list of elements from both inputs.
3713
+ *
3714
+ * See: http://hl7.org/fhirpath/#unionother-collection
3715
+ */
3716
+ union: (input, other) => {
3717
+ if (!other) {
3718
+ return input;
3719
+ }
3720
+ const otherArray = other.eval([]);
3721
+ return removeDuplicates([...input, ...otherArray]);
3722
+ },
3723
+ /**
3724
+ * Merge the input and other collections into a single collection
3725
+ * without eliminating duplicate values. Combining an empty collection
3726
+ * with a non-empty collection will return the non-empty collection.
3727
+ *
3728
+ * There is no expectation of order in the resulting collection.
3729
+ *
3730
+ * See: http://hl7.org/fhirpath/#combineother-collection-collection
3731
+ */
3732
+ combine: (input, other) => {
3733
+ if (!other) {
3734
+ return input;
3735
+ }
3736
+ const otherArray = other.eval([]);
3737
+ return [...input, ...otherArray];
3738
+ },
3739
+ /*
3740
+ * 5.5. Conversion
3741
+ *
3742
+ * See: https://hl7.org/fhirpath/#conversion
3743
+ */
3744
+ /**
3745
+ * The iif function in FHIRPath is an immediate if,
3746
+ * also known as a conditional operator (such as C’s ? : operator).
3747
+ *
3748
+ * The criterion expression is expected to evaluate to a Boolean.
3749
+ *
3750
+ * If criterion is true, the function returns the value of the true-result argument.
3751
+ *
3752
+ * If criterion is false or an empty collection, the function returns otherwise-result,
3753
+ * unless the optional otherwise-result is not given, in which case the function returns an empty collection.
3754
+ *
3755
+ * Note that short-circuit behavior is expected in this function. In other words,
3756
+ * true-result should only be evaluated if the criterion evaluates to true,
3757
+ * and otherwise-result should only be evaluated otherwise. For implementations,
3758
+ * this means delaying evaluation of the arguments.
3759
+ *
3760
+ * @param input
3761
+ * @param criterion
3762
+ * @param trueResult
3763
+ * @param otherwiseResult
3764
+ * @returns
3765
+ */
3766
+ iif: (input, criterion, trueResult, otherwiseResult) => {
3767
+ const evalResult = criterion.eval(input);
3768
+ if (evalResult.length > 1 || (evalResult.length === 1 && typeof evalResult[0].value !== 'boolean')) {
3769
+ throw new Error('Expected criterion to evaluate to a Boolean');
3770
+ }
3771
+ if (toJsBoolean(evalResult)) {
3772
+ return trueResult.eval(input);
3773
+ }
3774
+ if (otherwiseResult) {
3775
+ return otherwiseResult.eval(input);
3666
3776
  }
3667
- }
3668
- return [];
3669
- }
3670
- /**
3671
- * If the input collection contains a single item, this function will return true if:
3672
- * 1) the item is a Boolean
3673
- * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
3674
- * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3675
- * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3676
- *
3677
- * 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.
3678
- *
3679
- * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
3680
- *
3681
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3682
- *
3683
- * If the input collection is empty, the result is empty.
3684
- *
3685
- * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
3686
- *
3687
- * @param input
3688
- * @returns
3689
- */
3690
- function convertsToBoolean(input) {
3691
- if (input.length === 0) {
3692
- return [];
3693
- }
3694
- return [toBoolean(input).length === 1];
3695
- }
3696
- /**
3697
- * Returns the integer representation of the input.
3698
- *
3699
- * If the input collection contains a single item, this function will return a single integer if:
3700
- * 1) the item is an Integer
3701
- * 2) the item is a String and is convertible to an integer
3702
- * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
3703
- *
3704
- * If the item is not one the above types, the result is empty.
3705
- *
3706
- * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
3707
- *
3708
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3709
- *
3710
- * If the input collection is empty, the result is empty.
3711
- *
3712
- * See: https://hl7.org/fhirpath/#tointeger-integer
3713
- *
3714
- * @param input The input collection.
3715
- * @returns The string representation of the input.
3716
- */
3717
- function toInteger(input) {
3718
- if (input.length === 0) {
3719
- return [];
3720
- }
3721
- const [value] = validateInput(input, 1);
3722
- if (typeof value === 'number') {
3723
- return [value];
3724
- }
3725
- if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
3726
- return [parseInt(value, 10)];
3727
- }
3728
- if (typeof value === 'boolean') {
3729
- return [value ? 1 : 0];
3730
- }
3731
- return [];
3732
- }
3733
- /**
3734
- * Returns true if the input can be converted to string.
3735
- *
3736
- * If the input collection contains a single item, this function will return true if:
3737
- * 1) the item is an Integer
3738
- * 2) the item is a String and is convertible to an Integer
3739
- * 3) the item is a Boolean
3740
- * 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.
3741
- *
3742
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3743
- *
3744
- * If the input collection is empty, the result is empty.
3745
- *
3746
- * See: https://hl7.org/fhirpath/#convertstointeger-boolean
3747
- *
3748
- * @param input The input collection.
3749
- * @returns
3750
- */
3751
- function convertsToInteger(input) {
3752
- if (input.length === 0) {
3753
- return [];
3754
- }
3755
- return [toInteger(input).length === 1];
3756
- }
3757
- /**
3758
- * If the input collection contains a single item, this function will return a single date if:
3759
- * 1) the item is a Date
3760
- * 2) the item is a DateTime
3761
- * 3) the item is a String and is convertible to a Date
3762
- *
3763
- * If the item is not one of the above types, the result is empty.
3764
- *
3765
- * 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.
3766
- *
3767
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3768
- *
3769
- * If the input collection is empty, the result is empty.
3770
- *
3771
- * See: https://hl7.org/fhirpath/#todate-date
3772
- */
3773
- function toDate(input) {
3774
- if (input.length === 0) {
3775
- return [];
3776
- }
3777
- const [value] = validateInput(input, 1);
3778
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3779
- return [parseDateString(value)];
3780
- }
3781
- return [];
3782
- }
3783
- /**
3784
- * If the input collection contains a single item, this function will return true if:
3785
- * 1) the item is a Date
3786
- * 2) the item is a DateTime
3787
- * 3) the item is a String and is convertible to a Date
3788
- *
3789
- * 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.
3790
- *
3791
- * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
3792
- *
3793
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3794
- *
3795
- * If the input collection is empty, the result is empty.
3796
- *
3797
- * See: https://hl7.org/fhirpath/#convertstodate-boolean
3798
- */
3799
- function convertsToDate(input) {
3800
- if (input.length === 0) {
3801
3777
  return [];
3802
- }
3803
- return [toDate(input).length === 1];
3804
- }
3805
- /**
3806
- * If the input collection contains a single item, this function will return a single datetime if:
3807
- * 1) the item is a DateTime
3808
- * 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)
3809
- * 3) the item is a String and is convertible to a DateTime
3810
- *
3811
- * If the item is not one of the above types, the result is empty.
3812
- *
3813
- * 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.
3814
- *
3815
- * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
3816
- *
3817
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3818
- *
3819
- * If the input collection is empty, the result is empty.
3820
-
3821
- * See: https://hl7.org/fhirpath/#todatetime-datetime
3822
- *
3823
- * @param input
3824
- * @returns
3825
- */
3826
- function toDateTime(input) {
3827
- if (input.length === 0) {
3778
+ },
3779
+ /**
3780
+ * Converts an input collection to a boolean.
3781
+ *
3782
+ * If the input collection contains a single item, this function will return a single boolean if:
3783
+ * 1) the item is a Boolean
3784
+ * 2) the item is an Integer and is equal to one of the possible integer representations of Boolean values
3785
+ * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3786
+ * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3787
+ *
3788
+ * 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.
3789
+ *
3790
+ * See: https://hl7.org/fhirpath/#toboolean-boolean
3791
+ *
3792
+ * @param input
3793
+ * @returns
3794
+ */
3795
+ toBoolean: (input) => {
3796
+ if (input.length === 0) {
3797
+ return [];
3798
+ }
3799
+ const [{ value }] = validateInput(input, 1);
3800
+ if (typeof value === 'boolean') {
3801
+ return [{ type: exports.PropertyType.boolean, value }];
3802
+ }
3803
+ if (typeof value === 'number') {
3804
+ if (value === 0 || value === 1) {
3805
+ return booleanToTypedValue(!!value);
3806
+ }
3807
+ }
3808
+ if (typeof value === 'string') {
3809
+ const lowerStr = value.toLowerCase();
3810
+ if (['true', 't', 'yes', 'y', '1', '1.0'].includes(lowerStr)) {
3811
+ return booleanToTypedValue(true);
3812
+ }
3813
+ if (['false', 'f', 'no', 'n', '0', '0.0'].includes(lowerStr)) {
3814
+ return booleanToTypedValue(false);
3815
+ }
3816
+ }
3828
3817
  return [];
3829
- }
3830
- const [value] = validateInput(input, 1);
3831
- if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3832
- return [parseDateString(value)];
3833
- }
3834
- return [];
3835
- }
3836
- /**
3837
- * If the input collection contains a single item, this function will return true if:
3838
- * 1) the item is a DateTime
3839
- * 2) the item is a Date
3840
- * 3) the item is a String and is convertible to a DateTime
3841
- *
3842
- * 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.
3843
- *
3844
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3845
- *
3846
- * If the input collection is empty, the result is empty.
3847
- *
3848
- * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
3849
- *
3850
- * @param input
3851
- * @returns
3852
- */
3853
- function convertsToDateTime(input) {
3854
- if (input.length === 0) {
3818
+ },
3819
+ /**
3820
+ * If the input collection contains a single item, this function will return true if:
3821
+ * 1) the item is a Boolean
3822
+ * 2) the item is an Integer that is equal to one of the possible integer representations of Boolean values
3823
+ * 3) the item is a Decimal that is equal to one of the possible decimal representations of Boolean values
3824
+ * 4) the item is a String that is equal to one of the possible string representations of Boolean values
3825
+ *
3826
+ * 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.
3827
+ *
3828
+ * Possible values for Integer, Decimal, and String are described in the toBoolean() function.
3829
+ *
3830
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3831
+ *
3832
+ * If the input collection is empty, the result is empty.
3833
+ *
3834
+ * See: http://hl7.org/fhirpath/#convertstoboolean-boolean
3835
+ *
3836
+ * @param input
3837
+ * @returns
3838
+ */
3839
+ convertsToBoolean: (input) => {
3840
+ if (input.length === 0) {
3841
+ return [];
3842
+ }
3843
+ return booleanToTypedValue(functions.toBoolean(input).length === 1);
3844
+ },
3845
+ /**
3846
+ * Returns the integer representation of the input.
3847
+ *
3848
+ * If the input collection contains a single item, this function will return a single integer if:
3849
+ * 1) the item is an Integer
3850
+ * 2) the item is a String and is convertible to an integer
3851
+ * 3) the item is a Boolean, where true results in a 1 and false results in a 0.
3852
+ *
3853
+ * If the item is not one the above types, the result is empty.
3854
+ *
3855
+ * If the item is a String, but the string is not convertible to an integer (using the regex format (\\+|-)?\d+), the result is empty.
3856
+ *
3857
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3858
+ *
3859
+ * If the input collection is empty, the result is empty.
3860
+ *
3861
+ * See: https://hl7.org/fhirpath/#tointeger-integer
3862
+ *
3863
+ * @param input The input collection.
3864
+ * @returns The string representation of the input.
3865
+ */
3866
+ toInteger: (input) => {
3867
+ if (input.length === 0) {
3868
+ return [];
3869
+ }
3870
+ const [{ value }] = validateInput(input, 1);
3871
+ if (typeof value === 'number') {
3872
+ return [{ type: exports.PropertyType.integer, value }];
3873
+ }
3874
+ if (typeof value === 'string' && value.match(/^[+-]?\d+$/)) {
3875
+ return [{ type: exports.PropertyType.integer, value: parseInt(value, 10) }];
3876
+ }
3877
+ if (typeof value === 'boolean') {
3878
+ return [{ type: exports.PropertyType.integer, value: value ? 1 : 0 }];
3879
+ }
3855
3880
  return [];
3856
- }
3857
- return [toDateTime(input).length === 1];
3858
- }
3859
- /**
3860
- * If the input collection contains a single item, this function will return a single decimal if:
3861
- * 1) the item is an Integer or Decimal
3862
- * 2) the item is a String and is convertible to a Decimal
3863
- * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
3864
- * 4) If the item is not one of the above types, the result is empty.
3865
- *
3866
- * 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.
3867
- *
3868
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3869
- *
3870
- * If the input collection is empty, the result is empty.
3871
- *
3872
- * See: https://hl7.org/fhirpath/#decimal-conversion-functions
3873
- *
3874
- * @param input The input collection.
3875
- * @returns
3876
- */
3877
- function toDecimal(input) {
3878
- if (input.length === 0) {
3881
+ },
3882
+ /**
3883
+ * Returns true if the input can be converted to string.
3884
+ *
3885
+ * If the input collection contains a single item, this function will return true if:
3886
+ * 1) the item is an Integer
3887
+ * 2) the item is a String and is convertible to an Integer
3888
+ * 3) the item is a Boolean
3889
+ * 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.
3890
+ *
3891
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3892
+ *
3893
+ * If the input collection is empty, the result is empty.
3894
+ *
3895
+ * See: https://hl7.org/fhirpath/#convertstointeger-boolean
3896
+ *
3897
+ * @param input The input collection.
3898
+ * @returns
3899
+ */
3900
+ convertsToInteger: (input) => {
3901
+ if (input.length === 0) {
3902
+ return [];
3903
+ }
3904
+ return booleanToTypedValue(functions.toInteger(input).length === 1);
3905
+ },
3906
+ /**
3907
+ * If the input collection contains a single item, this function will return a single date if:
3908
+ * 1) the item is a Date
3909
+ * 2) the item is a DateTime
3910
+ * 3) the item is a String and is convertible to a Date
3911
+ *
3912
+ * If the item is not one of the above types, the result is empty.
3913
+ *
3914
+ * 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.
3915
+ *
3916
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3917
+ *
3918
+ * If the input collection is empty, the result is empty.
3919
+ *
3920
+ * See: https://hl7.org/fhirpath/#todate-date
3921
+ */
3922
+ toDate: (input) => {
3923
+ if (input.length === 0) {
3924
+ return [];
3925
+ }
3926
+ const [{ value }] = validateInput(input, 1);
3927
+ if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3928
+ return [{ type: exports.PropertyType.date, value: parseDateString(value) }];
3929
+ }
3879
3930
  return [];
3880
- }
3881
- const [value] = validateInput(input, 1);
3882
- if (typeof value === 'number') {
3883
- return [value];
3884
- }
3885
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
3886
- return [parseFloat(value)];
3887
- }
3888
- if (typeof value === 'boolean') {
3889
- return [value ? 1 : 0];
3890
- }
3891
- return [];
3892
- }
3893
- /**
3894
- * If the input collection contains a single item, this function will true if:
3895
- * 1) the item is an Integer or Decimal
3896
- * 2) the item is a String and is convertible to a Decimal
3897
- * 3) the item is a Boolean
3898
- *
3899
- * 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.
3900
- *
3901
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3902
- *
3903
- * If the input collection is empty, the result is empty.
3904
-
3905
- * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
3906
- *
3907
- * @param input The input collection.
3908
- * @returns
3909
- */
3910
- function convertsToDecimal(input) {
3911
- if (input.length === 0) {
3912
- return [];
3913
- }
3914
- return [toDecimal(input).length === 1];
3915
- }
3916
- /**
3917
- * If the input collection contains a single item, this function will return a single quantity if:
3918
- * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
3919
- * 2) the item is a Quantity
3920
- * 3) the item is a String and is convertible to a Quantity
3921
- * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
3922
- *
3923
- * If the item is not one of the above types, the result is empty.
3924
- *
3925
- * See: https://hl7.org/fhirpath/#quantity-conversion-functions
3926
- *
3927
- * @param input The input collection.
3928
- * @returns
3929
- */
3930
- function toQuantity(input) {
3931
- if (input.length === 0) {
3932
- return [];
3933
- }
3934
- const [value] = validateInput(input, 1);
3935
- if (isQuantity(value)) {
3936
- return [value];
3937
- }
3938
- if (typeof value === 'number') {
3939
- return [{ value, unit: '1' }];
3940
- }
3941
- if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
3942
- return [{ value: parseFloat(value), unit: '1' }];
3943
- }
3944
- if (typeof value === 'boolean') {
3945
- return [{ value: value ? 1 : 0, unit: '1' }];
3946
- }
3947
- return [];
3948
- }
3949
- /**
3950
- * If the input collection contains a single item, this function will return true if:
3951
- * 1) the item is an Integer, Decimal, or Quantity
3952
- * 2) the item is a String that is convertible to a Quantity
3953
- * 3) the item is a Boolean
3954
- *
3955
- * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
3956
- *
3957
- * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
3958
- *
3959
- * then the result is false.
3960
- *
3961
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3962
- *
3963
- * If the input collection is empty, the result is empty.
3964
- *
3965
- * 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.
3966
- *
3967
- * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
3968
- *
3969
- * @param input The input collection.
3970
- * @returns
3971
- */
3972
- function convertsToQuantity(input) {
3973
- if (input.length === 0) {
3974
- return [];
3975
- }
3976
- return [toQuantity(input).length === 1];
3977
- }
3978
- /**
3979
- * Returns the string representation of the input.
3980
- *
3981
- * If the input collection contains a single item, this function will return a single String if:
3982
- *
3983
- * 1) the item in the input collection is a String
3984
- * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
3985
- * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
3986
- *
3987
- * If the item is not one of the above types, the result is false.
3988
- *
3989
- * See: https://hl7.org/fhirpath/#tostring-string
3990
- *
3991
- * @param input The input collection.
3992
- * @returns The string representation of the input.
3993
- */
3994
- function toString(input) {
3995
- if (input.length === 0) {
3996
- return [];
3997
- }
3998
- const [value] = validateInput(input, 1);
3999
- if (value === null || value === undefined) {
4000
- return [];
4001
- }
4002
- if (isQuantity(value)) {
4003
- return [`${value.value} '${value.unit}'`];
4004
- }
4005
- return [value.toString()];
4006
- }
4007
- /**
4008
- * Returns true if the input can be converted to string.
4009
- *
4010
- * If the input collection contains a single item, this function will return true if:
4011
- * 1) the item is a String
4012
- * 2) the item is an Integer, Decimal, Date, Time, or DateTime
4013
- * 3) the item is a Boolean
4014
- * 4) the item is a Quantity
4015
- *
4016
- * If the item is not one of the above types, the result is false.
4017
- *
4018
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4019
- *
4020
- * If the input collection is empty, the result is empty.
4021
- *
4022
- * See: https://hl7.org/fhirpath/#tostring-string
4023
- *
4024
- * @param input The input collection.
4025
- * @returns
4026
- */
4027
- function convertsToString(input) {
4028
- if (input.length === 0) {
3931
+ },
3932
+ /**
3933
+ * If the input collection contains a single item, this function will return true if:
3934
+ * 1) the item is a Date
3935
+ * 2) the item is a DateTime
3936
+ * 3) the item is a String and is convertible to a Date
3937
+ *
3938
+ * 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.
3939
+ *
3940
+ * If the item contains a partial date (e.g. '2012-01'), the result is a partial date.
3941
+ *
3942
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3943
+ *
3944
+ * If the input collection is empty, the result is empty.
3945
+ *
3946
+ * See: https://hl7.org/fhirpath/#convertstodate-boolean
3947
+ */
3948
+ convertsToDate: (input) => {
3949
+ if (input.length === 0) {
3950
+ return [];
3951
+ }
3952
+ return booleanToTypedValue(functions.toDate(input).length === 1);
3953
+ },
3954
+ /**
3955
+ * If the input collection contains a single item, this function will return a single datetime if:
3956
+ * 1) the item is a DateTime
3957
+ * 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)
3958
+ * 3) the item is a String and is convertible to a DateTime
3959
+ *
3960
+ * If the item is not one of the above types, the result is empty.
3961
+ *
3962
+ * 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.
3963
+ *
3964
+ * If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime.
3965
+ *
3966
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3967
+ *
3968
+ * If the input collection is empty, the result is empty.
3969
+
3970
+ * See: https://hl7.org/fhirpath/#todatetime-datetime
3971
+ *
3972
+ * @param input
3973
+ * @returns
3974
+ */
3975
+ toDateTime: (input) => {
3976
+ if (input.length === 0) {
3977
+ return [];
3978
+ }
3979
+ const [{ value }] = validateInput(input, 1);
3980
+ if (typeof value === 'string' && value.match(/^\d{4}(-\d{2}(-\d{2})?)?/)) {
3981
+ return [{ type: exports.PropertyType.dateTime, value: parseDateString(value) }];
3982
+ }
4029
3983
  return [];
4030
- }
4031
- return [toString(input).length === 1];
4032
- }
4033
- /**
4034
- * If the input collection contains a single item, this function will return a single time if:
4035
- * 1) the item is a Time
4036
- * 2) the item is a String and is convertible to a Time
4037
- *
4038
- * If the item is not one of the above types, the result is empty.
4039
- *
4040
- * 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.
4041
- *
4042
- * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
4043
- *
4044
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4045
- *
4046
- * If the input collection is empty, the result is empty.
4047
- *
4048
- * See: https://hl7.org/fhirpath/#totime-time
4049
- *
4050
- * @param input
4051
- * @returns
4052
- */
4053
- function toTime(input) {
4054
- if (input.length === 0) {
3984
+ },
3985
+ /**
3986
+ * If the input collection contains a single item, this function will return true if:
3987
+ * 1) the item is a DateTime
3988
+ * 2) the item is a Date
3989
+ * 3) the item is a String and is convertible to a DateTime
3990
+ *
3991
+ * 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.
3992
+ *
3993
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
3994
+ *
3995
+ * If the input collection is empty, the result is empty.
3996
+ *
3997
+ * See: https://hl7.org/fhirpath/#convertstodatetime-boolean
3998
+ *
3999
+ * @param input
4000
+ * @returns
4001
+ */
4002
+ convertsToDateTime: (input) => {
4003
+ if (input.length === 0) {
4004
+ return [];
4005
+ }
4006
+ return booleanToTypedValue(functions.toDateTime(input).length === 1);
4007
+ },
4008
+ /**
4009
+ * If the input collection contains a single item, this function will return a single decimal if:
4010
+ * 1) the item is an Integer or Decimal
4011
+ * 2) the item is a String and is convertible to a Decimal
4012
+ * 3) the item is a Boolean, where true results in a 1.0 and false results in a 0.0.
4013
+ * 4) If the item is not one of the above types, the result is empty.
4014
+ *
4015
+ * 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.
4016
+ *
4017
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4018
+ *
4019
+ * If the input collection is empty, the result is empty.
4020
+ *
4021
+ * See: https://hl7.org/fhirpath/#decimal-conversion-functions
4022
+ *
4023
+ * @param input The input collection.
4024
+ * @returns
4025
+ */
4026
+ toDecimal: (input) => {
4027
+ if (input.length === 0) {
4028
+ return [];
4029
+ }
4030
+ const [{ value }] = validateInput(input, 1);
4031
+ if (typeof value === 'number') {
4032
+ return [{ type: exports.PropertyType.decimal, value }];
4033
+ }
4034
+ if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?$/)) {
4035
+ return [{ type: exports.PropertyType.decimal, value: parseFloat(value) }];
4036
+ }
4037
+ if (typeof value === 'boolean') {
4038
+ return [{ type: exports.PropertyType.decimal, value: value ? 1 : 0 }];
4039
+ }
4055
4040
  return [];
4056
- }
4057
- const [value] = validateInput(input, 1);
4058
- if (typeof value === 'string') {
4059
- const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
4060
- if (match) {
4061
- return [parseDateString('T' + match[1])];
4041
+ },
4042
+ /**
4043
+ * If the input collection contains a single item, this function will true if:
4044
+ * 1) the item is an Integer or Decimal
4045
+ * 2) the item is a String and is convertible to a Decimal
4046
+ * 3) the item is a Boolean
4047
+ *
4048
+ * 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.
4049
+ *
4050
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4051
+ *
4052
+ * If the input collection is empty, the result is empty.
4053
+
4054
+ * See: https://hl7.org/fhirpath/#convertstodecimal-boolean
4055
+ *
4056
+ * @param input The input collection.
4057
+ * @returns
4058
+ */
4059
+ convertsToDecimal: (input) => {
4060
+ if (input.length === 0) {
4061
+ return [];
4062
+ }
4063
+ return booleanToTypedValue(functions.toDecimal(input).length === 1);
4064
+ },
4065
+ /**
4066
+ * If the input collection contains a single item, this function will return a single quantity if:
4067
+ * 1) the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1')
4068
+ * 2) the item is a Quantity
4069
+ * 3) the item is a String and is convertible to a Quantity
4070
+ * 4) the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1'
4071
+ *
4072
+ * If the item is not one of the above types, the result is empty.
4073
+ *
4074
+ * See: https://hl7.org/fhirpath/#quantity-conversion-functions
4075
+ *
4076
+ * @param input The input collection.
4077
+ * @returns
4078
+ */
4079
+ toQuantity: (input) => {
4080
+ if (input.length === 0) {
4081
+ return [];
4082
+ }
4083
+ const [{ value }] = validateInput(input, 1);
4084
+ if (isQuantity(value)) {
4085
+ return [{ type: exports.PropertyType.Quantity, value }];
4086
+ }
4087
+ if (typeof value === 'number') {
4088
+ return [{ type: exports.PropertyType.Quantity, value: { value, unit: '1' } }];
4089
+ }
4090
+ if (typeof value === 'string' && value.match(/^-?\d{1,9}(\.\d{1,9})?/)) {
4091
+ return [{ type: exports.PropertyType.Quantity, value: { value: parseFloat(value), unit: '1' } }];
4092
+ }
4093
+ if (typeof value === 'boolean') {
4094
+ return [{ type: exports.PropertyType.Quantity, value: { value: value ? 1 : 0, unit: '1' } }];
4062
4095
  }
4063
- }
4064
- return [];
4065
- }
4066
- /**
4067
- * If the input collection contains a single item, this function will return true if:
4068
- * 1) the item is a Time
4069
- * 2) the item is a String and is convertible to a Time
4070
- *
4071
- * 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.
4072
- *
4073
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4074
- *
4075
- * If the input collection is empty, the result is empty.
4076
- *
4077
- * See: https://hl7.org/fhirpath/#convertstotime-boolean
4078
- *
4079
- * @param input
4080
- * @returns
4081
- */
4082
- function convertsToTime(input) {
4083
- if (input.length === 0) {
4084
4096
  return [];
4085
- }
4086
- return [toTime(input).length === 1];
4087
- }
4088
- /*
4089
- * 5.6. String Manipulation.
4090
- *
4091
- * See: https://hl7.org/fhirpath/#string-manipulation
4092
- */
4093
- /**
4094
- * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
4095
- *
4096
- * If substring is an empty string (''), the function returns 0.
4097
- *
4098
- * If the input or substring is empty ({ }), the result is empty ({ }).
4099
- *
4100
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4101
- *
4102
- * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
4103
- *
4104
- * @param input The input collection.
4105
- * @returns The index of the substring.
4106
- */
4107
- function indexOf(input, substringAtom) {
4108
- return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
4109
- }
4110
- /**
4111
- * 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.
4112
- *
4113
- * 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.
4114
- *
4115
- * If the input or start is empty, the result is empty.
4116
- *
4117
- * If an empty length is provided, the behavior is the same as if length had not been provided.
4118
- *
4119
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4120
- *
4121
- * @param input The input collection.
4122
- * @returns The index of the substring.
4123
- */
4124
- function substring(input, startAtom, lengthAtom) {
4125
- return applyStringFunc((str, start, length) => {
4126
- const startIndex = start;
4127
- const endIndex = length ? startIndex + length : str.length;
4128
- return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
4129
- }, input, startAtom, lengthAtom);
4130
- }
4131
- /**
4132
- *
4133
- * @param input The input collection.
4134
- * @returns The index of the substring.
4135
- */
4136
- function startsWith(input, prefixAtom) {
4137
- return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
4138
- }
4139
- /**
4140
- *
4141
- * @param input The input collection.
4142
- * @returns The index of the substring.
4143
- */
4144
- function endsWith(input, suffixAtom) {
4145
- return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
4146
- }
4147
- /**
4148
- *
4149
- * @param input The input collection.
4150
- * @returns The index of the substring.
4151
- */
4152
- function contains(input, substringAtom) {
4153
- return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
4154
- }
4155
- /**
4156
- *
4157
- * @param input The input collection.
4158
- * @returns The index of the substring.
4159
- */
4160
- function upper(input) {
4161
- return applyStringFunc((str) => str.toUpperCase(), input);
4162
- }
4163
- /**
4164
- *
4165
- * @param input The input collection.
4166
- * @returns The index of the substring.
4167
- */
4168
- function lower(input) {
4169
- return applyStringFunc((str) => str.toLowerCase(), input);
4170
- }
4171
- /**
4172
- *
4173
- * @param input The input collection.
4174
- * @returns The index of the substring.
4175
- */
4176
- function replace(input, patternAtom, substitionAtom) {
4177
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
4178
- }
4179
- /**
4180
- *
4181
- * @param input The input collection.
4182
- * @returns The index of the substring.
4183
- */
4184
- function matches(input, regexAtom) {
4185
- return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
4186
- }
4187
- /**
4188
- *
4189
- * @param input The input collection.
4190
- * @returns The index of the substring.
4191
- */
4192
- function replaceMatches(input, regexAtom, substitionAtom) {
4193
- return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
4194
- }
4195
- /**
4196
- *
4197
- * @param input The input collection.
4198
- * @returns The index of the substring.
4199
- */
4200
- function length(input) {
4201
- return applyStringFunc((str) => str.length, input);
4202
- }
4203
- /**
4204
- * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
4205
- *
4206
- * See: https://hl7.org/fhirpath/#tochars-collection
4207
- *
4208
- * @param input The input collection.
4209
- */
4210
- function toChars(input) {
4211
- return applyStringFunc((str) => (str ? str.split('') : undefined), input);
4212
- }
4213
- /*
4214
- * 5.7. Math
4215
- */
4216
- /**
4217
- * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
4218
- *
4219
- * If the input collection is empty, the result is empty.
4220
- *
4221
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4222
- *
4223
- * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
4224
- *
4225
- * @param input The input collection.
4226
- * @returns A collection containing the result.
4227
- */
4228
- function abs(input) {
4229
- return applyMathFunc(Math.abs, input);
4230
- }
4231
- /**
4232
- * Returns the first integer greater than or equal to the input.
4233
- *
4234
- * If the input collection is empty, the result is empty.
4235
- *
4236
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4237
- *
4238
- * See: https://hl7.org/fhirpath/#ceiling-integer
4239
- *
4240
- * @param input The input collection.
4241
- * @returns A collection containing the result.
4242
- */
4243
- function ceiling(input) {
4244
- return applyMathFunc(Math.ceil, input);
4245
- }
4246
- /**
4247
- * Returns e raised to the power of the input.
4248
- *
4249
- * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
4250
- *
4251
- * If the input collection is empty, the result is empty.
4252
- *
4253
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4254
- *
4255
- * See: https://hl7.org/fhirpath/#exp-decimal
4256
- *
4257
- * @param input The input collection.
4258
- * @returns A collection containing the result.
4259
- */
4260
- function exp(input) {
4261
- return applyMathFunc(Math.exp, input);
4262
- }
4263
- /**
4264
- * Returns the first integer less than or equal to the input.
4265
- *
4266
- * If the input collection is empty, the result is empty.
4267
- *
4268
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4269
- *
4270
- * See: https://hl7.org/fhirpath/#floor-integer
4271
- *
4272
- * @param input The input collection.
4273
- * @returns A collection containing the result.
4274
- */
4275
- function floor(input) {
4276
- return applyMathFunc(Math.floor, input);
4277
- }
4278
- /**
4279
- * Returns the natural logarithm of the input (i.e. the logarithm base e).
4280
- *
4281
- * When used with an Integer, it will be implicitly converted to a Decimal.
4282
- *
4283
- * If the input collection is empty, the result is empty.
4284
- *
4285
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4286
- *
4287
- * See: https://hl7.org/fhirpath/#ln-decimal
4288
- *
4289
- * @param input The input collection.
4290
- * @returns A collection containing the result.
4291
- */
4292
- function ln(input) {
4293
- return applyMathFunc(Math.log, input);
4294
- }
4295
- /**
4296
- * Returns the logarithm base base of the input number.
4297
- *
4298
- * When used with Integers, the arguments will be implicitly converted to Decimal.
4299
- *
4300
- * If base is empty, the result is empty.
4301
- *
4302
- * If the input collection is empty, the result is empty.
4303
- *
4304
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4305
- *
4306
- * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
4307
- *
4308
- * @param input The input collection.
4309
- * @returns A collection containing the result.
4310
- */
4311
- function log(input, baseAtom) {
4312
- return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
4313
- }
4314
- /**
4315
- * 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.
4316
- *
4317
- * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
4318
- *
4319
- * If the input is empty, or exponent is empty, the result is empty.
4320
- *
4321
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4322
- *
4323
- * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
4324
- *
4325
- * @param input The input collection.
4326
- * @returns A collection containing the result.
4327
- */
4328
- function power(input, expAtom) {
4329
- return applyMathFunc(Math.pow, input, expAtom);
4330
- }
4331
- /**
4332
- * 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.
4333
- *
4334
- * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
4335
- *
4336
- * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
4337
- *
4338
- * If the input collection is empty, the result is empty.
4339
- *
4340
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4341
- *
4342
- * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
4343
- *
4344
- * @param input The input collection.
4345
- * @returns A collection containing the result.
4346
- */
4347
- function round(input) {
4348
- return applyMathFunc(Math.round, input);
4349
- }
4350
- /**
4351
- * Returns the square root of the input number as a Decimal.
4352
- *
4353
- * If the square root cannot be represented (such as the square root of -1), the result is empty.
4354
- *
4355
- * If the input collection is empty, the result is empty.
4356
- *
4357
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4358
- *
4359
- * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
4360
- *
4361
- * See: https://hl7.org/fhirpath/#sqrt-decimal
4362
- *
4363
- * @param input The input collection.
4364
- * @returns A collection containing the result.
4365
- */
4366
- function sqrt(input) {
4367
- return applyMathFunc(Math.sqrt, input);
4368
- }
4369
- /**
4370
- * Returns the integer portion of the input.
4371
- *
4372
- * If the input collection is empty, the result is empty.
4373
- *
4374
- * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4375
- *
4376
- * See: https://hl7.org/fhirpath/#truncate-integer
4377
- *
4378
- * @param input The input collection.
4379
- * @returns A collection containing the result.
4380
- */
4381
- function truncate(input) {
4382
- return applyMathFunc((x) => x | 0, input);
4383
- }
4384
- /*
4385
- * 5.8. Tree navigation
4386
- */
4387
- const children = stub;
4388
- const descendants = stub;
4389
- /*
4390
- * 5.9. Utility functions
4391
- */
4392
- /**
4393
- * Adds a String representation of the input collection to the diagnostic log,
4394
- * using the name argument as the name in the log. This log should be made available
4395
- * to the user in some appropriate fashion. Does not change the input, so returns
4396
- * the input collection as output.
4397
- *
4398
- * If the projection argument is used, the trace would log the result of evaluating
4399
- * the project expression on the input, but still return the input to the trace
4400
- * function unchanged.
4401
- *
4402
- * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
4403
- *
4404
- * @param input The input collection.
4405
- * @param nameAtom The log name.
4406
- */
4407
- function trace(input, nameAtom) {
4408
- console.log('trace', input, nameAtom);
4409
- return input;
4410
- }
4411
- /**
4412
- * Returns the current date and time, including timezone offset.
4413
- *
4414
- * See: https://hl7.org/fhirpath/#now-datetime
4415
- */
4416
- function now() {
4417
- return [new Date().toISOString()];
4418
- }
4419
- /**
4420
- * Returns the current time.
4421
- *
4422
- * See: https://hl7.org/fhirpath/#timeofday-time
4423
- */
4424
- function timeOfDay() {
4425
- return [new Date().toISOString().substring(11)];
4426
- }
4427
- /**
4428
- * Returns the current date.
4429
- *
4430
- * See: https://hl7.org/fhirpath/#today-date
4431
- */
4432
- function today() {
4433
- return [new Date().toISOString().substring(0, 10)];
4434
- }
4435
- /**
4436
- * Calculates the difference between two dates or date/times.
4437
- *
4438
- * This is not part of the official FHIRPath spec.
4439
- *
4440
- * IBM FHIR issue: https://github.com/IBM/FHIR/issues/1014
4441
- * IBM FHIR PR: https://github.com/IBM/FHIR/pull/1023
4442
- */
4443
- function between(context, startAtom, endAtom, unitsAtom) {
4444
- const startDate = toDateTime(ensureArray(startAtom.eval(context)));
4445
- if (startDate.length === 0) {
4446
- throw new Error('Invalid start date');
4447
- }
4448
- const endDate = toDateTime(ensureArray(endAtom.eval(context)));
4449
- if (endDate.length === 0) {
4450
- throw new Error('Invalid end date');
4451
- }
4452
- const unit = unitsAtom.eval(context);
4453
- if (unit !== 'years' && unit !== 'months' && unit !== 'days') {
4454
- throw new Error('Invalid units');
4455
- }
4456
- const age = calculateAge(startDate[0], endDate[0]);
4457
- return [{ value: age[unit], unit }];
4458
- }
4459
- /*
4460
- * 6.3 Types
4461
- */
4462
- /**
4463
- * The is() function is supported for backwards compatibility with previous
4464
- * implementations of FHIRPath. Just as with the is keyword, the type argument
4465
- * is an identifier that must resolve to the name of a type in a model.
4466
- *
4467
- * For implementations with compile-time typing, this requires special-case
4468
- * handling when processing the argument to treat it as a type specifier rather
4469
- * than an identifier expression:
4470
- *
4471
- * @param input
4472
- * @param typeAtom
4473
- * @returns
4474
- */
4475
- function is(input, typeAtom) {
4476
- const typeName = typeAtom.name;
4477
- return input.map((value) => fhirPathIs(value, typeName));
4478
- }
4479
- /*
4480
- * 6.5 Boolean logic
4481
- */
4482
- /**
4483
- * 6.5.3. not() : Boolean
4484
- *
4485
- * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
4486
- *
4487
- * @param input
4488
- * @returns
4489
- */
4490
- function not(input) {
4491
- return toBoolean(input).map((value) => !value);
4492
- }
4493
- /*
4494
- * Additional functions
4495
- * See: https://hl7.org/fhir/fhirpath.html#functions
4496
- */
4497
- /**
4498
- * 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.
4499
- * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
4500
- * @param input The input collection.
4501
- * @returns
4502
- */
4503
- function resolve(input) {
4504
- return input
4505
- .map((e) => {
4506
- let refStr;
4507
- if (typeof e === 'string') {
4508
- refStr = e;
4509
- }
4510
- else if (typeof e === 'object') {
4511
- const ref = e;
4512
- if (ref.resource) {
4513
- return ref.resource;
4097
+ },
4098
+ /**
4099
+ * If the input collection contains a single item, this function will return true if:
4100
+ * 1) the item is an Integer, Decimal, or Quantity
4101
+ * 2) the item is a String that is convertible to a Quantity
4102
+ * 3) the item is a Boolean
4103
+ *
4104
+ * If the item is not one of the above types, or is not convertible to a Quantity using the following regex format:
4105
+ *
4106
+ * (?'value'(\+|-)?\d+(\.\d+)?)\s*('(?'unit'[^']+)'|(?'time'[a-zA-Z]+))?
4107
+ *
4108
+ * then the result is false.
4109
+ *
4110
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4111
+ *
4112
+ * If the input collection is empty, the result is empty.
4113
+ *
4114
+ * 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.
4115
+ *
4116
+ * See: https://hl7.org/fhirpath/#convertstoquantityunit-string-boolean
4117
+ *
4118
+ * @param input The input collection.
4119
+ * @returns
4120
+ */
4121
+ convertsToQuantity: (input) => {
4122
+ if (input.length === 0) {
4123
+ return [];
4124
+ }
4125
+ return booleanToTypedValue(functions.toQuantity(input).length === 1);
4126
+ },
4127
+ /**
4128
+ * Returns the string representation of the input.
4129
+ *
4130
+ * If the input collection contains a single item, this function will return a single String if:
4131
+ *
4132
+ * 1) the item in the input collection is a String
4133
+ * 2) the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation
4134
+ * 3) the item is a Boolean, where true results in 'true' and false in 'false'.
4135
+ *
4136
+ * If the item is not one of the above types, the result is false.
4137
+ *
4138
+ * See: https://hl7.org/fhirpath/#tostring-string
4139
+ *
4140
+ * @param input The input collection.
4141
+ * @returns The string representation of the input.
4142
+ */
4143
+ toString: (input) => {
4144
+ if (input.length === 0) {
4145
+ return [];
4146
+ }
4147
+ const [{ value }] = validateInput(input, 1);
4148
+ if (value === null || value === undefined) {
4149
+ return [];
4150
+ }
4151
+ if (isQuantity(value)) {
4152
+ return [{ type: exports.PropertyType.string, value: `${value.value} '${value.unit}'` }];
4153
+ }
4154
+ return [{ type: exports.PropertyType.string, value: value.toString() }];
4155
+ },
4156
+ /**
4157
+ * Returns true if the input can be converted to string.
4158
+ *
4159
+ * If the input collection contains a single item, this function will return true if:
4160
+ * 1) the item is a String
4161
+ * 2) the item is an Integer, Decimal, Date, Time, or DateTime
4162
+ * 3) the item is a Boolean
4163
+ * 4) the item is a Quantity
4164
+ *
4165
+ * If the item is not one of the above types, the result is false.
4166
+ *
4167
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4168
+ *
4169
+ * If the input collection is empty, the result is empty.
4170
+ *
4171
+ * See: https://hl7.org/fhirpath/#tostring-string
4172
+ *
4173
+ * @param input The input collection.
4174
+ * @returns
4175
+ */
4176
+ convertsToString: (input) => {
4177
+ if (input.length === 0) {
4178
+ return [];
4179
+ }
4180
+ return booleanToTypedValue(functions.toString(input).length === 1);
4181
+ },
4182
+ /**
4183
+ * If the input collection contains a single item, this function will return a single time if:
4184
+ * 1) the item is a Time
4185
+ * 2) the item is a String and is convertible to a Time
4186
+ *
4187
+ * If the item is not one of the above types, the result is empty.
4188
+ *
4189
+ * 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.
4190
+ *
4191
+ * If the item contains a partial time (e.g. '10:00'), the result is a partial time.
4192
+ *
4193
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4194
+ *
4195
+ * If the input collection is empty, the result is empty.
4196
+ *
4197
+ * See: https://hl7.org/fhirpath/#totime-time
4198
+ *
4199
+ * @param input
4200
+ * @returns
4201
+ */
4202
+ toTime: (input) => {
4203
+ if (input.length === 0) {
4204
+ return [];
4205
+ }
4206
+ const [{ value }] = validateInput(input, 1);
4207
+ if (typeof value === 'string') {
4208
+ const match = value.match(/^T?(\d{2}(:\d{2}(:\d{2})?)?)/);
4209
+ if (match) {
4210
+ return [{ type: exports.PropertyType.time, value: parseDateString('T' + match[1]) }];
4514
4211
  }
4515
- refStr = ref.reference;
4516
4212
  }
4517
- if (!refStr) {
4518
- return undefined;
4213
+ return [];
4214
+ },
4215
+ /**
4216
+ * If the input collection contains a single item, this function will return true if:
4217
+ * 1) the item is a Time
4218
+ * 2) the item is a String and is convertible to a Time
4219
+ *
4220
+ * 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.
4221
+ *
4222
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4223
+ *
4224
+ * If the input collection is empty, the result is empty.
4225
+ *
4226
+ * See: https://hl7.org/fhirpath/#convertstotime-boolean
4227
+ *
4228
+ * @param input
4229
+ * @returns
4230
+ */
4231
+ convertsToTime: (input) => {
4232
+ if (input.length === 0) {
4233
+ return [];
4519
4234
  }
4520
- const [resourceType, id] = refStr.split('/');
4521
- return { resourceType, id };
4522
- })
4523
- .filter((e) => !!e);
4524
- }
4525
- /**
4526
- * The as operator can be used to treat a value as a specific type.
4527
- * @param context The context value.
4528
- * @returns The value as the specific type.
4529
- */
4530
- function as(context) {
4531
- return context;
4532
- }
4533
- /*
4534
- * 12. Formal Specifications
4535
- */
4536
- /**
4537
- * Returns the type of the input.
4538
- *
4539
- * 12.2. Model Information
4540
- *
4541
- * The model information returned by the reflection function type() is specified as an
4542
- * XML Schema document (xsd) and included in this specification at the following link:
4543
- * https://hl7.org/fhirpath/modelinfo.xsd
4544
- *
4545
- * See: https://hl7.org/fhirpath/#model-information
4546
- *
4547
- * @param input The input collection.
4548
- * @returns
4549
- */
4550
- function type(input) {
4551
- return input.map((value) => {
4552
- if (typeof value === 'boolean') {
4553
- return { namespace: 'System', name: 'Boolean' };
4235
+ return booleanToTypedValue(functions.toTime(input).length === 1);
4236
+ },
4237
+ /*
4238
+ * 5.6. String Manipulation.
4239
+ *
4240
+ * See: https://hl7.org/fhirpath/#string-manipulation
4241
+ */
4242
+ /**
4243
+ * Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found.
4244
+ *
4245
+ * If substring is an empty string (''), the function returns 0.
4246
+ *
4247
+ * If the input or substring is empty ({ }), the result is empty ({ }).
4248
+ *
4249
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4250
+ *
4251
+ * See: https://hl7.org/fhirpath/#indexofsubstring-string-integer
4252
+ *
4253
+ * @param input The input collection.
4254
+ * @returns The index of the substring.
4255
+ */
4256
+ indexOf: (input, substringAtom) => {
4257
+ return applyStringFunc((str, substring) => str.indexOf(substring), input, substringAtom);
4258
+ },
4259
+ /**
4260
+ * 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.
4261
+ *
4262
+ * 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.
4263
+ *
4264
+ * If the input or start is empty, the result is empty.
4265
+ *
4266
+ * If an empty length is provided, the behavior is the same as if length had not been provided.
4267
+ *
4268
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4269
+ *
4270
+ * @param input The input collection.
4271
+ * @returns The index of the substring.
4272
+ */
4273
+ substring: (input, startAtom, lengthAtom) => {
4274
+ return applyStringFunc((str, start, length) => {
4275
+ const startIndex = start;
4276
+ const endIndex = length ? startIndex + length : str.length;
4277
+ return startIndex < 0 || startIndex >= str.length ? undefined : str.substring(startIndex, endIndex);
4278
+ }, input, startAtom, lengthAtom);
4279
+ },
4280
+ /**
4281
+ *
4282
+ * @param input The input collection.
4283
+ * @returns The index of the substring.
4284
+ */
4285
+ startsWith: (input, prefixAtom) => {
4286
+ return applyStringFunc((str, prefix) => str.startsWith(prefix), input, prefixAtom);
4287
+ },
4288
+ /**
4289
+ *
4290
+ * @param input The input collection.
4291
+ * @returns The index of the substring.
4292
+ */
4293
+ endsWith: (input, suffixAtom) => {
4294
+ return applyStringFunc((str, suffix) => str.endsWith(suffix), input, suffixAtom);
4295
+ },
4296
+ /**
4297
+ *
4298
+ * @param input The input collection.
4299
+ * @returns The index of the substring.
4300
+ */
4301
+ contains: (input, substringAtom) => {
4302
+ return applyStringFunc((str, substring) => str.includes(substring), input, substringAtom);
4303
+ },
4304
+ /**
4305
+ *
4306
+ * @param input The input collection.
4307
+ * @returns The index of the substring.
4308
+ */
4309
+ upper: (input) => {
4310
+ return applyStringFunc((str) => str.toUpperCase(), input);
4311
+ },
4312
+ /**
4313
+ *
4314
+ * @param input The input collection.
4315
+ * @returns The index of the substring.
4316
+ */
4317
+ lower: (input) => {
4318
+ return applyStringFunc((str) => str.toLowerCase(), input);
4319
+ },
4320
+ /**
4321
+ *
4322
+ * @param input The input collection.
4323
+ * @returns The index of the substring.
4324
+ */
4325
+ replace: (input, patternAtom, substitionAtom) => {
4326
+ return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, patternAtom, substitionAtom);
4327
+ },
4328
+ /**
4329
+ *
4330
+ * @param input The input collection.
4331
+ * @returns The index of the substring.
4332
+ */
4333
+ matches: (input, regexAtom) => {
4334
+ return applyStringFunc((str, regex) => !!str.match(regex), input, regexAtom);
4335
+ },
4336
+ /**
4337
+ *
4338
+ * @param input The input collection.
4339
+ * @returns The index of the substring.
4340
+ */
4341
+ replaceMatches: (input, regexAtom, substitionAtom) => {
4342
+ return applyStringFunc((str, pattern, substition) => str.replaceAll(pattern, substition), input, regexAtom, substitionAtom);
4343
+ },
4344
+ /**
4345
+ *
4346
+ * @param input The input collection.
4347
+ * @returns The index of the substring.
4348
+ */
4349
+ length: (input) => {
4350
+ return applyStringFunc((str) => str.length, input);
4351
+ },
4352
+ /**
4353
+ * Returns the list of characters in the input string. If the input collection is empty ({ }), the result is empty.
4354
+ *
4355
+ * See: https://hl7.org/fhirpath/#tochars-collection
4356
+ *
4357
+ * @param input The input collection.
4358
+ */
4359
+ toChars: (input) => {
4360
+ return applyStringFunc((str) => (str ? str.split('') : undefined), input);
4361
+ },
4362
+ /*
4363
+ * 5.7. Math
4364
+ */
4365
+ /**
4366
+ * Returns the absolute value of the input. When taking the absolute value of a quantity, the unit is unchanged.
4367
+ *
4368
+ * If the input collection is empty, the result is empty.
4369
+ *
4370
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4371
+ *
4372
+ * See: https://hl7.org/fhirpath/#abs-integer-decimal-quantity
4373
+ *
4374
+ * @param input The input collection.
4375
+ * @returns A collection containing the result.
4376
+ */
4377
+ abs: (input) => {
4378
+ return applyMathFunc(Math.abs, input);
4379
+ },
4380
+ /**
4381
+ * Returns the first integer greater than or equal to the input.
4382
+ *
4383
+ * If the input collection is empty, the result is empty.
4384
+ *
4385
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4386
+ *
4387
+ * See: https://hl7.org/fhirpath/#ceiling-integer
4388
+ *
4389
+ * @param input The input collection.
4390
+ * @returns A collection containing the result.
4391
+ */
4392
+ ceiling: (input) => {
4393
+ return applyMathFunc(Math.ceil, input);
4394
+ },
4395
+ /**
4396
+ * Returns e raised to the power of the input.
4397
+ *
4398
+ * If the input collection contains an Integer, it will be implicitly converted to a Decimal and the result will be a Decimal.
4399
+ *
4400
+ * If the input collection is empty, the result is empty.
4401
+ *
4402
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4403
+ *
4404
+ * See: https://hl7.org/fhirpath/#exp-decimal
4405
+ *
4406
+ * @param input The input collection.
4407
+ * @returns A collection containing the result.
4408
+ */
4409
+ exp: (input) => {
4410
+ return applyMathFunc(Math.exp, input);
4411
+ },
4412
+ /**
4413
+ * Returns the first integer less than or equal to the input.
4414
+ *
4415
+ * If the input collection is empty, the result is empty.
4416
+ *
4417
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4418
+ *
4419
+ * See: https://hl7.org/fhirpath/#floor-integer
4420
+ *
4421
+ * @param input The input collection.
4422
+ * @returns A collection containing the result.
4423
+ */
4424
+ floor: (input) => {
4425
+ return applyMathFunc(Math.floor, input);
4426
+ },
4427
+ /**
4428
+ * Returns the natural logarithm of the input (i.e. the logarithm base e).
4429
+ *
4430
+ * When used with an Integer, it will be implicitly converted to a Decimal.
4431
+ *
4432
+ * If the input collection is empty, the result is empty.
4433
+ *
4434
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4435
+ *
4436
+ * See: https://hl7.org/fhirpath/#ln-decimal
4437
+ *
4438
+ * @param input The input collection.
4439
+ * @returns A collection containing the result.
4440
+ */
4441
+ ln: (input) => {
4442
+ return applyMathFunc(Math.log, input);
4443
+ },
4444
+ /**
4445
+ * Returns the logarithm base base of the input number.
4446
+ *
4447
+ * When used with Integers, the arguments will be implicitly converted to Decimal.
4448
+ *
4449
+ * If base is empty, the result is empty.
4450
+ *
4451
+ * If the input collection is empty, the result is empty.
4452
+ *
4453
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4454
+ *
4455
+ * See: https://hl7.org/fhirpath/#logbase-decimal-decimal
4456
+ *
4457
+ * @param input The input collection.
4458
+ * @returns A collection containing the result.
4459
+ */
4460
+ log: (input, baseAtom) => {
4461
+ return applyMathFunc((value, base) => Math.log(value) / Math.log(base), input, baseAtom);
4462
+ },
4463
+ /**
4464
+ * 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.
4465
+ *
4466
+ * If the power cannot be represented (such as the -1 raised to the 0.5), the result is empty.
4467
+ *
4468
+ * If the input is empty, or exponent is empty, the result is empty.
4469
+ *
4470
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4471
+ *
4472
+ * See: https://hl7.org/fhirpath/#powerexponent-integer-decimal-integer-decimal
4473
+ *
4474
+ * @param input The input collection.
4475
+ * @returns A collection containing the result.
4476
+ */
4477
+ power: (input, expAtom) => {
4478
+ return applyMathFunc(Math.pow, input, expAtom);
4479
+ },
4480
+ /**
4481
+ * 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.
4482
+ *
4483
+ * If specified, the number of digits of precision must be >= 0 or the evaluation will end and signal an error to the calling environment.
4484
+ *
4485
+ * If the input collection contains a single item of type Integer, it will be implicitly converted to a Decimal.
4486
+ *
4487
+ * If the input collection is empty, the result is empty.
4488
+ *
4489
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4490
+ *
4491
+ * See: https://hl7.org/fhirpath/#roundprecision-integer-decimal
4492
+ *
4493
+ * @param input The input collection.
4494
+ * @returns A collection containing the result.
4495
+ */
4496
+ round: (input) => {
4497
+ return applyMathFunc(Math.round, input);
4498
+ },
4499
+ /**
4500
+ * Returns the square root of the input number as a Decimal.
4501
+ *
4502
+ * If the square root cannot be represented (such as the square root of -1), the result is empty.
4503
+ *
4504
+ * If the input collection is empty, the result is empty.
4505
+ *
4506
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4507
+ *
4508
+ * Note that this function is equivalent to raising a number of the power of 0.5 using the power() function.
4509
+ *
4510
+ * See: https://hl7.org/fhirpath/#sqrt-decimal
4511
+ *
4512
+ * @param input The input collection.
4513
+ * @returns A collection containing the result.
4514
+ */
4515
+ sqrt: (input) => {
4516
+ return applyMathFunc(Math.sqrt, input);
4517
+ },
4518
+ /**
4519
+ * Returns the integer portion of the input.
4520
+ *
4521
+ * If the input collection is empty, the result is empty.
4522
+ *
4523
+ * If the input collection contains multiple items, the evaluation of the expression will end and signal an error to the calling environment.
4524
+ *
4525
+ * See: https://hl7.org/fhirpath/#truncate-integer
4526
+ *
4527
+ * @param input The input collection.
4528
+ * @returns A collection containing the result.
4529
+ */
4530
+ truncate: (input) => {
4531
+ return applyMathFunc((x) => x | 0, input);
4532
+ },
4533
+ /*
4534
+ * 5.8. Tree navigation
4535
+ */
4536
+ children: stub,
4537
+ descendants: stub,
4538
+ /*
4539
+ * 5.9. Utility functions
4540
+ */
4541
+ /**
4542
+ * Adds a String representation of the input collection to the diagnostic log,
4543
+ * using the name argument as the name in the log. This log should be made available
4544
+ * to the user in some appropriate fashion. Does not change the input, so returns
4545
+ * the input collection as output.
4546
+ *
4547
+ * If the projection argument is used, the trace would log the result of evaluating
4548
+ * the project expression on the input, but still return the input to the trace
4549
+ * function unchanged.
4550
+ *
4551
+ * See: https://hl7.org/fhirpath/#tracename-string-projection-expression-collection
4552
+ *
4553
+ * @param input The input collection.
4554
+ * @param nameAtom The log name.
4555
+ */
4556
+ trace: (input, nameAtom) => {
4557
+ console.log('trace', input, nameAtom);
4558
+ return input;
4559
+ },
4560
+ /**
4561
+ * Returns the current date and time, including timezone offset.
4562
+ *
4563
+ * See: https://hl7.org/fhirpath/#now-datetime
4564
+ */
4565
+ now: () => {
4566
+ return [{ type: exports.PropertyType.dateTime, value: new Date().toISOString() }];
4567
+ },
4568
+ /**
4569
+ * Returns the current time.
4570
+ *
4571
+ * See: https://hl7.org/fhirpath/#timeofday-time
4572
+ */
4573
+ timeOfDay: () => {
4574
+ return [{ type: exports.PropertyType.time, value: new Date().toISOString().substring(11) }];
4575
+ },
4576
+ /**
4577
+ * Returns the current date.
4578
+ *
4579
+ * See: https://hl7.org/fhirpath/#today-date
4580
+ */
4581
+ today: () => {
4582
+ return [{ type: exports.PropertyType.date, value: new Date().toISOString().substring(0, 10) }];
4583
+ },
4584
+ /**
4585
+ * Calculates the difference between two dates or date/times.
4586
+ *
4587
+ * This is not part of the official FHIRPath spec.
4588
+ *
4589
+ * IBM FHIR issue: https://github.com/IBM/FHIR/issues/1014
4590
+ * IBM FHIR PR: https://github.com/IBM/FHIR/pull/1023
4591
+ */
4592
+ between: (context, startAtom, endAtom, unitsAtom) => {
4593
+ const startDate = functions.toDateTime(startAtom.eval(context));
4594
+ if (startDate.length === 0) {
4595
+ throw new Error('Invalid start date');
4554
4596
  }
4555
- if (typeof value === 'number') {
4556
- return { namespace: 'System', name: 'Integer' };
4597
+ const endDate = functions.toDateTime(endAtom.eval(context));
4598
+ if (endDate.length === 0) {
4599
+ throw new Error('Invalid end date');
4557
4600
  }
4558
- if (value && typeof value === 'object' && 'resourceType' in value) {
4559
- return { namespace: 'FHIR', name: value.resourceType };
4601
+ const unit = unitsAtom.eval(context)[0].value;
4602
+ if (unit !== 'years' && unit !== 'months' && unit !== 'days') {
4603
+ throw new Error('Invalid units');
4560
4604
  }
4561
- return null;
4562
- });
4563
- }
4564
- function conformsTo(input, systemAtom) {
4565
- const system = systemAtom.eval(undefined);
4566
- if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
4567
- throw new Error('Expected a StructureDefinition URL');
4568
- }
4569
- const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
4570
- return input.map((resource) => (resource === null || resource === void 0 ? void 0 : resource.resourceType) === expectedResourceType);
4571
- }
4605
+ const age = calculateAge(startDate[0].value, endDate[0].value);
4606
+ return [{ type: exports.PropertyType.Quantity, value: { value: age[unit], unit } }];
4607
+ },
4608
+ /*
4609
+ * 6.3 Types
4610
+ */
4611
+ /**
4612
+ * The is() function is supported for backwards compatibility with previous
4613
+ * implementations of FHIRPath. Just as with the is keyword, the type argument
4614
+ * is an identifier that must resolve to the name of a type in a model.
4615
+ *
4616
+ * For implementations with compile-time typing, this requires special-case
4617
+ * handling when processing the argument to treat it as a type specifier rather
4618
+ * than an identifier expression:
4619
+ *
4620
+ * @param input
4621
+ * @param typeAtom
4622
+ * @returns
4623
+ */
4624
+ is: (input, typeAtom) => {
4625
+ let typeName = '';
4626
+ if (typeAtom instanceof SymbolAtom) {
4627
+ typeName = typeAtom.name;
4628
+ }
4629
+ else if (typeAtom instanceof DotAtom) {
4630
+ typeName = typeAtom.left.name + '.' + typeAtom.right.name;
4631
+ }
4632
+ if (!typeName) {
4633
+ return [];
4634
+ }
4635
+ return input.map((value) => ({ type: exports.PropertyType.boolean, value: fhirPathIs(value, typeName) }));
4636
+ },
4637
+ /*
4638
+ * 6.5 Boolean logic
4639
+ */
4640
+ /**
4641
+ * 6.5.3. not() : Boolean
4642
+ *
4643
+ * Returns true if the input collection evaluates to false, and false if it evaluates to true. Otherwise, the result is empty ({ }):
4644
+ *
4645
+ * @param input
4646
+ * @returns
4647
+ */
4648
+ not: (input) => {
4649
+ return functions.toBoolean(input).map((value) => ({ type: exports.PropertyType.boolean, value: !value.value }));
4650
+ },
4651
+ /*
4652
+ * Additional functions
4653
+ * See: https://hl7.org/fhir/fhirpath.html#functions
4654
+ */
4655
+ /**
4656
+ * 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.
4657
+ * The items in the collection may also represent a Reference, in which case the Reference.reference is resolved.
4658
+ * @param input The input collection.
4659
+ * @returns
4660
+ */
4661
+ resolve: (input) => {
4662
+ return input
4663
+ .map((e) => {
4664
+ const value = e.value;
4665
+ let refStr;
4666
+ if (typeof value === 'string') {
4667
+ refStr = value;
4668
+ }
4669
+ else if (typeof value === 'object') {
4670
+ const ref = value;
4671
+ if (ref.resource) {
4672
+ return { type: exports.PropertyType.BackboneElement, value: ref.resource };
4673
+ }
4674
+ refStr = ref.reference;
4675
+ }
4676
+ if (!refStr) {
4677
+ return { type: exports.PropertyType.BackboneElement, value: null };
4678
+ }
4679
+ const [resourceType, id] = refStr.split('/');
4680
+ return { type: exports.PropertyType.BackboneElement, value: { resourceType, id } };
4681
+ })
4682
+ .filter((e) => !!e.value);
4683
+ },
4684
+ /**
4685
+ * The as operator can be used to treat a value as a specific type.
4686
+ * @param context The context value.
4687
+ * @returns The value as the specific type.
4688
+ */
4689
+ as: (context) => {
4690
+ return context;
4691
+ },
4692
+ /*
4693
+ * 12. Formal Specifications
4694
+ */
4695
+ /**
4696
+ * Returns the type of the input.
4697
+ *
4698
+ * 12.2. Model Information
4699
+ *
4700
+ * The model information returned by the reflection function type() is specified as an
4701
+ * XML Schema document (xsd) and included in this specification at the following link:
4702
+ * https://hl7.org/fhirpath/modelinfo.xsd
4703
+ *
4704
+ * See: https://hl7.org/fhirpath/#model-information
4705
+ *
4706
+ * @param input The input collection.
4707
+ * @returns
4708
+ */
4709
+ type: (input) => {
4710
+ return input.map(({ value }) => {
4711
+ if (typeof value === 'boolean') {
4712
+ return { type: exports.PropertyType.BackboneElement, value: { namespace: 'System', name: 'Boolean' } };
4713
+ }
4714
+ if (typeof value === 'number') {
4715
+ return { type: exports.PropertyType.BackboneElement, value: { namespace: 'System', name: 'Integer' } };
4716
+ }
4717
+ if (value && typeof value === 'object' && 'resourceType' in value) {
4718
+ return {
4719
+ type: exports.PropertyType.BackboneElement,
4720
+ value: { namespace: 'FHIR', name: value.resourceType },
4721
+ };
4722
+ }
4723
+ return { type: exports.PropertyType.BackboneElement, value: null };
4724
+ });
4725
+ },
4726
+ conformsTo: (input, systemAtom) => {
4727
+ const system = systemAtom.eval([])[0].value;
4728
+ if (!system.startsWith('http://hl7.org/fhir/StructureDefinition/')) {
4729
+ throw new Error('Expected a StructureDefinition URL');
4730
+ }
4731
+ const expectedResourceType = system.replace('http://hl7.org/fhir/StructureDefinition/', '');
4732
+ return input.map((value) => {
4733
+ var _a;
4734
+ return ({
4735
+ type: exports.PropertyType.boolean,
4736
+ value: ((_a = value.value) === null || _a === void 0 ? void 0 : _a.resourceType) === expectedResourceType,
4737
+ });
4738
+ });
4739
+ },
4740
+ };
4572
4741
  /*
4573
4742
  * Helper utilities
4574
4743
  */
@@ -4576,115 +4745,46 @@
4576
4745
  if (input.length === 0) {
4577
4746
  return [];
4578
4747
  }
4579
- const [value] = validateInput(input, 1);
4748
+ const [{ value }] = validateInput(input, 1);
4580
4749
  if (typeof value !== 'string') {
4581
4750
  throw new Error('String function cannot be called with non-string');
4582
4751
  }
4583
- const result = func(value, ...argsAtoms.map((atom) => atom && atom.eval(value)));
4584
- return result === undefined ? [] : [result];
4752
+ const result = func(value, ...argsAtoms.map((atom) => { var _a, _b; return atom && ((_b = (_a = atom.eval(input)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value); }));
4753
+ if (result === undefined) {
4754
+ return [];
4755
+ }
4756
+ if (Array.isArray(result)) {
4757
+ return result.map(toTypedValue);
4758
+ }
4759
+ return [toTypedValue(result)];
4585
4760
  }
4586
4761
  function applyMathFunc(func, input, ...argsAtoms) {
4587
4762
  if (input.length === 0) {
4588
4763
  return [];
4589
4764
  }
4590
- const [value] = validateInput(input, 1);
4765
+ const [{ value }] = validateInput(input, 1);
4591
4766
  const quantity = isQuantity(value);
4592
4767
  const numberInput = quantity ? value.value : value;
4593
4768
  if (typeof numberInput !== 'number') {
4594
4769
  throw new Error('Math function cannot be called with non-number');
4595
4770
  }
4596
- const result = func(numberInput, ...argsAtoms.map((atom) => atom.eval(undefined)));
4597
- return quantity ? [Object.assign(Object.assign({}, value), { value: result })] : [result];
4771
+ const result = func(numberInput, ...argsAtoms.map((atom) => { var _a, _b; return (_b = (_a = atom.eval([])) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value; }));
4772
+ const type = quantity ? exports.PropertyType.Quantity : input[0].type;
4773
+ const returnValue = quantity ? Object.assign(Object.assign({}, value), { value: result }) : result;
4774
+ return [{ type, value: returnValue }];
4598
4775
  }
4599
4776
  function validateInput(input, count) {
4600
4777
  if (input.length !== count) {
4601
4778
  throw new Error(`Expected ${count} arguments`);
4602
4779
  }
4780
+ for (const element of input) {
4781
+ if (element === null || element === undefined) {
4782
+ throw new Error('Expected non-null argument');
4783
+ }
4784
+ }
4603
4785
  return input;
4604
4786
  }
4605
4787
 
4606
- var functions = /*#__PURE__*/Object.freeze({
4607
- __proto__: null,
4608
- empty: empty,
4609
- exists: exists,
4610
- all: all,
4611
- allTrue: allTrue,
4612
- anyTrue: anyTrue,
4613
- allFalse: allFalse,
4614
- anyFalse: anyFalse,
4615
- subsetOf: subsetOf,
4616
- supersetOf: supersetOf,
4617
- count: count,
4618
- distinct: distinct,
4619
- isDistinct: isDistinct,
4620
- where: where,
4621
- select: select,
4622
- repeat: repeat,
4623
- ofType: ofType,
4624
- single: single,
4625
- first: first,
4626
- last: last,
4627
- tail: tail,
4628
- skip: skip,
4629
- take: take,
4630
- intersect: intersect,
4631
- exclude: exclude,
4632
- union: union,
4633
- combine: combine,
4634
- iif: iif,
4635
- toBoolean: toBoolean,
4636
- convertsToBoolean: convertsToBoolean,
4637
- toInteger: toInteger,
4638
- convertsToInteger: convertsToInteger,
4639
- toDate: toDate,
4640
- convertsToDate: convertsToDate,
4641
- toDateTime: toDateTime,
4642
- convertsToDateTime: convertsToDateTime,
4643
- toDecimal: toDecimal,
4644
- convertsToDecimal: convertsToDecimal,
4645
- toQuantity: toQuantity,
4646
- convertsToQuantity: convertsToQuantity,
4647
- toString: toString,
4648
- convertsToString: convertsToString,
4649
- toTime: toTime,
4650
- convertsToTime: convertsToTime,
4651
- indexOf: indexOf,
4652
- substring: substring,
4653
- startsWith: startsWith,
4654
- endsWith: endsWith,
4655
- contains: contains,
4656
- upper: upper,
4657
- lower: lower,
4658
- replace: replace,
4659
- matches: matches,
4660
- replaceMatches: replaceMatches,
4661
- length: length,
4662
- toChars: toChars,
4663
- abs: abs,
4664
- ceiling: ceiling,
4665
- exp: exp,
4666
- floor: floor,
4667
- ln: ln,
4668
- log: log,
4669
- power: power,
4670
- round: round,
4671
- sqrt: sqrt,
4672
- truncate: truncate,
4673
- children: children,
4674
- descendants: descendants,
4675
- trace: trace,
4676
- now: now,
4677
- timeOfDay: timeOfDay,
4678
- today: today,
4679
- between: between,
4680
- is: is,
4681
- not: not,
4682
- resolve: resolve,
4683
- as: as,
4684
- type: type,
4685
- conformsTo: conformsTo
4686
- });
4687
-
4688
4788
  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;
4689
4789
  function tokenize(str) {
4690
4790
  return new Tokenizer(str).tokenize();
@@ -5003,24 +5103,24 @@
5003
5103
  }
5004
5104
  const parserBuilder = new ParserBuilder()
5005
5105
  .registerPrefix('String', {
5006
- parse: (_, token) => new LiteralAtom(token.value),
5106
+ parse: (_, token) => new LiteralAtom({ type: exports.PropertyType.string, value: token.value }),
5007
5107
  })
5008
5108
  .registerPrefix('DateTime', {
5009
- parse: (_, token) => new LiteralAtom(parseDateString(token.value)),
5109
+ parse: (_, token) => new LiteralAtom({ type: exports.PropertyType.dateTime, value: parseDateString(token.value) }),
5010
5110
  })
5011
5111
  .registerPrefix('Quantity', {
5012
- parse: (_, token) => new LiteralAtom(parseQuantity(token.value)),
5112
+ parse: (_, token) => new LiteralAtom({ type: exports.PropertyType.Quantity, value: parseQuantity(token.value) }),
5013
5113
  })
5014
5114
  .registerPrefix('Number', {
5015
- parse: (_, token) => new LiteralAtom(parseFloat(token.value)),
5115
+ parse: (_, token) => new LiteralAtom({ type: exports.PropertyType.decimal, value: parseFloat(token.value) }),
5016
5116
  })
5017
5117
  .registerPrefix('Symbol', {
5018
5118
  parse: (_, token) => {
5019
5119
  if (token.value === 'false') {
5020
- return new LiteralAtom(false);
5120
+ return new LiteralAtom({ type: exports.PropertyType.boolean, value: false });
5021
5121
  }
5022
5122
  if (token.value === 'true') {
5023
- return new LiteralAtom(true);
5123
+ return new LiteralAtom({ type: exports.PropertyType.boolean, value: true });
5024
5124
  }
5025
5125
  return new SymbolAtom(token.value);
5026
5126
  },
@@ -5041,10 +5141,10 @@
5041
5141
  .infixLeft('!=', 9 /* Precedence.Equals */, (left, _, right) => new NotEqualsAtom(left, right))
5042
5142
  .infixLeft('~', 9 /* Precedence.Equivalent */, (left, _, right) => new EquivalentAtom(left, right))
5043
5143
  .infixLeft('!~', 9 /* Precedence.NotEquivalent */, (left, _, right) => new NotEquivalentAtom(left, right))
5044
- .infixLeft('<', 8 /* Precedence.LessThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x < y))
5045
- .infixLeft('<=', 8 /* Precedence.LessThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x <= y))
5046
- .infixLeft('>', 8 /* Precedence.GreaterThan */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x > y))
5047
- .infixLeft('>=', 8 /* Precedence.GreaterThanOrEquals */, (left, _, right) => new ComparisonOperatorAtom(left, right, (x, y) => x >= y))
5144
+ .infixLeft('<', 8 /* Precedence.LessThan */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x < y))
5145
+ .infixLeft('<=', 8 /* Precedence.LessThanOrEquals */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x <= y))
5146
+ .infixLeft('>', 8 /* Precedence.GreaterThan */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x > y))
5147
+ .infixLeft('>=', 8 /* Precedence.GreaterThanOrEquals */, (left, _, right) => new ArithemticOperatorAtom(left, right, (x, y) => x >= y))
5048
5148
  .infixLeft('&', 5 /* Precedence.Ampersand */, (left, _, right) => new ConcatAtom(left, right))
5049
5149
  .infixLeft('Symbol', 6 /* Precedence.Is */, (left, symbol, right) => {
5050
5150
  switch (symbol.value) {
@@ -5093,7 +5193,21 @@
5093
5193
  * @returns The result of the FHIRPath expression against the resource or object.
5094
5194
  */
5095
5195
  function evalFhirPath(input, context) {
5096
- return parseFhirPath(input).eval(context);
5196
+ // eval requires a TypedValue array
5197
+ // As a convenience, we can accept array or non-array, and TypedValue or unknown value
5198
+ if (!Array.isArray(context)) {
5199
+ context = [context];
5200
+ }
5201
+ const array = Array.isArray(context) ? context : [context];
5202
+ for (let i = 0; i < array.length; i++) {
5203
+ const el = array[i];
5204
+ if (!(typeof el === 'object' && 'type' in el && 'value' in el)) {
5205
+ array[i] = { type: exports.PropertyType.BackboneElement, value: el };
5206
+ }
5207
+ }
5208
+ return parseFhirPath(input)
5209
+ .eval(array)
5210
+ .map((e) => e.value);
5097
5211
  }
5098
5212
 
5099
5213
  const SEGMENT_SEPARATOR = '\r';
@@ -5286,7 +5400,12 @@
5286
5400
  let type = exports.SearchParameterType.TEXT;
5287
5401
  switch (searchParam.type) {
5288
5402
  case 'date':
5289
- type = exports.SearchParameterType.DATE;
5403
+ if (propertyType === exports.PropertyType.dateTime || propertyType === exports.PropertyType.instant) {
5404
+ type = exports.SearchParameterType.DATETIME;
5405
+ }
5406
+ else {
5407
+ type = exports.SearchParameterType.DATE;
5408
+ }
5290
5409
  break;
5291
5410
  case 'number':
5292
5411
  type = exports.SearchParameterType.NUMBER;