@medplum/core 2.0.23 → 2.0.24
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.cjs +14080 -13352
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.min.cjs +1 -1
- package/dist/esm/access.mjs +142 -0
- package/dist/esm/access.mjs.map +1 -0
- package/dist/esm/bundle.mjs +3 -3
- package/dist/esm/bundle.mjs.map +1 -1
- package/dist/esm/client.mjs +49 -25
- package/dist/esm/client.mjs.map +1 -1
- package/dist/esm/fhirlexer/parse.mjs.map +1 -1
- package/dist/esm/fhirmapper/parse.mjs +1 -1
- package/dist/esm/fhirmapper/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/functions.mjs +2 -2
- package/dist/esm/fhirpath/functions.mjs.map +1 -1
- package/dist/esm/fhirpath/parse.mjs +2 -1
- package/dist/esm/fhirpath/parse.mjs.map +1 -1
- package/dist/esm/fhirpath/utils.mjs +4 -5
- package/dist/esm/fhirpath/utils.mjs.map +1 -1
- package/dist/esm/format.mjs +1 -1
- package/dist/esm/format.mjs.map +1 -1
- package/dist/esm/hl7.mjs +6 -6
- package/dist/esm/hl7.mjs.map +1 -1
- package/dist/esm/index.min.mjs +1 -1
- package/dist/esm/index.mjs +5 -2
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/outcomes.mjs +38 -14
- package/dist/esm/outcomes.mjs.map +1 -1
- package/dist/esm/readablepromise.mjs +1 -1
- package/dist/esm/readablepromise.mjs.map +1 -1
- package/dist/esm/schema.mjs +1 -1
- package/dist/esm/schema.mjs.map +1 -1
- package/dist/esm/search/details.mjs +14 -16
- package/dist/esm/search/details.mjs.map +1 -1
- package/dist/esm/search/match.mjs +7 -5
- package/dist/esm/search/match.mjs.map +1 -1
- package/dist/esm/search/search.mjs +14 -5
- package/dist/esm/search/search.mjs.map +1 -1
- package/dist/esm/types.mjs +1 -1
- package/dist/esm/types.mjs.map +1 -1
- package/dist/esm/typeschema/types.mjs +278 -0
- package/dist/esm/typeschema/types.mjs.map +1 -0
- package/dist/esm/typeschema/validation.mjs +262 -0
- package/dist/esm/typeschema/validation.mjs.map +1 -0
- package/dist/esm/utils.mjs +3 -3
- package/dist/esm/utils.mjs.map +1 -1
- package/dist/types/access.d.ts +48 -0
- package/dist/types/client.d.ts +15 -20
- package/dist/types/fhirlexer/parse.d.ts +5 -4
- package/dist/types/fhirpath/functions.d.ts +1 -3
- package/dist/types/index.d.ts +3 -0
- package/dist/types/outcomes.d.ts +3 -1
- package/dist/types/search/search.d.ts +7 -0
- package/dist/types/typeschema/types.d.ts +5 -2
- package/dist/types/typeschema/validation.d.ts +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { getDataType, parseStructureDefinition } from './types.mjs';
|
|
2
|
+
import { OperationOutcomeError, validationError } from '../outcomes.mjs';
|
|
3
|
+
import { PropertyType } from '../types.mjs';
|
|
4
|
+
import { isEmpty, isLowerCase } from '../utils.mjs';
|
|
5
|
+
import { getTypedPropertyValue } from '../fhirpath/utils.mjs';
|
|
6
|
+
import '../fhirpath/parse.mjs';
|
|
7
|
+
import { createStructureIssue } from '../schema.mjs';
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* This file provides schema validation utilities for FHIR JSON objects.
|
|
11
|
+
*
|
|
12
|
+
* See: [JSON Representation of Resources](https://hl7.org/fhir/json.html)
|
|
13
|
+
* See: [FHIR Data Types](https://www.hl7.org/fhir/datatypes.html)
|
|
14
|
+
*/
|
|
15
|
+
const fhirTypeToJsType = {
|
|
16
|
+
base64Binary: 'string',
|
|
17
|
+
boolean: 'boolean',
|
|
18
|
+
canonical: 'string',
|
|
19
|
+
code: 'string',
|
|
20
|
+
date: 'string',
|
|
21
|
+
dateTime: 'string',
|
|
22
|
+
decimal: 'number',
|
|
23
|
+
id: 'string',
|
|
24
|
+
instant: 'string',
|
|
25
|
+
integer: 'number',
|
|
26
|
+
markdown: 'string',
|
|
27
|
+
oid: 'string',
|
|
28
|
+
positiveInt: 'number',
|
|
29
|
+
string: 'string',
|
|
30
|
+
time: 'string',
|
|
31
|
+
unsignedInt: 'number',
|
|
32
|
+
uri: 'string',
|
|
33
|
+
url: 'string',
|
|
34
|
+
uuid: 'string',
|
|
35
|
+
xhtml: 'string',
|
|
36
|
+
'http://hl7.org/fhirpath/System.String': 'string', // Not actually a FHIR type, but included in some StructureDefinition resources
|
|
37
|
+
};
|
|
38
|
+
/*
|
|
39
|
+
* This file provides schema validation utilities for FHIR JSON objects.
|
|
40
|
+
*
|
|
41
|
+
* See: [JSON Representation of Resources](https://hl7.org/fhir/json.html)
|
|
42
|
+
* See: [FHIR Data Types](https://www.hl7.org/fhir/datatypes.html)
|
|
43
|
+
*/
|
|
44
|
+
const validationRegexes = {
|
|
45
|
+
base64Binary: /^([A-Za-z\d+/]{4})*([A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/,
|
|
46
|
+
canonical: /^\S*$/,
|
|
47
|
+
code: /^[^\s]+( [^\s]+)*$/,
|
|
48
|
+
date: /^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1]))?)?$/,
|
|
49
|
+
dateTime: /^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\d|3[0-1])(T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?)?)?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00)?)?)?$/,
|
|
50
|
+
id: /^[A-Za-z0-9\-.]{1,64}$/,
|
|
51
|
+
instant: /^(\d(\d(\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])T([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?(Z|[+-]((0\d|1[0-3]):[0-5]\d|14:00))$/,
|
|
52
|
+
markdown: /^[\s\S]+$/,
|
|
53
|
+
oid: /^urn:oid:[0-2](\.(0|[1-9]\d*))+$/,
|
|
54
|
+
string: /^[\s\S]+$/,
|
|
55
|
+
time: /^([01]\d|2[0-3]):[0-5]\d:([0-5]\d|60)(\.\d{1,9})?$/,
|
|
56
|
+
uri: /^\S*$/,
|
|
57
|
+
url: /^\S*$/,
|
|
58
|
+
uuid: /^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
|
|
59
|
+
xhtml: /.*/,
|
|
60
|
+
};
|
|
61
|
+
function validateResource(resource, profile) {
|
|
62
|
+
return new ResourceValidator(resource.resourceType, profile).validate(resource);
|
|
63
|
+
}
|
|
64
|
+
class ResourceValidator {
|
|
65
|
+
constructor(resourceType, profile) {
|
|
66
|
+
this.issues = [];
|
|
67
|
+
if (!profile) {
|
|
68
|
+
this.schema = getDataType(resourceType);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
this.schema = parseStructureDefinition(profile);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
validate(resource) {
|
|
75
|
+
if (!resource) {
|
|
76
|
+
throw new OperationOutcomeError(validationError('Resource is null'));
|
|
77
|
+
}
|
|
78
|
+
const resourceType = resource.resourceType;
|
|
79
|
+
if (!resourceType) {
|
|
80
|
+
throw new OperationOutcomeError(validationError('Missing resource type'));
|
|
81
|
+
}
|
|
82
|
+
this.validateObject({ type: resourceType, value: resource }, this.schema, resourceType);
|
|
83
|
+
const issues = this.issues;
|
|
84
|
+
this.issues = []; // Reset issues to allow re-using the validator for other resources
|
|
85
|
+
if (issues.length > 0) {
|
|
86
|
+
throw new OperationOutcomeError({
|
|
87
|
+
resourceType: 'OperationOutcome',
|
|
88
|
+
issue: issues,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
validateObject(value, schema, path) {
|
|
93
|
+
for (const [key, _propSchema] of Object.entries(schema.fields)) {
|
|
94
|
+
this.checkProperty(value, key, schema, path + '.' + key);
|
|
95
|
+
}
|
|
96
|
+
//@TODO(mattwiller 2023-06-05): Detect extraneous properties in a single pass by keeping track of all keys that
|
|
97
|
+
// were correctly matched to resource properties as elements are validated above
|
|
98
|
+
this.checkAdditionalProperties(value, schema.fields, path);
|
|
99
|
+
}
|
|
100
|
+
checkProperty(value, key, schema, path) {
|
|
101
|
+
const propertyValues = getNestedProperty(value, key);
|
|
102
|
+
const element = schema.fields[key];
|
|
103
|
+
if (!element) {
|
|
104
|
+
throw new Error(`Missing element validation schema for ${key}`);
|
|
105
|
+
}
|
|
106
|
+
for (const property of propertyValues) {
|
|
107
|
+
if (isEmpty(property)) {
|
|
108
|
+
if (element.min > 0) {
|
|
109
|
+
this.issues.push(createStructureIssue(path, 'Missing required property'));
|
|
110
|
+
}
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
let values;
|
|
114
|
+
if (element.isArray) {
|
|
115
|
+
if (!Array.isArray(property)) {
|
|
116
|
+
this.issues.push(createStructureIssue(path, 'Expected array of values'));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
values = property;
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
if (Array.isArray(property)) {
|
|
123
|
+
this.issues.push(createStructureIssue(path, 'Expected single value'));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
values = [property];
|
|
127
|
+
}
|
|
128
|
+
for (const value of values) {
|
|
129
|
+
this.checkPropertyValue(value, path);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
checkPropertyValue(value, path) {
|
|
134
|
+
if (isLowerCase(value.type.charAt(0))) {
|
|
135
|
+
this.validatePrimitiveType(value, path);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
// Recursively validate as the expected data type
|
|
139
|
+
const type = getDataType(value.type);
|
|
140
|
+
this.validateObject(value, type, path);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
checkAdditionalProperties(typedValue, properties, path) {
|
|
144
|
+
const object = typedValue.value;
|
|
145
|
+
for (const key of Object.keys(object)) {
|
|
146
|
+
if (key === 'resourceType') {
|
|
147
|
+
continue; // Skip special resource type discriminator property in JSON
|
|
148
|
+
}
|
|
149
|
+
if (!(key in properties) &&
|
|
150
|
+
!isChoiceOfType(typedValue, key, properties) &&
|
|
151
|
+
!this.isPrimitiveExtension(typedValue, key, path)) {
|
|
152
|
+
this.issues.push(createStructureIssue(`${path}.${key}`, `Invalid additional property "${key}"`));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Checks the element for a primitive extension.
|
|
158
|
+
*
|
|
159
|
+
* FHIR elements with primitive data types are represented in two parts:
|
|
160
|
+
* 1) A JSON property with the name of the element, which has a JSON type of number, boolean, or string
|
|
161
|
+
* 2) a JSON property with _ prepended to the name of the element, which, if present, contains the value's id and/or extensions
|
|
162
|
+
*
|
|
163
|
+
* See: https://hl7.org/fhir/json.html#primitive
|
|
164
|
+
* @param typedValue The parent value
|
|
165
|
+
* @param key The property key to check
|
|
166
|
+
* @param path The path to the property
|
|
167
|
+
* @returns Whether the element is a primitive extension
|
|
168
|
+
*/
|
|
169
|
+
isPrimitiveExtension(typedValue, key, path) {
|
|
170
|
+
// Primitive element starts with underscore
|
|
171
|
+
if (!key.startsWith('_')) {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
// Then validate the element
|
|
175
|
+
//@TODO(mattwiller 2023-06-05): Move this to occur along with the rest of validation
|
|
176
|
+
this.validateObject({ type: 'Element', value: typedValue.value[key] }, getDataType('Element'), path);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
validatePrimitiveType(typedValue, path) {
|
|
180
|
+
const { type, value } = typedValue;
|
|
181
|
+
// First, make sure the value is the correct JS type
|
|
182
|
+
const expectedType = fhirTypeToJsType[type];
|
|
183
|
+
if (typeof value !== expectedType) {
|
|
184
|
+
this.issues.push(createStructureIssue(path, `Invalid JSON type at ${path}: expected ${expectedType}, but got ${typeof value}`));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
// Then, perform additional checks for specialty types
|
|
188
|
+
if (expectedType === 'string') {
|
|
189
|
+
this.validateString(value, type, path);
|
|
190
|
+
}
|
|
191
|
+
else if (expectedType === 'number') {
|
|
192
|
+
this.validateNumber(value, type, path);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
validateString(str, type, path) {
|
|
196
|
+
if (!str.trim()) {
|
|
197
|
+
this.issues.push(createStructureIssue(path, 'String must contain non-whitespace content'));
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const regex = validationRegexes[type];
|
|
201
|
+
if (regex && !regex.exec(str)) {
|
|
202
|
+
this.issues.push(createStructureIssue(path, 'Invalid ' + type + ' format'));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
validateNumber(n, type, path) {
|
|
206
|
+
if (isNaN(n) || !isFinite(n)) {
|
|
207
|
+
this.issues.push(createStructureIssue(path, 'Invalid numeric value'));
|
|
208
|
+
}
|
|
209
|
+
else if (isIntegerType(type) && !Number.isInteger(n)) {
|
|
210
|
+
this.issues.push(createStructureIssue(path, 'Expected number to be an integer'));
|
|
211
|
+
}
|
|
212
|
+
else if (type === PropertyType.positiveInt && n <= 0) {
|
|
213
|
+
this.issues.push(createStructureIssue(path, 'Expected number to be positive'));
|
|
214
|
+
}
|
|
215
|
+
else if (type === PropertyType.unsignedInt && n < 0) {
|
|
216
|
+
this.issues.push(createStructureIssue(path, 'Expected number to be non-negative'));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function isIntegerType(propertyType) {
|
|
221
|
+
return (propertyType === PropertyType.integer ||
|
|
222
|
+
propertyType === PropertyType.positiveInt ||
|
|
223
|
+
propertyType === PropertyType.unsignedInt);
|
|
224
|
+
}
|
|
225
|
+
function isChoiceOfType(typedValue, key, propertyDefinitions) {
|
|
226
|
+
const parts = key.split(/(?=[A-Z])/g); // Split before capital letters
|
|
227
|
+
let testProperty = '';
|
|
228
|
+
for (const part of parts) {
|
|
229
|
+
testProperty += part;
|
|
230
|
+
if (!propertyDefinitions[testProperty + '[x]']) {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const typedPropertyValue = getTypedPropertyValue(typedValue, testProperty);
|
|
234
|
+
return !!typedPropertyValue;
|
|
235
|
+
}
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
function getNestedProperty(value, key) {
|
|
239
|
+
const [firstProp, ...nestedProps] = key.split('.');
|
|
240
|
+
let propertyValues = [getTypedPropertyValue(value, firstProp)];
|
|
241
|
+
for (const prop of nestedProps) {
|
|
242
|
+
const next = [];
|
|
243
|
+
for (const current of propertyValues) {
|
|
244
|
+
if (current === undefined) {
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
else if (Array.isArray(current)) {
|
|
248
|
+
for (const element of current) {
|
|
249
|
+
next.push(getTypedPropertyValue(element, prop));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
next.push(getTypedPropertyValue(current, prop));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
propertyValues = next;
|
|
257
|
+
}
|
|
258
|
+
return propertyValues;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export { validateResource };
|
|
262
|
+
//# sourceMappingURL=validation.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.mjs","sources":["../../../src/typeschema/validation.ts"],"sourcesContent":["import { OperationOutcomeIssue, Resource, StructureDefinition } from '@medplum/fhirtypes';\nimport { ElementValidator, getDataType, parseStructureDefinition, InternalTypeSchema } from './types';\nimport { OperationOutcomeError, validationError } from '../outcomes';\nimport { PropertyType, TypedValue } from '../types';\nimport { getTypedPropertyValue } from '../fhirpath';\nimport { createStructureIssue } from '../schema';\nimport { isEmpty, isLowerCase } from '../utils';\n\n/*\n * This file provides schema validation utilities for FHIR JSON objects.\n *\n * See: [JSON Representation of Resources](https://hl7.org/fhir/json.html)\n * See: [FHIR Data Types](https://www.hl7.org/fhir/datatypes.html)\n */\nconst fhirTypeToJsType: Record<string, string> = {\n base64Binary: 'string',\n boolean: 'boolean',\n canonical: 'string',\n code: 'string',\n date: 'string',\n dateTime: 'string',\n decimal: 'number',\n id: 'string',\n instant: 'string',\n integer: 'number',\n markdown: 'string',\n oid: 'string',\n positiveInt: 'number',\n string: 'string',\n time: 'string',\n unsignedInt: 'number',\n uri: 'string',\n url: 'string',\n uuid: 'string',\n xhtml: 'string',\n 'http://hl7.org/fhirpath/System.String': 'string', // Not actually a FHIR type, but included in some StructureDefinition resources\n};\n\n/*\n * This file provides schema validation utilities for FHIR JSON objects.\n *\n * See: [JSON Representation of Resources](https://hl7.org/fhir/json.html)\n * See: [FHIR Data Types](https://www.hl7.org/fhir/datatypes.html)\n */\nconst validationRegexes: Record<string, RegExp> = {\n base64Binary: /^([A-Za-z\\d+/]{4})*([A-Za-z\\d+/]{2}==|[A-Za-z\\d+/]{3}=)?$/,\n canonical: /^\\S*$/,\n code: /^[^\\s]+( [^\\s]+)*$/,\n date: /^(\\d(\\d(\\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\\d|3[0-1]))?)?$/,\n dateTime:\n /^(\\d(\\d(\\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2]\\d|3[0-1])(T([01]\\d|2[0-3]):[0-5]\\d:([0-5]\\d|60)(\\.\\d{1,9})?)?)?(Z|[+-]((0\\d|1[0-3]):[0-5]\\d|14:00)?)?)?$/,\n id: /^[A-Za-z0-9\\-.]{1,64}$/,\n instant:\n /^(\\d(\\d(\\d[1-9]|[1-9]0)|[1-9]00)|[1-9]000)-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\\d|3[0-1])T([01]\\d|2[0-3]):[0-5]\\d:([0-5]\\d|60)(\\.\\d{1,9})?(Z|[+-]((0\\d|1[0-3]):[0-5]\\d|14:00))$/,\n markdown: /^[\\s\\S]+$/,\n oid: /^urn:oid:[0-2](\\.(0|[1-9]\\d*))+$/,\n string: /^[\\s\\S]+$/,\n time: /^([01]\\d|2[0-3]):[0-5]\\d:([0-5]\\d|60)(\\.\\d{1,9})?$/,\n uri: /^\\S*$/,\n url: /^\\S*$/,\n uuid: /^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,\n xhtml: /.*/,\n};\n\nexport function validateResource(resource: Resource, profile?: StructureDefinition): void {\n return new ResourceValidator(resource.resourceType, profile).validate(resource);\n}\n\nclass ResourceValidator {\n private issues: OperationOutcomeIssue[];\n private readonly schema: InternalTypeSchema;\n\n constructor(resourceType: string, profile?: StructureDefinition) {\n this.issues = [];\n if (!profile) {\n this.schema = getDataType(resourceType);\n } else {\n this.schema = parseStructureDefinition(profile);\n }\n }\n\n validate(resource: Resource): void {\n if (!resource) {\n throw new OperationOutcomeError(validationError('Resource is null'));\n }\n const resourceType = resource.resourceType;\n if (!resourceType) {\n throw new OperationOutcomeError(validationError('Missing resource type'));\n }\n\n this.validateObject({ type: resourceType, value: resource }, this.schema, resourceType);\n\n const issues = this.issues;\n this.issues = []; // Reset issues to allow re-using the validator for other resources\n if (issues.length > 0) {\n throw new OperationOutcomeError({\n resourceType: 'OperationOutcome',\n issue: issues,\n });\n }\n }\n\n private validateObject(value: TypedValue, schema: InternalTypeSchema, path: string): void {\n for (const [key, _propSchema] of Object.entries(schema.fields)) {\n this.checkProperty(value, key, schema, path + '.' + key);\n }\n\n //@TODO(mattwiller 2023-06-05): Detect extraneous properties in a single pass by keeping track of all keys that\n // were correctly matched to resource properties as elements are validated above\n this.checkAdditionalProperties(value, schema.fields, path);\n }\n\n private checkProperty(value: TypedValue, key: string, schema: InternalTypeSchema, path: string): void {\n const propertyValues = getNestedProperty(value, key);\n const element = schema.fields[key];\n if (!element) {\n throw new Error(`Missing element validation schema for ${key}`);\n }\n for (const property of propertyValues) {\n if (isEmpty(property)) {\n if (element.min > 0) {\n this.issues.push(createStructureIssue(path, 'Missing required property'));\n }\n return;\n }\n\n let values: TypedValue[];\n if (element.isArray) {\n if (!Array.isArray(property)) {\n this.issues.push(createStructureIssue(path, 'Expected array of values'));\n return;\n }\n values = property;\n } else {\n if (Array.isArray(property)) {\n this.issues.push(createStructureIssue(path, 'Expected single value'));\n return;\n }\n values = [property as TypedValue];\n }\n for (const value of values) {\n this.checkPropertyValue(value, path);\n }\n }\n }\n\n private checkPropertyValue(value: TypedValue, path: string): void {\n if (isLowerCase(value.type.charAt(0))) {\n this.validatePrimitiveType(value, path);\n } else {\n // Recursively validate as the expected data type\n const type = getDataType(value.type);\n this.validateObject(value, type, path);\n }\n }\n\n private checkAdditionalProperties(\n typedValue: TypedValue,\n properties: Record<string, ElementValidator>,\n path: string\n ): void {\n const object = typedValue.value as Record<string, unknown>;\n for (const key of Object.keys(object)) {\n if (key === 'resourceType') {\n continue; // Skip special resource type discriminator property in JSON\n }\n if (\n !(key in properties) &&\n !isChoiceOfType(typedValue, key, properties) &&\n !this.isPrimitiveExtension(typedValue, key, path)\n ) {\n this.issues.push(createStructureIssue(`${path}.${key}`, `Invalid additional property \"${key}\"`));\n }\n }\n }\n\n /**\n * Checks the element for a primitive extension.\n *\n * FHIR elements with primitive data types are represented in two parts:\n * 1) A JSON property with the name of the element, which has a JSON type of number, boolean, or string\n * 2) a JSON property with _ prepended to the name of the element, which, if present, contains the value's id and/or extensions\n *\n * See: https://hl7.org/fhir/json.html#primitive\n * @param typedValue The parent value\n * @param key The property key to check\n * @param path The path to the property\n * @returns Whether the element is a primitive extension\n */\n private isPrimitiveExtension(typedValue: TypedValue, key: string, path: string): boolean {\n // Primitive element starts with underscore\n if (!key.startsWith('_')) {\n return false;\n }\n\n // Then validate the element\n //@TODO(mattwiller 2023-06-05): Move this to occur along with the rest of validation\n this.validateObject({ type: 'Element', value: typedValue.value[key] }, getDataType('Element'), path);\n return true;\n }\n\n private validatePrimitiveType(typedValue: TypedValue, path: string): void {\n const { type, value } = typedValue;\n\n // First, make sure the value is the correct JS type\n const expectedType = fhirTypeToJsType[type];\n if (typeof value !== expectedType) {\n this.issues.push(\n createStructureIssue(path, `Invalid JSON type at ${path}: expected ${expectedType}, but got ${typeof value}`)\n );\n return;\n }\n\n // Then, perform additional checks for specialty types\n if (expectedType === 'string') {\n this.validateString(value as string, type as PropertyType, path);\n } else if (expectedType === 'number') {\n this.validateNumber(value as number, type as PropertyType, path);\n }\n }\n\n private validateString(str: string, type: PropertyType, path: string): void {\n if (!str.trim()) {\n this.issues.push(createStructureIssue(path, 'String must contain non-whitespace content'));\n return;\n }\n\n const regex = validationRegexes[type];\n if (regex && !regex.exec(str)) {\n this.issues.push(createStructureIssue(path, 'Invalid ' + type + ' format'));\n }\n }\n\n private validateNumber(n: number, type: PropertyType, path: string): void {\n if (isNaN(n) || !isFinite(n)) {\n this.issues.push(createStructureIssue(path, 'Invalid numeric value'));\n } else if (isIntegerType(type) && !Number.isInteger(n)) {\n this.issues.push(createStructureIssue(path, 'Expected number to be an integer'));\n } else if (type === PropertyType.positiveInt && n <= 0) {\n this.issues.push(createStructureIssue(path, 'Expected number to be positive'));\n } else if (type === PropertyType.unsignedInt && n < 0) {\n this.issues.push(createStructureIssue(path, 'Expected number to be non-negative'));\n }\n }\n}\n\nfunction isIntegerType(propertyType: PropertyType): boolean {\n return (\n propertyType === PropertyType.integer ||\n propertyType === PropertyType.positiveInt ||\n propertyType === PropertyType.unsignedInt\n );\n}\n\nfunction isChoiceOfType(\n typedValue: TypedValue,\n key: string,\n propertyDefinitions: Record<string, ElementValidator>\n): boolean {\n const parts = key.split(/(?=[A-Z])/g); // Split before capital letters\n let testProperty = '';\n for (const part of parts) {\n testProperty += part;\n if (!propertyDefinitions[testProperty + '[x]']) {\n continue;\n }\n const typedPropertyValue = getTypedPropertyValue(typedValue, testProperty);\n return !!typedPropertyValue;\n }\n return false;\n}\n\nfunction getNestedProperty(value: TypedValue, key: string): (TypedValue | TypedValue[] | undefined)[] {\n const [firstProp, ...nestedProps] = key.split('.');\n let propertyValues = [getTypedPropertyValue(value, firstProp)];\n for (const prop of nestedProps) {\n const next = [];\n for (const current of propertyValues) {\n if (current === undefined) {\n continue;\n } else if (Array.isArray(current)) {\n for (const element of current) {\n next.push(getTypedPropertyValue(element, prop));\n }\n } else {\n next.push(getTypedPropertyValue(current, prop));\n }\n }\n propertyValues = next;\n }\n return propertyValues;\n}\n"],"names":[],"mappings":";;;;;;;;AAQA;;;;;AAKG;AACH,MAAM,gBAAgB,GAA2B;AAC/C,IAAA,YAAY,EAAE,QAAQ;AACtB,IAAA,OAAO,EAAE,SAAS;AAClB,IAAA,SAAS,EAAE,QAAQ;AACnB,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,QAAQ,EAAE,QAAQ;AAClB,IAAA,OAAO,EAAE,QAAQ;AACjB,IAAA,EAAE,EAAE,QAAQ;AACZ,IAAA,OAAO,EAAE,QAAQ;AACjB,IAAA,OAAO,EAAE,QAAQ;AACjB,IAAA,QAAQ,EAAE,QAAQ;AAClB,IAAA,GAAG,EAAE,QAAQ;AACb,IAAA,WAAW,EAAE,QAAQ;AACrB,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,WAAW,EAAE,QAAQ;AACrB,IAAA,GAAG,EAAE,QAAQ;AACb,IAAA,GAAG,EAAE,QAAQ;AACb,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,KAAK,EAAE,QAAQ;IACf,uCAAuC,EAAE,QAAQ;CAClD,CAAC;AAEF;;;;;AAKG;AACH,MAAM,iBAAiB,GAA2B;AAChD,IAAA,YAAY,EAAE,2DAA2D;AAC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,CAAC,YAAY,GAAG,KAAK,CAAC,EAAE;YAC9C,SAAS;AACV,SAAA;QACD,MAAM,kBAAkB,GAAG,qBAAqB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;QAC3E,OAAO,CAAC,CAAC,kBAAkB,CAAC;AAC7B,KAAA;AACD,IAAA,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAiB,EAAE,GAAW,EAAA;AACvD,IAAA,MAAM,CAAC,SAAS,EAAE,GAAG,WAAW,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnD,IAAI,cAAc,GAAG,CAAC,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;AAC/D,IAAA,KAAK,MAAM,IAAI,IAAI,WAAW,EAAE;QAC9B,MAAM,IAAI,GAAG,EAAE,CAAC;AAChB,QAAA,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE;YACpC,IAAI,OAAO,KAAK,SAAS,EAAE;gBACzB,SAAS;AACV,aAAA;AAAM,iBAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;AACjC,gBAAA,KAAK,MAAM,OAAO,IAAI,OAAO,EAAE;oBAC7B,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;AACjD,iBAAA;AACF,aAAA;AAAM,iBAAA;gBACL,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;AACjD,aAAA;AACF,SAAA;QACD,cAAc,GAAG,IAAI,CAAC;AACvB,KAAA;AACD,IAAA,OAAO,cAAc,CAAC;AACxB;;;;"}
|
package/dist/esm/utils.mjs
CHANGED
|
@@ -452,7 +452,7 @@ function isLowerCase(c) {
|
|
|
452
452
|
* @returns The code if found; otherwise undefined.
|
|
453
453
|
*/
|
|
454
454
|
function getCodeBySystem(concept, system) {
|
|
455
|
-
return concept
|
|
455
|
+
return concept.coding?.find((coding) => coding.system === system)?.code;
|
|
456
456
|
}
|
|
457
457
|
/**
|
|
458
458
|
* Sets a code for a given system within a given codeable concept.
|
|
@@ -464,12 +464,12 @@ function setCodeBySystem(concept, system, code) {
|
|
|
464
464
|
if (!concept.coding) {
|
|
465
465
|
concept.coding = [];
|
|
466
466
|
}
|
|
467
|
-
const coding = concept.coding
|
|
467
|
+
const coding = concept.coding.find((c) => c.system === system);
|
|
468
468
|
if (coding) {
|
|
469
469
|
coding.code = code;
|
|
470
470
|
}
|
|
471
471
|
else {
|
|
472
|
-
concept.coding
|
|
472
|
+
concept.coding.push({ system, code });
|
|
473
473
|
}
|
|
474
474
|
}
|
|
475
475
|
/**
|
package/dist/esm/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sources":["../../src/utils.ts"],"sourcesContent":["import {\n Attachment,\n CodeableConcept,\n Device,\n Extension,\n Identifier,\n ObservationDefinition,\n ObservationDefinitionQualifiedInterval,\n Patient,\n Practitioner,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n Range,\n Reference,\n RelatedPerson,\n Resource,\n} from '@medplum/fhirtypes';\nimport { formatHumanName } from './format';\n\n/**\n * @internal\n */\nexport type ProfileResource = Patient | Practitioner | RelatedPerson;\n\ninterface Code {\n code?: CodeableConcept;\n}\n/**\n * @internal\n */\nexport type ResourceWithCode = Resource & Code;\n\n/**\n * Creates a reference resource.\n * @param resource The FHIR reesource.\n * @returns A reference resource.\n */\nexport function createReference<T extends Resource>(resource: T): Reference<T> {\n const reference = getReferenceString(resource);\n const display = getDisplayString(resource);\n return display === reference ? { reference } : { reference, display };\n}\n\n/**\n * Returns a reference string for a resource.\n * @param resource The FHIR resource.\n * @returns A reference string of the form resourceType/id.\n */\nexport function getReferenceString(resource: Resource): string {\n return resource.resourceType + '/' + resource.id;\n}\n\n/**\n * Returns the ID portion of a reference.\n * @param reference A FHIR reference.\n * @returns The ID portion of a reference.\n */\nexport function resolveId(reference: Reference | undefined): string | undefined {\n return reference?.reference?.split('/')[1];\n}\n\n/**\n * Returns true if the resource is a \"ProfileResource\".\n * @param resource The FHIR resource.\n * @returns True if the resource is a \"ProfileResource\".\n */\nexport function isProfileResource(resource: Resource): resource is ProfileResource {\n return (\n resource.resourceType === 'Patient' ||\n resource.resourceType === 'Practitioner' ||\n resource.resourceType === 'RelatedPerson'\n );\n}\n\n/**\n * Returns a display string for the resource.\n * @param resource The input resource.\n * @returns Human friendly display string.\n */\nexport function getDisplayString(resource: Resource): string {\n if (isProfileResource(resource)) {\n const profileName = getProfileResourceDisplayString(resource);\n if (profileName) {\n return profileName;\n }\n }\n if (resource.resourceType === 'Device') {\n const deviceName = getDeviceDisplayString(resource);\n if (deviceName) {\n return deviceName;\n }\n }\n if (resource.resourceType === 'Observation') {\n if ('code' in resource && resource.code?.text) {\n return resource.code.text;\n }\n }\n if (resource.resourceType === 'User') {\n if (resource.email) {\n return resource.email;\n }\n }\n if ('name' in resource && resource.name && typeof resource.name === 'string') {\n return resource.name;\n }\n return getReferenceString(resource);\n}\n\n/**\n * Returns a display string for a profile resource if one is found.\n * @param resource The profile resource.\n * @returns The display name if one is found.\n */\nfunction getProfileResourceDisplayString(resource: ProfileResource): string | undefined {\n const names = resource.name;\n if (names && names.length > 0) {\n return formatHumanName(names[0]);\n }\n return undefined;\n}\n\n/**\n * Returns a display string for a device resource if one is found.\n * @param device The device resource.\n * @returns The display name if one is found.\n */\nfunction getDeviceDisplayString(device: Device): string | undefined {\n const names = device.deviceName;\n if (names && names.length > 0) {\n return names[0].name;\n }\n return undefined;\n}\n\n/**\n * Returns an image URL for the resource, if one is available.\n * @param resource The input resource.\n * @returns The image URL for the resource or undefined.\n */\nexport function getImageSrc(resource: Resource): string | undefined {\n if (!('photo' in resource)) {\n return undefined;\n }\n\n const photo = resource.photo;\n if (!photo) {\n return undefined;\n }\n\n if (Array.isArray(photo)) {\n for (const p of photo) {\n const url = getPhotoImageSrc(p);\n if (url) {\n return url;\n }\n }\n } else {\n return getPhotoImageSrc(photo);\n }\n\n return undefined;\n}\n\nfunction getPhotoImageSrc(photo: Attachment): string | undefined {\n if (photo.url && photo.contentType && photo.contentType.startsWith('image/')) {\n return photo.url;\n }\n return undefined;\n}\n\n/**\n * Returns a Date property as a Date.\n * When working with JSON objects, Dates are often serialized as ISO-8601 strings.\n * When that happens, we need to safely convert to a proper Date object.\n * @param date The date property value, which could be a string or a Date object.\n * @returns A Date object.\n */\nexport function getDateProperty(date: string | undefined): Date | undefined {\n return date ? new Date(date) : undefined;\n}\n\n/**\n * Calculates the age in years from the birth date.\n * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.\n * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.\n * @returns The age in years, months, and days.\n */\nexport function calculateAge(\n birthDateStr: string,\n endDateStr?: string\n): { years: number; months: number; days: number } {\n const startDate = new Date(birthDateStr);\n startDate.setUTCHours(0, 0, 0, 0);\n\n const endDate = endDateStr ? new Date(endDateStr) : new Date();\n endDate.setUTCHours(0, 0, 0, 0);\n\n const startYear = startDate.getUTCFullYear();\n const startMonth = startDate.getUTCMonth();\n const startDay = startDate.getUTCDate();\n\n const endYear = endDate.getUTCFullYear();\n const endMonth = endDate.getUTCMonth();\n const endDay = endDate.getUTCDate();\n\n let years = endYear - startYear;\n if (endMonth < startMonth || (endMonth === startMonth && endDay < startDay)) {\n years--;\n }\n\n let months = endYear * 12 + endMonth - (startYear * 12 + startMonth);\n if (endDay < startDay) {\n months--;\n }\n\n const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));\n\n return { years, months, days };\n}\n\n/**\n * Calculates the age string for display using the age appropriate units.\n * If the age is greater than or equal to 2 years, then the age is displayed in years.\n * If the age is greater than or equal to 1 month, then the age is displayed in months.\n * Otherwise, the age is displayed in days.\n * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.\n * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.\n * @returns The age string.\n */\nexport function calculateAgeString(birthDateStr: string, endDateStr?: string): string | undefined {\n const { years, months, days } = calculateAge(birthDateStr, endDateStr);\n if (years >= 2) {\n return years.toString().padStart(3, '0') + 'Y';\n } else if (months >= 1) {\n return months.toString().padStart(3, '0') + 'M';\n } else {\n return days.toString().padStart(3, '0') + 'D';\n }\n}\n\n/**\n * Returns all questionnaire answers as a map by link ID.\n * @param response The questionnaire response resource.\n * @returns Questionnaire answers mapped by link ID.\n */\nexport function getQuestionnaireAnswers(\n response: QuestionnaireResponse\n): Record<string, QuestionnaireResponseItemAnswer> {\n const result: Record<string, QuestionnaireResponseItemAnswer> = {};\n buildQuestionnaireAnswerItems(response.item, result);\n return result;\n}\n\n/**\n * Recursively builds the questionnaire answer items map.\n * @param items The current questionnaire response items.\n * @param result The cumulative result map.\n */\nfunction buildQuestionnaireAnswerItems(\n items: QuestionnaireResponseItem[] | undefined,\n result: Record<string, QuestionnaireResponseItemAnswer>\n): void {\n if (items) {\n for (const item of items) {\n if (item.linkId && item.answer && item.answer.length > 0) {\n result[item.linkId] = item.answer[0];\n }\n buildQuestionnaireAnswerItems(item.item, result);\n }\n }\n}\n\n/**\n * Returns the resource identifier for the given system.\n *\n * If multiple identifiers exist with the same system, the first one is returned.\n *\n * If the system is not found, then returns undefined.\n * @param resource The resource to check.\n * @param system The identifier system.\n * @returns The identifier value if found; otherwise undefined.\n */\nexport function getIdentifier(resource: Resource, system: string): string | undefined {\n const identifiers = (resource as any).identifier as Identifier[] | Identifier | undefined;\n if (!identifiers) {\n return undefined;\n }\n const array = Array.isArray(identifiers) ? identifiers : [identifiers];\n for (const identifier of array) {\n if (identifier.system === system) {\n return identifier.value;\n }\n }\n return undefined;\n}\n\n/**\n * Returns an extension value by extension URLs.\n * @param resource The base resource.\n * @param urls Array of extension URLs. Each entry represents a nested extension.\n * @returns The extension value if found; undefined otherwise.\n */\nexport function getExtensionValue(resource: any, ...urls: string[]): string | undefined {\n // Let curr be the current resource or extension. Extensions can be nested.\n let curr: any = resource;\n\n // For each of the urls, try to find a matching nested extension.\n for (let i = 0; i < urls.length && curr; i++) {\n curr = (curr?.extension as Extension[] | undefined)?.find((e) => e.url === urls[i]);\n }\n\n return curr?.valueString as string | undefined;\n}\n\n/**\n * Returns an extension by extension URLs.\n * @param resource The base resource.\n * @param urls Array of extension URLs. Each entry represents a nested extension.\n * @returns The extension object if found; undefined otherwise.\n */\nexport function getExtension(resource: any, ...urls: string[]): Extension | undefined {\n // Let curr be the current resource or extension. Extensions can be nested.\n let curr: any = resource;\n\n // For each of the urls, try to find a matching nested extension.\n for (let i = 0; i < urls.length && curr; i++) {\n curr = (curr?.extension as Extension[] | undefined)?.find((e) => e.url === urls[i]);\n }\n\n return curr as Extension | undefined;\n}\n\n/**\n * FHIR JSON stringify.\n * Removes properties with empty string values.\n * Removes objects with zero properties.\n * See: https://www.hl7.org/fhir/json.html\n * @param value The input value.\n * @param pretty Optional flag to pretty-print the JSON.\n * @returns The resulting JSON string.\n */\nexport function stringify(value: any, pretty?: boolean): string {\n return JSON.stringify(value, stringifyReplacer, pretty ? 2 : undefined);\n}\n\n/**\n * Evaluates JSON key/value pairs for FHIR JSON stringify.\n * Removes properties with empty string values.\n * Removes objects with zero properties.\n * @param k Property key.\n * @param v Property value.\n * @returns The replaced value.\n */\nfunction stringifyReplacer(k: string, v: any): any {\n return !isArrayKey(k) && isEmpty(v) ? undefined : v;\n}\n\n/**\n * Returns true if the key is an array key.\n * @param k The property key.\n * @returns True if the key is an array key.\n */\nfunction isArrayKey(k: string): boolean {\n return !!k.match(/\\d+$/);\n}\n\n/**\n * Returns true if the value is empty (null, undefined, empty string, or empty object).\n * @param v Any value.\n * @returns True if the value is an empty string or an empty object.\n */\nexport function isEmpty(v: any): boolean {\n if (v === null || v === undefined) {\n return true;\n }\n const t = typeof v;\n return (t === 'string' && v === '') || (t === 'object' && Object.keys(v).length === 0);\n}\n\n/**\n * Resource equality.\n * Ignores meta.versionId and meta.lastUpdated.\n * @param object1 The first object.\n * @param object2 The second object.\n * @param path Optional path string.\n * @returns True if the objects are equal.\n */\nexport function deepEquals(object1: unknown, object2: unknown, path?: string): boolean {\n if (object1 === object2) {\n return true;\n }\n if (isEmpty(object1) && isEmpty(object2)) {\n return true;\n }\n if (isEmpty(object1) || isEmpty(object2)) {\n return false;\n }\n if (Array.isArray(object1) && Array.isArray(object2)) {\n return deepEqualsArray(object1, object2);\n }\n if (Array.isArray(object1) || Array.isArray(object2)) {\n return false;\n }\n if (isObject(object1) && isObject(object2)) {\n return deepEqualsObject(object1, object2, path);\n }\n if (isObject(object1) || isObject(object2)) {\n return false;\n }\n return false;\n}\n\nfunction deepEqualsArray(array1: unknown[], array2: unknown[]): boolean {\n if (array1.length !== array2.length) {\n return false;\n }\n for (let i = 0; i < array1.length; i++) {\n if (!deepEquals(array1[i], array2[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction deepEqualsObject(\n object1: Record<string, unknown>,\n object2: Record<string, unknown>,\n path: string | undefined\n): boolean {\n const keySet = new Set<string>();\n Object.keys(object1).forEach((k) => keySet.add(k));\n Object.keys(object2).forEach((k) => keySet.add(k));\n if (path === 'meta') {\n keySet.delete('versionId');\n keySet.delete('lastUpdated');\n keySet.delete('author');\n }\n for (const key of keySet) {\n const val1 = object1[key];\n const val2 = object2[key];\n if (!deepEquals(val1, val2, key)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Creates a deep clone of the input value.\n *\n * Limitations:\n * - Only supports JSON primitives and arrays.\n * - Does not support Functions, lambdas, etc.\n * - Does not support circular references.\n *\n * See: https://web.dev/structured-clone/\n * See: https://stackoverflow.com/questions/40488190/how-is-structured-clone-algorithm-different-from-deep-copy\n * @param input The input to clone.\n * @returns A deep clone of the input.\n */\nexport function deepClone<T>(input: T): T {\n return JSON.parse(JSON.stringify(input)) as T;\n}\n\n/**\n * Returns true if the input string is a UUID.\n * @param input The input string.\n * @returns True if the input string matches the UUID format.\n */\nexport function isUUID(input: string): boolean {\n return !!input.match(/^\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$/i);\n}\n\n/**\n * Returns true if the input is an object.\n * @param obj The candidate object.\n * @returns True if the input is a non-null non-undefined object.\n */\nexport function isObject(obj: unknown): obj is Record<string, unknown> {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n * Returns true if the input array is an array of strings.\n * @param arr Input array.\n * @returns True if the input array is an array of strings.\n */\nexport function isStringArray(arr: any[]): arr is string[] {\n return arr.every((e) => typeof e === 'string');\n}\n\n// Precompute hex octets\n// See: https://stackoverflow.com/a/55200387\nconst byteToHex: string[] = [];\nfor (let n = 0; n < 256; n++) {\n byteToHex.push(n.toString(16).padStart(2, '0'));\n}\n\n/**\n * Converts an ArrayBuffer to hex string.\n * See: https://stackoverflow.com/a/55200387\n * @param arrayBuffer The input array buffer.\n * @returns The resulting hex string.\n */\nexport function arrayBufferToHex(arrayBuffer: ArrayBuffer): string {\n const bytes = new Uint8Array(arrayBuffer);\n const result: string[] = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n result[i] = byteToHex[bytes[i]];\n }\n return result.join('');\n}\n\n/**\n * Converts an ArrayBuffer to a base-64 encoded string.\n * @param arrayBuffer The input array buffer.\n * @returns The base-64 encoded string.\n */\nexport function arrayBufferToBase64(arrayBuffer: ArrayBuffer): string {\n const bytes = new Uint8Array(arrayBuffer);\n const result: string[] = [];\n for (let i = 0; i < bytes.length; i++) {\n result[i] = String.fromCharCode(bytes[i]);\n }\n return window.btoa(result.join(''));\n}\n\nexport function capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.substring(1);\n}\n\nexport function isLowerCase(c: string): boolean {\n return c === c.toLowerCase() && c !== c.toUpperCase();\n}\n\n/**\n * Tries to find a code string for a given system within a given codeable concept.\n * @param concept The codeable concept.\n * @param system The system string.\n * @returns The code if found; otherwise undefined.\n */\nexport function getCodeBySystem(concept: CodeableConcept, system: string): string | undefined {\n return concept?.coding?.find((coding) => coding.system === system)?.code;\n}\n\n/**\n * Sets a code for a given system within a given codeable concept.\n * @param concept The codeable concept.\n * @param system The system string.\n * @param code The code value.\n */\nexport function setCodeBySystem(concept: CodeableConcept, system: string, code: string): void {\n if (!concept.coding) {\n concept.coding = [];\n }\n const coding = concept.coding?.find((c) => c.system === system);\n if (coding) {\n coding.code = code;\n } else {\n concept.coding?.push({ system, code });\n }\n}\n\n/**\n * Tries to find an observation interval for the given patient and value.\n * @param definition The observation definition.\n * @param patient The patient.\n * @param value The observation value.\n * @param category Optional interval category restriction.\n * @returns The observation interval if found; otherwise undefined.\n */\nexport function findObservationInterval(\n definition: ObservationDefinition,\n patient: Patient,\n value: number,\n category?: 'reference' | 'critical' | 'absolute'\n): ObservationDefinitionQualifiedInterval | undefined {\n return definition.qualifiedInterval?.find(\n (interval) =>\n observationIntervalMatchesPatient(interval, patient) &&\n observationIntervalMatchesValue(interval, value, definition.quantitativeDetails?.decimalPrecision) &&\n (category === undefined || interval.category === category)\n );\n}\n\n/**\n * Tries to find an observation reference range for the given patient and condition names.\n * @param definition The observation definition.\n * @param patient The patient.\n * @param names The condition names.\n * @returns The observation interval if found; otherwise undefined.\n */\nexport function findObservationReferenceRange(\n definition: ObservationDefinition,\n patient: Patient,\n names: string[]\n): ObservationDefinitionQualifiedInterval | undefined {\n return definition.qualifiedInterval?.find(\n (interval) => observationIntervalMatchesPatient(interval, patient) && names.includes(interval.condition as string)\n );\n}\n\n/**\n * Returns true if the patient matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient matches the observation interval.\n */\nfunction observationIntervalMatchesPatient(\n interval: ObservationDefinitionQualifiedInterval,\n patient: Patient\n): boolean {\n return observationIntervalMatchesGender(interval, patient) && observationIntervalMatchesAge(interval, patient);\n}\n\n/**\n * Returns true if the patient gender matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient gender matches the observation interval.\n */\nfunction observationIntervalMatchesGender(interval: ObservationDefinitionQualifiedInterval, patient: Patient): boolean {\n return !interval.gender || interval.gender === patient.gender;\n}\n\n/**\n * Returns true if the patient age matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient age matches the observation interval.\n */\nfunction observationIntervalMatchesAge(interval: ObservationDefinitionQualifiedInterval, patient: Patient): boolean {\n return !interval.age || matchesRange(calculateAge(patient.birthDate as string).years, interval.age);\n}\n\n/**\n * Returns true if the value matches the observation interval.\n * @param interval The observation interval.\n * @param value The observation value.\n * @param precision Optional precision in number of digits.\n * @returns True if the value matches the observation interval.\n */\nfunction observationIntervalMatchesValue(\n interval: ObservationDefinitionQualifiedInterval,\n value: number,\n precision?: number\n): boolean {\n return !!interval.range && matchesRange(value, interval.range, precision);\n}\n\n/**\n * Returns true if the value is in the range accounting for precision.\n * @param value The numeric value.\n * @param range The numeric range.\n * @param precision Optional precision in number of digits.\n * @returns True if the value is within the range.\n */\nexport function matchesRange(value: number, range: Range, precision?: number): boolean {\n return (\n (range.low?.value === undefined || preciseGreaterThanOrEquals(value, range.low.value, precision)) &&\n (range.high?.value === undefined || preciseLessThanOrEquals(value, range.high.value, precision))\n );\n}\n\n/**\n * Returns the input number rounded to the specified number of digits.\n * @param a The input number.\n * @param precision The precision in number of digits.\n * @returns The number rounded to the specified number of digits.\n */\nexport function preciseRound(a: number, precision: number): number {\n return parseFloat(a.toFixed(precision));\n}\n\n/**\n * Returns true if the two numbers are equal to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the two numbers are equal to the given precision.\n */\nexport function preciseEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) === toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is less than the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is less than the second number to the given precision.\n */\nexport function preciseLessThan(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) < toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is greater than the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is greater than the second number to the given precision.\n */\nexport function preciseGreaterThan(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) > toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is less than or equal to the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is less than or equal to the second number to the given precision.\n */\nexport function preciseLessThanOrEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) <= toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is greater than or equal to the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is greater than or equal to the second number to the given precision.\n */\nexport function preciseGreaterThanOrEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) >= toPreciseInteger(b, precision);\n}\n\n/**\n * Returns an integer representation of the number with the given precision.\n * For example, if precision is 2, then 1.2345 will be returned as 123.\n * @param a The number.\n * @param precision Optional precision in number of digits.\n * @returns The integer with the given precision.\n */\nfunction toPreciseInteger(a: number, precision?: number): number {\n if (precision === undefined) {\n return a;\n }\n return Math.round(a * Math.pow(10, precision));\n}\n\n/**\n * Finds the first resource in the input array that matches the specified code and system.\n * @param resources - The array of resources to search.\n * @param code - The code to search for.\n * @param system - The system to search for.\n * @returns The first resource in the input array that matches the specified code and system, or undefined if no such resource is found.\n */\nexport function findResourceByCode(\n resources: ResourceWithCode[],\n code: CodeableConcept | string,\n system: string\n): ResourceWithCode | undefined {\n return resources.find((r) =>\n typeof code === 'string'\n ? getCodeBySystem(r.code || {}, system) === code\n : getCodeBySystem(r.code || {}, system) === getCodeBySystem(code, system)\n );\n}\n"],"names":[],"mappings":";;AAiCA;;;;AAIG;AACG,SAAU,eAAe,CAAqB,Q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Identifier,\n ObservationDefinition,\n ObservationDefinitionQualifiedInterval,\n Patient,\n Practitioner,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n Range,\n Reference,\n RelatedPerson,\n Resource,\n} from '@medplum/fhirtypes';\nimport { formatHumanName } from './format';\n\n/**\n * @internal\n */\nexport type ProfileResource = Patient | Practitioner | RelatedPerson;\n\ninterface Code {\n code?: CodeableConcept;\n}\n/**\n * @internal\n */\nexport type ResourceWithCode = Resource & Code;\n\n/**\n * Creates a reference resource.\n * @param resource The FHIR reesource.\n * @returns A reference resource.\n */\nexport function createReference<T extends Resource>(resource: T): Reference<T> {\n const reference = getReferenceString(resource);\n const display = getDisplayString(resource);\n return display === reference ? { reference } : { reference, display };\n}\n\n/**\n * Returns a reference string for a resource.\n * @param resource The FHIR resource.\n * @returns A reference string of the form resourceType/id.\n */\nexport function getReferenceString(resource: Resource): string {\n return resource.resourceType + '/' + resource.id;\n}\n\n/**\n * Returns the ID portion of a reference.\n * @param reference A FHIR reference.\n * @returns The ID portion of a reference.\n */\nexport function resolveId(reference: Reference | undefined): string | undefined {\n return reference?.reference?.split('/')[1];\n}\n\n/**\n * Returns true if the resource is a \"ProfileResource\".\n * @param resource The FHIR resource.\n * @returns True if the resource is a \"ProfileResource\".\n */\nexport function isProfileResource(resource: Resource): resource is ProfileResource {\n return (\n resource.resourceType === 'Patient' ||\n resource.resourceType === 'Practitioner' ||\n resource.resourceType === 'RelatedPerson'\n );\n}\n\n/**\n * Returns a display string for the resource.\n * @param resource The input resource.\n * @returns Human friendly display string.\n */\nexport function getDisplayString(resource: Resource): string {\n if (isProfileResource(resource)) {\n const profileName = getProfileResourceDisplayString(resource);\n if (profileName) {\n return profileName;\n }\n }\n if (resource.resourceType === 'Device') {\n const deviceName = getDeviceDisplayString(resource);\n if (deviceName) {\n return deviceName;\n }\n }\n if (resource.resourceType === 'Observation') {\n if ('code' in resource && resource.code?.text) {\n return resource.code.text;\n }\n }\n if (resource.resourceType === 'User') {\n if (resource.email) {\n return resource.email;\n }\n }\n if ('name' in resource && resource.name && typeof resource.name === 'string') {\n return resource.name;\n }\n return getReferenceString(resource);\n}\n\n/**\n * Returns a display string for a profile resource if one is found.\n * @param resource The profile resource.\n * @returns The display name if one is found.\n */\nfunction getProfileResourceDisplayString(resource: ProfileResource): string | undefined {\n const names = resource.name;\n if (names && names.length > 0) {\n return formatHumanName(names[0]);\n }\n return undefined;\n}\n\n/**\n * Returns a display string for a device resource if one is found.\n * @param device The device resource.\n * @returns The display name if one is found.\n */\nfunction getDeviceDisplayString(device: Device): string | undefined {\n const names = device.deviceName;\n if (names && names.length > 0) {\n return names[0].name;\n }\n return undefined;\n}\n\n/**\n * Returns an image URL for the resource, if one is available.\n * @param resource The input resource.\n * @returns The image URL for the resource or undefined.\n */\nexport function getImageSrc(resource: Resource): string | undefined {\n if (!('photo' in resource)) {\n return undefined;\n }\n\n const photo = resource.photo;\n if (!photo) {\n return undefined;\n }\n\n if (Array.isArray(photo)) {\n for (const p of photo) {\n const url = getPhotoImageSrc(p);\n if (url) {\n return url;\n }\n }\n } else {\n return getPhotoImageSrc(photo);\n }\n\n return undefined;\n}\n\nfunction getPhotoImageSrc(photo: Attachment): string | undefined {\n if (photo.url && photo.contentType && photo.contentType.startsWith('image/')) {\n return photo.url;\n }\n return undefined;\n}\n\n/**\n * Returns a Date property as a Date.\n * When working with JSON objects, Dates are often serialized as ISO-8601 strings.\n * When that happens, we need to safely convert to a proper Date object.\n * @param date The date property value, which could be a string or a Date object.\n * @returns A Date object.\n */\nexport function getDateProperty(date: string | undefined): Date | undefined {\n return date ? new Date(date) : undefined;\n}\n\n/**\n * Calculates the age in years from the birth date.\n * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.\n * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.\n * @returns The age in years, months, and days.\n */\nexport function calculateAge(\n birthDateStr: string,\n endDateStr?: string\n): { years: number; months: number; days: number } {\n const startDate = new Date(birthDateStr);\n startDate.setUTCHours(0, 0, 0, 0);\n\n const endDate = endDateStr ? new Date(endDateStr) : new Date();\n endDate.setUTCHours(0, 0, 0, 0);\n\n const startYear = startDate.getUTCFullYear();\n const startMonth = startDate.getUTCMonth();\n const startDay = startDate.getUTCDate();\n\n const endYear = endDate.getUTCFullYear();\n const endMonth = endDate.getUTCMonth();\n const endDay = endDate.getUTCDate();\n\n let years = endYear - startYear;\n if (endMonth < startMonth || (endMonth === startMonth && endDay < startDay)) {\n years--;\n }\n\n let months = endYear * 12 + endMonth - (startYear * 12 + startMonth);\n if (endDay < startDay) {\n months--;\n }\n\n const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));\n\n return { years, months, days };\n}\n\n/**\n * Calculates the age string for display using the age appropriate units.\n * If the age is greater than or equal to 2 years, then the age is displayed in years.\n * If the age is greater than or equal to 1 month, then the age is displayed in months.\n * Otherwise, the age is displayed in days.\n * @param birthDateStr The birth date or start date in ISO-8601 format YYYY-MM-DD.\n * @param endDateStr Optional end date in ISO-8601 format YYYY-MM-DD. Default value is today.\n * @returns The age string.\n */\nexport function calculateAgeString(birthDateStr: string, endDateStr?: string): string | undefined {\n const { years, months, days } = calculateAge(birthDateStr, endDateStr);\n if (years >= 2) {\n return years.toString().padStart(3, '0') + 'Y';\n } else if (months >= 1) {\n return months.toString().padStart(3, '0') + 'M';\n } else {\n return days.toString().padStart(3, '0') + 'D';\n }\n}\n\n/**\n * Returns all questionnaire answers as a map by link ID.\n * @param response The questionnaire response resource.\n * @returns Questionnaire answers mapped by link ID.\n */\nexport function getQuestionnaireAnswers(\n response: QuestionnaireResponse\n): Record<string, QuestionnaireResponseItemAnswer> {\n const result: Record<string, QuestionnaireResponseItemAnswer> = {};\n buildQuestionnaireAnswerItems(response.item, result);\n return result;\n}\n\n/**\n * Recursively builds the questionnaire answer items map.\n * @param items The current questionnaire response items.\n * @param result The cumulative result map.\n */\nfunction buildQuestionnaireAnswerItems(\n items: QuestionnaireResponseItem[] | undefined,\n result: Record<string, QuestionnaireResponseItemAnswer>\n): void {\n if (items) {\n for (const item of items) {\n if (item.linkId && item.answer && item.answer.length > 0) {\n result[item.linkId] = item.answer[0];\n }\n buildQuestionnaireAnswerItems(item.item, result);\n }\n }\n}\n\n/**\n * Returns the resource identifier for the given system.\n *\n * If multiple identifiers exist with the same system, the first one is returned.\n *\n * If the system is not found, then returns undefined.\n * @param resource The resource to check.\n * @param system The identifier system.\n * @returns The identifier value if found; otherwise undefined.\n */\nexport function getIdentifier(resource: Resource, system: string): string | undefined {\n const identifiers = (resource as any).identifier as Identifier[] | Identifier | undefined;\n if (!identifiers) {\n return undefined;\n }\n const array = Array.isArray(identifiers) ? identifiers : [identifiers];\n for (const identifier of array) {\n if (identifier.system === system) {\n return identifier.value;\n }\n }\n return undefined;\n}\n\n/**\n * Returns an extension value by extension URLs.\n * @param resource The base resource.\n * @param urls Array of extension URLs. Each entry represents a nested extension.\n * @returns The extension value if found; undefined otherwise.\n */\nexport function getExtensionValue(resource: any, ...urls: string[]): string | undefined {\n // Let curr be the current resource or extension. Extensions can be nested.\n let curr: any = resource;\n\n // For each of the urls, try to find a matching nested extension.\n for (let i = 0; i < urls.length && curr; i++) {\n curr = (curr?.extension as Extension[] | undefined)?.find((e) => e.url === urls[i]);\n }\n\n return curr?.valueString as string | undefined;\n}\n\n/**\n * Returns an extension by extension URLs.\n * @param resource The base resource.\n * @param urls Array of extension URLs. Each entry represents a nested extension.\n * @returns The extension object if found; undefined otherwise.\n */\nexport function getExtension(resource: any, ...urls: string[]): Extension | undefined {\n // Let curr be the current resource or extension. Extensions can be nested.\n let curr: any = resource;\n\n // For each of the urls, try to find a matching nested extension.\n for (let i = 0; i < urls.length && curr; i++) {\n curr = (curr?.extension as Extension[] | undefined)?.find((e) => e.url === urls[i]);\n }\n\n return curr as Extension | undefined;\n}\n\n/**\n * FHIR JSON stringify.\n * Removes properties with empty string values.\n * Removes objects with zero properties.\n * See: https://www.hl7.org/fhir/json.html\n * @param value The input value.\n * @param pretty Optional flag to pretty-print the JSON.\n * @returns The resulting JSON string.\n */\nexport function stringify(value: any, pretty?: boolean): string {\n return JSON.stringify(value, stringifyReplacer, pretty ? 2 : undefined);\n}\n\n/**\n * Evaluates JSON key/value pairs for FHIR JSON stringify.\n * Removes properties with empty string values.\n * Removes objects with zero properties.\n * @param k Property key.\n * @param v Property value.\n * @returns The replaced value.\n */\nfunction stringifyReplacer(k: string, v: any): any {\n return !isArrayKey(k) && isEmpty(v) ? undefined : v;\n}\n\n/**\n * Returns true if the key is an array key.\n * @param k The property key.\n * @returns True if the key is an array key.\n */\nfunction isArrayKey(k: string): boolean {\n return !!k.match(/\\d+$/);\n}\n\n/**\n * Returns true if the value is empty (null, undefined, empty string, or empty object).\n * @param v Any value.\n * @returns True if the value is an empty string or an empty object.\n */\nexport function isEmpty(v: any): boolean {\n if (v === null || v === undefined) {\n return true;\n }\n const t = typeof v;\n return (t === 'string' && v === '') || (t === 'object' && Object.keys(v).length === 0);\n}\n\n/**\n * Resource equality.\n * Ignores meta.versionId and meta.lastUpdated.\n * @param object1 The first object.\n * @param object2 The second object.\n * @param path Optional path string.\n * @returns True if the objects are equal.\n */\nexport function deepEquals(object1: unknown, object2: unknown, path?: string): boolean {\n if (object1 === object2) {\n return true;\n }\n if (isEmpty(object1) && isEmpty(object2)) {\n return true;\n }\n if (isEmpty(object1) || isEmpty(object2)) {\n return false;\n }\n if (Array.isArray(object1) && Array.isArray(object2)) {\n return deepEqualsArray(object1, object2);\n }\n if (Array.isArray(object1) || Array.isArray(object2)) {\n return false;\n }\n if (isObject(object1) && isObject(object2)) {\n return deepEqualsObject(object1, object2, path);\n }\n if (isObject(object1) || isObject(object2)) {\n return false;\n }\n return false;\n}\n\nfunction deepEqualsArray(array1: unknown[], array2: unknown[]): boolean {\n if (array1.length !== array2.length) {\n return false;\n }\n for (let i = 0; i < array1.length; i++) {\n if (!deepEquals(array1[i], array2[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction deepEqualsObject(\n object1: Record<string, unknown>,\n object2: Record<string, unknown>,\n path: string | undefined\n): boolean {\n const keySet = new Set<string>();\n Object.keys(object1).forEach((k) => keySet.add(k));\n Object.keys(object2).forEach((k) => keySet.add(k));\n if (path === 'meta') {\n keySet.delete('versionId');\n keySet.delete('lastUpdated');\n keySet.delete('author');\n }\n for (const key of keySet) {\n const val1 = object1[key];\n const val2 = object2[key];\n if (!deepEquals(val1, val2, key)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Creates a deep clone of the input value.\n *\n * Limitations:\n * - Only supports JSON primitives and arrays.\n * - Does not support Functions, lambdas, etc.\n * - Does not support circular references.\n *\n * See: https://web.dev/structured-clone/\n * See: https://stackoverflow.com/questions/40488190/how-is-structured-clone-algorithm-different-from-deep-copy\n * @param input The input to clone.\n * @returns A deep clone of the input.\n */\nexport function deepClone<T>(input: T): T {\n return JSON.parse(JSON.stringify(input)) as T;\n}\n\n/**\n * Returns true if the input string is a UUID.\n * @param input The input string.\n * @returns True if the input string matches the UUID format.\n */\nexport function isUUID(input: string): boolean {\n return !!input.match(/^\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$/i);\n}\n\n/**\n * Returns true if the input is an object.\n * @param obj The candidate object.\n * @returns True if the input is a non-null non-undefined object.\n */\nexport function isObject(obj: unknown): obj is Record<string, unknown> {\n return obj !== null && typeof obj === 'object';\n}\n\n/**\n * Returns true if the input array is an array of strings.\n * @param arr Input array.\n * @returns True if the input array is an array of strings.\n */\nexport function isStringArray(arr: any[]): arr is string[] {\n return arr.every((e) => typeof e === 'string');\n}\n\n// Precompute hex octets\n// See: https://stackoverflow.com/a/55200387\nconst byteToHex: string[] = [];\nfor (let n = 0; n < 256; n++) {\n byteToHex.push(n.toString(16).padStart(2, '0'));\n}\n\n/**\n * Converts an ArrayBuffer to hex string.\n * See: https://stackoverflow.com/a/55200387\n * @param arrayBuffer The input array buffer.\n * @returns The resulting hex string.\n */\nexport function arrayBufferToHex(arrayBuffer: ArrayBuffer): string {\n const bytes = new Uint8Array(arrayBuffer);\n const result: string[] = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n result[i] = byteToHex[bytes[i]];\n }\n return result.join('');\n}\n\n/**\n * Converts an ArrayBuffer to a base-64 encoded string.\n * @param arrayBuffer The input array buffer.\n * @returns The base-64 encoded string.\n */\nexport function arrayBufferToBase64(arrayBuffer: ArrayBuffer): string {\n const bytes = new Uint8Array(arrayBuffer);\n const result: string[] = [];\n for (let i = 0; i < bytes.length; i++) {\n result[i] = String.fromCharCode(bytes[i]);\n }\n return window.btoa(result.join(''));\n}\n\nexport function capitalize(word: string): string {\n return word.charAt(0).toUpperCase() + word.substring(1);\n}\n\nexport function isLowerCase(c: string): boolean {\n return c === c.toLowerCase() && c !== c.toUpperCase();\n}\n\n/**\n * Tries to find a code string for a given system within a given codeable concept.\n * @param concept The codeable concept.\n * @param system The system string.\n * @returns The code if found; otherwise undefined.\n */\nexport function getCodeBySystem(concept: CodeableConcept, system: string): string | undefined {\n return concept.coding?.find((coding) => coding.system === system)?.code;\n}\n\n/**\n * Sets a code for a given system within a given codeable concept.\n * @param concept The codeable concept.\n * @param system The system string.\n * @param code The code value.\n */\nexport function setCodeBySystem(concept: CodeableConcept, system: string, code: string): void {\n if (!concept.coding) {\n concept.coding = [];\n }\n const coding = concept.coding.find((c) => c.system === system);\n if (coding) {\n coding.code = code;\n } else {\n concept.coding.push({ system, code });\n }\n}\n\n/**\n * Tries to find an observation interval for the given patient and value.\n * @param definition The observation definition.\n * @param patient The patient.\n * @param value The observation value.\n * @param category Optional interval category restriction.\n * @returns The observation interval if found; otherwise undefined.\n */\nexport function findObservationInterval(\n definition: ObservationDefinition,\n patient: Patient,\n value: number,\n category?: 'reference' | 'critical' | 'absolute'\n): ObservationDefinitionQualifiedInterval | undefined {\n return definition.qualifiedInterval?.find(\n (interval) =>\n observationIntervalMatchesPatient(interval, patient) &&\n observationIntervalMatchesValue(interval, value, definition.quantitativeDetails?.decimalPrecision) &&\n (category === undefined || interval.category === category)\n );\n}\n\n/**\n * Tries to find an observation reference range for the given patient and condition names.\n * @param definition The observation definition.\n * @param patient The patient.\n * @param names The condition names.\n * @returns The observation interval if found; otherwise undefined.\n */\nexport function findObservationReferenceRange(\n definition: ObservationDefinition,\n patient: Patient,\n names: string[]\n): ObservationDefinitionQualifiedInterval | undefined {\n return definition.qualifiedInterval?.find(\n (interval) => observationIntervalMatchesPatient(interval, patient) && names.includes(interval.condition as string)\n );\n}\n\n/**\n * Returns true if the patient matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient matches the observation interval.\n */\nfunction observationIntervalMatchesPatient(\n interval: ObservationDefinitionQualifiedInterval,\n patient: Patient\n): boolean {\n return observationIntervalMatchesGender(interval, patient) && observationIntervalMatchesAge(interval, patient);\n}\n\n/**\n * Returns true if the patient gender matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient gender matches the observation interval.\n */\nfunction observationIntervalMatchesGender(interval: ObservationDefinitionQualifiedInterval, patient: Patient): boolean {\n return !interval.gender || interval.gender === patient.gender;\n}\n\n/**\n * Returns true if the patient age matches the observation interval.\n * @param interval The observation interval.\n * @param patient The patient.\n * @returns True if the patient age matches the observation interval.\n */\nfunction observationIntervalMatchesAge(interval: ObservationDefinitionQualifiedInterval, patient: Patient): boolean {\n return !interval.age || matchesRange(calculateAge(patient.birthDate as string).years, interval.age);\n}\n\n/**\n * Returns true if the value matches the observation interval.\n * @param interval The observation interval.\n * @param value The observation value.\n * @param precision Optional precision in number of digits.\n * @returns True if the value matches the observation interval.\n */\nfunction observationIntervalMatchesValue(\n interval: ObservationDefinitionQualifiedInterval,\n value: number,\n precision?: number\n): boolean {\n return !!interval.range && matchesRange(value, interval.range, precision);\n}\n\n/**\n * Returns true if the value is in the range accounting for precision.\n * @param value The numeric value.\n * @param range The numeric range.\n * @param precision Optional precision in number of digits.\n * @returns True if the value is within the range.\n */\nexport function matchesRange(value: number, range: Range, precision?: number): boolean {\n return (\n (range.low?.value === undefined || preciseGreaterThanOrEquals(value, range.low.value, precision)) &&\n (range.high?.value === undefined || preciseLessThanOrEquals(value, range.high.value, precision))\n );\n}\n\n/**\n * Returns the input number rounded to the specified number of digits.\n * @param a The input number.\n * @param precision The precision in number of digits.\n * @returns The number rounded to the specified number of digits.\n */\nexport function preciseRound(a: number, precision: number): number {\n return parseFloat(a.toFixed(precision));\n}\n\n/**\n * Returns true if the two numbers are equal to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the two numbers are equal to the given precision.\n */\nexport function preciseEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) === toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is less than the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is less than the second number to the given precision.\n */\nexport function preciseLessThan(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) < toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is greater than the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is greater than the second number to the given precision.\n */\nexport function preciseGreaterThan(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) > toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is less than or equal to the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is less than or equal to the second number to the given precision.\n */\nexport function preciseLessThanOrEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) <= toPreciseInteger(b, precision);\n}\n\n/**\n * Returns true if the first number is greater than or equal to the second number to the given precision.\n * @param a The first number.\n * @param b The second number.\n * @param precision Optional precision in number of digits.\n * @returns True if the first number is greater than or equal to the second number to the given precision.\n */\nexport function preciseGreaterThanOrEquals(a: number, b: number, precision?: number): boolean {\n return toPreciseInteger(a, precision) >= toPreciseInteger(b, precision);\n}\n\n/**\n * Returns an integer representation of the number with the given precision.\n * For example, if precision is 2, then 1.2345 will be returned as 123.\n * @param a The number.\n * @param precision Optional precision in number of digits.\n * @returns The integer with the given precision.\n */\nfunction toPreciseInteger(a: number, precision?: number): number {\n if (precision === undefined) {\n return a;\n }\n return Math.round(a * Math.pow(10, precision));\n}\n\n/**\n * Finds the first resource in the input array that matches the specified code and system.\n * @param resources - The array of resources to search.\n * @param code - The code to search for.\n * @param system - The system to search for.\n * @returns The first resource in the input array that matches the specified code and system, or undefined if no such resource is found.\n */\nexport function findResourceByCode(\n resources: ResourceWithCode[],\n code: CodeableConcept | string,\n system: string\n): ResourceWithCode | undefined {\n return resources.find((r) =>\n typeof code === 'string'\n ? getCodeBySystem(r.code || {}, system) === code\n : getCodeBySystem(r.code || {}, system) === getCodeBySystem(code, system)\n );\n}\n"],"names":[],"mappings":";;AAiCA;;;;AAIG;AACG,SAAU,eAAe,CAAqB,QAAW,EAAA;AAC7D,IAAA,MAAM,SAAS,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC;AAC/C,IAAA,MAAM,OAAO,GAAG,gBAAgB,CAAC,QAAQ,CAAC,CAAC;AAC3C,IAAA,OAAO,OAAO,KAAK,SAAS,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AACxE,CAAC;AAED;;;;AAIG;AACG,SAAU,kBAAkB,CAAC,QAAkB,EAAA;IACnD,OAAO,QAAQ,CAAC,YAAY,GAAG,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC;AACnD,CAAC;AAED;;;;AAIG;AACG,SAAU,SAAS,CAAC,SAAgC,EAAA;IACxD,OAAO,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAC7C,CAAC;AAED;;;;AAIG;AACG,SAAU,iBAAiB,CAAC,QAAkB,EAAA;AAClD,I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CAAC;AACV,KAAA;AACD,IAAA,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC;AACjD,CAAC;AAED;;;;;;AAMG;SACa,kBAAkB,CAChC,SAA6B,EAC7B,IAA8B,EAC9B,MAAc,EAAA;AAEd,IAAA,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,KACtB,OAAO,IAAI,KAAK,QAAQ;AACtB,UAAE,eAAe,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,MAAM,CAAC,KAAK,IAAI;AAChD,UAAE,eAAe,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,MAAM,CAAC,KAAK,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAC5E,CAAC;AACJ;;;;"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { AccessPolicy, Resource, ResourceType } from '@medplum/fhirtypes';
|
|
2
|
+
/**
|
|
3
|
+
* Public resource types are in the "public" project.
|
|
4
|
+
* They are available to all users.
|
|
5
|
+
*/
|
|
6
|
+
export declare const publicResourceTypes: string[];
|
|
7
|
+
/**
|
|
8
|
+
* Protected resource types are in the "medplum" project.
|
|
9
|
+
* Reading and writing is limited to the system account.
|
|
10
|
+
*/
|
|
11
|
+
export declare const protectedResourceTypes: string[];
|
|
12
|
+
/**
|
|
13
|
+
* Project admin resource types are special resources that are only
|
|
14
|
+
* accessible to project administrators.
|
|
15
|
+
*/
|
|
16
|
+
export declare const projectAdminResourceTypes: string[];
|
|
17
|
+
/**
|
|
18
|
+
* Determines if the current user can read the specified resource type.
|
|
19
|
+
* @param accessPolicy The access policy.
|
|
20
|
+
* @param resourceType The resource type.
|
|
21
|
+
* @returns True if the current user can read the specified resource type.
|
|
22
|
+
*/
|
|
23
|
+
export declare function canReadResourceType(accessPolicy: AccessPolicy, resourceType: ResourceType): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Determines if the current user can write the specified resource type.
|
|
26
|
+
* This is a preliminary check before evaluating a write operation in depth.
|
|
27
|
+
* If a user cannot write a resource type at all, then don't bother looking up previous versions.
|
|
28
|
+
* @param accessPolicy The access policy.
|
|
29
|
+
* @param resourceType The resource type.
|
|
30
|
+
* @returns True if the current user can write the specified resource type.
|
|
31
|
+
*/
|
|
32
|
+
export declare function canWriteResourceType(accessPolicy: AccessPolicy, resourceType: ResourceType): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Determines if the current user can write the specified resource.
|
|
35
|
+
* This is a more in-depth check after building the candidate result of a write operation.
|
|
36
|
+
* @param accessPolicy The access policy.
|
|
37
|
+
* @param resource The resource.
|
|
38
|
+
* @returns True if the current user can write the specified resource type.
|
|
39
|
+
*/
|
|
40
|
+
export declare function canWriteResource(accessPolicy: AccessPolicy, resource: Resource): boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Returns true if the resource satisfies the current access policy.
|
|
43
|
+
* @param accessPolicy The access policy.
|
|
44
|
+
* @param resource The resource.
|
|
45
|
+
* @param readonlyMode True if the resource is being read.
|
|
46
|
+
* @returns True if the resource matches the access policy.
|
|
47
|
+
*/
|
|
48
|
+
export declare function matchesAccessPolicy(accessPolicy: AccessPolicy, resource: Resource, readonlyMode: boolean): boolean;
|