diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3507a1b0..bbda88d0f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
--
+- tx: `check-system-version` never influences which version of a code system is used (community decision on Zulip, Terminology Service Test Cases, check-system-version semantics): the version is chosen as if it weren't there - from the coding, the value set, `system-version`/`force-system-version`, or the default - and the operation fails (`VALUESET_VERSION_CHECK`) if that version doesn't match. Before, when nothing else named a version, the check's version was used. This includes the edition of an implicit SNOMED CT value set, and `$closure` tables. It is no longer echoed in expansion parameters. `check-valueset-version` is unchanged
+- tx-import: the sqlite-v2 importers (`loinc-v2`, `loinc-v2-classic`, `snomed-v2`, `snomed-v2-from-cache`, `rxnorm-v2`) take the classic importers' options: `-v, --version` for the release's version (`snomed-v2`'s was `--snomed-version`) and `-y, --yes` to replace an existing destination; without `-y` an existing destination is asked about. The earlier names (`--loinc-version`, `--rxnorm-version`, `--snomed-version`, `--overwrite`) still work. Documented in tx/importers/readme.md
### Fixed
@@ -26,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- tests: the ValueSet, ConceptMap and NamingSystem library tests (tests/library/*.tests.js, 104 tests) were never run, as jest runs only *.test.js; renamed, and a test now fails when a file of tests is one jest won't run
- tx: a request with no client side cache over uncachedMaxBodyMB, behind the cluster launcher, mostly got a 502 "the tx process did not answer (EPIPE)", not the 413 too-costly: the process answered and closed the connection with the body still coming. It now takes the rest of the body (without parsing it) and then answers (#461)
- tx: a JSON Bundle (a search page, say) was made in one go: a search for CodeSystems, 200 a page, with no _summary or _elements, made a page of 89 MB and held the server for 3 seconds (tx.fhir.org). A Bundle is now made an entry at a time, letting other requests run between, and written out in its parts (with no ETag: it isn't hashed)
+- The shl module and the VSAC value set database turned on sqlite3's verbose mode, which is for the whole process: every query of every module (the XIG and packages on npm.fhir.org) then captured a stack trace and formatted its arguments, to make the stack of an error longer. It is no longer turned on
### Removed
diff --git a/library/fhir/fhirpath/expression-node.js b/library/fhir/fhirpath/expression-node.js
index 931ab9e1f..df5281e2f 100644
--- a/library/fhir/fhirpath/expression-node.js
+++ b/library/fhir/fhirpath/expression-node.js
@@ -61,7 +61,7 @@ const FUNCTION_CODES = {
ConvertsToQuantity: 'convertsToQuantity', ConvertsToDateTime: 'convertsToDateTime',
ConvertsToDate: 'convertsToDate', ConvertsToTime: 'convertsToTime', ToBoolean: 'toBoolean',
ToInteger: 'toInteger', ToString: 'toString', ToDecimal: 'toDecimal', ToQuantity: 'toQuantity',
- ToDateTime: 'toDateTime', ToTime: 'toTime', ConformsTo: 'conformsTo',
+ ToDateTime: 'toDateTime', ToDate: 'toDate', ToTime: 'toTime', ConformsTo: 'conformsTo',
Round: 'round', Sqrt: 'sqrt', Abs: 'abs', Ceiling: 'ceiling', Exp: 'exp', Floor: 'floor',
Ln: 'ln', Log: 'log', Power: 'power', Truncate: 'truncate',
// R3 functions
@@ -95,7 +95,6 @@ function functionFromCode(name) {
/**
* The name of a function in an expression ('?custom?' for Custom, which has none of its own).
- * (Java's toCode gives 'isTime' for ConvertsToTime; this doesn't follow that.)
* @param {string} f
* @returns {string}
*/
diff --git a/library/fhir/fhirpath/fhirpath-engine.js b/library/fhir/fhirpath/fhirpath-engine.js
index f9c8080cd..0ea6f1052 100644
--- a/library/fhir/fhirpath/fhirpath-engine.js
+++ b/library/fhir/fhirpath/fhirpath-engine.js
@@ -99,9 +99,9 @@ class IssueMessage {
}
}
-/** Java's Function.toCode(): as functionToCode, but ConvertsToTime is 'isTime' */
+/** Java's Function.toCode() */
function toCode(f) {
- return f === Function.ConvertsToTime ? 'isTime' : functionToCode(f);
+ return functionToCode(f);
}
const uncapitalize = (s) => (s ? s.charAt(0).toLowerCase() + s.substring(1) : s);
@@ -1561,6 +1561,10 @@ class FHIRPathEngine {
case Function.ToBoolean:
this.checkContextPrimitive(focus, 'toBoolean', false, exp);
return S(FP_Boolean);
+ case Function.ToDate:
+ // the engines have no Date type of their own: a date is a DateTime, as @2015 and today() are
+ this.checkContextPrimitive(focus, 'toDate', false, exp);
+ return S(FP_DateTime);
case Function.ToDateTime:
this.checkContextPrimitive(focus, 'ToDateTime', false, exp);
return S(FP_DateTime);
diff --git a/library/fhir/fhirpath/parser.js b/library/fhir/fhirpath/parser.js
index 2a6fe19f5..0d14eeeba 100644
--- a/library/fhir/fhirpath/parser.js
+++ b/library/fhir/fhirpath/parser.js
@@ -16,11 +16,9 @@
* was written.
*
* Where this differs from Java's parser:
- * - a unary +/- applies to its operand, as the grammar says ("-a + b" is (-a) + b; Java's
- * parser makes it -(a + b)). In an operator chain, it's a Group, since a Unary node has
- * its own operation
- * - an operator chain starts on the first node of its first operand, also when that operand
- * starts with an indexer (Java's parser puts it on the indexer: "a[0] + b")
+ * - a unary +/- applies to its operand, as the grammar says ("-a + b" is (-a) + b; when the
+ * unary starts the expression, Java's parser makes it -(a + b)). In an operator chain, it's a
+ * Group, since a Unary node has its own operation (as Java's parser has it too)
* - a function's end is after its ')' (Java: after its name)
* - sort()'s arguments can have asc / desc after them: the parameter's `direction`
* - more than one indexer in a row ("a[0][1]") is allowed
@@ -65,7 +63,7 @@ const PARAM_COUNTS = {
HasValue: [0, 0], Encode: [1, 1], Decode: [1, 1], Escape: [1, 1], Unescape: [1, 1],
Trim: [0, 0], Split: [1, 1], Join: [0, 1], HtmlChecks1: [0, 0], HtmlChecks2: [0, 0],
Comparable: [1, 1], ToInteger: [0, 0], ToDecimal: [0, 0], ToString: [0, 0],
- ToQuantity: [0, 0], ToBoolean: [0, 0], ToDateTime: [0, 0], ToTime: [0, 0],
+ ToQuantity: [0, 0], ToBoolean: [0, 0], ToDateTime: [0, 0], ToDate: [0, 0], ToTime: [0, 0],
ConvertsToInteger: [0, 0], ConvertsToDecimal: [0, 0], ConvertsToString: [0, 0],
ConvertsToQuantity: [0, 0], ConvertsToBoolean: [0, 0], ConvertsToDateTime: [0, 0],
ConvertsToDate: [0, 0], ConvertsToTime: [0, 0], ConformsTo: [1, 1], Round: [0, 1],
diff --git a/library/server/config-check.js b/library/server/config-check.js
index ff76d0f91..74f626c69 100644
--- a/library/server/config-check.js
+++ b/library/server/config-check.js
@@ -878,7 +878,7 @@ function checkFile(file, where, report, what) {
}
const SOURCE_TYPES = ['internal', 'ucum', 'loinc', 'rxnorm', 'ndc', 'unii', 'snomed', 'cpt', 'omop', 'icd11',
- 'npm', 'npm/cs', 'url', 'url/cs', 'ocl', 'folder', 'file'];
+ 'snomed-v2', 'loinc-v2', 'rxnorm-v2', 'npm', 'npm/cs', 'url', 'url/cs', 'ocl', 'folder', 'file'];
/**
* The tx library yml: it parses, has a base url, and its sources are type[!]:details[=prefix]
diff --git a/library/server/daily-report.js b/library/server/daily-report.js
index 8685983c5..92adb3d95 100644
--- a/library/server/daily-report.js
+++ b/library/server/daily-report.js
@@ -39,6 +39,7 @@ const MODULE_TITLES = {
tx: 'Terminology server',
registry: 'Terminology server registry',
packages: 'Packages',
+ rest: 'FHIR REST',
xig: 'XIG',
shl: 'SMART Health Links',
ips: 'IPS',
diff --git a/rest/endpoint/endpoint.js b/rest/endpoint/endpoint.js
index e41ab740c..5400dd034 100644
--- a/rest/endpoint/endpoint.js
+++ b/rest/endpoint/endpoint.js
@@ -772,7 +772,13 @@ class Endpoint {
}
} finally {
if (this.options.stats) {
- this.options.stats.countRequest(interaction, Date.now() - start);
+ // under the endpoint, for the daily report (rest.js); a bundle as what it is
+ let name = interaction;
+ if (name === 'bundle') {
+ const type = freq && freq.body && freq.body.type;
+ name = type === 'transaction' || type === 'batch' ? type : 'bundle';
+ }
+ this.options.stats.countRequest(name, Date.now() - start, this.path);
}
}
}
diff --git a/rest/rest.js b/rest/rest.js
index e63e7570a..feafe67b4 100644
--- a/rest/rest.js
+++ b/rest/rest.js
@@ -146,6 +146,48 @@ class RestModule {
return this.endpoints.map(ep => ep.path);
}
+ /**
+ * The module's paragraph in the daily report (library/server/daily-report.js): for each
+ * endpoint, its reads, searches, writes and transactions over the period (and batches,
+ * and anything else, when there were any)
+ */
+ dailyReport({ since, now }) {
+ if (!this.stats) {
+ return null;
+ }
+ const counts = this.stats.countsSince(since, now);
+ // the configured endpoints first, in order, then any counted that aren't configured now
+ const paths = this.endpoints.map(ep => ep.path);
+ for (const p of Object.keys(counts.endpoints || {})) {
+ if (!paths.includes(p)) {
+ paths.push(p);
+ }
+ }
+ if (!paths.length) {
+ return null;
+ }
+ const n = (count, word, plural) => `${count.toLocaleString('en-US')} ${count === 1 ? word : (plural || word + 's')}`;
+ const lines = paths.map(p => {
+ const ops = (counts.endpoints && counts.endpoints[p]) || {};
+ const k = { reads: 0, searches: 0, writes: 0, transactions: 0, batches: 0, other: 0 };
+ for (const [op, c] of Object.entries(ops)) {
+ k[categoryOf(op)] += c;
+ }
+ let line = `- ${p || '(no endpoint)'}: ${n(k.reads, 'read')}, ${n(k.searches, 'search', 'searches')}, ${n(k.writes, 'write')}, ${n(k.transactions, 'transaction')}`;
+ const more = [];
+ if (k.batches) {
+ more.push(n(k.batches, 'batch', 'batches'));
+ }
+ if (k.other) {
+ more.push(n(k.other, 'other request'));
+ }
+ return more.length ? `${line} (and ${more.join(', ')})` : line;
+ });
+ const total = counts.total || 0;
+ const head = total === 0 ? 'No requests were served.' : `${n(total, 'request')} ${total === 1 ? 'was' : 'were'} served.`;
+ return `${head}\n\n${lines.join('\n')}`;
+ }
+
getStatus() {
return { enabled: true, endpoints: this.endpoints.map(ep => ({ path: ep.path, fhirVersion: ep.settings && ep.settings.fhirVersion, database: ep.cfg.database.type })) };
}
@@ -162,4 +204,18 @@ class RestModule {
}
}
+// what each counted interaction is, for the daily report: other is history, operations,
+// capabilities, and requests that weren't a FHIR interaction
+const CATEGORIES = {
+ read: 'reads', vread: 'reads',
+ 'search-type': 'searches', 'search-system': 'searches',
+ create: 'writes', update: 'writes', patch: 'writes', delete: 'writes',
+ 'conditional-update': 'writes', 'conditional-delete': 'writes', 'conditional-patch': 'writes',
+ transaction: 'transactions', batch: 'batches'
+};
+
+function categoryOf(interaction) {
+ return CATEGORIES[interaction] || 'other';
+}
+
module.exports = RestModule;
diff --git a/shl/shl.js b/shl/shl.js
index 6942c58b3..932e57770 100644
--- a/shl/shl.js
+++ b/shl/shl.js
@@ -5,7 +5,7 @@
//
const express = require('express');
-const sqlite3 = require('sqlite3').verbose();
+const sqlite3 = require('sqlite3');
const path = require('path');
const crypto = require('crypto');
const cron = require('node-cron');
diff --git a/tests/cs/cs-lang.test.js b/tests/cs/cs-lang.test.js
index ee00ca6b2..24730b8d5 100644
--- a/tests/cs/cs-lang.test.js
+++ b/tests/cs/cs-lang.test.js
@@ -190,7 +190,8 @@ describe('IETF Language CodeSystem Provider', () => {
await expect(
provider.filter(prep, true, 'language', 'exists', 'maybe')
- ).rejects.toThrow('Invalid exists value');
+ ).rejects.toMatchObject({ cause: 'invalid', msgId: 'VALUESET_BAD_FILTER_VALUE_BOOLEAN', statusCode: 422,
+ message: 'The value for a filter based on property \'language\' must be either \'true\' or \'false\', not \'maybe\'' });
});
test('should reject unsupported properties', async () => {
diff --git a/tests/cs/cs-loinc.test.js b/tests/cs/cs-loinc.test.js
index 41e2ca1a9..7c3f2a15d 100644
--- a/tests/cs/cs-loinc.test.js
+++ b/tests/cs/cs-loinc.test.js
@@ -536,6 +536,25 @@ describe('LOINC Provider', () => {
});
});
+ describe('Counting all the codes (count=0)', () => {
+ test('countAllCodes counts what the whole walk visits, and without the inactive codes what it doesn\'t call inactive (A9)', async () => {
+ const iter = await provider.iterator(null);
+ let all = 0;
+ let active = 0;
+ let c = await provider.nextContext(iter);
+ while (c) {
+ all++;
+ if (!await provider.isInactive(c)) {
+ active++;
+ }
+ c = await provider.nextContext(iter);
+ }
+ expect(all).toBeGreaterThan(active); // the test data has inactive codes
+ expect(await provider.countAllCodes(false)).toBe(all);
+ expect(await provider.countAllCodes(true)).toBe(active);
+ });
+ });
+
describe('Code Lookup', () => {
test('should locate known LOINC codes', async () => {
const testCodes = expectedResults.basic.knownCodes;
diff --git a/tests/cs/cs-mimetypes.test.js b/tests/cs/cs-mimetypes.test.js
index b3e749cbc..0ab07fb36 100644
--- a/tests/cs/cs-mimetypes.test.js
+++ b/tests/cs/cs-mimetypes.test.js
@@ -356,6 +356,16 @@ describe('MimeTypeServices', () => {
.rejects.toMatchObject({ cause: 'not-supported', message: 'The filter "base is-a text" is not understood or supported', msgId: 'FILTER_NOT_UNDERSTOOD', statusCode: 422 });
});
+ test('a bad filter value is the client\'s error: 422 invalid, not a server error', async () => {
+ for (const value of ['', 'text/plain; charset=utf-8', 'text/*', 'a/b/c']) {
+ await expect(provider.filter(await provider.getPrepContext(false), false, 'base', '=', value))
+ .rejects.toMatchObject({ cause: 'invalid', msgId: 'VALUESET_BAD_FILTER_VALUE_VALID_CODE', statusCode: 422 });
+ }
+ await expect(provider.filter(await provider.getPrepContext(false), false, 'registered', '=', 'maybe'))
+ .rejects.toMatchObject({ cause: 'invalid', msgId: 'VALUESET_BAD_FILTER_VALUE_BOOLEAN', statusCode: 422,
+ message: 'The value for a filter based on property \'registered\' must be either \'true\' or \'false\', not \'maybe\'' });
+ });
+
test('should handle null operation context', () => {
expect(() => provider._ensureOpContext(null)).toThrow();
});
diff --git a/tests/cs/cs-modifier-extensions.test.js b/tests/cs/cs-modifier-extensions.test.js
new file mode 100644
index 000000000..1f51d4b08
--- /dev/null
+++ b/tests/cs/cs-modifier-extensions.test.js
@@ -0,0 +1,186 @@
+//
+// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
+//
+// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause
+//
+
+/**
+ * Modifier extensions in code systems (and the whole-resource check they're found by), R3's
+ * codesystem-subsumes, and the child exists filter (B18).
+ *
+ * There's nowhere in a terminology resource where a modifier extension doesn't matter: each one is
+ * either understood (only on the element it's understood on) or the resource is refused (422).
+ * R3's codesystem-subsumes says a concept also subsumes a code declared elsewhere - an is-a link -
+ * so it's understood: the conversion from R3 makes it a child property, which the hierarchy uses.
+ */
+
+const { CodeSystem } = require('../../tx/library/codesystem');
+const { FhirCodeSystemProvider } = require('../../tx/cs/cs-cs');
+const { OperationContext } = require('../../tx/operation-context');
+const { Extensions } = require('../../tx/library/extensions');
+const { STORED_CONCEPTS } = require('../../tx/library/stored-concepts');
+const { TestUtilities } = require('../test-utilities');
+
+const MOD = [{ url: 'http://example.org/fhir/StructureDefinition/unknown-modifier', valueString: 'x' }];
+const SUBSUMES = 'http://hl7.org/fhir/StructureDefinition/codesystem-subsumes';
+
+function cs(extra = {}, concepts = null) {
+ return { resourceType: 'CodeSystem', url: 'http://example.org/cs/m', version: '1', status: 'active', content: 'complete',
+ hierarchyMeaning: 'is-a', ...extra,
+ concept: concepts || [{ code: 'A', display: 'A', concept: [{ code: 'A1', display: 'A1' }] }, { code: 'B', display: 'B' }] };
+}
+
+describe('modifier extensions in code systems', () => {
+ let opContext;
+
+ beforeAll(async () => {
+ opContext = new OperationContext('en-US', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions()));
+ });
+
+ test('a code system with one it doesn\'t understand can\'t be used: 422, with the element', () => {
+ const json = cs({}, [{ code: 'A', display: 'A', concept: [{ code: 'A1', display: 'A1', modifierExtension: MOD }] }]);
+ let error = null;
+ try {
+ FhirCodeSystemProvider.create(opContext, new CodeSystem(json), []);
+ } catch (e) {
+ error = e;
+ }
+ expect(error).not.toBeNull();
+ expect(error.statusCode).toBe(422);
+ expect(error.msgId).toBe('CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN');
+ expect(error.path).toBe('CodeSystem.concept[0].concept[0]');
+ expect(error.message).toContain('unknown-modifier');
+ });
+
+ test('so can\'t a supplement with one, whatever it supplements', () => {
+ const supplement = new CodeSystem({ resourceType: 'CodeSystem', url: 'http://example.org/cs/m-sup', version: '1', status: 'active',
+ content: 'supplement', supplements: 'http://example.org/cs/m', concept: [{ code: 'A', designation: [{ language: 'de', value: 'A-de' }], modifierExtension: MOD }] });
+ let error = null;
+ try {
+ FhirCodeSystemProvider.create(opContext, new CodeSystem(cs()), [supplement]);
+ } catch (e) {
+ error = e;
+ }
+ expect(error).not.toBeNull();
+ expect(error.msgId).toBe('CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN');
+ expect(error.path).toBe('CodeSystem.concept[0]');
+ });
+
+ test('a code system with none is used', () => {
+ expect(FhirCodeSystemProvider.create(opContext, new CodeSystem(cs()), [])).toBeDefined();
+ });
+
+ describe('R3\'s codesystem-subsumes is a child property', () => {
+ // B is also under A, said R3's way (on A)
+ const r3 = () => cs({}, [{ code: 'A', display: 'A', modifierExtension: [{ url: SUBSUMES, valueCode: 'B' }], concept: [{ code: 'A1', display: 'A1' }] },
+ { code: 'B', display: 'B' }]);
+
+ test('the conversion from R3 makes it a declared child property', () => {
+ const r5 = new CodeSystem(r3(), '3.0.2').jsonObj;
+ expect(r5.concept[0].modifierExtension).toBeUndefined();
+ expect(r5.concept[0].property).toEqual([{ code: 'child', valueCode: 'B' }]);
+ expect(r5.property).toHaveLength(1);
+ expect(r5.property[0].uri).toBe('http://hl7.org/fhir/concept-properties#child');
+ });
+
+ test('so A subsumes B, and the code system can be used', async () => {
+ const provider = FhirCodeSystemProvider.create(opContext, new CodeSystem(r3(), '3.0.2'), []);
+ expect(await provider.subsumesTest('A', 'B')).toBe('subsumes');
+ expect(await provider.subsumesTest('B', 'A')).toBe('subsumed-by');
+ });
+
+ test('a code system that already declares child keeps its code for it', () => {
+ const json = r3();
+ json.property = [{ code: 'kid', uri: 'http://hl7.org/fhir/concept-properties#child', type: 'code' }];
+ const r5 = new CodeSystem(json, '3.0.2').jsonObj;
+ expect(r5.property).toHaveLength(1);
+ expect(r5.concept[0].property).toEqual([{ code: 'kid', valueCode: 'B' }]);
+ });
+
+ test('it is not understood on anything but R3 content', () => {
+ expect(() => FhirCodeSystemProvider.create(opContext, new CodeSystem(r3(), '4.0.1'), [])).toThrow('isn\'t understood');
+ });
+ });
+
+ describe('child exists (B18)', () => {
+ async function codes(json, value) {
+ const provider = FhirCodeSystemProvider.create(opContext, new CodeSystem(json), []);
+ const filterContext = await provider.getPrepContext(true);
+ const results = await provider.filter(filterContext, true, 'child', 'exists', value);
+ const out = [];
+ results.reset();
+ while (await provider.filterMore(filterContext, results)) {
+ out.push((await provider.filterConcept(filterContext, results)).code);
+ }
+ return out.sort();
+ }
+
+ test('with no child property declared: the leaves, and those with children', async () => {
+ expect(await codes(cs(), 'false')).toEqual(['A1', 'B']);
+ expect(await codes(cs(), 'true')).toEqual(['A']);
+ });
+
+ test('a declared concept-properties#child property is the same thing', async () => {
+ const json = cs({ property: [{ code: 'child', uri: 'http://hl7.org/fhir/concept-properties#child', type: 'code' }] });
+ expect(await codes(json, 'false')).toEqual(['A1', 'B']);
+ expect(await codes(json, 'true')).toEqual(['A']);
+ });
+
+ test('children given by the child property count too', async () => {
+ const json = cs({ property: [{ code: 'child', uri: 'http://hl7.org/fhir/concept-properties#child', type: 'code' }] },
+ [{ code: 'A', display: 'A', property: [{ code: 'child', valueCode: 'B' }] }, { code: 'B', display: 'B' }]);
+ expect(await codes(json, 'true')).toEqual(['A']);
+ expect(await codes(json, 'false')).toEqual(['B']);
+ });
+
+ test('a child property of the code system\'s own (another uri) is filtered as that property', async () => {
+ const json = cs({ property: [{ code: 'child', uri: 'http://example.org/props#child', type: 'string' }] },
+ [{ code: 'A', display: 'A', concept: [{ code: 'A1', display: 'A1' }] }, { code: 'B', display: 'B', property: [{ code: 'child', valueString: 'x' }] }]);
+ expect(await codes(json, 'true')).toEqual(['B']);
+ });
+ });
+});
+
+describe('Extensions.checkNoModifiersAnywhere', () => {
+ const EQUIVALENCE = 'http://hl7.org/fhir/1.0/StructureDefinition/extension-ConceptMap.element.target.equivalence';
+ const KNOWN = [['ConceptMap.group.element.target', EQUIVALENCE]];
+ const map = (where) => {
+ const target = { code: 'B1', relationship: 'equivalent' };
+ const element = { code: 'A1', target: [target] };
+ (where === 'target' ? target : element).modifierExtension = [{ url: EQUIVALENCE, valueCode: 'equal' }];
+ return { resourceType: 'ConceptMap', group: [{ element: [element] }] };
+ };
+
+ test('a known modifier extension is understood on the element it\'s known on', () => {
+ expect(() => Extensions.checkNoModifiersAnywhere(map('target'), 'X', 'concept map', 'u', KNOWN)).not.toThrow();
+ });
+
+ test('and nowhere else', () => {
+ expect(() => Extensions.checkNoModifiersAnywhere(map('element'), 'X', 'concept map', 'u', KNOWN)).toThrow('ConceptMap.group[0].element[0] has a modifier');
+ });
+
+ test('a parameter, or a part of one, with a modifier extension is refused (400), and the resources in parameters aren\'t walked', () => {
+ const MODX = [{ url: 'http://example.org/fhir/StructureDefinition/unknown-modifier' }];
+ let error = null;
+ try {
+ Extensions.checkNoParameterModifiers({ resourceType: 'Parameters', parameter: [{ name: 'a', valueString: 'x' },
+ { name: 'b', part: [{ name: 'c', modifierExtension: MODX, valueString: 'y' }] }] });
+ } catch (e) {
+ error = e;
+ }
+ expect(error).not.toBeNull();
+ expect(error.statusCode).toBe(400);
+ expect(error.path).toBe('Parameters.parameter[1].part[0]');
+ expect(error.msgId).toBe('PARAMETERS_MODIFIER_EXTENSION_UNKNOWN');
+ expect(() => Extensions.checkNoParameterModifiers({ resourceType: 'Parameters', parameter: [
+ { name: 'tx-resource', resource: { resourceType: 'CodeSystem', modifierExtension: MODX } }] })).not.toThrow();
+ });
+
+ test('the concepts of an include held in a database aren\'t read', () => {
+ const include = { system: 'http://example.org/cs' };
+ include[STORED_CONCEPTS] = { count: 1, lookup: () => null };
+ Object.defineProperty(include, 'concept', { enumerable: true, get() { throw new Error('read the stored concepts'); } });
+ const vs = { resourceType: 'ValueSet', compose: { include: [include] } };
+ expect(() => Extensions.checkNoModifiersAnywhere(vs, 'X', 'value set', 'u')).not.toThrow();
+ });
+});
diff --git a/tests/cs/cs-ndc-history.test.js b/tests/cs/cs-ndc-history.test.js
index a5bbc43c0..1964d7905 100644
--- a/tests/cs/cs-ndc-history.test.js
+++ b/tests/cs/cs-ndc-history.test.js
@@ -255,6 +255,26 @@ describe('NDC import from a history of snapshots', () => {
provider.close();
});
+ test('countAllCodes counts the products and packages, and without the inactive ones the active ones (A9)', async () => {
+ // NDC has no iterator over all its codes, so the counts are checked against the database
+ const count = (sql) => new Promise((resolve, reject) => {
+ const db = new sqlite3.Database(dbPath, sqlite3.OPEN_READONLY);
+ db.get(sql, (err, row) => {
+ db.close();
+ if (err) {
+ reject(err);
+ } else {
+ resolve(row.n);
+ }
+ });
+ });
+ const all = await count('SELECT (SELECT COUNT(*) FROM NDCPackages) + (SELECT COUNT(*) FROM NDCProducts) AS n');
+ const active = await count('SELECT (SELECT COUNT(*) FROM NDCPackages WHERE Active = 1) + (SELECT COUNT(*) FROM NDCProducts WHERE Active = 1) AS n');
+ expect(all).toBeGreaterThan(active); // the test data has inactive codes
+ expect(await provider.countAllCodes(false)).toBe(all);
+ expect(await provider.countAllCodes(true)).toBe(active);
+ });
+
// the codes an include with these filters has, in order: the first filter's, checked against the rest
const select = async (...filters) => {
const prep = await provider.getPrepContext(true);
diff --git a/tests/cs/cs-omop.test.js b/tests/cs/cs-omop.test.js
index 61a409e4b..5ed4b0ea9 100644
--- a/tests/cs/cs-omop.test.js
+++ b/tests/cs/cs-omop.test.js
@@ -265,6 +265,24 @@ describe('OMOP Provider', () => {
}
});
+ test('the valid dates are dateTimes: a $lookup or expansion property value can\'t be a date (A6)', async () => {
+ let found = 0;
+ for (const conceptId of testData.sampleConcepts) {
+ const paramSet = [];
+ await provider.extendLookup(conceptId, ['valid-start-date', 'valid-end-date'], paramSet);
+ for (const p of paramSet.filter(p => p.name === 'property')) {
+ const code = p.part.find(part => part.name === 'code').valueCode;
+ if (code === 'valid-start-date' || code === 'valid-end-date') {
+ const value = p.part.find(part => part.name === 'value');
+ expect(value.valueDate).toBeUndefined();
+ expect(value.valueDateTime).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ found++;
+ }
+ }
+ }
+ expect(found).toBeGreaterThan(0);
+ });
+
test('should include relationships when available', async () => {
if (testData.sampleConcepts.length > 0) {
const conceptId = testData.sampleConcepts[0];
diff --git a/tests/cs/cs-rxnorm-filters.test.js b/tests/cs/cs-rxnorm-filters.test.js
index c0b11771f..a59fb5d71 100644
--- a/tests/cs/cs-rxnorm-filters.test.js
+++ b/tests/cs/cs-rxnorm-filters.test.js
@@ -63,6 +63,23 @@ describe('RxNorm filters, totals, status and lookup', () => {
}
});
+ test('countAllCodes counts what the whole walk visits, and without the inactive codes what it doesn\'t call inactive (A9)', async () => {
+ const iter = await provider.iterator(null);
+ let all = 0;
+ let active = 0;
+ let c = await provider.nextContext(iter);
+ while (c) {
+ all++;
+ if (!await provider.isInactive(c)) {
+ active++;
+ }
+ c = await provider.nextContext(iter);
+ }
+ expect(all).toBeGreaterThan(active); // the test data has inactive codes
+ expect(await provider.countAllCodes(false)).toBe(all);
+ expect(await provider.countAllCodes(true)).toBe(active);
+ });
+
// run the filters together, as one include does, and return the set
async function filterSet(...filters) {
const ctxt = await provider.getPrepContext(true);
diff --git a/tests/cs/cs-snomed.test.js b/tests/cs/cs-snomed.test.js
index 744636a10..753174368 100644
--- a/tests/cs/cs-snomed.test.js
+++ b/tests/cs/cs-snomed.test.js
@@ -858,6 +858,12 @@ describe('SNOMED CT Subset Validation', () => {
}
});
+ test('a filter value that should be true or false is 422 invalid, not a server error', async () => {
+ const filterContext = await provider.getPrepContext(true);
+ await expect(provider.filter(filterContext, true, 'inactive', '=', 'maybe'))
+ .rejects.toMatchObject({ cause: 'invalid', msgId: 'VALUESET_BAD_FILTER_VALUE_BOOLEAN', statusCode: 422 });
+ });
+
test('should perform text search on subset concepts', async () => {
const searchTests = [
{ term: 'disease', expectedCodes: ['64572001'] },
diff --git a/tests/cs/lang-validation.test.js b/tests/cs/lang-validation.test.js
index 2d0cccdb6..5c0efa4f8 100644
--- a/tests/cs/lang-validation.test.js
+++ b/tests/cs/lang-validation.test.js
@@ -299,9 +299,11 @@ describe('IETF language code validation', () => {
});
test('a filter value has to be a registered subtag of the right kind', async () => {
- await expect(build([['language', '=', 'zz']])).rejects.toThrow(/not a valid language subtag/);
- await expect(build([['region', '=', 'AB']])).rejects.toThrow(/not a valid region subtag/);
- await expect(build([['script', '=', 'Abcd']])).rejects.toThrow(/not a valid script subtag/);
+ await expect(build([['language', '=', 'zz']])).rejects.toThrow(/not a registered language subtag/);
+ await expect(build([['region', '=', 'AB']])).rejects.toThrow(/not a registered region subtag/);
+ await expect(build([['script', '=', 'Abcd']])).rejects.toThrow(/not a registered script subtag/);
+ // the client's mistake: a 422, not a server error
+ await expect(build([['language', '=', 'zz']])).rejects.toMatchObject({ msgId: 'VALUESET_BAD_FILTER_VALUE_VALID_CODE', statusCode: 422 });
});
});
diff --git a/tests/data/UcumFunctionalTests.xml b/tests/data/UcumFunctionalTests.xml
index dc4a0e101..ac8fbbc64 100644
--- a/tests/data/UcumFunctionalTests.xml
+++ b/tests/data/UcumFunctionalTests.xml
@@ -600,6 +600,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/data/fhirpath-check-java.json b/tests/data/fhirpath-check-java.json
index a3f5f13d4..8b0b5ec2c 100644
--- a/tests/data/fhirpath-check-java.json
+++ b/tests/data/fhirpath-check-java.json
@@ -1,5 +1,5 @@
{
- "core" : "43f1b8066d",
+ "core" : "6d5fd60351+",
"results" : {
"defineVariable('v1', 'value1').select(%v1)\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
"defineVariable('n1', name.first()).select(%n1.given)\t\t\tpatient-example.xml\t" : {"types":"ORDERED[http://hl7.org/fhir/StructureDefinition/string]"},
@@ -239,6 +239,31 @@
"true.toString()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
"1 'wk'.toString()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
"1 week.toString()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
+ "'2015-02-04T14:34'.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'2015-02-30'.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'2016-02-29'.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'2015-13'.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'not-a-date'.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "@2015-02-04T14:34:28Z.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "@2015-02.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.birthDate.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').value.convertsToDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'2015'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "'2015-02'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "'2015-02-04'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "'2015-02-04'.toDate() = @2015-02-04\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'2015-02-04T14:34'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "'2015-02-30'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "'not-a-date'.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "1.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "@2015-02-04.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "@2024-01-15T23:30:00-05:00.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "@2015-02T.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "{}.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "('2015' | '2016').toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "Patient.birthDate.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
+ "Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').value.toDate()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.DateTime]"},
"Patient.name.exists()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.exists(use = 'nickname')\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.exists(use = 'official')\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -313,6 +338,7 @@
"Patient.name.where(given = 'Jim').count() = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.where(given = 'X').count() = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.where($this.given = 'Jim').count() = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.extension.value.ofType(Reference).where(resolve() is Patient).empty()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.select(given).count() = 5\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.select(given | family).count() = 7\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"name.select(use.contains('i')).count()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
@@ -329,6 +355,20 @@
"Patient.name[0].given = 'Peter' | 'James'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name[1].given = 'Jim'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name[-1]\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhir/StructureDefinition/HumanName]"},
+ "name[0].given = 'Peter' | 'James'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[1].given = 'Jim'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0].family = 'Windsor'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[2].family = 'Windsor'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0].exists() and false\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "(name[0] | name[1]).count()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "name[0] = name[0]\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0] = name[1]\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0] is HumanName\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[1].given.count() + 1 = 2\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0].family + ', ' + name[0].given.first()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
+ "name[0].given[1] = 'James'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "name[0 + 1].given = 'Jim'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name.where(given[0] = 'Jim').use\t\t\tpatient-example.xml\t" : {"types":"ORDERED[http://hl7.org/fhir/StructureDefinition/code]"},
"Patient.name.first().single().exists()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.single().exists()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.name.first().given = 'Peter' | 'James'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -405,6 +445,7 @@
"'abcdefg'.substring(3, 0) = ''\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"'abcdefg'.substring(3, {}) = 'defg'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"'abcdefg'.substring(0, {}) = 'abcdefg'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'abcdefghijklmnopqrstuvwxyz'.substring(Appointment.minutesDuration)\t\t\tappointment-examplereq.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
"'12345'.startsWith('2') = false\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"'12345'.startsWith('1') = true\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"'12345'.startsWith('12') = true\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -564,6 +605,61 @@
"@2015-02-04T10:00 = @2015-02-04T11:00\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"@2015-02-04T10:00:00 = @2015-02-04T10:00\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"@2015-02-04T10:00-05:00 = @2015-02-04T10:00-05:00\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'-0.0'.toDecimal() = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'-0.0'.toDecimal() = 0.0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'-0.00'.toDecimal() = '0.0'.toDecimal()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'-0.0'.toDecimal() != 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'-0'.toInteger() = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "'007'.toInteger() = 7\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[0] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[0] != Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] != Patient.name[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[2]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] != Patient.name[2]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[5]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[3] = Patient.name[4]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[3]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[3] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[6] = Patient.name[7]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[7] = Patient.name[6]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[6]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[6] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[10]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[10] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[9]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[9] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[8]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[8] = Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[10] = Patient.name[11]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] = Patient.name[12]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.contact[0] = Patient.contact[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.contact[1] = Patient.contact[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.contact[0] = Patient.contact[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient = %resource\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "(Patient.name[0] | Patient.name[1]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "(Patient.name[1] | Patient.name[0]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "(Patient.name[1] | Patient.name[2] | Patient.name[5]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name.take(8).distinct().count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name[1].combine(Patient.name[0]).distinct().count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name[0].combine(Patient.name[1]).distinct().count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name[1].combine(Patient.name[0]).isDistinct()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[0].combine(Patient.name[1]).isDistinct()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1].combine(Patient.name[2]).isDistinct()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[0] in Patient.name.skip(1)\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name.skip(1) contains Patient.name[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] in Patient.name.skip(4)\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name.take(2).intersect(Patient.name[1]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name.take(2).intersect(Patient.name[0]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name.take(2).exclude(Patient.name[0]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name.take(2).exclude(Patient.name[1]).count()\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Integer]"},
+ "Patient.name[0].subsetOf(Patient.name.skip(1))\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name.skip(1).supersetOf(Patient.name[0])\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] ~ Patient.name[12]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[0] ~ Patient.name[1]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] ~ Patient.name[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[1] !~ Patient.name[0]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.name[6] ~ Patient.name[7]\t\t\tpatient-equality.json\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1 != 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"{} != {}\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1 != 2\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -953,6 +1049,21 @@
"{} - 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[]"},
"{} - {}\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[]"},
"@2015-02-04T10:00Z - 1 day = @2015-02-03T10:00Z\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "5 * -2 = -10\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-2 * -3 = 6\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1 - -1 = 2\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1 + -1 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2 * -3 + 1 = -5\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2 - -2 * 3 = 8\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "6 / -2 = -3\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "10 div -3 = -3\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "10 mod -3 = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-10 div 3 = -3\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-10 mod 3 = -1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "3 > -1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "(5 * -2).toString()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
+ "1 + -Patient.name.given.count() = -4\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2.5 * -2 = -5.0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1 * 1 = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1 * 0 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1.2 * 1.8 = 2.16\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -979,6 +1090,15 @@
"{} div 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[]"},
"{} div {}\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[]"},
"0 div 0.0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Decimal]"},
+ "5.5 div 0.7 = 7\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-5.5 div 0.7 = -7\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "5.5 div -0.7 = -7\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "0.75 div 0.5 = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2.9 div 1 = 2\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.0 div 1 = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "14.0 div 1 = 14\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.5 div 0.5 = 3\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "7 div 2.0 = 3\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1 mod 1 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"4 mod 2 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"5 mod 2 = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -991,6 +1111,20 @@
"5.5 mod 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Decimal]"},
"5 mod 0.0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Decimal]"},
"0.0 mod 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Decimal]"},
+ "5.5 mod 0.7 = 0.6\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-5.5 mod 0.7 = -0.6\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "5.5 mod -0.7 = 0.6\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "0.75 mod 0.5 = 0.25\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2.9 mod 1 = 0.9\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "2.50 mod 1 = 0.5\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.0 mod 1 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.0 mod 1 = 0.0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "14.0 mod 1 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.5 mod 0.5 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "-1.0 mod 1 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1 mod 1.0 = 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "1.0 mod 1 ~ 0\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "(2.00 mod 1 = 0) and (2.5 mod 1 = 0).not()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1.round() = 1\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"3.14159.round(3) = 3.142\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"{}.round().empty()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -1043,6 +1177,7 @@
"Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').exists()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.birthDate.extension(%`ext-patient-birthTime`).exists()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime1').empty()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/' + 'patient-birthTime').value.toString()\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.String]"},
"1.type().namespace = 'System'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"1.type().name = 'Integer'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"'1'.type().namespace = 'System'\t\t\tpatient-example.xml\t" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
@@ -1210,6 +1345,9 @@
"%resource.parameter.where(name='goodHtml').value.htmlChecks()\t\t\tparameters-example-html.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"%resource.parameter.where(name='badHtml').value.htmlChecks()\t\t\tparameters-example-html.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"%resource.parameter.where(name='notString').value.htmlChecks().empty()\t\t\tparameters-example-html.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Bundle.entry.resource.where(id='p-inline').text.div.htmlChecks()\t\t\tbundle-html-p-nesting.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Bundle.entry.resource.where(id='p-nested-p').text.div.htmlChecks()\t\t\tbundle-html-p-nesting.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
+ "Bundle.entry.resource.where(id='p-table').text.div.htmlChecks()\t\t\tbundle-html-p-nesting.xml\thtml" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"$this.toString().length() >= 10\tObservation.effective\t\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"$this.toString().length() > 10\tObservation.effective\tdateTime\tobservation-example.xml\tsemantic" : {"types":"SINGLETON[http://hl7.org/fhirpath/System.Boolean]"},
"$this.toString().length() > 10\tObservation.effective\tPeriod\tobservation-example.xml\tsemantic" : {"error":"PathEngineException: Error evaluating FHIRPath expression: The function toString can only be used on primitives, but this type is [http://hl7.org/fhir/StructureDefinition/Period] (@char 7)"},
diff --git a/tests/library/fhir/fhirpath-check.test.js b/tests/library/fhir/fhirpath-check.test.js
index e5d19f76e..af7a61499 100644
--- a/tests/library/fhir/fhirpath-check.test.js
+++ b/tests/library/fhir/fhirpath-check.test.js
@@ -90,7 +90,8 @@ function checkTest(engine, t) {
}
// where library/fhir/fhirpath/parser.js is stricter than Java's (as fhirpath-parser.test.js)
-const PARSER_STRICTER = new Set(['text.div.htmlChecks()', '@T14:34:28Z.is(Time)', '@T14:34:28+10:00.is(Time)']);
+// (.div: div is an operator in the grammar, so a member called div needs backticks; Java's parser allows it)
+const PARSER_STRICTER = new Set(['text.div.htmlChecks()', '@T14:34:28Z.is(Time)', '@T14:34:28+10:00.is(Time)', 'Bundle.entry.resource.where(id=\'p-inline\').text.div.htmlChecks()', 'Bundle.entry.resource.where(id=\'p-nested-p\').text.div.htmlChecks()', 'Bundle.entry.resource.where(id=\'p-table\').text.div.htmlChecks()']);
describe('the fhir-test-cases FHIRPath suite (r5/fhirpath/tests-fhir-r5.xml)', () => {
const suite = readSuite();
diff --git a/tests/library/fhir/fhirpath-parser.test.js b/tests/library/fhir/fhirpath-parser.test.js
index b8de755e2..44890b549 100644
--- a/tests/library/fhir/fhirpath-parser.test.js
+++ b/tests/library/fhir/fhirpath-parser.test.js
@@ -305,7 +305,7 @@ describe('real expressions', () => {
test('the test suite\'s expressions parse, except the ones that are meant not to', () => {
// fhirpath.js's grammar is stricter than Java's parser about these: div is a keyword
// (text.`div` is right), and times have no time zone
- const STRICTER = new Set(['text.div.htmlChecks()', '@T14:34:28Z.is(Time)', '@T14:34:28+10:00.is(Time)']);
+ const STRICTER = new Set(['text.div.htmlChecks()', '@T14:34:28Z.is(Time)', '@T14:34:28+10:00.is(Time)', 'Bundle.entry.resource.where(id=\'p-inline\').text.div.htmlChecks()', 'Bundle.entry.resource.where(id=\'p-nested-p\').text.div.htmlChecks()', 'Bundle.entry.resource.where(id=\'p-table\').text.div.htmlChecks()']);
const failed = [];
for (const { text, invalid } of fromSuite) {
let n = null;
diff --git a/tests/library/ucum-limits.test.js b/tests/library/ucum-limits.test.js
new file mode 100644
index 000000000..16632c1e5
--- /dev/null
+++ b/tests/library/ucum-limits.test.js
@@ -0,0 +1,132 @@
+/**
+ * Limits on the complexity of UCUM units and values, as UcumEssenceService.java has them (a port of
+ * its UcumComplexityLimitTests): a short hostile unit - km2000, a chain of Ym24 - used to take
+ * minutes of CPU to canonicalise, and $validate-code against a value set with a canonical filter
+ * does that to the code it is given. And the grammar mistakes the parser used to accept (A15).
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { UcumService } = require('../../tx/library/ucum-service');
+const { Decimal, Pair } = require('../../tx/library/ucum-types');
+
+// (UcumComplexityLimitTests.java also limits the size of decimal values and the time a regex search
+// may take; FHIRsmith doesn't give either a request's input - values are JavaScript numbers, and
+// nothing searches - so those are not ported)
+
+const repeat = (unit, count, sep) => Array(count).fill(unit).join(sep);
+
+// (Jest can't stop a synchronous loop: a regression shows as a test that takes too long)
+function quick(fn, ms = 5000) {
+ const t = Date.now();
+ const r = fn();
+ expect(Date.now() - t).toBeLessThan(ms);
+ return r;
+}
+
+describe('UCUM complexity limits', () => {
+ let ucum;
+
+ beforeAll(() => {
+ ucum = new UcumService();
+ ucum.init(fs.readFileSync(path.join(__dirname, '../../tx/data/ucum-essence.xml'), 'utf8'));
+ });
+
+ function assertRejected(unit) {
+ quick(() => {
+ expect(() => ucum.getCanonicalUnits(unit)).toThrow();
+ expect(ucum.validate(unit)).not.toBeNull();
+ });
+ }
+
+ test('large exponents', () => {
+ assertRejected('km2000000000');
+ assertRejected('km100000');
+ assertRejected('km400');
+ assertRejected('km31');
+ assertRejected('km-31');
+ assertRejected('km99999999999'); // doesn't fit in an int
+ assertRejected('m99999999999999999999');
+ });
+
+ test('too many components', () => {
+ assertRejected(repeat('Ym', 21, '.'));
+ assertRejected(repeat('2', 21, '.'));
+ });
+
+ test('total exponent too large', () => {
+ assertRejected(repeat('Ym24', 10, '.'));
+ assertRejected('Ym30.Ym30.Ym');
+ assertRejected(repeat('Ym3', 21, '/'));
+ });
+
+ test('nesting too deep', () => {
+ assertRejected('(((((((((((m)))))))))))');
+ });
+
+ test('realistic units still work', () => {
+ quick(() => {
+ expect(ucum.validate('10*23')).toBeNull();
+ expect(ucum.validate('10*-24')).toBeNull();
+ expect(ucum.validate('10*12/L')).toBeNull();
+ expect(ucum.getCanonicalUnits('km30')).toBe('m30');
+ expect(ucum.getCanonicalUnits('km-30')).toBe('m-30');
+ expect(ucum.getCanonicalUnits(repeat('Ym', 20, '.'))).toBe('m20');
+ expect(ucum.getCanonicalUnits('Ym30.Ym30')).toBe('m60');
+ expect(ucum.getCanonicalUnits('((((((((((m))))))))))')).toBe('m');
+ });
+ });
+
+ test('too many terms', () => {
+ assertRejected(repeat('{a}', 100000, ''));
+ assertRejected('m' + repeat('{a}', 100000, ''));
+ assertRejected('m' + repeat('/', 100000, '') + 'm');
+ assertRejected(repeat('{a}', 51, '.'));
+ });
+
+ test('long tokens are cheap', () => {
+ quick(() => {
+ for (let i = 0; i < 10; i++) {
+ expect(ucum.validate(repeat('a', 200000, ''))).not.toBeNull();
+ expect(ucum.validate('[' + repeat('a', 200000, '') + ']')).not.toBeNull();
+ expect(ucum.validate(repeat('1', 200000, ''))).not.toBeNull();
+ expect(ucum.validate('+' + repeat('1', 200000, ''))).not.toBeNull();
+ }
+ expect(ucum.validate('{' + repeat('a', 1000000, '') + '}')).toBeNull();
+ });
+ });
+
+ test('validate edge cases', () => {
+ expect(ucum.validate(null)).not.toBeNull();
+ expect(ucum.validate('{abc')).toContain('unterminated annotation');
+ expect(ucum.validate('{aé}')).toContain('non-ascii');
+ expect(ucum.validate('{a}')).toBeNull();
+ expect(ucum.validate('m{a}')).toBeNull();
+ });
+
+ test('error messages are short', () => {
+ const big = repeat('a', 200000, '');
+ for (const u of [big, 'm.' + big, '{' + big]) {
+ expect(ucum.validate(u).length).toBeLessThan(500);
+ }
+ });
+});
+
+describe('UCUM grammar (A15)', () => {
+ let ucum;
+
+ beforeAll(() => {
+ ucum = new UcumService();
+ ucum.init(fs.readFileSync(path.join(__dirname, '../../tx/data/ucum-essence.xml'), 'utf8'));
+ });
+
+ test('no unit is unity in arithmetic, but not a valid unit', () => {
+ expect(ucum.validate('')).not.toBeNull();
+ // (as in Java: the canonical form of unity is no units at all - as for '1' and '%')
+ expect(ucum.getCanonicalUnits('')).toBe(ucum.getCanonicalUnits('1'));
+ expect(ucum.isComparable('', '1')).toBe(true);
+ expect(ucum.convert(new Decimal('2'), '', '%').comparesTo(new Decimal('200'))).toBe(0);
+ expect(ucum.multiply(new Pair(new Decimal('2'), ''), new Pair(new Decimal('3'), 'm')).getCode()).toBe('m');
+ expect(ucum.divideBy(new Pair(new Decimal('2'), ''), new Pair(new Decimal('4'), 's')).getCode()).toBe('s-1');
+ });
+});
diff --git a/tests/server/module-daily-reports.test.js b/tests/server/module-daily-reports.test.js
index 3e4f88229..79f8750e4 100644
--- a/tests/server/module-daily-reports.test.js
+++ b/tests/server/module-daily-reports.test.js
@@ -17,6 +17,7 @@ const PublisherModule = require('../../publisher/publisher');
const TestingModule = require('../../testing/testing');
const { TestReportStore: TestingStore } = require('../../testing/store');
const IpsModule = require('../../ips/ips');
+const RestModule = require('../../rest/rest');
const { IpsStore } = require('../../ips/store');
const HOUR = 60 * 60 * 1000;
@@ -118,6 +119,25 @@ describe('module paragraphs', () => {
});
+ test('rest: reads, searches, writes and transactions for each endpoint', () => {
+ const module = Object.create(RestModule.prototype);
+ module.endpoints = [{ path: '/fhir/r4' }, { path: '/fhir/r5' }];
+ const r4 = { read: 1000, vread: 200, 'search-type': 40, 'search-system': 2, create: 3, update: 4, 'conditional-update': 1,
+ patch: 1, delete: 1, transaction: 2, batch: 1, 'history-instance': 5, operation: 3 };
+ const old = { read: 1 }; // an endpoint no longer configured
+ const total = [r4, old].reduce((t, o) => t + Object.values(o).reduce((a, b) => a + b, 0), 0);
+ module.stats = { countsSince: () => ({ total, operations: {}, endpoints: { '/fhir/r4': r4, '/fhir/old': old }, persisted: true }) };
+ expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('1,264 requests were served.\n\n' +
+ '- /fhir/r4: 1,200 reads, 42 searches, 10 writes, 2 transactions (and 1 batch, 8 other requests)\n' +
+ '- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions\n' +
+ '- /fhir/old: 1 read, 0 searches, 0 writes, 0 transactions');
+
+ module.stats = statsWith({});
+ expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('No requests were served.\n\n' +
+ '- /fhir/r4: 0 reads, 0 searches, 0 writes, 0 transactions\n' +
+ '- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions');
+ });
+
test('registry: client requests, servers registered, and those that never answered', () => {
const data = new ServerRegistries();
const registry = new ServerRegistry();
diff --git a/tests/tx/closure-enabled.test.js b/tests/tx/closure-enabled.test.js
index bfe7825ce..84f5cb44a 100644
--- a/tests/tx/closure-enabled.test.js
+++ b/tests/tx/closure-enabled.test.js
@@ -351,8 +351,9 @@ describe('$closure (enabled)', () => {
await post(app, params(name('checked'), reset, txResource,
{ name: 'check-system-version', valueCanonical: SYS + '|9.9.9' }));
const res = await post(app, params(name('checked'), concept('code2')));
- // the version rule is applied as it would be on $validate-code: there is no 9.9.9
- expect(res.status).toBe(422);
+ // the version rule is applied as it would be on $validate-code: check-system-version
+ // doesn't choose the version, so the one there is is used, and isn't 9.9.9
+ expect(res.status).toBe(400);
expect(res.body.resourceType).toBe('OperationOutcome');
expect(issueText(res)).toMatch(/9\.9\.9/);
});
diff --git a/tests/tx/compare-get.test.js b/tests/tx/compare-get.test.js
new file mode 100644
index 000000000..a56413a37
--- /dev/null
+++ b/tests/tx/compare-get.test.js
@@ -0,0 +1,52 @@
+// ValueSet/$compare by GET (bug triage A1): the handlers took req.body as the Parameters, so
+// every GET failed with a 500 ("params must be provided"). A missing or unknown value set is a
+// 400 or 404 OperationOutcome, not a response sent half way through and then a crash.
+
+const request = require('supertest');
+const { getTestApp, shutdownTestApp } = require('./setup');
+
+const R5 = '/tx/r5';
+const GENDER_VS = 'http://hl7.org/fhir/ValueSet/administrative-gender';
+
+describe('ValueSet/$compare by GET', () => {
+ let app;
+
+ beforeAll(async () => {
+ app = await getTestApp();
+ }, 120000);
+
+ afterAll(async () => {
+ await shutdownTestApp();
+ });
+
+ const get = (path, query) => request(app).get(path).query(query).set('Accept', 'application/fhir+json');
+ const result = (res) => (res.body.parameter || []).find(p => p.name === 'result');
+
+ test('type level: thisUrl and otherUrl', async () => {
+ const res = await get(`${R5}/ValueSet/$compare`, { thisUrl: GENDER_VS, otherUrl: GENDER_VS });
+ expect(res.status).toBe(200);
+ expect(res.body.resourceType).toBe('Parameters');
+ expect(result(res).valueCode).toBe('same');
+ });
+
+ test('instance level: otherUrl', async () => {
+ const res = await get(`${R5}/ValueSet/core-administrative-gender/$compare`, { otherUrl: GENDER_VS });
+ expect(res.status).toBe(200);
+ expect(result(res).valueCode).toBe('same');
+ });
+
+ test('a missing value set is a 400', async () => {
+ const res = await get(`${R5}/ValueSet/$compare`, { thisUrl: GENDER_VS });
+ expect(res.status).toBe(400);
+ expect(res.body.resourceType).toBe('OperationOutcome');
+ expect(res.body.issue[0].code).toBe('required');
+ expect(res.body.issue[0].details.text).toContain('otherUrl');
+ });
+
+ test('an unknown value set is a 404', async () => {
+ const res = await get(`${R5}/ValueSet/$compare`, { thisUrl: GENDER_VS, otherUrl: 'http://example.org/fhir/ValueSet/none' });
+ expect(res.status).toBe(404);
+ expect(res.body.resourceType).toBe('OperationOutcome');
+ expect(res.body.issue[0].code).toBe('not-found');
+ });
+});
diff --git a/tests/tx/expand-active-text-filter.test.js b/tests/tx/expand-active-text-filter.test.js
new file mode 100644
index 000000000..5ddeb1e6a
--- /dev/null
+++ b/tests/tx/expand-active-text-filter.test.js
@@ -0,0 +1,88 @@
+/**
+ * $expand with activeOnly and a text filter (A10): an inactive code - here marked by the
+ * inactive property, not by status - is left out whether or not there's a filter, and
+ * whether the whole expansion, a page of it or only its size (count=0) is asked for.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const CODE_SYSTEM = {
+ resourceType: 'CodeSystem',
+ url: 'http://example.org/cs/act',
+ version: '1.0',
+ status: 'active',
+ content: 'complete',
+ property: [{ code: 'inactive', uri: 'http://hl7.org/fhir/concept-properties#inactive', type: 'boolean' }],
+ concept: [
+ { code: 'A1', display: 'Alpha one' },
+ { code: 'A2', display: 'Alpha two', property: [{ code: 'inactive', valueBoolean: true }] }
+ ]
+};
+
+const VALUE_SET = {
+ resourceType: 'ValueSet',
+ url: 'http://example.org/vs/act',
+ status: 'active',
+ compose: { include: [{ system: 'http://example.org/cs/act' }] }
+};
+
+describe('$expand activeOnly with a text filter (A10)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
+ endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }, { path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ const cases = [];
+ for (const ep of ['r4', 'r5']) {
+ for (const filter of [null, 'alpha']) {
+ for (const count of [null, 0, 1]) {
+ cases.push([`${ep}, ${filter ? 'filter ' + filter : 'no filter'}, ${count == null ? 'unpaged' : 'count=' + count}`, ep, filter, count]);
+ }
+ }
+ }
+
+ test.each(cases)('%s: only A1', async (name, ep, filter, count) => {
+ const parameter = [
+ { name: 'valueSet', resource: VALUE_SET },
+ { name: 'tx-resource', resource: CODE_SYSTEM },
+ { name: 'activeOnly', valueBoolean: true }
+ ];
+ if (filter) {
+ parameter.push({ name: 'filter', valueString: filter });
+ }
+ if (count != null) {
+ parameter.push({ name: 'count', valueInteger: count });
+ }
+ const res = await request(app)
+ .post(`/tx/${ep}/ValueSet/$expand`)
+ .set('Accept', 'application/json')
+ .set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter });
+ expect(res.status).toBe(200);
+ const codes = (res.body.expansion.contains || []).map(c => c.code);
+ expect(codes).toEqual(count === 0 ? [] : ['A1']);
+ if (!(filter && count === 1)) {
+ // (a page of a text filter's matches has no total: the rest aren't read)
+ expect(res.body.expansion.total).toBe(1);
+ }
+ });
+});
diff --git a/tests/tx/expand-count-status.test.js b/tests/tx/expand-count-status.test.js
new file mode 100644
index 000000000..1f1aae414
--- /dev/null
+++ b/tests/tx/expand-count-status.test.js
@@ -0,0 +1,366 @@
+/**
+ * $expand with activeOnly and excludeNotForUI, with count=0 (the total only) and without (A9).
+ * count=0 is answered by counting rather than building the codes; those shortcuts must leave out
+ * what the full expansion leaves out (inactive codes for activeOnly, abstract ones for
+ * excludeNotForUI), and must not count a code twice when two includes overlap. Each case checks
+ * the total, and for full expansions the codes, against what the value set holds.
+ * The same cases are in the tx ecosystem IG's parameters suite (parameters-count-*).
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const CODE_SYSTEM = {
+ "resourceType": "CodeSystem",
+ "id": "parameters-count",
+ "url": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "version": "1.0.0",
+ "name": "ParametersCountTest",
+ "title": "Code system for the count and parameters tests",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "caseSensitive": true,
+ "hierarchyMeaning": "is-a",
+ "content": "complete",
+ "property": [
+ {
+ "code": "status",
+ "uri": "http://hl7.org/fhir/concept-properties#status",
+ "type": "code"
+ },
+ {
+ "code": "notSelectable",
+ "uri": "http://hl7.org/fhir/concept-properties#notSelectable",
+ "type": "boolean"
+ },
+ {
+ "code": "parent",
+ "uri": "http://hl7.org/fhir/concept-properties#parent",
+ "type": "code"
+ }
+ ],
+ "concept": [
+ {
+ "code": "a",
+ "display": "Alpha",
+ "concept": [
+ {
+ "code": "e",
+ "display": "Epsilon",
+ "property": [
+ {
+ "code": "parent",
+ "valueCode": "c"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "code": "b",
+ "display": "Beta",
+ "property": [
+ {
+ "code": "status",
+ "valueCode": "retired"
+ }
+ ]
+ },
+ {
+ "code": "c",
+ "display": "Gamma",
+ "property": [
+ {
+ "code": "notSelectable",
+ "valueBoolean": true
+ }
+ ],
+ "concept": [
+ {
+ "code": "c1",
+ "display": "Gamma one"
+ },
+ {
+ "code": "c2",
+ "display": "Gamma two"
+ }
+ ]
+ },
+ {
+ "code": "d",
+ "display": "Delta",
+ "property": [
+ {
+ "code": "status",
+ "valueCode": "retired"
+ },
+ {
+ "code": "notSelectable",
+ "valueBoolean": true
+ }
+ ]
+ }
+ ]
+};
+
+const VALUE_SETS = {
+ "all": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-all",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-all",
+ "version": "1.0.0",
+ "name": "ParametersCountAll",
+ "title": "All of the count code system",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count"
+ }
+ ]
+ }
+ },
+ "isa": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-isa",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-isa",
+ "version": "1.0.0",
+ "name": "ParametersCountIsa",
+ "title": "is-a c (abstract), including e, a child of c by its parent property",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "filter": [
+ {
+ "property": "concept",
+ "op": "is-a",
+ "value": "c"
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "enum": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-enum",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-enum",
+ "version": "1.0.0",
+ "name": "ParametersCountEnum",
+ "title": "Listed codes: a, b (inactive), c (abstract), d (inactive and abstract), e",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "concept": [
+ {
+ "code": "a"
+ },
+ {
+ "code": "b"
+ },
+ {
+ "code": "c"
+ },
+ {
+ "code": "d"
+ },
+ {
+ "code": "e"
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "overlap": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-overlap",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-overlap",
+ "version": "1.0.0",
+ "name": "ParametersCountOverlap",
+ "title": "All of the code system, and is-a c again: the two includes overlap",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count"
+ },
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "filter": [
+ {
+ "property": "concept",
+ "op": "is-a",
+ "value": "c"
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "overlap-enum": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-overlap-enum",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-overlap-enum",
+ "version": "1.0.0",
+ "name": "ParametersCountOverlapEnum",
+ "title": "Two includes that list overlapping codes: a, b and b, c",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "concept": [
+ {
+ "code": "a"
+ },
+ {
+ "code": "b"
+ }
+ ]
+ },
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "concept": [
+ {
+ "code": "b"
+ },
+ {
+ "code": "c"
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "exclude": {
+ "resourceType": "ValueSet",
+ "id": "parameters-count-exclude",
+ "url": "http://hl7.org/fhir/test/ValueSet/parameters-count-exclude",
+ "version": "1.0.0",
+ "name": "ParametersCountExclude",
+ "title": "All of the code system, but c1",
+ "status": "active",
+ "experimental": false,
+ "date": "2026-12-03",
+ "publisher": "FHIR Project",
+ "compose": {
+ "include": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count"
+ }
+ ],
+ "exclude": [
+ {
+ "system": "http://hl7.org/fhir/test/CodeSystem/parameters-count",
+ "concept": [
+ {
+ "code": "c1"
+ }
+ ]
+ }
+ ]
+ }
+ }
+};
+
+// the codes each value set holds ('all-filter' is 'all' with the text filter gamma)
+const MEMBERS = {"all": ["a", "b", "c", "c1", "c2", "d", "e"], "isa": ["c", "c1", "c2", "e"], "enum": ["a", "b", "c", "d", "e"], "overlap": ["a", "b", "c", "c1", "c2", "d", "e"], "overlap-enum": ["a", "b", "c"], "exclude": ["a", "b", "c", "c2", "d", "e"], "all-filter": ["c", "c1", "c2"]};
+// i: inactive (retired), n: notSelectable (abstract)
+const FLAGS = {"a": "", "b": "i", "c": "n", "c1": "", "c2": "", "d": "in", "e": ""};
+
+const PARAMS = {
+ plain: { activeOnly: false, excludeNotForUI: false },
+ active: { activeOnly: true, excludeNotForUI: false },
+ notforui: { activeOnly: false, excludeNotForUI: true },
+ both: { activeOnly: true, excludeNotForUI: true }
+};
+
+function expected(vs, p) {
+ return MEMBERS[vs].filter(c => !(p.activeOnly && FLAGS[c].includes('i')) && !(p.excludeNotForUI && FLAGS[c].includes('n'))).sort();
+}
+
+const cases = [];
+for (const vs of [...Object.keys(VALUE_SETS), 'all-filter']) {
+ for (const [pk, p] of Object.entries(PARAMS)) {
+ for (const count0 of [true, false]) {
+ cases.push([`${vs} ${pk} ${count0 ? 'count=0' : 'full'}`, vs, p, count0]);
+ }
+ }
+}
+
+describe('$expand totals with activeOnly and excludeNotForUI (A9)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
+ endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ test.each(cases)('%s', async (name, vs, p, count0) => {
+ const parameter = [
+ { name: 'valueSet', resource: VALUE_SETS[vs === 'all-filter' ? 'all' : vs] },
+ { name: 'excludeNested', valueBoolean: true },
+ { name: 'tx-resource', resource: CODE_SYSTEM }
+ ];
+ if (vs === 'all-filter') {
+ parameter.push({ name: 'filter', valueString: 'gamma' });
+ }
+ if (p.activeOnly) {
+ parameter.push({ name: 'activeOnly', valueBoolean: true });
+ }
+ if (p.excludeNotForUI) {
+ parameter.push({ name: 'excludeNotForUI', valueBoolean: true });
+ }
+ if (count0) {
+ parameter.push({ name: 'count', valueInteger: 0 });
+ }
+ const res = await request(app)
+ .post('/tx/r5/ValueSet/$expand')
+ .set('Accept', 'application/json')
+ .set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter });
+ expect(res.status).toBe(200);
+ const want = expected(vs, p);
+ expect(res.body.expansion.total).toBe(want.length);
+ const codes = (res.body.expansion.contains || []).map(c => c.code).sort();
+ expect(codes).toEqual(count0 ? [] : want);
+ });
+});
diff --git a/tests/tx/expand-import-issues.test.js b/tests/tx/expand-import-issues.test.js
new file mode 100644
index 000000000..a20d059f6
--- /dev/null
+++ b/tests/tx/expand-import-issues.test.js
@@ -0,0 +1,116 @@
+/**
+ * $expand of a value set that imports another (A11): the issues the import's expansion reports
+ * (expansion-issue, referring to a contained OperationOutcome) are reported by the expansion that
+ * imports it - whether the import adds codes or only narrows an include, through an import of an
+ * import, and on a page. Each is reported once: an import used twice, or an issue the importing
+ * value set finds itself, is not reported again.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const CS = 'http://example.org/cs/money';
+const INNER = 'http://example.org/vs/inner';
+const MIDDLE = 'http://example.org/vs/middle';
+const EXPANSION_ISSUE = 'http://hl7.org/fhir/StructureDefinition/expansion-issue';
+
+const RESOURCES = [
+ {
+ resourceType: 'CodeSystem', url: CS, version: '1', status: 'active', content: 'complete',
+ concept: [{ code: 'USD', display: 'US dollar' }, { code: 'EUR', display: 'Euro' }]
+ },
+ {
+ resourceType: 'ValueSet', url: INNER, status: 'active',
+ compose: { include: [{ system: CS, concept: [{ code: 'USD' }, { code: 'NO_SUCH_CURRENCY' }] }] }
+ },
+ {
+ resourceType: 'ValueSet', url: MIDDLE, status: 'active',
+ compose: { include: [{ valueSet: [INNER] }] }
+ }
+];
+
+function outer(...include) {
+ return { resourceType: 'ValueSet', url: 'http://example.org/vs/outer', status: 'active', compose: { include } };
+}
+
+// the issues the expansion reports, by message id
+function issues(vs) {
+ const ids = [];
+ for (const ext of (vs.expansion && vs.expansion.extension) || []) {
+ if (ext.url === EXPANSION_ISSUE) {
+ const oo = (vs.contained || []).find(r => '#' + r.id === ext.valueReference.reference);
+ expect(oo).toBeDefined();
+ for (const i of oo.issue) {
+ ids.push(i.extension.find(e => e.url.endsWith('operationoutcome-message-id')).valueString);
+ }
+ }
+ }
+ return ids.sort();
+}
+
+describe('$expand reports the issues of the value sets it imports (A11)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
+ endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }, { path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ async function expand(vs, ep = 'r5', extra = []) {
+ const res = await request(app)
+ .post(`/tx/${ep}/ValueSet/$expand`)
+ .set('Accept', 'application/json')
+ .set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter: [
+ { name: 'valueSet', resource: vs }, ...RESOURCES.map(r => ({ name: 'tx-resource', resource: r })), ...extra] });
+ expect(res.status).toBe(200);
+ return res.body;
+ }
+
+ const UNKNOWN = ['VALUESET_EXPANSION_INCLUDE_UNKNOWN_CODE'];
+
+ test('the inner value set itself reports the unknown code', async () => {
+ expect(issues(await expand(RESOURCES[1]))).toEqual(UNKNOWN);
+ });
+
+ test.each([
+ ['an import', [{ valueSet: [INNER] }], 'r5', []],
+ ['an import, on R4', [{ valueSet: [INNER] }], 'r4', []],
+ ['an import that narrows an include', [{ system: CS, valueSet: [INNER] }], 'r5', []],
+ ['an import of an import', [{ valueSet: [MIDDLE] }], 'r5', []],
+ ['the same import twice: reported once', [{ valueSet: [INNER] }, { valueSet: [INNER] }], 'r5', []],
+ ['an import and an import of it: reported once', [{ valueSet: [INNER] }, { valueSet: [MIDDLE] }], 'r5', []],
+ ['an import, a page of the expansion', [{ valueSet: [INNER] }], 'r5', [{ name: 'count', valueInteger: 1 }]]
+ ])('%s', async (name, include, ep, extra) => {
+ const vs = await expand(outer(...include), ep, extra);
+ expect(vs.expansion.contains.map(c => c.code)).toEqual(['USD']);
+ expect(issues(vs)).toEqual(UNKNOWN);
+ });
+
+ test('an issue the importing value set finds itself is reported once', async () => {
+ const vs = await expand(outer({ valueSet: [INNER] }, { system: CS, concept: [{ code: 'NO_SUCH_CURRENCY' }] }));
+ expect(issues(vs)).toEqual(UNKNOWN);
+ });
+
+ test('an expansion with no issues anywhere reports none', async () => {
+ const vs = await expand(outer({ system: CS }));
+ expect(issues(vs)).toEqual([]);
+ expect(vs.contained).toBeUndefined();
+ });
+});
diff --git a/tests/tx/fixtures/test-library-ucum-uri.yaml b/tests/tx/fixtures/test-library-ucum-uri.yaml
new file mode 100644
index 000000000..0da193cfd
--- /dev/null
+++ b/tests/tx/fixtures/test-library-ucum-uri.yaml
@@ -0,0 +1,9 @@
+# Test library for the supplement property tests: the URI code system and UCUM, which have no
+# properties of their own, alongside the automatic R5 core loading.
+
+base:
+ url: https://storage.googleapis.com/tx-fhir-org
+
+sources:
+ - internal:urls
+ - ucum:tx/data/ucum-essence.xml
diff --git a/tests/tx/implicit-valuesets.test.js b/tests/tx/implicit-valuesets.test.js
index 62bc91b17..163f65f7b 100644
--- a/tests/tx/implicit-valuesets.test.js
+++ b/tests/tx/implicit-valuesets.test.js
@@ -84,10 +84,11 @@ describe('TxParameters.requestedSystemVersion', () => {
const params = () => new TxParameters(langDefs, i18n, false);
const SCT = 'http://snomed.info/sct';
- test('force-system-version wins over system-version, which wins over check-system-version', () => {
+ test('force-system-version wins over system-version; check-system-version never names the version', () => {
const p = params();
p.seeVersionRule(SCT + '|http://snomed.info/sct/731000124108', false, 'check');
- expect(p.requestedSystemVersion(SCT)).toBe('http://snomed.info/sct/731000124108');
+ // check-system-version only checks the version chosen: it doesn't choose one
+ expect(p.requestedSystemVersion(SCT)).toBeNull();
p.seeVersionRule(SCT + '|http://snomed.info/sct/900000000000207008', false, 'default');
expect(p.requestedSystemVersion(SCT)).toBe('http://snomed.info/sct/900000000000207008');
p.seeVersionRule(SCT + '|http://snomed.info/sct/83821000000107', false, 'override');
diff --git a/tests/tx/implicit-vcl-valueset.test.js b/tests/tx/implicit-vcl-valueset.test.js
new file mode 100644
index 000000000..b943fddbb
--- /dev/null
+++ b/tests/tx/implicit-vcl-valueset.test.js
@@ -0,0 +1,93 @@
+/**
+ * Implicit VCL value sets (A16): a value set url http://fhir.org/VCL?v1={percent-encoded VCL} is the
+ * value set the expression is - for $expand and $validate-code by url, and as an include.valueSet,
+ * which is how the VCL parser writes a sub-expression that one include can't hold.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+const { parseVCL, VCL_URI } = require('../../vcl/vcl-parser');
+
+jest.setTimeout(60000);
+
+const G = 'http://hl7.org/fhir/administrative-gender';
+const vclUrl = (vcl) => VCL_URI + encodeURIComponent(vcl).replace(/\(/g, '%28').replace(/\)/g, '%29');
+
+describe('implicit VCL value sets', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library.yaml'),
+ endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ async function expand(parameter) {
+ const res = await request(app).post('/tx/r5/ValueSet/$expand').set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter });
+ return res;
+ }
+ const codes = (res) => (res.body.expansion.contains || []).map(c => c.code).sort();
+
+ test('$expand by url', async () => {
+ const res = await expand([{ name: 'url', valueUri: vclUrl(`(${G})(male;female)`) }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['female', 'male']);
+ });
+
+ test('$expand by url: an exclusion', async () => {
+ const res = await expand([{ name: 'url', valueUri: vclUrl(`(${G})* - (${G})male`) }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['female', 'other', 'unknown']);
+ });
+
+ test('$expand of a compose the parser wrote with an implicit value set: an exclusion inside a union', async () => {
+ // (male or female) or (all but male): everything - the exclusion is not compose.exclude
+ const vs = parseVCL(`(${G})(male;female);((${G})* - (${G})male)`);
+ expect(vs.compose.include[1].valueSet[0]).toMatch(/^http:\/\/fhir\.org\/VCL\?v1=/);
+ const res = await expand([{ name: 'valueSet', resource: vs }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['female', 'male', 'other', 'unknown']);
+ });
+
+ test('$expand of a compose with an intersection across an implicit value set', async () => {
+ // male, if it is also female: nothing
+ const vs = parseVCL(`(${G})(male,female)`);
+ const res = await expand([{ name: 'valueSet', resource: vs }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual([]);
+ const both = await expand([{ name: 'valueSet', resource: parseVCL(`(${G})((male;female),(male;other))`) }]);
+ expect(codes(both)).toEqual(['male']);
+ });
+
+ test('$validate-code by url', async () => {
+ const validate = async (code) => {
+ const res = await request(app).post('/tx/r5/ValueSet/$validate-code').set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter: [
+ { name: 'url', valueUri: vclUrl(`(${G})* - (${G})male`) }, { name: 'system', valueUri: G }, { name: 'code', valueCode: code }] });
+ expect(res.status).toBe(200);
+ return res.body.parameter.find(p => p.name === 'result').valueBoolean;
+ };
+ expect(await validate('female')).toBe(true);
+ expect(await validate('male')).toBe(false);
+ });
+
+ test('a url that is not valid VCL', async () => {
+ const res = await expand([{ name: 'url', valueUri: vclUrl(`(${G})(male;female`) }]);
+ expect(res.status).toBe(400);
+ expect(res.body.issue[0].details.text).toMatch(/is not valid VCL/);
+ });
+});
diff --git a/tests/tx/issue-codes.test.js b/tests/tx/issue-codes.test.js
new file mode 100644
index 000000000..6c9d9260b
--- /dev/null
+++ b/tests/tx/issue-codes.test.js
@@ -0,0 +1,50 @@
+// Every issue code the server writes literally is a FHIR IssueType code (A7: subsumes said
+// 'not found', with a space, so its OperationOutcome wasn't valid FHIR). A source scan, so a
+// mistake in a rarely-taken error path is found without a test that takes it.
+
+const fs = require('fs');
+const path = require('path');
+
+// http://hl7.org/fhir/issue-type (R5; R4 has the same codes, less 'success' and 'limited-filter')
+const ISSUE_TYPES = new Set([
+ 'invalid', 'structure', 'required', 'value', 'invariant', 'security', 'login', 'unknown',
+ 'expired', 'forbidden', 'suppressed', 'processing', 'not-supported', 'duplicate', 'multiple-matches', 'not-found',
+ 'deleted', 'too-long', 'code-invalid', 'extension', 'too-costly', 'business-rule', 'conflict', 'limited-filter',
+ 'transient', 'lock-error', 'no-store', 'exception', 'timeout', 'incomplete', 'throttled', 'informational',
+ 'success'
+]);
+
+function sources(dir, out = []) {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) {
+ if (e.name !== 'node_modules') {
+ sources(p, out);
+ }
+ } else if (e.name.endsWith('.js')) {
+ out.push(p);
+ }
+ }
+ return out;
+}
+
+test('every literal issue code in new Issue(...) and buildOperationOutcome(...) is an IssueType', () => {
+ const root = path.join(__dirname, '../..');
+ const bad = [];
+ for (const file of [...sources(path.join(root, 'tx')), ...sources(path.join(root, 'library'))]) {
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
+ lines.forEach((line, i) => {
+ for (const m of line.matchAll(/new Issue\(\s*['"]\w+['"]\s*,\s*['"]([^'"]+)['"]/g)) {
+ if (!ISSUE_TYPES.has(m[1])) {
+ bad.push(`${path.relative(root, file)}:${i + 1}: ${m[1]}`);
+ }
+ }
+ for (const m of line.matchAll(/buildOperationOutcome\(\s*['"]\w+['"]\s*,\s*['"]([^'"]+)['"]/g)) {
+ if (!ISSUE_TYPES.has(m[1])) {
+ bad.push(`${path.relative(root, file)}:${i + 1}: ${m[1]}`);
+ }
+ }
+ });
+ }
+ expect(bad).toEqual([]);
+});
diff --git a/tests/tx/lookup-display-language.test.js b/tests/tx/lookup-display-language.test.js
new file mode 100644
index 000000000..8e3c374d5
--- /dev/null
+++ b/tests/tx/lookup-display-language.test.js
@@ -0,0 +1,73 @@
+/**
+ * $lookup's parent and child descriptions are displays of those codes, in the language asked for
+ * - displayLanguage, else Accept-Language - as the display of the code looked up is (A14). The
+ * language of a description followed only Accept-Language, so displayLanguage=de gave a German
+ * display with an English parent. Messages stay in Accept-Language's language.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const CS = {
+ resourceType: 'CodeSystem', url: 'http://example.org/cs/lang', version: '1.0', status: 'active', content: 'complete', hierarchyMeaning: 'is-a',
+ concept: [{
+ code: 'A', display: 'Alpha', designation: [{ language: 'de', value: 'Alpha-DE' }, { language: 'es', value: 'Alfa' }],
+ concept: [{ code: 'A1', display: 'Alpha one', designation: [{ language: 'de', value: 'Alpha eins' }, { language: 'es', value: 'Alfa uno' }] }]
+ }]
+};
+
+describe('$lookup parent and child descriptions follow displayLanguage (A14)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library.yaml'),
+ endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ async function lookup(code, prop, displayLanguage, acceptLanguage) {
+ const parameter = [{ name: 'system', valueUri: CS.url }, { name: 'code', valueCode: code }, { name: 'property', valueCode: prop }, { name: 'tx-resource', resource: CS }];
+ if (displayLanguage) {
+ parameter.push({ name: 'displayLanguage', valueCode: displayLanguage });
+ }
+ let req = request(app).post('/tx/r5/CodeSystem/$lookup').set('Content-Type', 'application/json');
+ if (acceptLanguage) {
+ req = req.set('Accept-Language', acceptLanguage);
+ }
+ const res = await req.send({ resourceType: 'Parameters', parameter });
+ expect(res.status).toBe(200);
+ const ps = res.body.parameter;
+ return {
+ display: ps.find(p => p.name === 'display').valueString,
+ descriptions: ps.filter(p => p.name === 'property' && p.part[0].valueCode === prop).map(p => p.part.find(x => x.name === 'description').valueString)
+ };
+ }
+
+ test.each([
+ ['displayLanguage=de', 'de', null],
+ ['Accept-Language: de', null, 'de'],
+ ['displayLanguage=de, Accept-Language: es', 'de', 'es']
+ ])('%s: German throughout', async (name, displayLanguage, acceptLanguage) => {
+ expect(await lookup('A1', 'parent', displayLanguage, acceptLanguage)).toEqual({ display: 'Alpha eins', descriptions: ['Alpha-DE'] });
+ expect(await lookup('A', 'child', displayLanguage, acceptLanguage)).toEqual({ display: 'Alpha-DE', descriptions: ['Alpha eins'] });
+ });
+
+ test('no language asked for: the code system\'s own displays', async () => {
+ expect(await lookup('A1', 'parent', null, null)).toEqual({ display: 'Alpha one', descriptions: ['Alpha'] });
+ });
+});
diff --git a/tests/tx/modifier-extensions.test.js b/tests/tx/modifier-extensions.test.js
index 5b0cd44c2..741374c50 100644
--- a/tests/tx/modifier-extensions.test.js
+++ b/tests/tx/modifier-extensions.test.js
@@ -35,7 +35,7 @@ describe('unknown modifier extensions in a value set', () => {
txModule = new TXModule();
await txModule.initialize({
librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
- endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }]
+ endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }, { path: '/tx/r5', fhirVersion: '5.0', context: null }]
}, app);
}, 60000);
@@ -64,4 +64,55 @@ describe('unknown modifier extensions in a value set', () => {
});
}
}
+
+ // A5: $translate didn't check its map at all. Everything in a map is about translating, so a
+ // modifier anywhere in it means the map can't be used
+ const cm = (where) => {
+ const map = { resourceType: 'ConceptMap', url: 'http://example.org/fhir/ConceptMap/k10', version: '1', status: 'active',
+ group: [{ source: CS.url, target: 'http://example.org/tgt', element: [{ code: 'code1', target: [{ code: 'B1', equivalence: 'equivalent' }] }] }] };
+ if (where === 'ConceptMap') {
+ map.modifierExtension = MOD;
+ } else if (where === 'target') {
+ map.group[0].element[0].target[0].modifierExtension = MOD;
+ }
+ return map;
+ };
+ for (const [where, path] of [['ConceptMap', 'ConceptMap'], ['target', 'ConceptMap.group[0].element[0].target[0]']]) {
+ for (const reverse of [false, true]) {
+ test(`on a concept map's ${where}: $translate${reverse ? ' (reverse)' : ''} is refused with a 422 at ${path}`, async () => {
+ const map = cm(where);
+ const parameter = [{ name: 'url', valueUri: map.url }, { name: 'tx-resource', resource: map }];
+ if (reverse) {
+ parameter.push({ name: 'system', valueUri: 'http://example.org/tgt' }, { name: 'code', valueCode: 'B1' }, { name: 'reverse', valueBoolean: true });
+ } else {
+ parameter.push({ name: 'system', valueUri: CS.url }, { name: 'code', valueCode: 'code1' });
+ }
+ const res = await request(app).post('/tx/r4/ConceptMap/$translate').set('Accept', 'application/json').set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter });
+ expect(res.status).toBe(422);
+ const issue = res.body.issue[0];
+ expect(issue.code).toBe('business-rule');
+ expect(issue.expression).toEqual([path]);
+ expect(issue.details.text).toContain('http://example.org/fhir/StructureDefinition/unknown-modifier');
+ expect(issue.extension[0].valueString).toBe('CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN');
+ });
+ }
+ }
+
+ // ...except the one the tx module understands: the Java convertors' R4 equivalence, on an R5 map
+ // converted from R4, which $translate reports as the equivalence
+ test('the Java convertors\' equivalence modifier is understood, and reported', async () => {
+ const map = cm('none');
+ const target = map.group[0].element[0].target[0];
+ delete target.modifierExtension;
+ delete target.equivalence;
+ target.relationship = 'equivalent';
+ target.modifierExtension = [{ url: 'http://hl7.org/fhir/1.0/StructureDefinition/extension-ConceptMap.element.target.equivalence', valueCode: 'equal' }];
+ const res = await request(app).post('/tx/r5/ConceptMap/$translate').set('Accept', 'application/json').set('Content-Type', 'application/json')
+ .send({ resourceType: 'Parameters', parameter: [{ name: 'url', valueUri: map.url }, { name: 'tx-resource', resource: map },
+ { name: 'system', valueUri: CS.url }, { name: 'sourceCode', valueCode: 'code1' }] });
+ expect(res.status).toBe(200);
+ const match = res.body.parameter.find(p => p.name === 'match');
+ expect(match.part.find(p => p.name === 'concept').valueCoding.code).toBe('B1');
+ });
});
diff --git a/tests/tx/parser-depth-limits.test.js b/tests/tx/parser-depth-limits.test.js
index db5352fbb..80fff028c 100644
--- a/tests/tx/parser-depth-limits.test.js
+++ b/tests/tx/parser-depth-limits.test.js
@@ -18,7 +18,7 @@ const path = require('path');
const { parseVCL, validateVCLExpression, VCLParseException, MAX_VCL_DEPTH } = require('../../vcl/vcl-parser');
const { ECLLexer, ECLParser, MAX_ECL_DEPTH, MAX_ECL_TERMS } = require('../../tx/sct/ecl');
const { SnomedExpressionParser, MAX_EXPRESSION_DEPTH } = require('../../tx/sct/expressions');
-const { MAX_UCUM_TERMS } = require('../../tx/library/ucum-parsers');
+const { MAX_TERMS, MAX_COMPONENTS, MAX_NESTING } = require('../../tx/library/ucum-parsers');
const { UcumService } = require('../../tx/library/ucum-service');
const HOSTILE = 50000;
@@ -47,7 +47,10 @@ describe('VCL parser limits', () => {
});
test('a terminated filter list still parses', () => {
- expect(() => parseVCL('(http://x){a}.b')).not.toThrow();
+ expect(() => parseVCL('(http://x){concept< parseVCL('(http://x){a,c}.b')).not.toThrow();
+ // ({a} is neither: a list of codes has at least two, and a is not a filter)
+ expect(() => parseVCL('(http://x){a}.b')).toThrow(VCLParseException);
});
test('nesting up to the limit parses', () => {
@@ -65,6 +68,48 @@ describe('VCL parser limits', () => {
expect(e).toBeInstanceOf(VCLParseException);
expect(e.message).toMatch(/nests more than/);
});
+
+ test('filter lists ({...}) nest too, and count towards the same limit', () => {
+ const lists = (n) => 'p^' + '{q^'.repeat(n - 1) + '{x=y' + '}'.repeat(n);
+ expect(() => parseVCL(lists(MAX_VCL_DEPTH))).not.toThrow();
+ expect(thrown(() => parseVCL(lists(MAX_VCL_DEPTH + 1)))).toBeInstanceOf(VCLParseException);
+ expect(thrown(() => parseVCL(lists(HOSTILE)))).toBeInstanceOf(VCLParseException);
+ });
+
+ // each of these took quadratic time (or time in proportion to depth times size) at one point
+ describe('large expressions take linear time', () => {
+ const list = (n, f, sep) => Array.from({ length: n }, (_, i) => f(i)).join(sep);
+ const codes = list(100000, i => 'c' + i, ';');
+ const big = list(1000, i => 'p=c' + i, ';');
+
+ test('a union of codes', () => {
+ expect(parseVCL(codes).compose.include[0].concept.length).toBe(100000);
+ });
+
+ test('an intersection of two lists of codes', () => {
+ expect(parseVCL(`(${codes}),(${codes})`).compose.include[0].concept.length).toBe(100000);
+ });
+
+ test('a union of codes in many systems', () => {
+ expect(parseVCL(list(100000, i => `(http://s${i})c${i}`, ';')).compose.include.length).toBe(100000);
+ });
+
+ test('nested unions and intersections of filters', () => {
+ let s = big;
+ for (let i = 0; i < 49; i++) {
+ s = `((${s}),q${i}=x);(${big})`;
+ }
+ expect(parseVCL(s).compose.include.length).toBeGreaterThan(0);
+ });
+
+ test('nested intersections in different systems', () => {
+ let s = 'a';
+ for (let i = 0; i < 99; i++) {
+ s = `(http://s${i})a${i},(${s}),(${big})`;
+ }
+ expect(parseVCL(s).compose.include.length).toBeGreaterThan(0);
+ });
+ });
});
describe('ECL parser limits', () => {
@@ -155,22 +200,26 @@ describe('UCUM parser limits', () => {
const product = (n) => Array(n).fill('m').join('.');
+ // the limits are UcumEssenceService.java's (ExpressionParser): see ucum-limits.test.js
+ const LIMIT = /too complex|Too many components|nested too deeply|unexpected token/;
+
test('ordinary units are untouched', () => {
expect(ucum.validate('kg.m2/s2')).toBeNull();
- expect(ucum.validate('(' .repeat(20) + 'm' + ')'.repeat(20))).toBeNull();
- expect(ucum.validate(product(MAX_UCUM_TERMS / 2))).toBeNull();
+ expect(ucum.validate('('.repeat(MAX_NESTING) + 'm' + ')'.repeat(MAX_NESTING))).toBeNull();
+ expect(ucum.validate(product(MAX_COMPONENTS))).toBeNull();
});
test('a unit past the term limit is invalid', () => {
- expect(ucum.validate(product(MAX_UCUM_TERMS + 1))).toMatch(/more than \d+ terms/);
+ expect(ucum.validate(Array(MAX_TERMS + 1).fill('{a}').join('.'))).toMatch(/too complex/);
});
test('hostile units are our error, not a RangeError', () => {
- for (const unit of [product(HOSTILE), '('.repeat(HOSTILE) + 'm' + ')'.repeat(HOSTILE), '/'.repeat(HOSTILE) + 'm']) {
- expect(ucum.validate(unit)).toMatch(/more than \d+ terms/);
+ for (const unit of [product(HOSTILE), '('.repeat(HOSTILE) + 'm' + ')'.repeat(HOSTILE), '/'.repeat(HOSTILE) + 'm',
+ Array(HOSTILE).fill('{a}').join('.')]) {
+ expect(ucum.validate(unit)).toMatch(LIMIT);
const e = thrown(() => ucum.getCanonicalUnits(unit));
expect(e).not.toBeInstanceOf(RangeError);
- expect(e.message).toMatch(/more than \d+ terms/);
+ expect(e.message).toMatch(LIMIT);
}
});
});
diff --git a/tests/tx/sqlite-v2-cli-options.test.js b/tests/tx/sqlite-v2-cli-options.test.js
new file mode 100644
index 000000000..40a73a578
--- /dev/null
+++ b/tests/tx/sqlite-v2-cli-options.test.js
@@ -0,0 +1,124 @@
+/**
+ * The sqlite-v2 importers take the classic importers' options (tx/importers/sqlite-v2/cli-options.js):
+ * -v, --version and -y, --yes, with their earlier names (--loinc-version, --overwrite...) still
+ * working, hidden. An existing destination without -y is asked about, or refused with no one to ask.
+ */
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { Command } = require('commander');
+const inquirer = require('inquirer');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('../../tx/importers/sqlite-v2/cli-options');
+
+const VERSION = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true };
+
+// parse args as tx-import import would, and resolve the common options
+async function run(args, version = VERSION) {
+ let result;
+ const program = new Command().exitOverride();
+ addCommonOptions(program.command('import')
+ .requiredOption('-s, --source ', 'source')
+ .requiredOption('-d, --dest ', 'dest'), version)
+ .exitOverride()
+ .action(async (o) => {
+ result = await resolveCommonOptions(o, version);
+ });
+ await program.parseAsync(['import', ...args], { from: 'user' });
+ return result;
+}
+
+describe('sqlite-v2 importer options', () => {
+ let dir;
+ let dest;
+ let tty;
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'v2-cli-'));
+ dest = path.join(dir, 'loinc.db');
+ tty = process.stdin.isTTY;
+ });
+ afterEach(() => {
+ process.stdin.isTTY = tty;
+ jest.restoreAllMocks();
+ fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('-v and --version give the version; the earlier name still works', async () => {
+ expect((await run(['-s', dir, '-d', dest, '-v', '2.83'])).version).toBe('2.83');
+ expect((await run(['-s', dir, '-d', dest, '--version', '2.83'])).version).toBe('2.83');
+ expect((await run(['-s', dir, '-d', dest, '--loinc-version', '2.83'])).version).toBe('2.83');
+ });
+
+ test('a required version that is missing is an error that says how to give it', async () => {
+ await expect(run(['-s', dir, '-d', dest])).rejects.toThrow('-v, --version is required (e.g. 2.83)');
+ });
+
+ test('an importer that takes no version has no -v', async () => {
+ await expect(run(['-s', dir, '-d', dest, '-v', 'x'], null)).rejects.toThrow(/unknown option '-v'/);
+ expect((await run(['-s', dir, '-d', dest], null)).version).toBeUndefined();
+ });
+
+ test('a destination that isn\'t there needs nothing; -y, --yes or --overwrite replace one that is', async () => {
+ expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(false);
+ fs.writeFileSync(dest, 'x');
+ expect((await run(['-s', dir, '-d', dest, '-v', '1', '-y'])).overwrite).toBe(true);
+ expect((await run(['-s', dir, '-d', dest, '-v', '1', '--yes'])).overwrite).toBe(true);
+ expect((await run(['-s', dir, '-d', dest, '-v', '1', '--overwrite'])).overwrite).toBe(true);
+ });
+
+ test('an existing destination without -y is asked about, or refused with no one to ask', async () => {
+ fs.writeFileSync(dest, 'x');
+ process.stdin.isTTY = false;
+ await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('use -y, --yes to replace it');
+ process.stdin.isTTY = true;
+ const prompt = jest.spyOn(inquirer, 'prompt').mockResolvedValueOnce({ replace: true }).mockResolvedValueOnce({ replace: false });
+ expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(true);
+ await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('Import cancelled');
+ expect(prompt).toHaveBeenCalledTimes(2);
+ });
+
+ test('a failure is reported as the classic importers do, with exit code 1, not thrown', async () => {
+ const logged = [];
+ const module = { getName: () => 'loinc-v2', logError: (m) => logged.push(m) };
+ const exitCode = process.exitCode;
+ const stack = jest.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ await importAction(module, async () => { throw new Error('required LOINC file missing'); })({});
+ expect(logged).toEqual(['loinc-v2 import failed: required LOINC file missing']);
+ expect(process.exitCode).toBe(1);
+ expect(stack).not.toHaveBeenCalled();
+ await importAction(module, async () => { throw new Error('x'); })({ verbose: true });
+ expect(stack).toHaveBeenCalledTimes(1);
+ } finally {
+ process.exitCode = exitCode;
+ }
+ });
+
+ test('--verbose shows the stack wherever it is on the command line (tx-import has a --verbose of its own)', async () => {
+ const module = { getName: () => 'loinc-v2', logError: () => {} };
+ const exitCode = process.exitCode;
+ const stack = jest.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ for (const args of [['loinc-v2', 'import', '-d', 'x.db', '--verbose'], ['--verbose', 'loinc-v2', 'import', '-d', 'x.db']]) {
+ stack.mockClear();
+ const program = new Command().exitOverride().option('--verbose', 'enable verbose logging');
+ addCommonOptions(program.command('loinc-v2').command('import').option('-d, --dest '))
+ .action(importAction(module, async () => { throw new Error('required LOINC file missing'); }));
+ await program.parseAsync(args, { from: 'user' });
+ expect(stack).toHaveBeenCalledTimes(1);
+ }
+ } finally {
+ process.exitCode = exitCode;
+ }
+ });
+
+ test('the help shows -v, --version and -y, --yes, not the earlier names', () => {
+ const program = new Command();
+ const cmd = addCommonOptions(program.command('import'), VERSION);
+ const help = cmd.helpInformation();
+ expect(help).toContain('-v, --version ');
+ expect(help).toContain('-y, --yes');
+ expect(help).toContain('--verbose');
+ expect(help).not.toContain('--loinc-version');
+ expect(help).not.toContain('--overwrite');
+ });
+});
diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js
index f86a2bb1b..55879f3be 100644
--- a/tests/tx/sqlite-v2-loinc.test.js
+++ b/tests/tx/sqlite-v2-loinc.test.js
@@ -514,6 +514,27 @@ describe('LOINC v2 dialect against main\'s provider (same fixture)', () => {
expect(await p2.processSelection(null, inc('6298-4,NOPE-3'), [], false, -1, -1)).toBeNull();
});
+ test('a supplement\'s property: $expand and $lookup report it, with its uri, as main does (A12)', async () => {
+ const supp = { resourceType: 'CodeSystem', url: 'http://example.org/cs/loinc-supp', version: '1.0', status: 'active', content: 'supplement', supplements: L,
+ property: [{ code: 'localNote', uri: 'http://example.org/prop/localNote', type: 'string' }],
+ concept: [{ code: '10332-5', property: [{ code: 'localNote', valueString: 'note from supplement' }] }] };
+ const common = [{ name: 'useSupplement', valueCanonical: supp.url }, { name: 'tx-resource', resource: supp }, { name: 'property', valueCode: 'localNote' }];
+ const r = await both(async () => {
+ const e = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter: [
+ { name: 'valueSet', resource: vs([{ system: L, concept: [{ code: '10332-5' }] }]) }, ...common] });
+ const l = await request(app).post('/tx/r5/CodeSystem/$lookup').send({ resourceType: 'Parameters', parameter: [
+ { name: 'system', valueUri: L }, { name: 'code', valueCode: '10332-5' }, ...common] });
+ return { declared: e.body.expansion.property, listed: e.body.expansion.contains[0].property,
+ lookup: l.body.parameter.filter((p) => p.name === 'property' && p.part[0].valueCode === 'localNote').map((p) => p.part) };
+ });
+ expect(r.v2).toEqual({
+ declared: [{ code: 'localNote', uri: 'http://example.org/prop/localNote' }],
+ listed: [{ code: 'localNote', valueString: 'note from supplement' }],
+ lookup: [[{ name: 'code', valueCode: 'localNote' }, { name: 'value', valueString: 'note from supplement' }]]
+ });
+ expect(r.classic).toEqual(r.v2);
+ });
+
test('$expand whole system: the same codes as main; activeOnly drops the DISCOURAGED terms', async () => {
const all = await both(() => expand({ valueSet: vs([{ system: L }]), count: 1000 }));
expect(all.v2.total).toBe(484);
@@ -524,9 +545,9 @@ describe('LOINC v2 dialect against main\'s provider (same fixture)', () => {
expect(sorted(codes(act.v2))).toEqual(sorted(codes(act.classic)));
expect(act.v2.total).toBe(482);
expect(codes(act.v2)).not.toContain('22760-3');
- // count=0: the total only, the code system's size as main reports it (activeOnly does not change it)
+ // count=0: the total only, the size of the expansion it stands for - without the DISCOURAGED terms (A9)
const n = await both(() => expand({ valueSet: vs([{ system: L }]), count: 0, activeOnly: true }));
- expect([n.v2.total, n.v2.contains]).toEqual([484, undefined]);
+ expect([n.v2.total, n.v2.contains]).toEqual([482, undefined]);
expect(n.v2.total).toBe(n.classic.total);
});
diff --git a/tests/tx/sqlite-v2-rxnorm-filters.test.js b/tests/tx/sqlite-v2-rxnorm-filters.test.js
index e1915e16a..f8a6f48fd 100644
--- a/tests/tx/sqlite-v2-rxnorm-filters.test.js
+++ b/tests/tx/sqlite-v2-rxnorm-filters.test.js
@@ -178,7 +178,8 @@ describe('sqlite-v2 RxNorm filters, as main', () => {
const r = await both(null, {});
expect(r.main.codes).toEqual(['100', '200', '300', '400', '600', '90']);
expect(r.main.total).toBe(6);
- expect((await both(null, { count: 0, inactive: false })).main.total).toBe(6);
+ // obsolete concepts are inactive: without the inactive codes, count=0 doesn't count them (A9)
+ expect((await both(null, { count: 0, inactive: false })).main.total).toBe(5);
});
test.each([[[['STY', '=', 'T200']]], [[['has_ingredient', '=', 'CUI:200']]], [[['TTY', 'in', 'SCD,SBD']]]])('the filter API (expand.js\'s usual path) %j: the codes of main, in its order', async (filters) => {
diff --git a/tests/tx/stored-expansion.test.js b/tests/tx/stored-expansion.test.js
new file mode 100644
index 000000000..ceaf272bb
--- /dev/null
+++ b/tests/tx/stored-expansion.test.js
@@ -0,0 +1,228 @@
+//
+// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
+//
+// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause
+//
+
+/**
+ * A value set's stored expansion (tx/library/stored-expansion.js), used when its compose can't be
+ * (there isn't one, or a code system it includes isn't available): an expansion made with the
+ * parameters it records. A request's count, offset, filter, activeOnly, excludeNotForUI and
+ * excludeNested are applied to it (A8: they were ignored); the rest must match, or the request is
+ * refused (422) - for $expand, an import, and $validate-code.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const CS = 'http://example.org/fhir/CodeSystem/stored';
+const CODESYSTEM = { resourceType: 'CodeSystem', url: CS, version: '1.0.0', status: 'active', content: 'complete', hierarchyMeaning: 'is-a',
+ property: [{ code: 'inactive', uri: 'http://hl7.org/fhir/concept-properties#inactive', type: 'boolean' }],
+ concept: [{ code: 'a', display: 'Alpha' }, { code: 'b', display: 'Beta', property: [{ code: 'inactive', valueBoolean: true }] },
+ { code: 'c', display: 'Gamma', concept: [{ code: 'c1', display: 'Gamma one' }] }] };
+
+// a value set with no compose, and its stored expansion
+function vs(expansion = {}, extra = {}) {
+ return { resourceType: 'ValueSet', url: 'http://example.org/fhir/ValueSet/stored', version: '1', status: 'active', ...extra,
+ expansion: { identifier: 'urn:uuid:3c1f9a52-7b4e-4f0a-8d2c-5e6f7a8b9c0d', timestamp: '2026-01-01T00:00:00Z', total: 4,
+ parameter: [{ name: 'used-codesystem', valueUri: CS + '|1.0.0' }],
+ contains: [{ system: CS, version: '1.0.0', code: 'a', display: 'Alpha' },
+ { system: CS, version: '1.0.0', code: 'b', display: 'Beta', inactive: true },
+ { system: CS, version: '1.0.0', code: 'c', display: 'Gamma', abstract: true,
+ contains: [{ system: CS, version: '1.0.0', code: 'c1', display: 'Gamma one' }] }],
+ ...expansion } };
+}
+
+describe('stored expansions', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json());
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
+ endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ }, 60000);
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ const post = (op, parameter, lang = null) => {
+ let r = request(app).post('/tx/r5/ValueSet/$' + op).set('Accept', 'application/json').set('Content-Type', 'application/json');
+ if (lang) {
+ r = r.set('Accept-Language', lang);
+ }
+ return r.send({ resourceType: 'Parameters', parameter });
+ };
+ const expand = (valueSet, more = [], lang = null) => post('expand', [{ name: 'valueSet', resource: valueSet }, ...more], lang);
+ const codes = (res) => {
+ const out = [];
+ const walk = list => (list || []).forEach(c => { out.push(c.code); walk(c.contains); });
+ walk(res.body.expansion.contains);
+ return out;
+ };
+ const refused = (res, msgId) => {
+ expect(res.status).toBe(422);
+ expect(res.body.issue[0].code).toBe('not-supported');
+ expect(res.body.issue[0].extension[0].valueString).toBe(msgId);
+ };
+
+ describe('$expand: what is applied to it (A8)', () => {
+ test('nothing asked: all of it, the hierarchy kept', async () => {
+ const res = await expand(vs());
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['a', 'b', 'c', 'c1']);
+ expect(res.body.expansion.total).toBe(4);
+ expect(res.body.expansion.contains[2].contains[0].code).toBe('c1');
+ });
+
+ test('count and offset page it', async () => {
+ let res = await expand(vs(), [{ name: 'count', valueInteger: 1 }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['a']);
+ expect(res.body.expansion.total).toBe(4);
+ res = await expand(vs(), [{ name: 'offset', valueInteger: 1 }, { name: 'count', valueInteger: 2 }]);
+ expect(codes(res)).toEqual(['b', 'c']);
+ });
+
+ test('filter selects from it', async () => {
+ const res = await expand(vs(), [{ name: 'filter', valueString: 'beta' }]);
+ expect(res.status).toBe(200);
+ expect(codes(res)).toEqual(['b']);
+ });
+
+ test('activeOnly leaves out its inactive codes', async () => {
+ const res = await expand(vs(), [{ name: 'activeOnly', valueBoolean: true }]);
+ expect(codes(res)).toEqual(['a', 'c', 'c1']);
+ });
+
+ test('excludeNotForUI leaves out its abstract codes, and what is under them moves up', async () => {
+ const res = await expand(vs(), [{ name: 'excludeNotForUI', valueBoolean: true }]);
+ expect(codes(res)).toEqual(['a', 'b', 'c1']);
+ expect(res.body.expansion.contains.map(c => c.code)).toEqual(['a', 'b', 'c1']);
+ });
+
+ test('excludeNested flattens it', async () => {
+ const res = await expand(vs(), [{ name: 'excludeNested', valueBoolean: true }]);
+ expect(res.body.expansion.contains.map(c => c.code)).toEqual(['a', 'b', 'c', 'c1']);
+ });
+
+ test('the parameters it was made with are carried over', async () => {
+ const res = await expand(vs());
+ expect(res.body.expansion.parameter).toContainEqual({ name: 'used-codesystem', valueUri: CS + '|1.0.0' });
+ });
+ });
+
+ describe('$expand: what must match', () => {
+ test('display language: the default (en) matches, another does not', async () => {
+ expect((await expand(vs(), [{ name: 'displayLanguage', valueCode: 'en' }])).status).toBe(200);
+ expect((await expand(vs(), [], 'en-US')).status).toBe(200);
+ refused(await expand(vs(), [{ name: 'displayLanguage', valueCode: 'de' }]), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ refused(await expand(vs(), [], 'de'), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ });
+
+ test('display language: the value set\'s language, or the one it was made with, matches', async () => {
+ expect((await expand(vs({}, { language: 'de' }), [{ name: 'displayLanguage', valueCode: 'de' }])).status).toBe(200);
+ const made = vs({ parameter: [{ name: 'displayLanguage', valueCode: 'fr' }] });
+ expect((await expand(made, [{ name: 'displayLanguage', valueCode: 'fr' }])).status).toBe(200);
+ refused(await expand(made, [{ name: 'displayLanguage', valueCode: 'en' }]), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ });
+
+ test('made with activeOnly: it has no inactive codes to give a request that wants them', async () => {
+ const made = vs({ parameter: [{ name: 'activeOnly', valueBoolean: true }] });
+ refused(await expand(made), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ expect((await expand(made, [{ name: 'activeOnly', valueBoolean: true }])).status).toBe(200);
+ });
+
+ test('only part of an expansion: offset, or fewer codes than the total', async () => {
+ refused(await expand(vs({ total: 10 })), 'VALUESET_STORED_EXPANSION_PARTIAL');
+ refused(await expand(vs({ offset: 2 })), 'VALUESET_STORED_EXPANSION_PARTIAL');
+ });
+
+ test('made with a filter: only the same filter', async () => {
+ const made = vs({ parameter: [{ name: 'filter', valueString: 'gamma' }] });
+ refused(await expand(made), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ expect((await expand(made, [{ name: 'filter', valueString: 'gamma' }])).status).toBe(200);
+ });
+
+ test('properties and designations it does not have', async () => {
+ refused(await expand(vs(), [{ name: 'property', valueString: 'inactive' }]), 'VALUESET_STORED_EXPANSION_MISSING');
+ const declares = vs({ property: [{ code: 'inactive', uri: 'http://hl7.org/fhir/concept-properties#inactive' }] });
+ expect((await expand(declares, [{ name: 'property', valueString: 'inactive' }])).status).toBe(200);
+ refused(await expand(vs(), [{ name: 'includeDesignations', valueBoolean: true }]), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ });
+
+ test('code system versions', async () => {
+ expect((await expand(vs(), [{ name: 'force-system-version', valueCanonical: CS + '|1.0.0' }])).status).toBe(200);
+ refused(await expand(vs(), [{ name: 'force-system-version', valueCanonical: CS + '|2.0.0' }]), 'VALUESET_STORED_EXPANSION_VERSION');
+ refused(await expand(vs(), [{ name: 'check-system-version', valueCanonical: CS + '|2.0.0' }]), 'VALUESET_STORED_EXPANSION_VERSION');
+ });
+
+ test('a supplement it was not made with', async () => {
+ refused(await expand(vs(), [{ name: 'useSupplement', valueCanonical: 'http://example.org/fhir/CodeSystem/stored-supplement' }]),
+ 'VALUESET_STORED_EXPANSION_MISSING');
+ });
+
+ test('a compose whose code system is available is expanded, whatever the stored expansion', async () => {
+ const withCompose = vs({ parameter: [{ name: 'activeOnly', valueBoolean: true }] });
+ withCompose.compose = { include: [{ system: CS }] };
+ const res = await expand(withCompose, [{ name: 'tx-resource', resource: CODESYSTEM }]);
+ expect(res.status).toBe(200);
+ expect(codes(res).sort()).toEqual(['a', 'b', 'c', 'c1']);
+ });
+
+ test('a compose whose code system is not available: the stored expansion, if it matches', async () => {
+ const withCompose = vs({ parameter: [{ name: 'activeOnly', valueBoolean: true }] });
+ withCompose.compose = { include: [{ system: CS }] };
+ refused(await expand(withCompose), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ expect((await expand(withCompose, [{ name: 'activeOnly', valueBoolean: true }])).status).toBe(200);
+ });
+ });
+
+ describe('imports', () => {
+ const outer = { resourceType: 'ValueSet', url: 'http://example.org/fhir/ValueSet/outer', status: 'active',
+ compose: { include: [{ valueSet: ['http://example.org/fhir/ValueSet/stored'] }] } };
+
+ test('what is applied to it is applied to the import', async () => {
+ const res = await expand(outer, [{ name: 'tx-resource', resource: vs() }, { name: 'activeOnly', valueBoolean: true }]);
+ expect(res.status).toBe(200);
+ expect(codes(res).sort()).toEqual(['a', 'c', 'c1']);
+ });
+
+ test('what must match must match', async () => {
+ refused(await expand(outer, [{ name: 'tx-resource', resource: vs() }, { name: 'displayLanguage', valueCode: 'de' }]),
+ 'VALUESET_STORED_EXPANSION_PARAMETER');
+ });
+ });
+
+ describe('$validate-code', () => {
+ const validate = (valueSet, code, more = []) => post('validate-code', [{ name: 'valueSet', resource: valueSet },
+ { name: 'system', valueUri: CS }, { name: 'code', valueCode: code }, { name: 'tx-resource', resource: CODESYSTEM }, ...more]);
+ const result = res => res.body.parameter.find(p => p.name === 'result').valueBoolean;
+
+ test('membership is the stored expansion\'s', async () => {
+ expect(result(await validate(vs(), 'a'))).toBe(true);
+ });
+
+ test('activeOnly: an inactive code is not in it', async () => {
+ expect(result(await validate(vs(), 'b'))).toBe(true);
+ expect(result(await validate(vs(), 'b', [{ name: 'activeOnly', valueBoolean: true }]))).toBe(false);
+ });
+
+ test('only what decides membership must match: not the display language', async () => {
+ expect((await validate(vs(), 'a', [{ name: 'displayLanguage', valueCode: 'de' }])).status).toBe(200);
+ refused(await validate(vs({ total: 10 }), 'a'), 'VALUESET_STORED_EXPANSION_PARTIAL');
+ refused(await validate(vs({ parameter: [{ name: 'activeOnly', valueBoolean: true }] }), 'a'), 'VALUESET_STORED_EXPANSION_PARAMETER');
+ });
+ });
+});
diff --git a/tests/tx/subsumes.test.js b/tests/tx/subsumes.test.js
index 6ab46de3f..e887cd615 100644
--- a/tests/tx/subsumes.test.js
+++ b/tests/tx/subsumes.test.js
@@ -293,6 +293,9 @@ describe('Subsumes Worker', () => {
expect(response.status).toBe(404);
expect(response.body.resourceType).toBe('OperationOutcome');
+ // a valid IssueType (it was 'not found'), and the tx-issue-type that goes with it (A7)
+ expect(response.body.issue[0].code).toBe('not-found');
+ expect(response.body.issue[0].details.coding).toEqual([{ system: 'http://hl7.org/fhir/tools/CodeSystem/tx-issue-type', code: 'not-found' }]);
});
test('should return 400 when codes are missing for instance subsumes', async () => {
diff --git a/tests/tx/supplement-display.test.js b/tests/tx/supplement-display.test.js
new file mode 100644
index 000000000..c45c48d00
--- /dev/null
+++ b/tests/tx/supplement-display.test.js
@@ -0,0 +1,84 @@
+/**
+ * The display a provider gives a code from the supplements in use (CodeSystemProvider
+ * _displayFromSupplements: the descriptions of $lookup's parent and child properties, $closure's
+ * displays), A13: a display designation in the language asked for is used whatever the supplement's
+ * own language - one declared in another, or none, where a designation without a language is in its
+ * supplement's - and a request in the code system's language keeps its own displays.
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const DISPLAY = { system: 'http://terminology.hl7.org/CodeSystem/designation-usage', code: 'display' };
+
+const BASE = {
+ resourceType: 'CodeSystem', url: 'http://example.org/cs/hier', version: '1.0', status: 'active', content: 'complete', hierarchyMeaning: 'is-a',
+ concept: [{ code: 'A', display: 'Alpha', concept: [{ code: 'A1', display: 'Alpha one' }] }]
+};
+
+function supplement(language, designationLanguage) {
+ const d = (value) => Object.assign({ use: DISPLAY, value }, designationLanguage ? { language: designationLanguage } : {});
+ return Object.assign({
+ resourceType: 'CodeSystem', url: 'http://example.org/cs/hier-es', version: '1.0', status: 'active', content: 'supplement', supplements: BASE.url,
+ concept: [{ code: 'A', designation: [d('Alfa')] }, { code: 'A1', designation: [d('Alfa uno')] }]
+ }, language ? { language } : {});
+}
+
+describe('displays from supplements: $lookup parent and child descriptions (A13)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library.yaml'),
+ endpoints: [{ path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ async function lookup(code, supp, language) {
+ const res = await request(app).post('/tx/r5/CodeSystem/$lookup')
+ .set('Content-Type', 'application/json').set('Accept-Language', language)
+ .send({ resourceType: 'Parameters', parameter: [
+ { name: 'system', valueUri: BASE.url }, { name: 'code', valueCode: code }, { name: 'useSupplement', valueCanonical: supp.url },
+ { name: 'tx-resource', resource: BASE }, { name: 'tx-resource', resource: supp }] });
+ expect(res.status).toBe(200);
+ const ps = res.body.parameter;
+ const description = (prop) => {
+ const p = ps.find(x => x.name === 'property' && x.part[0].valueCode === prop);
+ return p ? p.part.find(x => x.name === 'description').valueString : null;
+ };
+ return { display: ps.find(p => p.name === 'display').valueString, parent: description('parent'), child: description('child') };
+ }
+
+ test.each([
+ ['a supplement in that language', 'es', 'es'],
+ ['a supplement in another language', 'en', 'es'],
+ ['a supplement with no language', null, 'es'],
+ ['a supplement in that language, its designations without one', 'es', null]
+ ])('es, %s: the parent and child are described in Spanish', async (name, language, designationLanguage) => {
+ const supp = supplement(language, designationLanguage);
+ expect(await lookup('A1', supp, 'es')).toEqual({ display: 'Alfa uno', parent: 'Alfa', child: null });
+ expect(await lookup('A', supp, 'es')).toEqual({ display: 'Alfa', parent: null, child: 'Alfa uno' });
+ });
+
+ test('en: the code system\'s own displays', async () => {
+ expect(await lookup('A1', supplement('es', 'es'), 'en')).toEqual({ display: 'Alpha one', parent: 'Alpha', child: null });
+ });
+
+ test('a designation without a language, in a supplement without one, is not taken to be in the language asked for', async () => {
+ expect(await lookup('A1', supplement(null, null), 'es')).toEqual({ display: 'Alpha one', parent: 'Alpha', child: null });
+ });
+});
diff --git a/tests/tx/supplement-properties.test.js b/tests/tx/supplement-properties.test.js
new file mode 100644
index 000000000..e73b6a74c
--- /dev/null
+++ b/tests/tx/supplement-properties.test.js
@@ -0,0 +1,114 @@
+/**
+ * The properties a CodeSystem supplement in use gives a code, in $expand and $lookup, whatever
+ * the code system's provider (A12): built-in ones with no properties of their own (UCUM, the URI
+ * code system) and FHIR CodeSystems alike. Reported when asked for, as the code system's own are,
+ * with the supplement's definition (the uri, in expansion.property and R4's extension), and once.
+ * (LOINC, main's and sqlite-v2's: sqlite-v2-loinc.test.js)
+ */
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+
+jest.setTimeout(60000);
+
+const NOTE_URI = 'http://example.org/prop/localNote';
+
+function supplement(system, code) {
+ return {
+ resourceType: 'CodeSystem', url: 'http://example.org/cs/supp', version: '1.0', status: 'active', content: 'supplement', supplements: system,
+ property: [{ code: 'localNote', uri: NOTE_URI, type: 'string' }],
+ concept: [{ code, property: [{ code: 'localNote', valueString: 'note from supplement' }] }]
+ };
+}
+
+const OWN = {
+ resourceType: 'CodeSystem', url: 'http://example.org/cs/own', version: '1', status: 'active', content: 'complete',
+ property: [{ code: 'p1', uri: 'http://example.org/prop/p1', type: 'string' }],
+ concept: [{ code: 'x', display: 'X', property: [{ code: 'p1', valueString: 'own' }] }]
+};
+
+const SYSTEMS = [
+ ['UCUM', 'http://unitsofmeasure.org', 'mg', []],
+ ['the URI code system', 'urn:ietf:rfc:3986', 'http://example.org/thing', []],
+ ['a FHIR CodeSystem', OWN.url, 'x', [OWN]]
+];
+
+describe('supplement properties, for every provider (A12)', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json({ limit: '10mb' }));
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-ucum-uri.yaml'),
+ endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }, { path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ });
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ function common(system, code, resources, properties) {
+ const s = supplement(system, code);
+ return [
+ { name: 'useSupplement', valueCanonical: s.url },
+ ...[s, ...resources].map(r => ({ name: 'tx-resource', resource: r })),
+ ...properties.map(p => ({ name: 'property', valueCode: p }))
+ ];
+ }
+
+ async function expand(ep, system, code, resources, properties) {
+ const res = await request(app).post(`/tx/${ep}/ValueSet/$expand`).set('Content-Type', 'application/json').send({
+ resourceType: 'Parameters', parameter: [
+ { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system, concept: [{ code }] }] } } },
+ ...common(system, code, resources, properties)]
+ });
+ expect(res.status).toBe(200);
+ return res.body.expansion;
+ }
+
+ async function lookup(system, code, resources, properties) {
+ const res = await request(app).post('/tx/r5/CodeSystem/$lookup').set('Content-Type', 'application/json').send({
+ resourceType: 'Parameters', parameter: [{ name: 'system', valueUri: system }, { name: 'code', valueCode: code }, ...common(system, code, resources, properties)]
+ });
+ expect(res.status).toBe(200);
+ return res.body.parameter.filter(p => p.name === 'property').map(p => p.part.find(x => x.name === 'code').valueCode + '=' + p.part.find(x => x.name === 'value').valueString);
+ }
+
+ test.each(SYSTEMS)('%s: $expand reports the property asked for, with its uri', async (name, system, code, resources) => {
+ const exp = await expand('r5', system, code, resources, ['localNote']);
+ expect(exp.property).toEqual([{ code: 'localNote', uri: NOTE_URI }]);
+ expect(exp.contains[0].property).toEqual([{ code: 'localNote', valueString: 'note from supplement' }]);
+ });
+
+ test.each(SYSTEMS)('%s: on R4, the uri is in the expansion.property extension', async (name, system, code, resources) => {
+ const exp = await expand('r4', system, code, resources, ['localNote']);
+ const decl = exp.extension.filter(e => e.url === 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.property');
+ expect(decl).toEqual([{ url: decl[0].url, extension: [{ url: 'code', valueCode: 'localNote' }, { url: 'uri', valueUri: NOTE_URI }] }]);
+ });
+
+ test.each(SYSTEMS)('%s: $expand doesn\'t report it when it isn\'t asked for', async (name, system, code, resources) => {
+ const exp = await expand('r5', system, code, resources, []);
+ expect(exp.property).toBeUndefined();
+ expect(exp.contains[0].property).toBeUndefined();
+ });
+
+ test.each(SYSTEMS)('%s: $lookup reports it when asked for, and not when another property is', async (name, system, code, resources) => {
+ expect(await lookup(system, code, resources, ['localNote'])).toEqual(['localNote=note from supplement']);
+ expect(await lookup(system, code, resources, ['nothing'])).toEqual([]);
+ });
+
+ test('a FHIR CodeSystem: its own properties and the supplement\'s, each once', async () => {
+ const exp = await expand('r5', OWN.url, 'x', [OWN], ['*']);
+ expect(exp.contains[0].property).toEqual([{ code: 'p1', valueString: 'own' }, { code: 'localNote', valueString: 'note from supplement' }]);
+ // ('*' brings the standard ones too: inactive and notSelectable, which are not strings)
+ expect((await lookup(OWN.url, 'x', [OWN], ['*'])).filter(p => !p.endsWith('=undefined')).sort()).toEqual(['localNote=note from supplement', 'p1=own']);
+ });
+});
diff --git a/tests/tx/test-cases.test.js b/tests/tx/test-cases.test.js
index a64da6b3f..7d65d5a5d 100644
--- a/tests/tx/test-cases.test.js
+++ b/tests/tx/test-cases.test.js
@@ -830,6 +830,454 @@ describe('parameters', () => {
await runTest({"suite":"parameters","test":"parameters-lookup-supplement-bad"}, "4.0");
});
+ it("parameters-count-all-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-all-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-all-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-full"}, "5.0");
+ });
+
+ it("parameters-count-all-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-full"}, "4.0");
+ });
+
+ it("parameters-count-all-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-all-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-all-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-full"}, "5.0");
+ });
+
+ it("parameters-count-all-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-full"}, "4.0");
+ });
+
+ it("parameters-count-isa-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-isa-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-isa-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-isa-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-full"}, "4.0");
+ });
+
+ it("parameters-count-isa-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-isa-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-isa-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-isa-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-full"}, "4.0");
+ });
+
+ it("parameters-count-enum-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-enum-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-enum-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-enum-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-full"}, "4.0");
+ });
+
+ it("parameters-count-enum-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-enum-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-enum-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-enum-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-overlap-enum-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-full"}, "4.0");
+ });
+
+ it("parameters-count-exclude-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-exclude-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-exclude-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-exclude-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-full"}, "4.0");
+ });
+
+ it("parameters-count-exclude-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-exclude-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-exclude-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-exclude-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-full"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-plain-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-plain-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-plain-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-plain-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-full"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-active-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-active-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-active-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-active-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-full"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-notforui-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-notforui-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-notforui-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-notforui-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-full"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-both-count0" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-both-count0" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-count0"}, "4.0");
+ });
+
+ it("parameters-count-all-filter-both-full" + 'R5', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-both-full" + 'R4', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-full"}, "4.0");
+ });
+
});
describe('language', () => {
@@ -1027,6 +1475,46 @@ describe('language', () => {
await runTest({"suite":"language","test":"language-lookup-en-multi-de-param"}, "4.0");
});
+ it("language-lookup-en-multi-child-de-header" + 'R5', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-child-de-header" + 'R4', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-header"}, "4.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param" + 'R5', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param" + 'R4', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param"}, "4.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param-es-header" + 'R5', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param-es-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param-es-header" + 'R4', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param-es-header"}, "4.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-header" + 'R5', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-header" + 'R4', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-header"}, "4.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-param" + 'R5', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-param"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-param" + 'R4', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-param"}, "4.0");
+ });
+
it("language-xform-en-multi-de-default" + 'R5', async () => {
await runTest({"suite":"language","test":"language-xform-en-multi-de-default"}, "5.0");
});
@@ -1908,28 +2396,84 @@ describe('extensions', () => {
await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild"}, "4.0");
});
- it("validate-supplements-grandchild-wrong-display" + 'R5', async () => {
- await runTest({"suite":"extensions","test":"validate-supplements-grandchild-wrong-display"}, "5.0");
+ it("lookup-supplements-hierarchy-child-de" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de"}, "5.0");
});
- it("validate-supplements-grandchild-wrong-display" + 'R4', async () => {
- await runTest({"suite":"extensions","test":"validate-supplements-grandchild-wrong-display"}, "4.0");
+ it("lookup-supplements-hierarchy-child-de" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de"}, "4.0");
});
- it("validate-supplement-nolang-display" + 'R5', async () => {
- await runTest({"suite":"extensions","test":"validate-supplement-nolang-display"}, "5.0");
+ it("lookup-supplements-hierarchy-child-nl" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl"}, "5.0");
});
- it("validate-supplement-nolang-display" + 'R4', async () => {
- await runTest({"suite":"extensions","test":"validate-supplement-nolang-display"}, "4.0");
+ it("lookup-supplements-hierarchy-child-nl" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl"}, "4.0");
});
- it("validate-supplement-nolang-designation" + 'R5', async () => {
- await runTest({"suite":"extensions","test":"validate-supplement-nolang-designation"}, "5.0");
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr"}, "5.0");
});
- it("validate-supplement-nolang-designation" + 'R4', async () => {
- await runTest({"suite":"extensions","test":"validate-supplement-nolang-designation"}, "4.0");
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr"}, "4.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-de-param" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-de-param" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param"}, "4.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-nl-param" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl-param"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-nl-param" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl-param"}, "4.0");
+ });
+
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr-param" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr-param"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr-param" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr-param"}, "4.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-de-param-nl-header" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param-nl-header"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-de-param-nl-header" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param-nl-header"}, "4.0");
+ });
+
+ it("validate-supplements-grandchild-wrong-display" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplements-grandchild-wrong-display"}, "5.0");
+ });
+
+ it("validate-supplements-grandchild-wrong-display" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplements-grandchild-wrong-display"}, "4.0");
+ });
+
+ it("validate-supplement-nolang-display" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplement-nolang-display"}, "5.0");
+ });
+
+ it("validate-supplement-nolang-display" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplement-nolang-display"}, "4.0");
+ });
+
+ it("validate-supplement-nolang-designation" + 'R5', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplement-nolang-designation"}, "5.0");
+ });
+
+ it("validate-supplement-nolang-designation" + 'R4', async () => {
+ await runTest({"suite":"extensions","test":"validate-supplement-nolang-designation"}, "4.0");
});
it("validate-supplement-nolang-other-lang" + 'R5', async () => {
@@ -4907,32 +5451,810 @@ describe('errors', () => {
await runTest({"suite":"errors","test":"combination-ok"}, "5.0");
});
- it("combination-ok" + 'R4', async () => {
- await runTest({"suite":"errors","test":"combination-ok"}, "4.0");
+ it("combination-ok" + 'R4', async () => {
+ await runTest({"suite":"errors","test":"combination-ok"}, "4.0");
+ });
+
+ it("combination-bad" + 'R5', async () => {
+ await runTest({"suite":"errors","test":"combination-bad"}, "5.0");
+ });
+
+ it("combination-bad" + 'R4', async () => {
+ await runTest({"suite":"errors","test":"combination-bad"}, "4.0");
+ });
+
+ it("infer-unknown-system" + 'R5', async () => {
+ await runTest({"suite":"errors","test":"infer-unknown-system"}, "5.0");
+ });
+
+ it("infer-unknown-system" + 'R4', async () => {
+ await runTest({"suite":"errors","test":"infer-unknown-system"}, "4.0");
+ });
+
+ it("infer-unknown-system-import" + 'R5', async () => {
+ await runTest({"suite":"errors","test":"infer-unknown-system-import"}, "5.0");
+ });
+
+ it("infer-unknown-system-import" + 'R4', async () => {
+ await runTest({"suite":"errors","test":"infer-unknown-system-import"}, "4.0");
+ });
+
+});
+
+describe('modifiers', () => {
+ // Modifier extensions: a resource or a parameter with a modifier extension the server doesn't understand can't be used, wherever the extension is - on the resource, any element in it, a resource it depends on (a code system or supplement), or a parameter of the request - and whether or not the operation reads that element: a modifier extension changes the meaning of what it's on, and there's nowhere in these resources where that doesn't matter. Each test presents the resources in the request with a made-up modifier extension in one place, to one operation, and the request is refused as an error in the request (4xx), with an issue that says where the extension is. The same requests without the extension succeed
+
+ it("modifier-vs-root-expand" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-expand"}, "5.0");
+ });
+
+ it("modifier-vs-root-expand" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-expand"}, "4.0");
+ });
+
+ it("modifier-vs-root-validate" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-validate"}, "5.0");
+ });
+
+ it("modifier-vs-root-validate" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-validate"}, "4.0");
+ });
+
+ it("modifier-vs-compose" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-compose"}, "5.0");
+ });
+
+ it("modifier-vs-compose" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-compose"}, "4.0");
+ });
+
+ it("modifier-vs-include" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include"}, "5.0");
+ });
+
+ it("modifier-vs-include" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include"}, "4.0");
+ });
+
+ it("modifier-vs-include-concept" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept"}, "5.0");
+ });
+
+ it("modifier-vs-include-concept" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept"}, "4.0");
+ });
+
+ it("modifier-vs-include-concept-designation" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept-designation"}, "5.0");
+ });
+
+ it("modifier-vs-include-concept-designation" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept-designation"}, "4.0");
+ });
+
+ it("modifier-vs-include-filter" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-filter"}, "5.0");
+ });
+
+ it("modifier-vs-include-filter" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-filter"}, "4.0");
+ });
+
+ it("modifier-vs-exclude" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude"}, "5.0");
+ });
+
+ it("modifier-vs-exclude" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude"}, "4.0");
+ });
+
+ it("modifier-vs-exclude-concept" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude-concept"}, "5.0");
+ });
+
+ it("modifier-vs-exclude-concept" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude-concept"}, "4.0");
+ });
+
+ it("modifier-vs-expansion" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion"}, "5.0");
+ });
+
+ it("modifier-vs-expansion" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion"}, "4.0");
+ });
+
+ it("modifier-vs-expansion-contains" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion-contains"}, "5.0");
+ });
+
+ it("modifier-vs-expansion-contains" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion-contains"}, "4.0");
+ });
+
+ it("modifier-cs-root-lookup" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-lookup"}, "5.0");
+ });
+
+ it("modifier-cs-root-lookup" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-lookup"}, "4.0");
+ });
+
+ it("modifier-cs-root-expand" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-expand"}, "5.0");
+ });
+
+ it("modifier-cs-root-expand" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-expand"}, "4.0");
+ });
+
+ it("modifier-cs-concept" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept"}, "5.0");
+ });
+
+ it("modifier-cs-concept" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept"}, "4.0");
+ });
+
+ it("modifier-cs-concept-nested" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-nested"}, "5.0");
+ });
+
+ it("modifier-cs-concept-nested" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-nested"}, "4.0");
+ });
+
+ it("modifier-cs-concept-designation" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-designation"}, "5.0");
+ });
+
+ it("modifier-cs-concept-designation" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-designation"}, "4.0");
+ });
+
+ it("modifier-cs-concept-property" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-property"}, "5.0");
+ });
+
+ it("modifier-cs-concept-property" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-property"}, "4.0");
+ });
+
+ it("modifier-cs-property" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-property"}, "5.0");
+ });
+
+ it("modifier-cs-property" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-property"}, "4.0");
+ });
+
+ it("modifier-cs-filter" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-filter"}, "5.0");
+ });
+
+ it("modifier-cs-filter" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-filter"}, "4.0");
+ });
+
+ it("modifier-cs-supplement" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement"}, "5.0");
+ });
+
+ it("modifier-cs-supplement" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement"}, "4.0");
+ });
+
+ it("modifier-cs-supplement-designation" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement-designation"}, "5.0");
+ });
+
+ it("modifier-cs-supplement-designation" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement-designation"}, "4.0");
+ });
+
+ it("modifier-cm-root" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-root"}, "5.0");
+ });
+
+ it("modifier-cm-root" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-root"}, "4.0");
+ });
+
+ it("modifier-cm-group" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-group"}, "5.0");
+ });
+
+ it("modifier-cm-group" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-group"}, "4.0");
+ });
+
+ it("modifier-cm-element" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-element"}, "5.0");
+ });
+
+ it("modifier-cm-element" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-element"}, "4.0");
+ });
+
+ it("modifier-cm-target" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-target"}, "5.0");
+ });
+
+ it("modifier-cm-target" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-target"}, "4.0");
+ });
+
+ it("modifier-cm-dependson" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-dependson"}, "5.0");
+ });
+
+ it("modifier-cm-dependson" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-dependson"}, "4.0");
+ });
+
+ it("modifier-cm-unmapped" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-unmapped"}, "5.0");
+ });
+
+ it("modifier-cm-unmapped" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-unmapped"}, "4.0");
+ });
+
+ it("modifier-param-expand" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-expand"}, "5.0");
+ });
+
+ it("modifier-param-expand" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-expand"}, "4.0");
+ });
+
+ it("modifier-param-validate" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-validate"}, "5.0");
+ });
+
+ it("modifier-param-validate" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-validate"}, "4.0");
+ });
+
+ it("modifier-param-cs-validate" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-cs-validate"}, "5.0");
+ });
+
+ it("modifier-param-cs-validate" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-cs-validate"}, "4.0");
+ });
+
+ it("modifier-param-lookup" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-lookup"}, "5.0");
+ });
+
+ it("modifier-param-lookup" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-lookup"}, "4.0");
+ });
+
+ it("modifier-param-subsumes" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-subsumes"}, "5.0");
+ });
+
+ it("modifier-param-subsumes" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-subsumes"}, "4.0");
+ });
+
+ it("modifier-param-translate" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-translate"}, "5.0");
+ });
+
+ it("modifier-param-translate" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-translate"}, "4.0");
+ });
+
+ it("modifier-param-tx-resource" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-tx-resource"}, "5.0");
+ });
+
+ it("modifier-param-tx-resource" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-tx-resource"}, "4.0");
+ });
+
+ it("modifier-param-unknown" + 'R5', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-unknown"}, "5.0");
+ });
+
+ it("modifier-param-unknown" + 'R4', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-unknown"}, "4.0");
+ });
+
+});
+
+describe('stored-expansion', () => {
+ // Stored expansions: a value set that has an expansion of its own (ValueSet.expansion) - here, sent in the request - is used only when its compose can't be (there isn't one, or a code system it includes isn't available), and then as an expansion made with the parameters it records (expansion.parameter; one that isn't there was the default). The request's count, offset, filter, activeOnly, excludeNotForUI and excludeNested are applied to it; the rest must match what it was made with - the display language (the value set's language, or the default, en, when it doesn't say), designations, properties, the code system versions it was made from, the supplements used - and one that is only part of an expansion, or was made with a filter, isn't the value set. When it can't answer the request, the request is refused (4xx): a stored expansion made some other way is not the answer. The same goes for a value set with a stored expansion that is imported, and for $validate-code, where only what decides membership must match (displays are checked against the code system)
+
+ it("stored-expansion-expand-none" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-none"}, "5.0");
+ });
+
+ it("stored-expansion-expand-none" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-none"}, "4.0");
+ });
+
+ it("stored-expansion-expand-count" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-count" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count"}, "4.0");
+ });
+
+ it("stored-expansion-expand-count-zero" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count-zero"}, "5.0");
+ });
+
+ it("stored-expansion-expand-count-zero" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count-zero"}, "4.0");
+ });
+
+ it("stored-expansion-expand-offset-count" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-offset-count" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-count"}, "4.0");
+ });
+
+ it("stored-expansion-expand-offset-past" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-past"}, "5.0");
+ });
+
+ it("stored-expansion-expand-offset-past" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-past"}, "4.0");
+ });
+
+ it("stored-expansion-expand-filter" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter"}, "4.0");
+ });
+
+ it("stored-expansion-expand-filter-parent" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-parent"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-parent" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-parent"}, "4.0");
+ });
+
+ it("stored-expansion-expand-filter-none" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-none"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-none" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-none"}, "4.0");
+ });
+
+ it("stored-expansion-expand-filter-count" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-count" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-count"}, "4.0");
+ });
+
+ it("stored-expansion-expand-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly"}, "4.0");
+ });
+
+ it("stored-expansion-expand-activeonly-false" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-false"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly-false" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-false"}, "4.0");
+ });
+
+ it("stored-expansion-expand-notforui" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-expand-notforui" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-notforui"}, "4.0");
+ });
+
+ it("stored-expansion-expand-nested" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-nested"}, "5.0");
+ });
+
+ it("stored-expansion-expand-nested" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-nested"}, "4.0");
+ });
+
+ it("stored-expansion-expand-activeonly-notforui" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly-notforui" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-notforui"}, "4.0");
+ });
+
+ it("stored-expansion-expand-lang-en" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-en" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en"}, "4.0");
+ });
+
+ it("stored-expansion-expand-lang-en-us" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en-us"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-en-us" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en-us"}, "4.0");
+ });
+
+ it("stored-expansion-expand-lang-vs" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-vs"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-vs" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-vs"}, "4.0");
+ });
+
+ it("stored-expansion-expand-lang-made" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-made"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-made" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-made"}, "4.0");
+ });
+
+ it("stored-expansion-expand-made-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-expand-made-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-activeonly"}, "4.0");
+ });
+
+ it("stored-expansion-expand-made-filter" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-filter"}, "5.0");
+ });
+
+ it("stored-expansion-expand-made-filter" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-filter"}, "4.0");
+ });
+
+ it("stored-expansion-expand-property" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-property"}, "5.0");
+ });
+
+ it("stored-expansion-expand-property" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-property"}, "4.0");
+ });
+
+ it("stored-expansion-expand-designations" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-designations"}, "5.0");
+ });
+
+ it("stored-expansion-expand-designations" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-designations"}, "4.0");
+ });
+
+ it("stored-expansion-expand-force-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-force-version"}, "5.0");
+ });
+
+ it("stored-expansion-expand-force-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-force-version"}, "4.0");
+ });
+
+ it("stored-expansion-expand-check-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-check-version"}, "5.0");
+ });
+
+ it("stored-expansion-expand-check-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-check-version"}, "4.0");
+ });
+
+ it("stored-expansion-expand-supplement" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-supplement"}, "5.0");
+ });
+
+ it("stored-expansion-expand-supplement" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-supplement"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-lang" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-lang-made" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-made"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang-made" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-made"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-lang-vs" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-vs"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang-vs" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-vs"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-made-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-activeonly"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-made-notforui" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-notforui" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-notforui"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-made-postcoord" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-postcoord"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-postcoord" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-postcoord"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-partial-total" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-total"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-partial-total" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-total"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-partial-offset" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-offset"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-partial-offset" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-offset"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-made-filter" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-filter" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-made-filter-other" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter-other"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-filter-other" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter-other"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-property" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-property" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-property-all" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property-all"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-property-all" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property-all"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-designations" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designations"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-designations" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designations"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-designation" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designation"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-designation" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designation"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-force-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-force-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-force-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-force-version"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-check-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-check-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-check-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-check-version"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-system-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-system-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-system-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-system-version"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-version-unrecorded" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-version-unrecorded"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-version-unrecorded" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-version-unrecorded"}, "4.0");
+ });
+
+ it("stored-expansion-refuse-supplement" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-supplement"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-supplement" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-supplement"}, "4.0");
+ });
+
+ it("stored-expansion-compose-available" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-available"}, "5.0");
+ });
+
+ it("stored-expansion-compose-available" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-available"}, "4.0");
+ });
+
+ it("stored-expansion-compose-unavailable" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable"}, "5.0");
+ });
+
+ it("stored-expansion-compose-unavailable" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable"}, "4.0");
+ });
+
+ it("stored-expansion-compose-unavailable-refuse" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable-refuse"}, "5.0");
+ });
+
+ it("stored-expansion-compose-unavailable-refuse" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable-refuse"}, "4.0");
+ });
+
+ it("stored-expansion-import" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import"}, "5.0");
+ });
+
+ it("stored-expansion-import" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import"}, "4.0");
+ });
+
+ it("stored-expansion-import-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-import-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-activeonly"}, "4.0");
+ });
+
+ it("stored-expansion-import-filter" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-filter"}, "5.0");
+ });
+
+ it("stored-expansion-import-filter" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-filter"}, "4.0");
+ });
+
+ it("stored-expansion-import-count" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-count"}, "5.0");
+ });
+
+ it("stored-expansion-import-count" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-count"}, "4.0");
+ });
+
+ it("stored-expansion-import-refuse-lang" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-lang"}, "5.0");
+ });
+
+ it("stored-expansion-import-refuse-lang" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-lang"}, "4.0");
+ });
+
+ it("stored-expansion-import-refuse-partial" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-partial"}, "5.0");
+ });
+
+ it("stored-expansion-import-refuse-partial" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-partial"}, "4.0");
+ });
+
+ it("stored-expansion-validate-member" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-member"}, "5.0");
+ });
+
+ it("stored-expansion-validate-member" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-member"}, "4.0");
+ });
+
+ it("stored-expansion-validate-not-member" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-not-member"}, "5.0");
+ });
+
+ it("stored-expansion-validate-not-member" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-not-member"}, "4.0");
+ });
+
+ it("stored-expansion-validate-inactive" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive"}, "5.0");
+ });
+
+ it("stored-expansion-validate-inactive" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive"}, "4.0");
+ });
+
+ it("stored-expansion-validate-inactive-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-validate-inactive-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive-activeonly"}, "4.0");
+ });
+
+ it("stored-expansion-validate-lang" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-lang"}, "5.0");
+ });
+
+ it("stored-expansion-validate-lang" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-lang"}, "4.0");
});
- it("combination-bad" + 'R5', async () => {
- await runTest({"suite":"errors","test":"combination-bad"}, "5.0");
+ it("stored-expansion-validate-refuse-partial" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-partial"}, "5.0");
});
- it("combination-bad" + 'R4', async () => {
- await runTest({"suite":"errors","test":"combination-bad"}, "4.0");
+ it("stored-expansion-validate-refuse-partial" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-partial"}, "4.0");
});
- it("infer-unknown-system" + 'R5', async () => {
- await runTest({"suite":"errors","test":"infer-unknown-system"}, "5.0");
+ it("stored-expansion-validate-refuse-made-activeonly" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-made-activeonly"}, "5.0");
});
- it("infer-unknown-system" + 'R4', async () => {
- await runTest({"suite":"errors","test":"infer-unknown-system"}, "4.0");
+ it("stored-expansion-validate-refuse-made-activeonly" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-made-activeonly"}, "4.0");
});
- it("infer-unknown-system-import" + 'R5', async () => {
- await runTest({"suite":"errors","test":"infer-unknown-system-import"}, "5.0");
+ it("stored-expansion-validate-refuse-version" + 'R5', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-version"}, "5.0");
});
- it("infer-unknown-system-import" + 'R4', async () => {
- await runTest({"suite":"errors","test":"infer-unknown-system-import"}, "4.0");
+ it("stored-expansion-validate-refuse-version" + 'R4', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-version"}, "4.0");
});
});
@@ -6032,6 +7354,54 @@ describe('case', () => {
await runTest({"suite":"case","test":"case-cs-subsumes-other-case"}, "4.0");
});
+ it("case-ci-activeonly-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-activeonly-other-case"}, "5.0");
+ });
+
+ it("case-ci-activeonly-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-activeonly-other-case"}, "4.0");
+ });
+
+ it("case-ci-active-vs-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-active-vs-other-case"}, "5.0");
+ });
+
+ it("case-ci-active-vs-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-active-vs-other-case"}, "4.0");
+ });
+
+ it("case-ci-in-filter-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-other-case"}, "5.0");
+ });
+
+ it("case-ci-in-filter-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-other-case"}, "4.0");
+ });
+
+ it("case-ci-in-filter-expand-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-expand-other-case"}, "5.0");
+ });
+
+ it("case-ci-in-filter-expand-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-expand-other-case"}, "4.0");
+ });
+
+ it("case-ci-not-in-filter-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-other-case"}, "5.0");
+ });
+
+ it("case-ci-not-in-filter-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-other-case"}, "4.0");
+ });
+
+ it("case-ci-not-in-filter-expand-other-case" + 'R5', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-expand-other-case"}, "5.0");
+ });
+
+ it("case-ci-not-in-filter-expand-other-case" + 'R4', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-expand-other-case"}, "4.0");
+ });
+
});
describe('translate', () => {
@@ -8106,6 +9476,54 @@ describe('loinc', () => {
await runTest({"suite":"loinc","test":"loinc-translate-sct-answer"}, "4.0");
});
+ it("loinc-expand-supplement-property" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property"}, "5.0");
+ });
+
+ it("loinc-expand-supplement-property" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property"}, "4.0");
+ });
+
+ it("loinc-expand-supplement-property-mixed" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-mixed"}, "5.0");
+ });
+
+ it("loinc-expand-supplement-property-mixed" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-mixed"}, "4.0");
+ });
+
+ it("loinc-expand-supplement-property-not-asked" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("loinc-expand-supplement-property-not-asked" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-not-asked"}, "4.0");
+ });
+
+ it("loinc-lookup-supplement-property" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property"}, "4.0");
+ });
+
+ it("loinc-lookup-supplement-property-mixed" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-mixed"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property-mixed" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-mixed"}, "4.0");
+ });
+
+ it("loinc-lookup-supplement-property-not-asked" + 'R5', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property-not-asked" + 'R4', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-not-asked"}, "4.0");
+ });
+
});
describe('snomed', () => {
@@ -9143,6 +10561,54 @@ describe('snomed', () => {
await runTest({"suite":"snomed","test":"snomed-expand-display-regex-nl"}, "4.0");
});
+ it("snomed-expand-supplement-property" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property"}, "5.0");
+ });
+
+ it("snomed-expand-supplement-property" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property"}, "4.0");
+ });
+
+ it("snomed-expand-supplement-property-mixed" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-mixed"}, "5.0");
+ });
+
+ it("snomed-expand-supplement-property-mixed" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-mixed"}, "4.0");
+ });
+
+ it("snomed-expand-supplement-property-not-asked" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("snomed-expand-supplement-property-not-asked" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-not-asked"}, "4.0");
+ });
+
+ it("snomed-lookup-supplement-property" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property"}, "4.0");
+ });
+
+ it("snomed-lookup-supplement-property-mixed" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-mixed"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property-mixed" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-mixed"}, "4.0");
+ });
+
+ it("snomed-lookup-supplement-property-not-asked" + 'R5', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property-not-asked" + 'R4', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-not-asked"}, "4.0");
+ });
+
});
describe('sct-ec', () => {
@@ -11464,6 +12930,54 @@ describe('UCUM', () => {
await runTest({"suite":"UCUM","test":"validate-ucum-all-bad"}, "4.0");
});
+ it("validate-ucum-all-double-solidus" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-double-solidus"}, "5.0");
+ });
+
+ it("validate-ucum-all-double-solidus" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-double-solidus"}, "4.0");
+ });
+
+ it("validate-ucum-all-stray-close" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-stray-close"}, "5.0");
+ });
+
+ it("validate-ucum-all-stray-close" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-stray-close"}, "4.0");
+ });
+
+ it("validate-ucum-all-two-annotations" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-two-annotations"}, "5.0");
+ });
+
+ it("validate-ucum-all-two-annotations" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-two-annotations"}, "4.0");
+ });
+
+ it("validate-ucum-all-signed-factor" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-signed-factor"}, "5.0");
+ });
+
+ it("validate-ucum-all-signed-factor" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-signed-factor"}, "4.0");
+ });
+
+ it("validate-ucum-all-annotated-number" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-number"}, "5.0");
+ });
+
+ it("validate-ucum-all-annotated-number" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-number"}, "4.0");
+ });
+
+ it("validate-ucum-all-annotated-bracket" + 'R5', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-bracket"}, "5.0");
+ });
+
+ it("validate-ucum-all-annotated-bracket" + 'R4', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-bracket"}, "4.0");
+ });
+
it("ucum-subsumes-equivalent" + 'R5', async () => {
await runTest({"suite":"UCUM","test":"ucum-subsumes-equivalent"}, "5.0");
});
@@ -16337,6 +17851,230 @@ describe('parameters', () => {
await runTest({"suite":"parameters","test":"parameters-lookup-supplement-bad"}, "5.0");
});
+ it("parameters-count-all-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-all-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-active-full"}, "5.0");
+ });
+
+ it("parameters-count-all-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-all-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-both-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-active-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-isa-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-isa-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-isa-both-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-active-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-enum-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-enum-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-enum-both-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-active-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-both-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-active-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-overlap-enum-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-overlap-enum-both-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-active-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-exclude-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-exclude-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-exclude-both-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-plain-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-plain-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-plain-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-active-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-active-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-active-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-notforui-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-notforui-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-notforui-full"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-both-count0" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-count0"}, "5.0");
+ });
+
+ it("parameters-count-all-filter-both-full" + 'R5-cached', async () => {
+ await runTest({"suite":"parameters","test":"parameters-count-all-filter-both-full"}, "5.0");
+ });
+
});
describe('language', () => {
@@ -16438,6 +18176,26 @@ describe('language', () => {
await runTest({"suite":"language","test":"language-lookup-en-multi-de-param"}, "5.0");
});
+ it("language-lookup-en-multi-child-de-header" + 'R5-cached', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param" + 'R5-cached', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-child-de-param-es-header" + 'R5-cached', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-child-de-param-es-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-header" + 'R5-cached', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-header"}, "5.0");
+ });
+
+ it("language-lookup-en-multi-parent-de-param" + 'R5-cached', async () => {
+ await runTest({"suite":"language","test":"language-lookup-en-multi-parent-de-param"}, "5.0");
+ });
+
it("language-xform-en-multi-de-default" + 'R5-cached', async () => {
await runTest({"suite":"language","test":"language-xform-en-multi-de-default"}, "5.0");
});
@@ -16871,24 +18629,52 @@ describe('extensions', () => {
await runTest({"suite":"extensions","test":"validate-coding-good2-supplement"}, "5.0");
});
- it("validate-code-inactive-display-lenient" + 'R5-cached', async () => {
- await runTest({"suite":"extensions","test":"validate-code-inactive-display-lenient"}, "5.0");
+ it("validate-code-inactive-display-lenient" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"validate-code-inactive-display-lenient"}, "5.0");
+ });
+
+ it("validate-code-inactive-display-notlenient" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"validate-code-inactive-display-notlenient"}, "5.0");
+ });
+
+ it("validate-code-inactive" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"validate-code-inactive"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-grandchild" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-de" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-child-nl" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl"}, "5.0");
+ });
+
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr"}, "5.0");
});
- it("validate-code-inactive-display-notlenient" + 'R5-cached', async () => {
- await runTest({"suite":"extensions","test":"validate-code-inactive-display-notlenient"}, "5.0");
+ it("lookup-supplements-hierarchy-child-de-param" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param"}, "5.0");
});
- it("validate-code-inactive" + 'R5-cached', async () => {
- await runTest({"suite":"extensions","test":"validate-code-inactive"}, "5.0");
+ it("lookup-supplements-hierarchy-child-nl-param" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-nl-param"}, "5.0");
});
- it("lookup-supplements-hierarchy-child" + 'R5-cached', async () => {
- await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child"}, "5.0");
+ it("lookup-supplements-hierarchy-grandchild-nolang-fr-param" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild-nolang-fr-param"}, "5.0");
});
- it("lookup-supplements-hierarchy-grandchild" + 'R5-cached', async () => {
- await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-grandchild"}, "5.0");
+ it("lookup-supplements-hierarchy-child-de-param-nl-header" + 'R5-cached', async () => {
+ await runTest({"suite":"extensions","test":"lookup-supplements-hierarchy-child-de-param-nl-header"}, "5.0");
});
it("validate-supplements-grandchild-wrong-display" + 'R5-cached', async () => {
@@ -18424,6 +20210,400 @@ describe('errors', () => {
});
+describe('modifiers', () => {
+ // Modifier extensions: a resource or a parameter with a modifier extension the server doesn't understand can't be used, wherever the extension is - on the resource, any element in it, a resource it depends on (a code system or supplement), or a parameter of the request - and whether or not the operation reads that element: a modifier extension changes the meaning of what it's on, and there's nowhere in these resources where that doesn't matter. Each test presents the resources in the request with a made-up modifier extension in one place, to one operation, and the request is refused as an error in the request (4xx), with an issue that says where the extension is. The same requests without the extension succeed
+
+ it("modifier-vs-root-expand" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-expand"}, "5.0");
+ });
+
+ it("modifier-vs-root-validate" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-root-validate"}, "5.0");
+ });
+
+ it("modifier-vs-compose" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-compose"}, "5.0");
+ });
+
+ it("modifier-vs-include" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include"}, "5.0");
+ });
+
+ it("modifier-vs-include-concept" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept"}, "5.0");
+ });
+
+ it("modifier-vs-include-concept-designation" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-concept-designation"}, "5.0");
+ });
+
+ it("modifier-vs-include-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-include-filter"}, "5.0");
+ });
+
+ it("modifier-vs-exclude" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude"}, "5.0");
+ });
+
+ it("modifier-vs-exclude-concept" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-exclude-concept"}, "5.0");
+ });
+
+ it("modifier-vs-expansion" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion"}, "5.0");
+ });
+
+ it("modifier-vs-expansion-contains" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-vs-expansion-contains"}, "5.0");
+ });
+
+ it("modifier-cs-root-lookup" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-lookup"}, "5.0");
+ });
+
+ it("modifier-cs-root-expand" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-root-expand"}, "5.0");
+ });
+
+ it("modifier-cs-concept" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept"}, "5.0");
+ });
+
+ it("modifier-cs-concept-nested" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-nested"}, "5.0");
+ });
+
+ it("modifier-cs-concept-designation" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-designation"}, "5.0");
+ });
+
+ it("modifier-cs-concept-property" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-concept-property"}, "5.0");
+ });
+
+ it("modifier-cs-property" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-property"}, "5.0");
+ });
+
+ it("modifier-cs-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-filter"}, "5.0");
+ });
+
+ it("modifier-cs-supplement" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement"}, "5.0");
+ });
+
+ it("modifier-cs-supplement-designation" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cs-supplement-designation"}, "5.0");
+ });
+
+ it("modifier-cm-root" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-root"}, "5.0");
+ });
+
+ it("modifier-cm-group" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-group"}, "5.0");
+ });
+
+ it("modifier-cm-element" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-element"}, "5.0");
+ });
+
+ it("modifier-cm-target" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-target"}, "5.0");
+ });
+
+ it("modifier-cm-dependson" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-dependson"}, "5.0");
+ });
+
+ it("modifier-cm-unmapped" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-cm-unmapped"}, "5.0");
+ });
+
+ it("modifier-param-expand" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-expand"}, "5.0");
+ });
+
+ it("modifier-param-validate" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-validate"}, "5.0");
+ });
+
+ it("modifier-param-cs-validate" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-cs-validate"}, "5.0");
+ });
+
+ it("modifier-param-lookup" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-lookup"}, "5.0");
+ });
+
+ it("modifier-param-subsumes" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-subsumes"}, "5.0");
+ });
+
+ it("modifier-param-translate" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-translate"}, "5.0");
+ });
+
+ it("modifier-param-tx-resource" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-tx-resource"}, "5.0");
+ });
+
+ it("modifier-param-unknown" + 'R5-cached', async () => {
+ await runTest({"suite":"modifiers","test":"modifier-param-unknown"}, "5.0");
+ });
+
+});
+
+describe('stored-expansion', () => {
+ // Stored expansions: a value set that has an expansion of its own (ValueSet.expansion) - here, sent in the request - is used only when its compose can't be (there isn't one, or a code system it includes isn't available), and then as an expansion made with the parameters it records (expansion.parameter; one that isn't there was the default). The request's count, offset, filter, activeOnly, excludeNotForUI and excludeNested are applied to it; the rest must match what it was made with - the display language (the value set's language, or the default, en, when it doesn't say), designations, properties, the code system versions it was made from, the supplements used - and one that is only part of an expansion, or was made with a filter, isn't the value set. When it can't answer the request, the request is refused (4xx): a stored expansion made some other way is not the answer. The same goes for a value set with a stored expansion that is imported, and for $validate-code, where only what decides membership must match (displays are checked against the code system)
+
+ it("stored-expansion-expand-none" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-none"}, "5.0");
+ });
+
+ it("stored-expansion-expand-count" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-count-zero" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-count-zero"}, "5.0");
+ });
+
+ it("stored-expansion-expand-offset-count" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-offset-past" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-offset-past"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-parent" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-parent"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-none" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-none"}, "5.0");
+ });
+
+ it("stored-expansion-expand-filter-count" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-filter-count"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly-false" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-false"}, "5.0");
+ });
+
+ it("stored-expansion-expand-notforui" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-expand-nested" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-nested"}, "5.0");
+ });
+
+ it("stored-expansion-expand-activeonly-notforui" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-activeonly-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-en" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-en-us" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-en-us"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-vs" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-vs"}, "5.0");
+ });
+
+ it("stored-expansion-expand-lang-made" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-lang-made"}, "5.0");
+ });
+
+ it("stored-expansion-expand-made-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-expand-made-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-made-filter"}, "5.0");
+ });
+
+ it("stored-expansion-expand-property" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-property"}, "5.0");
+ });
+
+ it("stored-expansion-expand-designations" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-designations"}, "5.0");
+ });
+
+ it("stored-expansion-expand-force-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-force-version"}, "5.0");
+ });
+
+ it("stored-expansion-expand-check-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-check-version"}, "5.0");
+ });
+
+ it("stored-expansion-expand-supplement" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-expand-supplement"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang-made" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-made"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-lang-vs" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-lang-vs"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-notforui" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-notforui"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-postcoord" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-postcoord"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-partial-total" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-total"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-partial-offset" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-partial-offset"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-made-filter-other" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-made-filter-other"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-property" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-property-all" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-property-all"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-designations" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designations"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-designation" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-designation"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-force-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-force-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-check-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-check-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-system-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-system-version"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-version-unrecorded" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-version-unrecorded"}, "5.0");
+ });
+
+ it("stored-expansion-refuse-supplement" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-refuse-supplement"}, "5.0");
+ });
+
+ it("stored-expansion-compose-available" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-available"}, "5.0");
+ });
+
+ it("stored-expansion-compose-unavailable" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable"}, "5.0");
+ });
+
+ it("stored-expansion-compose-unavailable-refuse" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-compose-unavailable-refuse"}, "5.0");
+ });
+
+ it("stored-expansion-import" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import"}, "5.0");
+ });
+
+ it("stored-expansion-import-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-import-filter" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-filter"}, "5.0");
+ });
+
+ it("stored-expansion-import-count" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-count"}, "5.0");
+ });
+
+ it("stored-expansion-import-refuse-lang" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-lang"}, "5.0");
+ });
+
+ it("stored-expansion-import-refuse-partial" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-import-refuse-partial"}, "5.0");
+ });
+
+ it("stored-expansion-validate-member" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-member"}, "5.0");
+ });
+
+ it("stored-expansion-validate-not-member" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-not-member"}, "5.0");
+ });
+
+ it("stored-expansion-validate-inactive" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive"}, "5.0");
+ });
+
+ it("stored-expansion-validate-inactive-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-inactive-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-validate-lang" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-lang"}, "5.0");
+ });
+
+ it("stored-expansion-validate-refuse-partial" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-partial"}, "5.0");
+ });
+
+ it("stored-expansion-validate-refuse-made-activeonly" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-made-activeonly"}, "5.0");
+ });
+
+ it("stored-expansion-validate-refuse-version" + 'R5-cached', async () => {
+ await runTest({"suite":"stored-expansion","test":"stored-expansion-validate-refuse-version"}, "5.0");
+ });
+
+});
+
describe('deprecated', () => {
// Testing Deprecated+Withdrawn warnings
@@ -18983,6 +21163,30 @@ describe('case', () => {
await runTest({"suite":"case","test":"case-cs-subsumes-other-case"}, "5.0");
});
+ it("case-ci-activeonly-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-activeonly-other-case"}, "5.0");
+ });
+
+ it("case-ci-active-vs-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-active-vs-other-case"}, "5.0");
+ });
+
+ it("case-ci-in-filter-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-other-case"}, "5.0");
+ });
+
+ it("case-ci-in-filter-expand-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-in-filter-expand-other-case"}, "5.0");
+ });
+
+ it("case-ci-not-in-filter-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-other-case"}, "5.0");
+ });
+
+ it("case-ci-not-in-filter-expand-other-case" + 'R5-cached', async () => {
+ await runTest({"suite":"case","test":"case-ci-not-in-filter-expand-other-case"}, "5.0");
+ });
+
});
describe('translate', () => {
@@ -20101,6 +22305,30 @@ describe('loinc', () => {
await runTest({"suite":"loinc","test":"loinc-translate-sct-answer"}, "5.0");
});
+ it("loinc-expand-supplement-property" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property"}, "5.0");
+ });
+
+ it("loinc-expand-supplement-property-mixed" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-mixed"}, "5.0");
+ });
+
+ it("loinc-expand-supplement-property-not-asked" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-expand-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property-mixed" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-mixed"}, "5.0");
+ });
+
+ it("loinc-lookup-supplement-property-not-asked" + 'R5-cached', async () => {
+ await runTest({"suite":"loinc","test":"loinc-lookup-supplement-property-not-asked"}, "5.0");
+ });
+
});
describe('snomed', () => {
@@ -20622,6 +22850,30 @@ describe('snomed', () => {
await runTest({"suite":"snomed","test":"snomed-expand-display-regex-nl"}, "5.0");
});
+ it("snomed-expand-supplement-property" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property"}, "5.0");
+ });
+
+ it("snomed-expand-supplement-property-mixed" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-mixed"}, "5.0");
+ });
+
+ it("snomed-expand-supplement-property-not-asked" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-expand-supplement-property-not-asked"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property-mixed" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-mixed"}, "5.0");
+ });
+
+ it("snomed-lookup-supplement-property-not-asked" + 'R5-cached', async () => {
+ await runTest({"suite":"snomed","test":"snomed-lookup-supplement-property-not-asked"}, "5.0");
+ });
+
});
describe('sct-ec', () => {
@@ -21799,6 +24051,30 @@ describe('UCUM', () => {
await runTest({"suite":"UCUM","test":"validate-ucum-all-bad"}, "5.0");
});
+ it("validate-ucum-all-double-solidus" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-double-solidus"}, "5.0");
+ });
+
+ it("validate-ucum-all-stray-close" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-stray-close"}, "5.0");
+ });
+
+ it("validate-ucum-all-two-annotations" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-two-annotations"}, "5.0");
+ });
+
+ it("validate-ucum-all-signed-factor" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-signed-factor"}, "5.0");
+ });
+
+ it("validate-ucum-all-annotated-number" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-number"}, "5.0");
+ });
+
+ it("validate-ucum-all-annotated-bracket" + 'R5-cached', async () => {
+ await runTest({"suite":"UCUM","test":"validate-ucum-all-annotated-bracket"}, "5.0");
+ });
+
it("ucum-subsumes-equivalent" + 'R5-cached', async () => {
await runTest({"suite":"UCUM","test":"ucum-subsumes-equivalent"}, "5.0");
});
diff --git a/tests/tx/text-index-store.test.js b/tests/tx/text-index-store.test.js
index d8d1bd97e..393b418fa 100644
--- a/tests/tx/text-index-store.test.js
+++ b/tests/tx/text-index-store.test.js
@@ -168,6 +168,32 @@ describe('TextIndexStore', () => {
}
});
+ test.each([
+ ['damaged pages', () => {
+ // keep the header and the first page (the schema); the tables' pages are garbage
+ const bytes = fs.readFileSync(file);
+ const pageSize = bytes.readUInt16BE(16);
+ bytes.fill(0xA5, pageSize);
+ fs.writeFileSync(file, bytes);
+ }],
+ ['not a database', () => fs.writeFileSync(file, 'this is not a database, but it is long enough to look like one at first glance'.repeat(20))]
+ ])('a damaged store (%s) is started again, and its indexes built again', async (_, damage) => {
+ let store = new TextIndexStore(file).open();
+ await store.prepare([item(codeSystem(CONCEPTS))]);
+ store.close();
+ damage();
+ const warnings = [];
+ const cs = codeSystem(CONCEPTS.map(c => ({ ...c })));
+ store = new TextIndexStore(file, { log: { warn: m => warnings.push(m) } }).open();
+ try {
+ expect(warnings).toEqual([expect.stringContaining('is damaged')]);
+ expect(await store.prepare([item(cs)])).toEqual({ kept: 0, built: 1, objects: 1 });
+ expect(TextIndexStore.indexFor(cs).searchCodes(new TextQuery('ap'))).toEqual([0]);
+ } finally {
+ store.close();
+ }
+ });
+
test('a supplement with an index in the store is searched from it, with the same answers', async () => {
const concepts = [
{ code: '2000-8', display: 'Kaltsiy qon zardobida', designation: [{ language: 'en', value: 'Calcium [Moles/volume] in Serum or Plasma' }] },
diff --git a/tests/tx/translate-product.test.js b/tests/tx/translate-product.test.js
new file mode 100644
index 000000000..a578c8a02
--- /dev/null
+++ b/tests/tx/translate-product.test.js
@@ -0,0 +1,111 @@
+// $translate's match.product (bug triage A4): it was built from R4's product.property, .system and
+// .value only, so an R5 map's product (attribute, value[x]) came out as an empty element and an
+// empty Coding. It's built in R5's form - attribute and value[x] - from either form of the map
+// (the internal form keeps R4's: tx/xversion), and xv-parameters.js makes it R4's element and
+// concept for R4 (and R3).
+
+const path = require('path');
+const express = require('express');
+const request = require('supertest');
+const TXModule = require('../../tx/tx');
+const { parametersFromR5 } = require('../../tx/xversion/xv-parameters');
+
+const SRC = 'http://example.org/src';
+const TGT = 'http://example.org/tgt';
+
+// a map with one target, whose product is given
+function map(product, extra = {}) {
+ return {
+ resourceType: 'ConceptMap', url: 'http://example.org/cm/prod', version: '1.0', status: 'active', ...extra,
+ group: [{ source: SRC, target: TGT, element: [{ code: 'A1', target: [{ code: 'B1', ...product }] }] }]
+ };
+}
+
+function products(body) {
+ const match = body.parameter.find(p => p.name === 'match');
+ return match.part.filter(p => p.name === 'product').map(p => p.part);
+}
+
+describe('$translate match.product', () => {
+ let app;
+ let txModule;
+
+ beforeAll(async () => {
+ app = express();
+ app.use(express.json());
+ txModule = new TXModule();
+ await txModule.initialize({
+ librarySource: path.join(__dirname, 'fixtures', 'test-library-snomed.yaml'),
+ endpoints: [{ path: '/tx/r4', fhirVersion: '4.0', context: null }, { path: '/tx/r5', fhirVersion: '5.0', context: null }]
+ }, app);
+ }, 120000);
+
+ afterAll(async () => {
+ if (txModule) {
+ await txModule.shutdown();
+ }
+ });
+
+ // R4 names the source system and code system and code; R5, sourceSystem and sourceCode
+ const translate = (version, cm) => request(app).post(`/tx/${version}/ConceptMap/$translate`)
+ .set('Content-Type', 'application/json').set('Accept', 'application/json')
+ .send({ resourceType: 'Parameters', parameter: [
+ { name: 'url', valueUri: cm.url },
+ { name: version === 'r4' ? 'system' : 'sourceSystem', valueUri: SRC },
+ { name: version === 'r4' ? 'code' : 'sourceCode', valueCode: 'A1' },
+ { name: 'tx-resource', resource: cm }] });
+
+ test('R5: an R5 map\'s product is attribute and value[x]', async () => {
+ const res = await translate('r5', map({ relationship: 'equivalent', product: [
+ { attribute: 'http://example.org/attr/out', valueCode: 'child-dose' },
+ { attribute: 'dose', valueCoding: { system: 'http://example.org/doses', code: 'd1' } }] },
+ { additionalAttribute: [{ code: 'dose', uri: 'http://example.org/attr/dose', type: 'Coding' }] }));
+ expect(res.status).toBe(200);
+ expect(products(res.body)).toEqual([
+ [{ name: 'attribute', valueUri: 'http://example.org/attr/out' }, { name: 'value', valueCode: 'child-dose' }],
+ // an attribute defined in additionalAttribute is reported by its uri
+ [{ name: 'attribute', valueUri: 'http://example.org/attr/dose' }, { name: 'value', valueCoding: { system: 'http://example.org/doses', code: 'd1' } }]
+ ]);
+ });
+
+ test('R4: an R4 map\'s product is element and concept', async () => {
+ const res = await translate('r4', map({ equivalence: 'equivalent', product: [
+ { property: 'http://example.org/attr/out', system: 'http://example.org/doses', value: 'd1', display: 'Dose 1' },
+ { property: 'http://example.org/attr/note', value: 'plain' }] }));
+ expect(res.status).toBe(200);
+ expect(products(res.body)).toEqual([
+ [{ name: 'element', valueUri: 'http://example.org/attr/out' },
+ { name: 'concept', valueCoding: { system: 'http://example.org/doses', code: 'd1', display: 'Dose 1' } }],
+ [{ name: 'element', valueUri: 'http://example.org/attr/note' }, { name: 'concept', valueCoding: { code: 'plain' } }]
+ ]);
+ });
+});
+
+describe('match.product for R4 and R3 (xv-parameters)', () => {
+ const r5 = {
+ resourceType: 'Parameters', parameter: [{ name: 'result', valueBoolean: true }, { name: 'match', part: [
+ { name: 'relationship', valueCode: 'equivalent' },
+ { name: 'product', part: [{ name: 'attribute', valueUri: 'http://example.org/a' }, { name: 'value', valueCode: 'x' }] },
+ { name: 'product', part: [{ name: 'attribute', valueUri: 'http://example.org/q' }, { name: 'value', valueQuantity: { value: 1, unit: 'mg' } }] },
+ { name: 'originMap', valueCanonical: 'http://example.org/cm' }] }]
+ };
+ const prods = p => p.parameter[1].part.filter(pp => pp.name === 'product').map(pp => pp.part);
+
+ test('R4: element and concept; a value with no code has no concept', () => {
+ const before = JSON.stringify(r5);
+ expect(prods(parametersFromR5(r5, '4.0.1'))).toEqual([
+ [{ name: 'element', valueUri: 'http://example.org/a' }, { name: 'concept', valueCoding: { code: 'x' } }],
+ [{ name: 'element', valueUri: 'http://example.org/q' }]
+ ]);
+ expect(JSON.stringify(r5)).toBe(before);
+ });
+
+ test('R3: the same, with R3\'s equivalence and source', () => {
+ const out = parametersFromR5(r5, '3.0.2');
+ expect(prods(out)[0]).toEqual([{ name: 'element', valueUri: 'http://example.org/a' }, { name: 'concept', valueCoding: { code: 'x' } }]);
+ const match = out.parameter[1].part;
+ expect(match.find(p => p.name === 'equivalence').valueCode).toBe('equivalent');
+ expect(match.find(p => p.name === 'relationship')).toBeUndefined();
+ expect(match.find(p => p.name === 'source').valueUri).toBe('http://example.org/cm');
+ });
+});
diff --git a/tests/tx/xversion-copy-on-write.test.js b/tests/tx/xversion-copy-on-write.test.js
index 8f1873379..fa4224ffc 100644
--- a/tests/tx/xversion-copy-on-write.test.js
+++ b/tests/tx/xversion-copy-on-write.test.js
@@ -241,7 +241,10 @@ describe('parametersFromR5', () => {
const r3 = parametersFromR5(deepFreeze(translateParameters()), '3.0.2');
const om = r3.parameter[1].part.find(p => p.name === 'originMap');
expect(om).toEqual({ name: 'originMap', valueUri: 'http://example.org/cm' });
- expect(r3.parameter[1].part.find(p => p.name === 'relationship')).toBeDefined();
+ // R3's match has the same shape as R4's: equivalence and source, not relationship (A4)
+ expect(r3.parameter[1].part.find(p => p.name === 'relationship')).toBeUndefined();
+ expect(r3.parameter[1].part.find(p => p.name === 'equivalence')).toBeDefined();
+ expect(r3.parameter[1].part.find(p => p.name === 'source')).toEqual({ name: 'source', valueUri: 'http://example.org/cm' });
});
test('parameters with nothing to convert are shared with the original', () => {
diff --git a/tests/tx/xversion-roundtrip.test.js b/tests/tx/xversion-roundtrip.test.js
new file mode 100644
index 000000000..4f8dfc3a2
--- /dev/null
+++ b/tests/tx/xversion-roundtrip.test.js
@@ -0,0 +1,175 @@
+//
+// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
+//
+// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause
+//
+
+/**
+ * The tx module's own version conversion (tx/xversion) against the terminology cases in
+ * fhir-test-cases conversion/roundtrip40_N (the cases the Java convertors are tested on).
+ *
+ * The tx conversions aren't full conversions: the internal form is R5 enough to work, with R4
+ * elements left in it (ConceptMap keeps equivalence beside relationship, for one). So these
+ * don't compare it with what the Java convertors make. What they check is what the tx module
+ * promises:
+ * - R4 in comes out as the same R4 (nothing that matters is lost on the way through)
+ * - what goes out as R4 is R4: the R5 elements R4 doesn't have are in cross-version
+ * extensions, not left in (the r6 cases are taken as R5: for these resources they're the same,
+ * except for the R6-only elements in R6_ONLY)
+ * - converting from R5 doesn't change the stored resource (it's copy on write)
+ *
+ * Without a fhir-test-cases clone ($FHIR_TEST_CASES, or ../test-cases beside FHIRsmith) the cases
+ * are downloaded into test-cache (tests/helpers/fhir-test-cases.js).
+ */
+
+const fs = require('fs');
+const path = require('path');
+const fhirJson = require('../../library/fhir/fhir-json');
+const folders = require('../../library/server/folder-setup');
+const { PackageManager } = require('../../library/fhir/package-manager');
+const { testCaseSelection } = require('../helpers/fhir-test-cases');
+const { convertResourceToR5, convertResourceFromR5 } = require('../../tx/xversion/xv-resource');
+
+const TYPES = ['CodeSystem', 'ValueSet', 'ConceptMap', 'NamingSystem', 'TerminologyCapabilities', 'Parameters', 'OperationOutcome'];
+const KINDS = ['resource', 'converted', 'returned'];
+
+// R6 elements, in the r6 cases, that R5 doesn't have: tx doesn't know them (its internal form is
+// R5), so they're not converted
+const R6_ONLY = [
+ 'ConceptMap.allowedRelationship',
+ 'TerminologyCapabilities.supplements',
+ 'TerminologyCapabilities.codeSystem.supplement',
+ 'TerminologyCapabilities.codeSystem.versionAlgorithmString',
+ 'TerminologyCapabilities.codeSystem.versionAlgorithmCoding',
+ 'TerminologyCapabilities.codeSystem.version.value',
+ 'TerminologyCapabilities.codeSystem.version.content',
+ 'TerminologyCapabilities.codeSystem.version.supplement',
+ 'TerminologyCapabilities.implementation.fragmentSupport',
+ 'TerminologyCapabilities.implementation.supplementSupport',
+ 'ValueSet.compose.include.filter.filter',
+ 'ValueSet.compose.exclude.filter.filter'
+];
+
+const selection = testCaseSelection('conversion/roundtrip40_N',
+ m => ['r4', 'r6'].flatMap(v => cases(m, v).flatMap(n => KINDS.map(k => `${v}/${k}/${n}`))));
+
+/** The cases of a version that are terminology resources */
+function cases(manifest, version) {
+ return Object.entries(manifest[version] || {}).filter(([, type]) => TYPES.includes(type)).map(([n]) => n).sort();
+}
+
+function read(version, name) {
+ return fhirJson.parse(fs.readFileSync(path.join(selection.folder, version, 'resource', name), 'utf8'));
+}
+
+// a deep copy, as if it had been read again (the conversions to R5 change what they're given)
+function again(resource) {
+ return fhirJson.parse(fhirJson.stringify(resource));
+}
+
+/**
+ * The elements of a resource that its R4 definition doesn't have (names only: choice types,
+ * primitive _x companions and nested types are followed; extension content isn't)
+ */
+function notR4(obj, type, definitions, base = type, out = []) {
+ const def = definitions(type);
+ if (!def) {
+ return out;
+ }
+ const els = def.snapshot.element;
+ const cap = s => s[0].toUpperCase() + s.slice(1);
+ for (const [k, v] of Object.entries(obj)) {
+ if (k === 'resourceType') {
+ continue;
+ }
+ const key = k.startsWith('_') ? k.slice(1) : k;
+ let el = els.find(e => e.path === `${base}.${key}`);
+ let choiceType = null;
+ if (!el) {
+ el = els.find(e => {
+ const name = e.path.slice(base.length + 1, -3);
+ return e.path.endsWith('[x]') && e.path.startsWith(base + '.') && !name.includes('.') && key.startsWith(name) &&
+ e.type.some(t => cap(t.code) === key.slice(name.length));
+ });
+ if (el) {
+ choiceType = key.slice(el.path.length - base.length - 4);
+ }
+ }
+ if (!el) {
+ out.push(`${base}.${key}`);
+ continue;
+ }
+ if (k.startsWith('_') || ['extension', 'modifierExtension', 'contained'].includes(key)) {
+ continue;
+ }
+ const tc = choiceType || (el.type && el.type[0].code);
+ for (const item of (Array.isArray(v) ? v : [v])) {
+ if (!item || typeof item !== 'object') {
+ continue;
+ }
+ if (el.contentReference) {
+ notR4(item, type, definitions, el.contentReference.slice(1), out);
+ } else if (tc === 'BackboneElement' || tc === 'Element') {
+ notR4(item, type, definitions, `${base}.${key}`, out);
+ } else if (/^[A-Z]/.test(tc) && tc !== 'Resource') {
+ notR4(item, tc, definitions, tc, out);
+ }
+ }
+ }
+ return out;
+}
+
+describe('tx version conversion (fhir-test-cases conversion/roundtrip40_N)', () => {
+ let definitions;
+
+ beforeAll(async () => {
+ const cache = folders.ensureFolder('terminology-cache');
+ const pm = new PackageManager(['https://packages2.fhir.org/packages', 'https://packages.fhir.org'], cache);
+ const folder = path.join(cache, await pm.fetch('hl7.fhir.r4.core', '4.0.1'), 'package');
+ const sds = {};
+ definitions = type => {
+ if (!(type in sds)) {
+ const f = path.join(folder, `StructureDefinition-${type}.json`);
+ sds[type] = fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : null;
+ }
+ return sds[type];
+ };
+ }, 120000);
+
+ test('there are cases for both versions', () => {
+ expect(cases(selection.manifest, 'r4').length).toBeGreaterThan(100);
+ expect(cases(selection.manifest, 'r6').length).toBeGreaterThan(100);
+ });
+
+ describe('R4 in comes out as the same R4', () => {
+ test.each(cases(selection.manifest, 'r4'))('%s', name => {
+ const src = read('r4', name);
+ const internal = convertResourceToR5(again(src), '4.0.1');
+ const out = convertResourceFromR5(internal, '4.0.1');
+ expect(fhirJson.stringify(again(out))).toEqual(fhirJson.stringify(src));
+ expect(notR4(out, src.resourceType, definitions)).toEqual([]);
+ });
+ });
+
+ describe('R5 goes out as R4, and the R5 resource is unchanged', () => {
+ test.each(cases(selection.manifest, 'r6'))('%s', name => {
+ const src = read('r6', name);
+ const before = fhirJson.stringify(src);
+ const out = convertResourceFromR5(src, '4.0.1');
+ expect(fhirJson.stringify(src)).toEqual(before);
+ expect(notR4(out, src.resourceType, definitions).filter(p => !R6_ONLY.includes(p))).toEqual([]);
+ });
+ });
+
+ test('A3: the products of an unmatched target survive the trip through R5 (ConceptMap-102)', () => {
+ const src = read('r4', 'ConceptMap-102.json');
+ const products = cm => cm.group.flatMap(g => g.element.flatMap(e => (e.target || []).filter(t => t.product))).length;
+ const internal = convertResourceToR5(again(src), '4.0.1');
+ // in R5, a noMap with them on the element
+ const bcyst = internal.group[0].element.find(e => e.code === 'BCYST');
+ expect(bcyst.noMap).toBe(true);
+ expect(bcyst.target).toBeUndefined();
+ expect(bcyst.extension.map(e => e.url)).toEqual(['http://hl7.org/fhir/4.0/StructureDefinition/extension-ConceptMap.group.element.target.product']);
+ expect(products(convertResourceFromR5(internal, '4.0.1'))).toBe(products(src));
+ });
+});
diff --git a/tests/tx/xversion.test.js b/tests/tx/xversion.test.js
index 558c8e694..b9f7d3fc3 100644
--- a/tests/tx/xversion.test.js
+++ b/tests/tx/xversion.test.js
@@ -306,3 +306,50 @@ describe('xversion — ValueSet compose.property', () => {
expect(convertResourceToR5(r4, '4.0').compose).toEqual({ include: [{ system: 'http://x' }] });
});
});
+
+describe('xversion — ValueSet expansion from R4 (a stored expansion a client sends)', () => {
+ const X = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.';
+ // as the Java convertors (and valueSetFromR5) write it
+ const r4 = () => ({ resourceType: 'ValueSet', status: 'active', expansion: {
+ timestamp: '2026-12-01T00:00:00Z',
+ extension: [
+ { url: 'http://other/ext', valueString: 'keep-me' },
+ { url: X + 'expansion.property', extension: [
+ { url: 'code', valueCode: 'inactive' }, { url: 'uri', valueUri: 'http://hl7.org/fhir/concept-properties#inactive' }] },
+ { url: X + 'expansion.property', extension: [{ url: 'code', valueCode: 'local' }] },
+ { url: X + 'expansion.next', valueUri: 'http://x/next' }
+ ],
+ contains: [{ system: 'http://x', code: 'a',
+ extension: [{ url: X + 'expansion.contains.property', extension: [{ url: 'code', valueCode: 'inactive' }, { url: 'value', valueBoolean: true }] }],
+ designation: [{ value: 'A', extension: [{ url: X + 'compose.include.concept.designation.additionalUse', valueCoding: { system: 'http://snomed.info/sct', code: '900000000000013009' } }] }],
+ contains: [{ system: 'http://x', code: 'a1',
+ extension: [{ url: X + 'expansion.contains.property', extension: [{ url: 'code', valueCode: 'local' }, { url: 'value', valueCoding: { system: 'http://y', code: 'z' } }] }] }]
+ }]
+ } });
+
+ test('R4 -> R5 lifts expansion.property, next, contains.property and additionalUse out of the extensions', () => {
+ const out = convertResourceToR5(r4(), '4.0');
+ expect(out.expansion.property).toEqual([
+ { code: 'inactive', uri: 'http://hl7.org/fhir/concept-properties#inactive' }, { code: 'local' }]);
+ expect(out.expansion.next).toBe('http://x/next');
+ expect(out.expansion.extension).toEqual([{ url: 'http://other/ext', valueString: 'keep-me' }]);
+ const a = out.expansion.contains[0];
+ expect(a.property).toEqual([{ code: 'inactive', valueBoolean: true }]);
+ expect(a.extension).toBeUndefined();
+ expect(a.designation[0]).toEqual({ value: 'A', additionalUse: [{ system: 'http://snomed.info/sct', code: '900000000000013009' }] });
+ expect(a.contains[0].property).toEqual([{ code: 'local', valueCoding: { system: 'http://y', code: 'z' } }]);
+ });
+
+ test('round trip R5 -> R4 -> R5', () => {
+ const r5 = convertResourceToR5(r4(), '4.0');
+ const back = convertResourceToR5(JSON.parse(JSON.stringify(convertResourceFromR5(r5, '4.0'))), '4.0');
+ expect(back.expansion.property).toEqual(r5.expansion.property);
+ expect(back.expansion.contains[0].property).toEqual(r5.expansion.contains[0].property);
+ expect(back.expansion.contains[0].contains[0].property).toEqual(r5.expansion.contains[0].contains[0].property);
+ expect(back.expansion.next).toBe('http://x/next');
+ });
+
+ test('an R3 expansion too', () => {
+ expect(convertResourceToR5(r4(), '3.0').expansion.property.map(p => p.code)).toEqual(['inactive', 'local']);
+ });
+});
diff --git a/tests/vcl/vcl-parser.test.js b/tests/vcl/vcl-parser.test.js
index 87999808e..8287c8894 100644
--- a/tests/vcl/vcl-parser.test.js
+++ b/tests/vcl/vcl-parser.test.js
@@ -188,35 +188,28 @@ describe('VCL Parser', () => {
});
test('Conjunction with comma', () => {
+ // , is an intersection (A16): codes that are both A and B - nothing, so B is an implicit value set
const vs = parseVCL('A,B');
expect(vs.compose.include.length).toBe(1);
const include = vs.compose.include[0];
- expect(include.concept.length).toBe(2);
- expect(include.concept[0].code).toBe('A');
- expect(include.concept[1].code).toBe('B');
+ expect(include.concept).toEqual([{ code: 'A' }]);
+ expect(include.valueSet).toEqual(['http://fhir.org/VCL?v1=B']);
});
test('Disjunction with semicolon', () => {
+ // codes in the same (no) system: one include
const vs = parseVCL('A;B');
- expect(vs.compose.include.length).toBe(2);
- expect(vs.compose.include[0].concept[0].code).toBe('A');
- expect(vs.compose.include[1].concept[0].code).toBe('B');
+ expect(vs.compose.include.length).toBe(1);
+ expect(vs.compose.include[0].concept).toEqual([{ code: 'A' }, { code: 'B' }]);
});
test('Wildcard with system', () => {
+ // all of the system: an include with just the system (A16)
const vs = parseVCL('(http://snomed.info/sct)*');
- expect(vs.compose.include.length).toBe(1);
- const include = vs.compose.include[0];
- expect(include.system).toBe('http://snomed.info/sct');
- expect(include.filter.length).toBe(1);
-
- const filter = include.filter[0];
- expect(filter.property).toBe('concept');
- expect(filter.op).toBe(FilterOperator.EXISTS);
- expect(filter.value).toBe('true');
+ expect(vs.compose.include).toEqual([{ system: 'http://snomed.info/sct' }]);
});
test('Multiple status codes', () => {
@@ -397,6 +390,12 @@ describe('VCL Parser', () => {
expect(() => parseVCL(null)).toThrow(VCLParseException);
});
+ test('anything but a string fails (a repeated request parameter is an array)', () => {
+ expect(() => parseVCL(['A', 'B'])).toThrow('VCL expression must be a string');
+ expect(() => parseVCL({ length: 1 })).toThrow(VCLParseException);
+ expect(() => new (require('../../vcl/vcl-parser').VCLLexer)(['A'])).toThrow(VCLParseException);
+ });
+
test('Invalid syntax should fail', () => {
expect(() => parseVCL('((unclosed')).toThrow(VCLParseException);
expect(() => parseVCL('A B C')).toThrow(VCLParseException); // No operators between codes
@@ -489,15 +488,13 @@ describe('VCL Parser', () => {
test('VCLParserClass should handle simple expressions', () => {
const { VCLLexer, VCLParserClass } = require('../../vcl/vcl-parser');
- const lexer = new VCLLexer('A,B');
+ const lexer = new VCLLexer('A;B');
const tokens = lexer.tokenize();
const parser = new VCLParserClass(tokens);
const vs = parser.parse();
-
+
expect(vs.compose.include.length).toBe(1);
- expect(vs.compose.include[0].concept.length).toBe(2);
- expect(vs.compose.include[0].concept[0].code).toBe('A');
- expect(vs.compose.include[0].concept[1].code).toBe('B');
+ expect(vs.compose.include[0].concept).toEqual([{ code: 'A' }, { code: 'B' }]);
});
});
});
diff --git a/tests/vcl/vcl-test-cases.test.js b/tests/vcl/vcl-test-cases.test.js
new file mode 100644
index 000000000..04a0a0275
--- /dev/null
+++ b/tests/vcl/vcl-test-cases.test.js
@@ -0,0 +1,43 @@
+/**
+ * The shared VCL test cases (fhir-test-cases vcl/vcl-tests.json, also run by org.hl7.fhir.core's
+ * VCLParser): each expression, and the compose it is, or that it is not valid VCL. The rules are in
+ * the readme beside them. Every implicit value set URL in a compose parses too.
+ */
+
+const fs = require('fs');
+const { testCaseFile } = require('../helpers/fhir-test-cases');
+const { parseVCL, vclFromImplicitUrl } = require('../../vcl/vcl-parser');
+
+const suite = JSON.parse(fs.readFileSync(testCaseFile('vcl/vcl-tests.json'), 'utf8'));
+
+/** the implicit value set URLs in a compose */
+function implicitUrls(compose) {
+ const urls = [];
+ for (const cs of [...(compose.include || []), ...(compose.exclude || [])]) {
+ for (const vs of cs.valueSet || []) {
+ urls.push(vs);
+ }
+ for (const f of cs.filter || []) {
+ urls.push(f.value);
+ }
+ }
+ return urls.filter(u => vclFromImplicitUrl(u) !== null);
+}
+
+describe('VCL: the shared test cases (fhir-test-cases vcl/vcl-tests.json)', () => {
+ test('the cases are there', () => {
+ expect(suite.cases.length).toBeGreaterThan(50);
+ });
+
+ test.each(suite.cases.map(c => [c.name, c]))('%s', (name, c) => {
+ if (c.error) {
+ expect(() => parseVCL(c.vcl)).toThrow();
+ return;
+ }
+ const vs = parseVCL(c.vcl);
+ expect(vs.compose).toEqual(c.compose);
+ for (const url of implicitUrls(vs.compose)) {
+ expect(() => parseVCL(vclFromImplicitUrl(url))).not.toThrow();
+ }
+ });
+});
diff --git a/tests/vcl/vcl.test.js b/tests/vcl/vcl.test.js
index 3e51cf18f..bdee0fc6a 100644
--- a/tests/vcl/vcl.test.js
+++ b/tests/vcl/vcl.test.js
@@ -1,16 +1,99 @@
+/**
+ * The /VCL web endpoint: ?vcl= any valid VCL (or an implicit VCL value set URL) gives the ValueSet;
+ * anything else is a 400 with the parser's message.
+ */
+const express = require('express');
+const request = require('supertest');
+const VCLModule = require('../../vcl/vcl');
+const { VCL_URI } = require('../../vcl/vcl-parser');
describe('VCL Module', () => {
+ let app;
+ const counted = [];
- beforeEach(async () => {
- // nothing
+ beforeAll(async () => {
+ const mod = new VCLModule({ countRequest: (name, tat) => counted.push([name, tat]) });
+ await mod.initialize({ enabled: true });
+ app = express();
+ app.use('/VCL', mod.router);
});
-
- afterEach(async () => {
- // nothing
+
+ const get = (vcl) => request(app).get('/VCL').query({ vcl });
+
+ // these all use characters the module once had a (never used) whitelist against: ; ^ < ~ * " { } ? !
+ test.each([
+ ['union', 'A;B'],
+ ['value set', '^http://hl7.org/fhir/ValueSet/payeetype'],
+ ['is-a', '(http://snomed.info/sct)concept<<17311000168105'],
+ ['is-not-a', '(http://snomed.info/sct)concept~<<929360061000036106'],
+ ['star', '(http://hl7.org/fhir/administrative-gender)*'],
+ ['regex', '(http://loinc.org)COMPONENT/".*Dichloroethane.*"'],
+ ['in a list', '(http://loinc.org)parent^{LP46821-2,LP259418-4}'],
+ ['exists', 'ingredient?true'],
+ ['descendent-leaf', '(http://snomed.info/sct)concept!!<17311000168105'],
+ ['exclusion', '(http://hl7.org/fhir/administrative-gender)* - (http://hl7.org/fhir/administrative-gender)male']
+ ])('accepts valid VCL: %s', async (name, vcl) => {
+ const res = await get(vcl);
+ expect(res.status).toBe(200);
+ expect(res.body.resourceType).toBe('ValueSet');
+ expect(res.body.url).toMatch(/^cid:/);
+ expect(res.body.compose.include.length).toBeGreaterThan(0);
});
-
- describe('Initialization', () => {
- test('Place Holder', () => {
+
+ test('the compose is the parser\'s', async () => {
+ const res = await get('(http://hl7.org/fhir/administrative-gender)(male;female)');
+ expect(res.body.compose).toEqual({
+ include: [{ system: 'http://hl7.org/fhir/administrative-gender', concept: [{ code: 'male' }, { code: 'female' }] }]
});
});
-});
\ No newline at end of file
+
+ test('an implicit VCL value set URL: its expression, and the URL as the url', async () => {
+ const url = VCL_URI + encodeURIComponent('(http://hl7.org/fhir/administrative-gender)(male;female)');
+ const res = await get(url);
+ expect(res.status).toBe(200);
+ expect(res.body.url).toBe(url);
+ expect(res.body.compose.include[0].concept).toEqual([{ code: 'male' }, { code: 'female' }]);
+ });
+
+ test('the old http://fhir.org/VCL/ form', async () => {
+ const res = await get('http://fhir.org/VCL/A;B');
+ expect(res.status).toBe(200);
+ expect(res.body.compose.include[0].concept).toEqual([{ code: 'A' }, { code: 'B' }]);
+ });
+
+ test.each([
+ ['mixed operators', 'A;B,C'],
+ ['unbalanced', '(A;B'],
+ ['unexpected character', 'A&B'],
+ ['too deep', '('.repeat(200) + 'a' + ')'.repeat(200)],
+ ['bad implicit URL', VCL_URI + '%E0%A4%A']
+ ])('invalid VCL is a 400 with the parser\'s message: %s', async (name, vcl) => {
+ const res = await get(vcl);
+ expect(res.status).toBe(400);
+ expect(res.body.error).toBe('VCL parsing error');
+ expect(res.body.message).toBeTruthy();
+ });
+
+ test('no expression is a 400', async () => {
+ expect((await request(app).get('/VCL')).status).toBe(400);
+ });
+
+ test('a repeated vcl parameter (an array) is a 400', async () => {
+ const res = await request(app).get('/VCL?vcl=A&vcl=B');
+ expect(res.status).toBe(400);
+ expect(res.body.error).toBe('Parameter pollution detected');
+ });
+
+ test('an unknown parameter is a 400', async () => {
+ expect((await request(app).get('/VCL').query({ vcl: 'A', other: 'x' })).status).toBe(400);
+ });
+
+ test('an expression over the length limit is a 400', async () => {
+ expect((await get('A'.repeat(10001))).status).toBe(400);
+ });
+
+ test('requests are counted', () => {
+ expect(counted.length).toBeGreaterThan(0);
+ expect(counted[0][0]).toBe('vcl');
+ });
+});
diff --git a/translations/Messages.properties b/translations/Messages.properties
index cd3a3b75e..708db7191 100644
--- a/translations/Messages.properties
+++ b/translations/Messages.properties
@@ -186,6 +186,8 @@ CONCEPTMAP_GROUP_TARGET_UNKNOWN = The Target Code System {0} is not fully define
TRANSLATE_TARGET_CS_UNKNOWN = The code system {0} is not known, and the code ''{1}'' has not been validated
TRANSLATE_SCT_EDITION_TOP_LEVEL_ONE = No translation: the only {0} ancestor of {1} is the top-level hierarchy concept {2}
TRANSLATE_SCT_EDITION_TOP_LEVEL_MANY = No translation: the only {0} ancestors of {1} are the top-level hierarchy concepts {2}
+CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN = The code system {0} can''t be processed: {1} has a modifier extension that isn''t understood ({2})
+CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN = The concept map {0} can''t be processed: {1} has a modifier extension that isn''t understood ({2})
CONCEPTMAP_SHAREABLE_EXTRA_MISSING = Published concept maps SHOULD conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} should be present, but it is not
CONCEPTMAP_SHAREABLE_EXTRA_MISSING_HL7 = Concept maps published by HL7 SHALL conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} should be present, but it is not
CONCEPTMAP_SHAREABLE_MISSING = Published concept maps SHOULD conform to the ShareableConceptMap profile, which says that the element ConceptMap.{0} is mandatory, but it is not present
@@ -573,7 +575,7 @@ NO_VALID_DISPLAY_FOUND_other = No valid Display Names found for {1}#{2} in the l
No_validator_configured = No validator configured
no_value_set = ValueSet has no url property
Node_type__is_not_allowed = Node type {0} is not allowed
-None_of_the_provided_codes_are_in_the_value_set_one = The provided code {2} was not found in the value set ''{1}''
+None_of_the_provided_codes_are_in_the_value_set_one = The provided code {2} is not in the value set ''{1}''
None_of_the_provided_codes_are_in_the_value_set_other = None of the provided codes [{2}] are in the value set ''{1}''
Not_done_yet = Not done yet
Not_done_yet__resolve__locally_2 = Not done yet - resolve {0} locally (2)
@@ -906,10 +908,10 @@ Terminology_TX_Code_ValueSet_MISSING = No code provided, and a code is required
Terminology_TX_Code_ValueSetMax = No code provided, and a code must be provided from the value set {0} (max value set {1})
Terminology_TX_Coding_Count = Expected {0} but found {1} coding elements
Terminology_TX_Confirm_1_CC = Could not confirm that the codings provided are in the value set {0} and a coding from this value set is required (class = {1})
-Terminology_TX_Confirm_2_CC = Could not confirm that the codings provided are in the value set {0} and a coding should come from this value set unless it has no suitable code (the validator cannot judge what is suitable) (class = {1})
+Terminology_TX_Confirm_2_CC = Could not confirm that the codings provided are in the value set {0} and a coding should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) (class = {1})
Terminology_TX_Confirm_3_CC = Could not confirm that the codings provided are in the value set {0} and a coding is recommended to come from this value set (class = {1})
-Terminology_TX_Confirm_4a = The code provided ({2}) was not found in the value set {0}, and a code from this value set is required: {1}
-Terminology_TX_Confirm_5 = The code provided ({1}) is not in the value set {0}, and a code should come from this value set unless it has no suitable code (the validator cannot judge what is suitable)
+Terminology_TX_Confirm_4a = The code provided ({2}) is not in the value set {0}, and a code from this value set is required: {1}
+Terminology_TX_Confirm_5 = The code provided ({1}) is not in the value set {0}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable)
Terminology_TX_Confirm_6 = The code provided ({1}) is not in the value set {0}, and a code is recommended to come from this value set
Terminology_TX_Display_Wrong = Display should be ''{0}''
Terminology_TX_Error_CodeableConcept = Error {0} validating CodeableConcept
@@ -922,18 +924,18 @@ TERMINOLOGY_TX_NOSVC_BOUND_REQ = Could not confirm that the codes provided are f
Terminology_TX_NoValid_1_CC = None of the codings provided are in the value set {0}, and a coding from this value set is required) (codes = {1})
Terminology_TX_NoValid_10 = The code provided is not in the maximum value set {0}, and a code from this value set is required) (code = {1}#{2})
Terminology_TX_NoValid_11 = The code provided is not in the maximum value set {0}, and a code from this value set is required) (code = {1}#{2}), error = {3})
-Terminology_TX_NoValid_12 = The Coding provided ({2}) was not found in the value set {0}, and a code is required from this value set. {1}
-Terminology_TX_NoValid_13 = The Coding provided ({2}) was not found in the value set {0}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable). {1}
-Terminology_TX_NoValid_14 = The Coding provided ({2}) was not found in the value set {0}, and a code is recommended to come from this value set. {1}
+Terminology_TX_NoValid_12 = The Coding provided ({2}) is not in the value set {0}, and a code is required from this value set. {1}
+Terminology_TX_NoValid_13 = The Coding provided ({2}) is not in the value set {0}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable). {1}
+Terminology_TX_NoValid_14 = The Coding provided ({2}) is not in the value set {0}, and a code is recommended to come from this value set. {1}
Terminology_TX_NoValid_15 = The value provided (''{0}'') could not be validated in the absence of a terminology server
-Terminology_TX_NoValid_16 = The value provided (''{0}'') was not found in the value set {1}, and a code is required from this value set {2}
-Terminology_TX_NoValid_17 = The value provided (''{0}'') was not found in the value set {1}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) {2}
-Terminology_TX_NoValid_18 = The value provided (''{0}'') was not found in the value set {1}, and a code is recommended to come from this value set{2}
+Terminology_TX_NoValid_16 = The value provided (''{0}'') is not in the value set {1}, and a code is required from this value set {2}
+Terminology_TX_NoValid_17 = The value provided (''{0}'') is not in the value set {1}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) {2}
+Terminology_TX_NoValid_18 = The value provided (''{0}'') is not in the value set {1}, and a code is recommended to come from this value set{2}
Terminology_TX_NoValid_2_CC = None of the codings provided are in the value set {0}, and a coding should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) (codes = {1})
Terminology_TX_NoValid_3_CC = None of the codings provided are in the value set {0}, and a coding is recommended to come from this value set (codes = {1})
-Terminology_TX_NoValid_4 = The Coding provided ({2}) was not found in the value set {0}, and a code is required from this value set {1}
-Terminology_TX_NoValid_5 = The Coding provided ({2}) was not found in the value set {0}, and a code should come from this value set unless it has no suitable code (the validator cannot judge what is suitable) {1}
-Terminology_TX_NoValid_6 = The Coding provided ({2}) was not found in the value set {0}, and a code is recommended to come from this value set {1}
+Terminology_TX_NoValid_4 = The Coding provided ({2}) is not in the value set {0}, and a code is required from this value set {1}
+Terminology_TX_NoValid_5 = The Coding provided ({2}) is not in the value set {0}, and a code should come from this value set unless it has no suitable code (note that the validator cannot judge what is suitable) {1}
+Terminology_TX_NoValid_6 = The Coding provided ({2}) is not in the value set {0}, and a code is recommended to come from this value set {1}
Terminology_TX_NoValid_7 = None of the codes provided could be validated against the maximum value set {0}, (error = {2})
Terminology_TX_NoValid_8 = None of the codes provided are in the maximum value set {0}, and a code from this value set is required) (codes = {1})
Terminology_TX_NoValid_9 = The code provided ({2}) could not be validated against the maximum value set {0}, (error = {1})
@@ -1103,6 +1105,12 @@ UNABLE_TO_HANDLE_SYSTEM__PROPERTY_FILTER_WITH_OP__ = Unable to handle system {0}
UNABLE_TO_HANDLE_SYSTEM_FILTER_WITH_NO_VALUE = The system {0} filter with property = {1}, op = {2} has no value
UNABLE_TO_INFER_CODESYSTEM = The System URI could not be determined for the code ''{0}'' in the ValueSet ''{1}''
UNABLE_TO_INFER_CODESYSTEM_UNKNOWN_SYSTEM = The System URI could not be determined for the code ''{0}'' in the ValueSet ''{1}'': a definition for the CodeSystem ''{2}'' it includes could not be found
+PARAMETERS_MODIFIER_EXTENSION_UNKNOWN = The request can''t be processed: the parameter {0} at {1} has a modifier extension that isn''t understood ({2})
+VALUESET_STORED_EXPANSION_MISSING = The value set {0} has a stored expansion with no {1} ''{2}'', which this request asks for, so the stored expansion can''t be used for it
+VALUESET_STORED_EXPANSION_PARAMETER = The value set {0} has a stored expansion made with {1} = ''{2}'', but this request has {1} = ''{3}'', so the stored expansion can''t be used for it
+VALUESET_STORED_EXPANSION_PARTIAL = The value set {0} has a stored expansion that is only part of its expansion ({1}), so the stored expansion can''t be used for this request
+VALUESET_STORED_EXPANSION_VERSION = The value set {0} has a stored expansion made with version {1} of {2}, but this request asks for version {3} ({4}), so the stored expansion can''t be used for it
+VALUESET_VCL_INVALID = The implicit VCL value set ''{0}'' is not valid VCL: {1}
VALUESET_MODIFIER_EXTENSION_UNKNOWN = The value set {0} can''t be processed: {1} has a modifier extension that isn''t understood ({2})
Unable_to_locate_the_profile__in_order_to_validate_against_it = Unable to locate the profile ''{0}'' in order to validate against it
Unable_to_process_request_for_resource_for___ = Unable to process request for resource for {0} / {1}
@@ -1404,7 +1412,7 @@ VS_EXP_IMPORT_UNK_X = Unable to find excluded value set ''{0}''
Wrong_namespace__expected_ = Wrong namespace - expected ''{0}''
Wrong_type_for_resource = Wrong type for resource
Wrong_type_for_resource_expected = Wrong type for resource. Expected {0} but found {1}
-TEXT_LINK_DATA_NOT_FOUND = The target of the textLink data reference ''{0}'' was not found in the resource
+TEXT_LINK_DATA_NOT_FOUND = The target of the textLink data reference ''{0}'' is not in the resource
TEXT_LINK_DATA_MULTIPLE_MATCHES = Multiple matching targets for the textLink data reference ''{0}'' were found in the resource
XHTML_URL_DATA_DATA_INVALID = The data should be valid base64 content for a data: URL: {0}
XHTML_URL_DATA_DATA_INVALID_COMMA = Comma found in data portion of data URL: {0}
@@ -1483,7 +1491,7 @@ QUESTIONNAIRE_QR_AUTHOR_END = The authored date ''{0}'' is after the end of the
CONCEPTMAP_GROUP_TARGET_DUPLICATION_DIFFERENT = A {2} relationship has already been defined from the code {0} to the code {1}, but this defines a new relationship {3}
CONCEPTMAP_GROUP_TARGET_DUPLICATION = A {2} relationship has already been defined from the code {0} to the code {1}
TEXT_LINK_NO_DIV = A textLink extension was found, but there was no xhtml element present for that targets of the html references
-TEXT_LINK_NO_ID = The html id ''{0}'' was not found in the xhtml
+TEXT_LINK_NO_ID = The html id ''{0}'' is not in the xhtml
TEXT_LINK_NO_DATA = No data element was found in the textLink extension
TEXT_LINK_SELECTOR_INVALID = The textLink selector ''{0}'' is invalid: {1}
SD_CONTEXT_SHOULD_ELEMENT_NOT_FOUND = The element {0} is not valid
diff --git a/tx/cs/cs-api.js b/tx/cs/cs-api.js
index 435705bf2..92935eb50 100644
--- a/tx/cs/cs-api.js
+++ b/tx/cs/cs-api.js
@@ -40,6 +40,38 @@ class CodeSystemProvider {
*/
supplements;
+ /**
+ * The languages displays are in (display(), the supplements' displays): those the request asked
+ * for. Accept-Language unless the operation says otherwise - $lookup's displayLanguage (A14).
+ * opContext.langs is still what messages are in
+ * @type {Languages|null}
+ */
+ _displayLanguages = null;
+
+ /** @returns {Languages} the languages displays are in (see _displayLanguages) */
+ displayLanguages() {
+ return this._displayLanguages || this.opContext.langs;
+ }
+
+ /**
+ * The languages displays are to be in, for an operation that has its own (displayLanguage);
+ * a wildcard is left out - display() takes the code system's display when nothing matches
+ * @param {Languages|null} languages
+ */
+ useDisplayLanguages(languages) {
+ if (!languages) {
+ this._displayLanguages = null;
+ return;
+ }
+ const langs = new Languages(languages.definitions || null);
+ for (const l of languages.languages || languages) {
+ if (l && l.code !== '*') {
+ langs.add(l);
+ }
+ }
+ this._displayLanguages = langs;
+ }
+
constructor(opContext, supplements = null) {
this.opContext = opContext;
this.supplements = supplements;
@@ -66,6 +98,9 @@ class CodeSystemProvider {
if (!(supplement instanceof CodeSystem)) {
throw new Error(`Supplement ${index} must be a CodeSystem instance, got ${typeof supplement}`);
}
+ // a supplement changes what the code system says, so one with a modifier extension the
+ // server doesn't understand can't be used (whatever provider it supplements)
+ Extensions.checkNoModifiersAnywhere(supplement, 'CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN', 'code system', supplement.vurl);
});
}
@@ -211,12 +246,14 @@ class CodeSystemProvider {
* contain, computed WITHOUT materialising them - used by the count=0 (count
* only) expansion fast path. `excludeInactive` mirrors the expansion's
* active-only handling. Defaults to totalCount(); providers that distinguish
- * active from inactive override this to honour excludeInactive.
+ * active from inactive override this to honour excludeInactive. Returns null
+ * when excludeInactive is asked for and the provider can't count that way
+ * (the caller then walks the codes)
* @param {boolean} excludeInactive
- * @returns {integer}
+ * @returns {integer|null}
*/
- async countAllCodes(excludeInactive) { // eslint-disable-line no-unused-vars
- return await this.totalCount();
+ async countAllCodes(excludeInactive) {
+ return excludeInactive ? null : await this.totalCount();
}
/**
@@ -532,39 +569,37 @@ class CodeSystemProvider {
_displayFromSupplements(code) {
assert(typeof code === 'string', 'code must be string');
- if (this.supplements) {
- const concepts = [];
- // displays have preference
- for (const supplement of this.supplements) {
- // Check if supplement language matches and has displays
- if (this.resourceLanguageMatches(supplement.jsonObj, this.opContext.langs, false)) {
- // Check if any concept has a display
- const concept= supplement.getConceptByCode(code);
- if (concept) {
- if (concept.display) {
- return concept.display;
- }
- concepts.push(concept);
- }
+ if (!this.supplements) {
+ return null;
+ }
+ const langs = this.displayLanguages();
+ // displays have preference: one in a supplement whose language the request asked for
+ for (const supplement of this.supplements) {
+ if (this.resourceLanguageMatches(supplement.jsonObj, langs, false)) {
+ const concept = supplement.getConceptByCode(code);
+ if (concept && concept.display) {
+ return concept.display;
}
}
- // Check concept designations for display uses
- for (const concept in concepts) {
- if (concept.designation) {
- for (const designation of concept.designation) {
- if (CodeSystem.isUseADisplay(designation.use) && this.opContext.langs.hasMatch(designation.language)) {
- return designation.value;
- }
- }
+ }
+ // then a designation for display in a language the request asked for, in any supplement - a
+ // supplement's language says nothing about its designations' (a language pack may be declared
+ // en, with de designations); one without a language is in its supplement's (A13)
+ for (const supplement of this.supplements) {
+ const concept = supplement.getConceptByCode(code);
+ for (const designation of (concept && concept.designation) || []) {
+ const lang = designation.language || supplement.jsonObj.language;
+ if (lang && CodeSystem.isUseADisplay(designation.use) && this.resourceLanguageMatches({ language: lang }, langs, false)) {
+ return designation.value;
}
}
- // still here? try again, for any non-language display
- for (const supplement of this.supplements) {
- if (!supplement.jsonObj.language) {
- const concept= supplement.getConceptByCode(code);
- if (concept && concept.display) {
- return concept.display;
- }
+ }
+ // still here? try again, for any non-language display
+ for (const supplement of this.supplements) {
+ if (!supplement.jsonObj.language) {
+ const concept = supplement.getConceptByCode(code);
+ if (concept && concept.display) {
+ return concept.display;
}
}
}
diff --git a/tx/cs/cs-cs.js b/tx/cs/cs-cs.js
index e55877a7b..ebab417c5 100644
--- a/tx/cs/cs-cs.js
+++ b/tx/cs/cs-cs.js
@@ -182,6 +182,8 @@ class FhirCodeSystemProvider extends BaseCSServices {
if (codeSystem.content == 'supplements') {
throw new Issue('error', 'invalid', null, 'CODESYSTEM_CS_NO_SUPPLEMENT', opContext.i18n.translate('CODESYSTEM_CS_NO_SUPPLEMENT', opContext.langs, codeSystem.vurl));
}
+ // the whole code system: there's nowhere in it a modifier extension doesn't matter
+ Extensions.checkNoModifiersAnywhere(codeSystem, 'CODESYSTEM_MODIFIER_EXTENSION_UNKNOWN', 'code system', codeSystem.vurl);
this.codeSystem = codeSystem;
this.hasHierarchyFlag = codeSystem.hasHierarchy();
@@ -281,6 +283,19 @@ class FhirCodeSystemProvider extends BaseCSServices {
return this.codeSystem.codeMap.size;
}
+ async countAllCodes(excludeInactive) {
+ if (!excludeInactive) {
+ return this.totalCount();
+ }
+ let n = 0;
+ for (const concept of this.codeSystem.codeMap.values()) {
+ if (!this._isInactive(concept, false)) {
+ n++;
+ }
+ }
+ return n;
+ }
+
/**
* @returns {Object[]|null} Defined properties for the code system
*/
@@ -469,10 +484,11 @@ class FhirCodeSystemProvider extends BaseCSServices {
}
// Use language-aware display logic
- if (this.opContext.langs && !this.opContext.langs.isEnglishOrNothing()) {
+ const langs = this.displayLanguages();
+ if (langs && !langs.isEnglishOrNothing()) {
// Try to find exact language match in designations
if (ctxt.concept.designation && Array.isArray(ctxt.concept.designation)) {
- for (const lang of this.opContext.langs.languages) {
+ for (const lang of langs.languages) {
for (const designation of ctxt.concept.designation) {
if (designation.language) {
const designationLang = new Language(designation.language);
@@ -486,7 +502,7 @@ class FhirCodeSystemProvider extends BaseCSServices {
// Check if the CodeSystem's language matches requested languages
if (this.defaultLanguage) {
- for (const requestedLang of this.opContext.langs.languages) {
+ for (const requestedLang of langs.languages) {
if (this.defaultLanguage.matchesForDisplay(requestedLang)) {
return ctxt.concept.display?.trim() || '';
}
@@ -844,18 +860,8 @@ class FhirCodeSystemProvider extends BaseCSServices {
properties.push({ ...p, definition: pd });
}
- // Add properties from supplements
- if (this.supplements) {
- for (const supplement of this.supplements) {
- const supplementConcept = supplement.getConceptByCode(ctxt.code);
- if (supplementConcept) {
- for (let p of supplementConcept.property || []) {
- let pd = this.getPropertyDefinition(supplement.jsonObj, p.code);
- properties.push({...p, definition: pd});
- }
- }
- }
- }
+ // (the supplements' properties are added by $expand and $lookup, for every provider:
+ // library/supplement-properties.js)
return properties;
}
@@ -1497,14 +1503,17 @@ class FhirCodeSystemProvider extends BaseCSServices {
results = await this._handleConceptFilter(filterContext, prop, op, value);
}
- // Handle child existence filter
- if (prop === 'child' && op === 'exists') {
+ // Handle child existence filter: whether the concept has children in the hierarchy (nesting,
+ // and parent/child properties). A child property the code system declares is the same thing
+ // unless it's declared with another uri - then it's the code system's own, and the property
+ // filter below applies (B18: it used to replace this whenever child was declared)
+ if (prop === 'child' && op === 'exists' && !this.redefinesStandardProperty('child')) {
results = await this._handleChildExistsFilter(filterContext, value);
}
// Handle property-based filters
const propertyDefs = this.propertyDefinitions();
- if (propertyDefs) {
+ if (propertyDefs && !(prop === 'child' && results)) {
const propertyDef = propertyDefs.find(p => p.code === prop);
if (propertyDef) {
results = await this._handlePropertyFilter(filterContext, propertyDef, op, value);
diff --git a/tx/cs/cs-lang.js b/tx/cs/cs-lang.js
index b2fd5b2db..079036837 100644
--- a/tx/cs/cs-lang.js
+++ b/tx/cs/cs-lang.js
@@ -529,7 +529,9 @@ class IETFLanguageCodeProvider extends CodeSystemProvider {
script: this.languageDefinitions.scripts, region: this.languageDefinitions.regions }[prop];
const canonical = [...known.keys()].find(k => k.toLowerCase() === value.toLowerCase());
if (!canonical) {
- throw new Error(`'${value}' is not a valid ${prop} subtag, so it cannot be filtered on`);
+ throw new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_VALID_CODE',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_VALID_CODE', this.opContext.langs,
+ [prop, value, this.system(), `not a registered ${prop} subtag`]), 'vs-invalid', 422);
}
filterContext.filters.push(new IETFLanguageEqualityFilter(prop, canonical));
return;
@@ -541,7 +543,8 @@ class IETFLanguageCodeProvider extends CodeSystemProvider {
}
if (value !== 'true' && value !== 'false') {
- throw new Error(`Invalid exists value: ${value}, must be 'true' or 'false'`);
+ throw new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_BOOLEAN',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_BOOLEAN', this.opContext.langs, [prop, value]), 'vs-invalid', 422);
}
const componentIndex = CODES_LanguageComponent.indexOf(prop);
diff --git a/tx/cs/cs-loinc.js b/tx/cs/cs-loinc.js
index 2eb4d8168..d2f5a2b8c 100644
--- a/tx/cs/cs-loinc.js
+++ b/tx/cs/cs-loinc.js
@@ -236,6 +236,7 @@ class LoincServices extends BaseCSServices {
// Shared data from factory
this.langs = sharedData.langs;
this.codes = sharedData.codes;
+ this._sharedData = sharedData; // (countAllCodes keeps its count there)
this.codeList = sharedData.codeList;
// whether TextIndex is the stemmed one (loinc-text-index.js): how a text filter is searched
this.currentTextIndex = !!sharedData.currentTextIndex;
@@ -285,6 +286,30 @@ class LoincServices extends BaseCSServices {
return this.codes.size;
}
+ /**
+ * count=0 of all of LOINC: the codes isInactive doesn't call inactive, counted once and kept
+ * with the shared data (the codes are all in memory)
+ */
+ async countAllCodes(excludeInactive) {
+ if (!excludeInactive) {
+ return this.codes.size;
+ }
+ if (this._sharedData.activeCount == null) {
+ let n = 0;
+ for (const context of this.codes.values()) {
+ if (!LoincServices.#statusIsInactive(context.status)) {
+ n++;
+ }
+ }
+ this._sharedData.activeCount = n;
+ }
+ return this._sharedData.activeCount;
+ }
+
+ static #statusIsInactive(status) {
+ return status == 'DISCOURAGED';
+ }
+
hasParents() {
return true; // LOINC has hierarchical relationships
}
@@ -371,7 +396,7 @@ class LoincServices extends BaseCSServices {
async isInactive(context) {
await this.#ensureContext(context);
- return context.status == 'DISCOURAGED'; // Handle via status if needed
+ return LoincServices.#statusIsInactive(context.status);
}
async getStatus(context) {
diff --git a/tx/cs/cs-mimetypes.js b/tx/cs/cs-mimetypes.js
index 9e673d3e8..738ebf959 100644
--- a/tx/cs/cs-mimetypes.js
+++ b/tx/cs/cs-mimetypes.js
@@ -564,22 +564,29 @@ class MimeTypeServices extends CodeSystemProvider {
#parseBase(value) {
const trimmed = (value || '').trim();
if (!trimmed) {
- throw new Error('The base filter needs a value of the form "type" or "type/subtype"');
+ throw this.#badBase(value, 'a base is of the form "type" or "type/subtype"');
}
if (trimmed.includes(';')) {
- throw new Error(`Invalid base filter '${value}': a base is a type or type/subtype, and carries no parameters`);
+ throw this.#badBase(value, 'a base is a type or type/subtype, and carries no parameters');
}
if (trimmed.includes('*')) {
- throw new Error(`Invalid base filter '${value}': wildcards are not supported`);
+ throw this.#badBase(value, 'wildcards are not supported');
}
const parts = trimmed.split('/');
if (parts.length > 2 || parts.some(p => !p.trim())) {
- throw new Error(`Invalid base filter '${value}': expected "type" or "type/subtype"`);
+ throw this.#badBase(value, 'expected "type" or "type/subtype"');
}
return new MimeTypeFilter(parts[0].trim().toLowerCase(),
parts.length === 2 ? parts[1].trim().toLowerCase() : null);
}
+ /** A base filter value that isn't a type or type/subtype: the client's error, not the server's */
+ #badBase(value, reason) {
+ return new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_VALID_CODE',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_VALID_CODE', this.opContext.langs,
+ ['base', value, this.system(), reason]), 'vs-invalid', 422);
+ }
+
async filter(filterContext, forIteration, prop, op, value) {
assert(filterContext && filterContext instanceof FilterExecutionContext, 'filterContext must be a FilterExecutionContext');
assert(prop != null && typeof prop === 'string', 'prop must be a non-null string');
@@ -627,7 +634,8 @@ class MimeTypeServices extends CodeSystemProvider {
#parseRegistered(value) {
const trimmed = (value || '').trim().toLowerCase();
if (trimmed !== 'true' && trimmed !== 'false') {
- throw new Error(`Invalid registered filter '${value}': the value must be true or false`);
+ throw new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_BOOLEAN',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_BOOLEAN', this.opContext.langs, ['registered', value]), 'vs-invalid', 422);
}
if (!this.registeredTypes) {
throw new Error('The registered filter cannot be used: no copy of the IANA media types '
diff --git a/tx/cs/cs-ndc.js b/tx/cs/cs-ndc.js
index b636ce43c..f0b851e47 100644
--- a/tx/cs/cs-ndc.js
+++ b/tx/cs/cs-ndc.js
@@ -58,13 +58,14 @@ class NdcPropertyFilter {
}
class NdcServices extends CodeSystemProvider {
- constructor(opContext, supplements, db, lookupTables, packageCount, productCount, version) {
+ constructor(opContext, supplements, db, lookupTables, packageCount, productCount, version, activeCount = null) {
super(opContext, supplements);
this.db = db;
this._version = version;
this._lookupTables = lookupTables;
this._packageCount = packageCount;
this._productCount = productCount;
+ this._activeCount = activeCount;
}
// Clean up database connection when provider is destroyed
@@ -93,6 +94,14 @@ class NdcServices extends CodeSystemProvider {
return this._packageCount + this._productCount;
}
+ /**
+ * count=0 of all of NDC: there's no iterator over all the codes, so a walk would find none - the
+ * products and packages are counted when the factory loads, the active ones too
+ */
+ async countAllCodes(excludeInactive) {
+ return excludeInactive ? this._activeCount : this.totalCount();
+ }
+
hasParents() {
return false; // No hierarchical relationships
}
@@ -671,6 +680,7 @@ class NdcServicesFactory extends CodeSystemFactoryProvider {
this._lookupTables = null;
this._packageCount = null;
this._productCount = null;
+ this._activeCount = null;
this._version = null;
}
@@ -762,6 +772,15 @@ class NdcServicesFactory extends CodeSystemFactoryProvider {
}));
});
+ // the active ones, for count=0 with activeOnly (countAllCodes)
+ this._activeCount = await new Promise((resolve, reject) => {
+ tempDb.get('SELECT (SELECT COUNT(NDCKey) FROM NDCPackages WHERE Active = 1) + (SELECT COUNT(NDCKey) FROM NDCProducts WHERE Active = 1) as count',
+ guarded(reject, (err, row) => {
+ if (err) reject(err);
+ else resolve(row.count);
+ }));
+ });
+
} finally {
tempDb.close();
}
@@ -785,7 +804,8 @@ class NdcServicesFactory extends CodeSystemFactoryProvider {
this._lookupTables,
this._packageCount,
this._productCount,
- this._version
+ this._version,
+ this._activeCount
);
}
diff --git a/tx/cs/cs-omop.js b/tx/cs/cs-omop.js
index 3c3b6cb0d..0650c2d66 100644
--- a/tx/cs/cs-omop.js
+++ b/tx/cs/cs-omop.js
@@ -439,7 +439,8 @@ class OMOPServices extends BaseCSServices {
name: type,
part: [
{ name: 'code', valueCode: name },
- { name: 'value', valueDate: value }
+ // dateTime, which can be just a date: a $lookup or expansion property value can't be a date (A6)
+ { name: 'value', valueDateTime: value }
]
};
diff --git a/tx/cs/cs-rxnorm.js b/tx/cs/cs-rxnorm.js
index 1008f0951..75f7ef601 100644
--- a/tx/cs/cs-rxnorm.js
+++ b/tx/cs/cs-rxnorm.js
@@ -158,6 +158,7 @@ class RxNormServices extends BaseCSServices {
this.rels = sharedData.rels;
this.reltypes = sharedData.reltypes;
this.totalCodeCount = sharedData.totalCodeCount;
+ this._sharedData = sharedData; // (countAllCodes keeps its count there)
this.textIndex = !!sharedData.textIndex;
this.located = sharedData.located || null;
}
@@ -187,6 +188,25 @@ class RxNormServices extends BaseCSServices {
return this.totalCodeCount;
}
+ /**
+ * count=0 of all of RxNorm: the concepts iterator(null) walks (archived ones aren't among them),
+ * but the obsolete ones - those whose display atom is suppressed (SUPPRESS = O, as #isObsolete
+ * picks it). One query, counted once and kept with the shared data
+ */
+ async countAllCodes(excludeInactive) {
+ if (!excludeInactive) {
+ return this.totalCodeCount;
+ }
+ if (this._sharedData.activeCodeCount == null) {
+ const cf = this.getCodeField();
+ const row = await this.#dbGet(
+ `SELECT COUNT(*) AS n FROM (SELECT SUPPRESS, MIN(${DISPLAY_RANK_SQL}) AS rnk FROM rxnconso ` +
+ `WHERE SAB = ? AND TTY <> 'SY' GROUP BY ${cf}) WHERE SUPPRESS IS NOT 'O'`, [this.getSAB()]);
+ this._sharedData.activeCodeCount = row ? row.n : 0;
+ }
+ return this._sharedData.activeCodeCount;
+ }
+
getSAB() {
return this.isNCI ? 'NCI' : 'RXNORM';
}
diff --git a/tx/cs/cs-snomed.js b/tx/cs/cs-snomed.js
index ed3660cec..df22a3dca 100644
--- a/tx/cs/cs-snomed.js
+++ b/tx/cs/cs-snomed.js
@@ -4209,7 +4209,8 @@ class SnomedProvider extends BaseCSServices {
this.opContext.i18n.translate('FILTER_NOT_UNDERSTOOD', this.opContext.langs, [prop, op, value]), 'vs-invalid', 422);
}
if (value !== 'true' && value !== 'false') {
- throw new Error(`Invalid filter value: ${value}`);
+ throw new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_BOOLEAN',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_BOOLEAN', this.opContext.langs, [prop, value]), 'vs-invalid', 422);
}
filterContext.filters.push(this.sct.filterInactive(value === 'true'));
return null;
@@ -4265,7 +4266,8 @@ class SnomedProvider extends BaseCSServices {
this.opContext.i18n.translate('FILTER_NOT_UNDERSTOOD', this.opContext.langs, [prop, op, value]), 'vs-invalid', 422);
}
if (value !== 'true' && value !== 'false') {
- throw new Error(`Invalid filter value: ${value}`);
+ throw new Issue('error', 'invalid', null, 'VALUESET_BAD_FILTER_VALUE_BOOLEAN',
+ this.opContext.i18n.translate('VALUESET_BAD_FILTER_VALUE_BOOLEAN', this.opContext.langs, [prop, value]), 'vs-invalid', 422);
}
const filter = new SnomedFilterContext();
filter.mappedScheme = scheme;
diff --git a/tx/cs/cs-uri.js b/tx/cs/cs-uri.js
index f89ed1e19..f95934251 100644
--- a/tx/cs/cs-uri.js
+++ b/tx/cs/cs-uri.js
@@ -102,22 +102,10 @@ class UriServices extends CodeSystemProvider {
}
async properties(code) {
-
- const ctxt = await this.#ensureContext(code);
- // Collect properties from all supplements
- let allProperties = [];
-
- if (this.supplements) {
- for (const supplement of this.supplements) {
- const concept = supplement.getConceptByCode(ctxt); // ← Uses CodeSystem API
- if (concept && concept.property) {
- // Add all properties from this concept
- allProperties = allProperties.concat(concept.property);
- }
- }
- }
-
- return allProperties;
+ await this.#ensureContext(code);
+ // a URI has no properties of its own (the supplements' are added by $expand and $lookup:
+ // library/supplement-properties.js)
+ return [];
}
async sameConcept(a, b) {
diff --git a/tx/importers/import-loinc-v2-classic.module.js b/tx/importers/import-loinc-v2-classic.module.js
index b1dab5914..379b11e00 100644
--- a/tx/importers/import-loinc-v2-classic.module.js
+++ b/tx/importers/import-loinc-v2-classic.module.js
@@ -31,6 +31,7 @@
// literal either way, as cs-loinc.js reports them).
const fs = require('fs');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const Database = require('better-sqlite3');
const { BaseTerminologyModule } = require('./tx-import-base');
const { TerminologyBuilder, vacuumFile } = require('./sqlite-v2/builder');
@@ -237,17 +238,17 @@ class LoincV2ClassicModule extends BaseTerminologyModule {
getSupportedFormats() { return ['sqlite']; }
registerCommands(cmd) {
- cmd.command('import')
+ const version = { arg: 'version', help: 'checked against the classic Config (default: its version)', oldFlag: 'loinc-version' };
+ addCommonOptions(cmd.command('import')
.description('Convert a classic FHIRsmith LOINC .db into a terminology file')
.requiredOption('-s, --source ', 'classic LOINC .db (e.g. loinc-2.77-a.db)')
- .requiredOption('-d, --dest ', 'destination .db')
- .option('-v, --loinc-version ', 'checked against the classic Config (default: its version)')
- .option('--overwrite', 'replace the destination')
- .action(async (o) => {
- const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: o.loincVersion,
- overwrite: !!o.overwrite, log: (m) => this.logInfo(m) });
+ .requiredOption('-d, --dest ', 'destination .db'), version)
+ .action(importAction(this, async (o) => {
+ const c = await resolveCommonOptions(o, version);
+ const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: c.version,
+ overwrite: c.overwrite, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
- });
+ }));
}
}
diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js
index b73066415..653739bb6 100644
--- a/tx/importers/import-loinc-v2.module.js
+++ b/tx/importers/import-loinc-v2.module.js
@@ -30,6 +30,7 @@
// parent / child entry order) only when the parent links' seq does not reproduce it.
const fs = require('fs');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const path = require('path');
const Database = require('better-sqlite3');
const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder');
@@ -519,16 +520,16 @@ class LoincV2Module extends BaseTerminologyModule {
getSupportedFormats() { return ['directory']; }
registerCommands(cmd) {
- cmd.command('import')
+ const version = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true };
+ addCommonOptions(cmd.command('import')
.description('Import an unzipped LOINC release into a terminology file')
.requiredOption('-s, --source ', 'release root (contains LoincTable/ and AccessoryFiles/)')
- .requiredOption('-d, --dest ', 'destination .db')
- .requiredOption('-v, --loinc-version ', 'e.g. 2.83')
- .option('--overwrite', 'replace the destination')
- .action(async (o) => {
- const s = await importLoincV2({ source: o.source, dest: o.dest, version: o.loincVersion, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) });
+ .requiredOption('-d, --dest ', 'destination .db'), version)
+ .action(importAction(this, async (o) => {
+ const c = await resolveCommonOptions(o, version);
+ const s = await importLoincV2({ source: o.source, dest: o.dest, version: c.version, overwrite: c.overwrite, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
- });
+ }));
}
}
diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js
index e56567cc6..88cdcf8b4 100644
--- a/tx/importers/import-rxnorm-v2.module.js
+++ b/tx/importers/import-rxnorm-v2.module.js
@@ -31,6 +31,7 @@
// order concepts by (primary TTY rank, ingredient group): the numbering's sort key.
const fs = require('fs');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const path = require('path');
const { BaseTerminologyModule } = require('./tx-import-base');
const { TerminologyBuilder } = require('./sqlite-v2/builder');
@@ -289,18 +290,18 @@ class RxNormV2Module extends BaseTerminologyModule {
getSupportedFormats() { return ['directory']; }
registerCommands(cmd) {
- cmd.command('import')
+ const version = { arg: 'MMDDYYYY', help: 'e.g. 03022026', oldFlag: 'rxnorm-version', required: true };
+ addCommonOptions(cmd.command('import')
.description('Import an unzipped RxNorm full release (rrf folder) into a terminology file')
.requiredOption('-s, --source ', 'the rrf/ folder of the release')
.requiredOption('-d, --dest ', 'destination .db')
- .requiredOption('-v, --rxnorm-version ', 'e.g. 03022026')
- .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)')
- .option('--overwrite', 'replace the destination')
- .action(async (o) => {
- const s = await importRxNormV2({ source: o.source, dest: o.dest, version: o.rxnormVersion,
- overwrite: !!o.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) });
+ .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)'), version)
+ .action(importAction(this, async (o) => {
+ const c = await resolveCommonOptions(o, version);
+ const s = await importRxNormV2({ source: o.source, dest: o.dest, version: c.version,
+ overwrite: c.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
- });
+ }));
}
}
diff --git a/tx/importers/import-sct-v2-cache.module.js b/tx/importers/import-sct-v2-cache.module.js
index cf0cef6b9..3a536032f 100644
--- a/tx/importers/import-sct-v2-cache.module.js
+++ b/tx/importers/import-sct-v2-cache.module.js
@@ -16,6 +16,7 @@
// b082f98); known defects of older cache vintages stop the import unless forced.
const path = require('path');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const { BaseTerminologyModule } = require('./tx-import-base');
const {
SnomedStrings, SnomedReferences, SnomedDescriptions, SnomedConceptList, SnomedRelationshipList,
@@ -367,18 +368,18 @@ class SnomedV2FromCacheModule extends BaseTerminologyModule {
getSupportedFormats() { return ['file']; }
registerCommands(cmd) {
- cmd.command('import')
+ addCommonOptions(cmd.command('import')
.description('Reverse-load a FHIRsmith SNOMED CT cache (*.cache) into a terminology file')
.requiredOption('-s, --source ', 'the .cache file')
.requiredOption('-d, --dest ', 'destination .db')
.option('--date-shift ', 'days to add to every cache date (auto: fix caches built east of UTC)', 'auto')
- .option('--overwrite', 'replace the destination')
- .option('--force', 'import a cache with known defects (see the warnings)')
- .action(async (o) => {
- const s = await importSnomedV2FromCache({ source: o.source, dest: o.dest, overwrite: !!o.overwrite,
+ .option('--force', 'import a cache with known defects (see the warnings)'))
+ .action(importAction(this, async (o) => {
+ const c = await resolveCommonOptions(o);
+ const s = await importSnomedV2FromCache({ source: o.source, dest: o.dest, overwrite: c.overwrite,
dateShift: o.dateShift, force: !!o.force, log: (msg) => this.logInfo(msg) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
- });
+ }));
cmd.command('inspect')
.description('Check FHIRsmith SNOMED CT caches for the known defects of older cache vintages (no import)')
.argument('', '.cache files')
diff --git a/tx/importers/import-sct-v2.module.js b/tx/importers/import-sct-v2.module.js
index b1e65d480..abf557089 100644
--- a/tx/importers/import-sct-v2.module.js
+++ b/tx/importers/import-sct-v2.module.js
@@ -8,6 +8,7 @@
// module dependency refset as meta moduleDependencies).
const path = require('path');
+const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options');
const { BaseTerminologyModule } = require('./tx-import-base');
const { tsvRows, firstLine } = require('./sqlite-v2/text');
const {
@@ -153,20 +154,20 @@ class SnomedV2Module extends BaseTerminologyModule {
getSupportedFormats() { return ['directory']; }
registerCommands(cmd) {
- cmd.command('import')
+ const version = { arg: 'YYYYMMDD', help: 'release date', oldFlag: 'snomed-version', required: true };
+ addCommonOptions(cmd.command('import')
.description('Import an RF2 Snapshot into a terminology file')
.requiredOption('-s, --source ', 'unzipped RF2 release (the Snapshot folder is used)')
.requiredOption('-d, --dest ', 'destination .db')
.requiredOption('-e, --edition ', 'edition module id')
- .requiredOption('--snomed-version ', 'release date')
.option('--version-uri ', 'version URI to record')
- .option('--overwrite', 'replace the destination')
- .option('-l, --language ', 'default language code')
- .action(async (o) => {
- const s = await importSnomedV2({ source: o.source, dest: o.dest, edition: o.edition, version: o.snomedVersion,
- versionUri: o.versionUri, language: o.language, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) });
+ .option('-l, --language ', 'default language code'), version)
+ .action(importAction(this, async (o) => {
+ const c = await resolveCommonOptions(o, version);
+ const s = await importSnomedV2({ source: o.source, dest: o.dest, edition: o.edition, version: c.version,
+ versionUri: o.versionUri, language: o.language, overwrite: c.overwrite, log: (m) => this.logInfo(m) });
this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`);
- });
+ }));
}
}
diff --git a/tx/importers/readme.md b/tx/importers/readme.md
index ac74bb64f..706225252 100644
--- a/tx/importers/readme.md
+++ b/tx/importers/readme.md
@@ -12,6 +12,7 @@ additional terminologies.
- [Common Commands](#common-commands)
- [Configuration Management](#configuration-management)
- [Terminology-Specific Usage](#terminology-specific-usage)
+ - [sqlite-v2 Terminology Files](#sqlite-v2-terminology-files)
- [Advanced Features](#advanced-features)
- [Troubleshooting](#troubleshooting)
@@ -65,6 +66,7 @@ additional terminologies.
| **RxNorm Subset** | `rxnorm-subset` | Create RxNorm subsets for testing | 10-30 min |
| **UNII** | `unii` | Unique Ingredient Identifier (FDA) | 15-45 min |
| **NDC** | `ndc` | National Drug Code Directory | 30-90 min |
+| **sqlite-v2 files** | `loinc-v2`, `loinc-v2-classic`, `snomed-v2`, `snomed-v2-from-cache`, `rxnorm-v2` | LOINC, SNOMED CT and RxNorm as sqlite-v2 terminology files - see [sqlite-v2 Terminology Files](#sqlite-v2-terminology-files) | varies |
## Common Commands
@@ -495,6 +497,65 @@ json is the same data as product.txt and unfinished_product.txt, so it adds no c
tx-import ndc versions --source /path/to/ndc
```
+### sqlite-v2 Terminology Files
+
+The sqlite-v2 importers write a terminology file in the sqlite-v2 format: one SQLite file per
+code system version, served by the sqlite-v2 providers (`loinc-v2:`, `snomed-v2:` and `rxnorm-v2:`
+sources in the library - see [tx/README.md](../README.md) and
+[tx/sqlite-v2/README.md](../sqlite-v2/README.md) for the format and the providers). They are
+separate from the importers above, whose files the other providers read.
+
+| Command | From | To |
+|---------|------|----|
+| `loinc-v2` | an unzipped LOINC release | `loinc-v2:` file |
+| `loinc-v2-classic` | a classic LOINC `.db` (made by `loinc` above) | `loinc-v2:` file |
+| `snomed-v2` | an unzipped RF2 release (the Snapshot is used) | `snomed-v2:` file |
+| `snomed-v2-from-cache` | a SNOMED CT `.cache` (made by `snomed` above) | `snomed-v2:` file |
+| `rxnorm-v2` | the `rrf/` folder of an unzipped RxNorm full release | `rxnorm-v2:` file |
+
+The `-classic` and `-from-cache` importers rebuild a sqlite-v2 file from a file the other
+providers use, for a release that isn't at hand any more.
+
+```bash
+tx-import loinc-v2 import -s /path/to/loinc_release -d ./data/loinc-2.83.db -v 2.83
+tx-import loinc-v2-classic import -s ./data/loinc-2.77-a.db -d ./data/loinc-2.77.db
+tx-import snomed-v2 import -s /path/to/SnomedCT_InternationalRF2 -d ./data/sct-intl-20260701.db \
+ -e 900000000000207008 -v 20260701
+tx-import snomed-v2-from-cache import -s ./data/sct_uk_20261021.cache -d ./data/sct-uk-20261021.db
+tx-import rxnorm-v2 import -s /path/to/RxNorm_full/rrf -d ./data/rxnorm-03022026.db -v 03022026
+```
+
+**Options:** `-s, --source`, `-d, --dest`, `-v, --version` and `-y, --yes` as in
+[Common Import Options](#common-import-options), with these differences:
+- `--source` and `--dest` are required: these importers don't ask for them, and don't remember
+ them (no configuration history)
+- `-v, --version` is the release's version: the LOINC version (`2.83`), the RxNorm release
+ (`MMDDYYYY`), the SNOMED CT release date (`YYYYMMDD`). `loinc-v2-classic` checks it against the
+ classic file (it defaults to the file's version); `snomed-v2-from-cache` takes it from the cache
+- `-y, --yes` replaces an existing destination without asking. Without it, an existing
+ destination is asked about, or refused when there is no one to ask
+- the earlier names `--loinc-version`, `--rxnorm-version`, `--snomed-version` and `--overwrite`
+ still work
+- they always report each step; `--verbose` adds the stack trace to an error. There is no
+ `--no-indexes`: the indexes are part of the format
+- `loinc-v2` has no `--main-only` or `--languages`: every language variant is imported
+
+Importer-specific options:
+- `snomed-v2`: `-e, --edition ` (required) the edition's module id; `--version-uri `
+ the version URI to record; `-l, --language ` the default language
+- `snomed-v2-from-cache`: `--date-shift ` days to add to every cache date (default
+ `auto`, which fixes caches built east of UTC); `--force` imports a cache with known defects.
+ `tx-import snomed-v2-from-cache inspect ` checks caches for those defects
+ without importing
+- `rxnorm-v2`: `--atom-relationships` also stores RXNREL's atom-level rows, for `REL` / `RELA` =
+ `AUI:` filters (refused otherwise)
+
+Each importer keeps its working tables in `.stage` beside the destination (so the disk needs
+room for both). An existing destination is deleted when the import starts, so an import that
+fails leaves none: import to a new name if the old file is still in use. A file of the earlier
+sqlite-v2 schema is refused at start-up with a message to import it again: there is no in-place
+upgrade.
+
## Advanced Features
### Progress Tracking
@@ -631,4 +692,5 @@ tx-import help
- **UNII**: SQLite database with simple structure
- **NDC**: SQLite database supporting multiple versions
- **LOINC Subset**: File-based subset matching original structure
-- **RxNorm Subset**: RRF file-based subset matching original structure
\ No newline at end of file
+- **RxNorm Subset**: RRF file-based subset matching original structure
+- **sqlite-v2** (`loinc-v2`, `snomed-v2`, `rxnorm-v2` and the rebuilding importers): one SQLite terminology file per code system version - [tx/sqlite-v2/README.md](../sqlite-v2/README.md)
\ No newline at end of file
diff --git a/tx/importers/sqlite-v2/cli-options.js b/tx/importers/sqlite-v2/cli-options.js
new file mode 100644
index 000000000..8c6d3062a
--- /dev/null
+++ b/tx/importers/sqlite-v2/cli-options.js
@@ -0,0 +1,101 @@
+/**
+ * The command-line options the sqlite-v2 importers share with the classic ones (the "Common
+ * Import Options" in tx/importers/readme.md): -v, --version for the release's version, -y, --yes
+ * to replace an existing destination without asking, and --verbose for the stack of an error.
+ * Without -y, an existing destination is asked about, as the classic importers do (and refused
+ * when there is no one to ask). Their earlier names still work, hidden: --loinc-version,
+ * --rxnorm-version, --snomed-version and --overwrite. (tx-import's own version is
+ * -V, --cli-version, so --version reaches the importer)
+ */
+const fs = require('fs');
+const { Option } = require('commander');
+const inquirer = require('inquirer');
+
+/**
+ * Adds -v, --version (with the importer's earlier name for it, hidden) and -y, --yes (with
+ * --overwrite, hidden) to an import command
+ * @param {import('commander').Command} cmd
+ * @param {Object} [version] - none for an importer that takes the version from its source
+ * @param {string} version.arg - the value's name in the help, e.g. 'version' or 'MMDDYYYY'
+ * @param {string} version.help - what it is, e.g. 'e.g. 2.83'
+ * @param {string} version.oldFlag - the earlier long name, e.g. 'loinc-version'
+ * @returns {import('commander').Command} cmd
+ */
+function addCommonOptions(cmd, version) {
+ if (version) {
+ cmd.option(`-v, --version <${version.arg}>`, version.help);
+ cmd.addOption(new Option(`--${version.oldFlag} <${version.arg}>`).hideHelp());
+ }
+ cmd.option('-y, --yes', 'replace an existing destination without asking');
+ cmd.addOption(new Option('--overwrite').hideHelp());
+ cmd.option('--verbose', 'show the stack trace of an error');
+ return cmd;
+}
+
+/**
+ * The import command's action, reporting a failure as the classic importers do: " import
+ * failed: " (the stack too with --verbose), and exit code 1 - not an uncaught rejection
+ * @param {Object} module - the importer module (BaseTerminologyModule)
+ * @param {function(Object): Promise} fn - the action
+ * @returns {function(Object): Promise}
+ */
+function importAction(module, fn) {
+ return async (o, cmd) => {
+ try {
+ await fn(o);
+ } catch (error) {
+ module.logError(`${module.getName()} import failed: ${error.message}`);
+ if (verboseOf(o, cmd)) {
+ console.error(error.stack);
+ }
+ process.exitCode = 1;
+ }
+ };
+}
+
+/**
+ * Whether --verbose was given. tx-import has a --verbose of its own, and commander gives a flag
+ * to the program wherever it appears on the command line, so the import command's own options
+ * never have it: it's in the options with the globals
+ * @param {Object} o - the import command's parsed options
+ * @param {Object} [cmd] - the import command (commander passes it after the options)
+ * @returns {boolean}
+ */
+function verboseOf(o, cmd) {
+ if (o && o.verbose) {
+ return true;
+ }
+ return !!(cmd && typeof cmd.optsWithGlobals === 'function' && cmd.optsWithGlobals().verbose);
+}
+
+/**
+ * The version and overwrite settings from the parsed options, asking about an existing
+ * destination when neither -y nor --overwrite was given
+ * @param {Object} o - the parsed options (with dest)
+ * @param {Object} [version] - as for addCommonOptions, with required: true when there is no default
+ * @returns {Promise<{version: string|undefined, overwrite: boolean}>}
+ */
+async function resolveCommonOptions(o, version) {
+ let value;
+ if (version) {
+ const oldKey = version.oldFlag.replace(/-([a-z])/g, (m, c) => c.toUpperCase());
+ value = o.version !== undefined ? o.version : o[oldKey];
+ if (version.required && (value === undefined || value === '')) {
+ throw new Error(`-v, --version <${version.arg}> is required (${version.help})`);
+ }
+ }
+ let overwrite = !!(o.yes || o.overwrite);
+ if (!overwrite && o.dest && fs.existsSync(o.dest)) {
+ if (!process.stdin.isTTY) {
+ throw new Error(`${o.dest} exists: use -y, --yes to replace it`);
+ }
+ const { replace } = await inquirer.prompt([{ type: 'confirm', name: 'replace', message: `${o.dest} exists. Replace it?`, default: false }]);
+ if (!replace) {
+ throw new Error('Import cancelled: the destination exists');
+ }
+ overwrite = true;
+ }
+ return { version: value, overwrite };
+}
+
+module.exports = { addCommonOptions, resolveCommonOptions, importAction };
diff --git a/tx/library.js b/tx/library.js
index b01fa59c8..d4c676df8 100644
--- a/tx/library.js
+++ b/tx/library.js
@@ -1047,7 +1047,9 @@ class Library {
const json = await contentLoader.loadFile(resource, contentLoader.fhirVersion());
// narrative is shown as-is in a page, so it must not carry script (see narrative-check.js)
assertNoActiveContent(json);
- cs = new CodeSystem(json);
+ // R3 code systems are converted (codesystem-subsumes becomes a child property); the others
+ // are read as they are
+ cs = new CodeSystem(json, VersionUtilities.isR3Ver(contentLoader.fhirVersion()) ? contentLoader.fhirVersion() : undefined);
} catch (e) {
// one unacceptable resource (e.g. contained resources the server doesn't support)
// must not stop the rest of the package loading
@@ -1402,7 +1404,9 @@ class Library {
const json = await contentLoader.loadFile(entry, contentLoader.fhirVersion());
// narrative is shown as-is in a page, so it must not carry script (see narrative-check.js)
assertNoActiveContent(json);
- cs = new CodeSystem(json);
+ // R3 code systems are converted (codesystem-subsumes becomes a child property); the others
+ // are read as they are
+ cs = new CodeSystem(json, VersionUtilities.isR3Ver(contentLoader.fhirVersion()) ? contentLoader.fhirVersion() : undefined);
} catch (e) {
// one unacceptable resource must not stop the rest of the package loading
this.log.warn(`Package ${contentLoader.pid()}: skipping CodeSystem ${entry.id || entry.filename || ''}: ${e.message}`);
diff --git a/tx/library/conceptmap.js b/tx/library/conceptmap.js
index 438cc38c1..2cebcf36f 100644
--- a/tx/library/conceptmap.js
+++ b/tx/library/conceptmap.js
@@ -6,6 +6,25 @@ const {conceptMapToR5, conceptMapFromR5} = require("../xversion/xv-conceptmap");
* Represents a FHIR ConceptMap resource with version conversion support
* @class
*/
+// The Java version convertors put an R4 equivalence that R5's relationship can't say (equal,
+// subsumes, inexact...) on the R5 target as this modifier extension. It's the one modifier
+// extension the tx module understands: $translate reports it as the equivalence
+const EXT_OLD_CONCEPTMAP_EQUIVALENCE = 'http://hl7.org/fhir/1.0/StructureDefinition/extension-ConceptMap.element.target.equivalence';
+
+/**
+ * A target's R4 equivalence: target.equivalence (an R4 map - the internal form keeps it), or the
+ * Java convertors' modifier extension (an R5 map converted from R4)
+ * @param {Object} target - ConceptMap.group.element.target
+ * @returns {string|undefined}
+ */
+function equivalenceOf(target) {
+ if (target.equivalence) {
+ return target.equivalence;
+ }
+ const ext = (target.modifierExtension || []).find(e => e.url === EXT_OLD_CONCEPTMAP_EQUIVALENCE);
+ return ext ? (ext.valueCode ?? ext.valueString) : undefined;
+}
+
class ConceptMap extends CanonicalResource {
@@ -344,7 +363,7 @@ class ConceptMap extends CanonicalResource {
system: system,
code: target.code,
display: target.display,
- equivalence: target.equivalence,
+ equivalence: equivalenceOf(target),
relationship: target.relationship
});
});
@@ -372,7 +391,7 @@ class ConceptMap extends CanonicalResource {
targetSystem: group.target,
targetCode: target.code,
targetDisplay: target.display,
- equivalence: target.equivalence,
+ equivalence: equivalenceOf(target),
relationship: target.relationship,
comment: target.comment
});
@@ -488,4 +507,4 @@ class ConceptMap extends CanonicalResource {
}
-module.exports = { ConceptMap };
\ No newline at end of file
+module.exports = { ConceptMap, equivalenceOf, EXT_OLD_CONCEPTMAP_EQUIVALENCE };
\ No newline at end of file
diff --git a/tx/library/extensions.js b/tx/library/extensions.js
index 7e47b769c..89001c71a 100644
--- a/tx/library/extensions.js
+++ b/tx/library/extensions.js
@@ -1,5 +1,9 @@
const {getValuePrimitive} = require("../../library/utils/utilities");
const {Issue} = require("./operation-outcome");
+const { STORED_CONCEPTS } = require("./stored-concepts");
+
+// the resources checkNoModifiersAnywhere has found none in
+const checkedAnywhere = new WeakSet();
const Extensions = {
@@ -58,6 +62,95 @@ const Extensions = {
return true;
},
+ /**
+ * A whole resource checked for modifier extensions, at every level. There's nowhere in a
+ * terminology resource where a modifier extension doesn't matter, so a resource with one the
+ * server doesn't understand can't be used: the first one found is refused (422), with the
+ * element's path. A resource that passes is remembered, so a large stored one is walked once,
+ * not on every request. Contained resources aren't walked here: each is checked when it's used.
+ * @param {Object} resource - the resource (or its wrapper, with jsonObj)
+ * @param {string} msgId - the message id (e.g. CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN)
+ * @param {string} kind - for the message: e.g. 'concept map'
+ * @param {string} id - for the message: the resource's url|version
+ * @param {Array>} [known] - the modifier extensions the server understands, and
+ * where: [element path without indexes (e.g. ConceptMap.group.element.target), url]. One is
+ * understood only on the element it's listed for
+ */
+ checkNoModifiersAnywhere(resource, msgId, kind, id, known = []) {
+ if (!resource) {
+ return;
+ }
+ const obj = resource.jsonObj || resource;
+ if (checkedAnywhere.has(obj)) {
+ return;
+ }
+ const walk = (o, path, element) => {
+ if (Array.isArray(o)) {
+ o.forEach((item, i) => walk(item, `${path}[${i}]`, element));
+ return;
+ }
+ if (!o || typeof o !== 'object') {
+ return;
+ }
+ const unknown = Array.isArray(o.modifierExtension)
+ ? o.modifierExtension.filter(e => !known.some(([at, url]) => at === element && url === e.url)) : [];
+ if (unknown.length > 0) {
+ const urls = [...new Set(unknown.map(e => e.url))];
+ throw new Issue('error', 'business-rule', path, msgId,
+ `The ${kind} ${id || ''} can't be processed: ${path} has a modifier extension that isn't understood (${urls.join(', ')})`,
+ 'vs-invalid', 422).handleAsOO(422);
+ }
+ // the concepts of an include held in a database (stored-concepts.js) aren't read: the
+ // provider only stores the list when none of them has a modifier extension
+ const stored = o[STORED_CONCEPTS] !== undefined;
+ for (const k of Object.keys(o)) {
+ // extensions and contained resources are not the resource's own elements
+ if (k === 'extension' || k === 'modifierExtension' || k === 'contained' || k.startsWith('_') || (stored && k === 'concept')) {
+ continue;
+ }
+ const v = o[k];
+ if (v && typeof v === 'object') {
+ walk(v, `${path}.${k}`, `${element}.${k}`);
+ }
+ }
+ };
+ const type = obj.resourceType || 'Resource';
+ walk(obj, type, type);
+ checkedAnywhere.add(obj);
+ },
+
+ /**
+ * The parameters of a request (a Parameters resource), checked for modifier extensions: on a
+ * parameter, or a part of one, at any depth. The server understands none, and a modifier
+ * extension changes what a parameter means, so the request can't be done as asked (400). The
+ * resources in parameters aren't walked here: each is checked when it's used.
+ * @param {Object} params - the Parameters resource
+ */
+ checkNoParameterModifiers(params) {
+ if (!params || params.resourceType !== 'Parameters') {
+ return;
+ }
+ const walk = (list, path) => {
+ if (!Array.isArray(list)) {
+ return;
+ }
+ list.forEach((p, i) => {
+ if (!p || typeof p !== 'object') {
+ return;
+ }
+ const at = `${path}[${i}]`;
+ if (Array.isArray(p.modifierExtension) && p.modifierExtension.length > 0) {
+ const urls = [...new Set(p.modifierExtension.map(e => e.url))];
+ throw new Issue('error', 'business-rule', at, 'PARAMETERS_MODIFIER_EXTENSION_UNKNOWN',
+ `The request can't be processed: the parameter ${p.name ? "'" + p.name + "' " : ''}at ${at} has a modifier extension that isn't understood (${urls.join(', ')})`,
+ null, 400).handleAsOO(400);
+ }
+ walk(p.part, `${at}.part`);
+ });
+ };
+ walk(params.parameter, 'Parameters.parameter');
+ },
+
readString(resource, url) {
if (!resource) {
return undefined;
diff --git a/tx/library/stored-expansion.js b/tx/library/stored-expansion.js
new file mode 100644
index 000000000..c22c011f5
--- /dev/null
+++ b/tx/library/stored-expansion.js
@@ -0,0 +1,231 @@
+//
+// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
+//
+// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause
+//
+
+/**
+ * Whether a value set's stored expansion (ValueSet.expansion, in the value set as it came: sent
+ * in the request, or in a package) can answer a request - for $expand (and an import, which is
+ * expanded the same way) and for $validate-code.
+ *
+ * A stored expansion is an expansion made with the parameters in its expansion.parameter; one
+ * that isn't there was the default. It can answer a request only if what the request asks for can
+ * be had from it:
+ * - count, offset and filter are applied to it (they needn't match), and so are activeOnly,
+ * excludeNotForUI and excludeNested - unless it was made with a narrower one (activeOnly=true,
+ * and the request wants inactive codes, which aren't there)
+ * - what can't be made from it must match: the display language (a request for the language
+ * it's in - by default, the value set's language, or the default, English - matches),
+ * designations, properties, the code system versions it was made from, the supplements used
+ * - one that is only part of an expansion (paged), or was made with a text filter, isn't the
+ * value set, and can't answer anything else
+ * For $validate-code only what decides membership matters: displays are checked against the code
+ * system, not the stored expansion.
+ *
+ * When it can't, the caller expands the compose if it can; if it can't (there isn't one, or a
+ * code system it includes isn't available), the request is refused (422) - a stored expansion
+ * made some other way is not the answer to this request.
+ */
+
+const { Issue } = require('./operation-outcome');
+const { Language } = require('../../library/i18n/languages');
+const { VersionUtilities } = require('../../library/fhir/version-utilities');
+
+const SUPPLEMENT_EXT = 'http://hl7.org/fhir/StructureDefinition/valueset-supplement';
+
+/** The values of each parameter of an expansion, as strings, by name */
+function parametersOf(expansion) {
+ const map = new Map();
+ for (const p of expansion.parameter || []) {
+ const vn = Object.keys(p).find(k => k.startsWith('value'));
+ if (!p.name || !vn) {
+ continue;
+ }
+ if (!map.has(p.name)) {
+ map.set(p.name, []);
+ }
+ map.get(p.name).push(String(p[vn]));
+ }
+ return map;
+}
+
+function countContains(list) {
+ let n = 0;
+ for (const c of list || []) {
+ n += 1 + countContains(c.contains);
+ }
+ return n;
+}
+
+/** a boolean parameter of the stored expansion (absent: false, the default) */
+function storedBool(stored, name) {
+ const v = stored.get(name);
+ return !!v && v[0] === 'true';
+}
+
+/** The versions of a code system the stored expansion records using */
+function versionsUsed(expansion, stored, system) {
+ const versions = new Set();
+ for (const name of ['used-codesystem', 'version']) {
+ for (const v of stored.get(name) || []) {
+ const i = v.indexOf('|');
+ if (i > 0 && v.substring(0, i) === system) {
+ versions.add(v.substring(i + 1));
+ }
+ }
+ }
+ const walk = list => {
+ for (const c of list || []) {
+ if (c.system === system && c.version) {
+ versions.add(c.version);
+ }
+ walk(c.contains);
+ }
+ };
+ walk(expansion.contains);
+ return [...versions];
+}
+
+function versionMatches(wanted, used) {
+ if (wanted === used) {
+ return true;
+ }
+ try {
+ return VersionUtilities.versionMatches(wanted, used);
+ } catch (e) {
+ return false;
+ }
+}
+
+/**
+ * Why a value set's stored expansion can't answer a request, if it can't
+ * @param {Object} vs - the value set (JSON), with an expansion
+ * @param {TxParameters} params - the request's parameters
+ * @param {string} purpose - 'expand' or 'validate'
+ * @param {string} [filterText] - the request's text filter ($expand), if any
+ * @returns {{msgId: string, args: string[]}|null} null if it can
+ */
+function storedExpansionProblem(vs, params, purpose, filterText = null) {
+ const expansion = vs.expansion;
+ const stored = parametersOf(expansion);
+ const expand = purpose === 'expand';
+
+ // only part of an expansion: a page of one
+ const n = countContains(expansion.contains);
+ if (typeof expansion.offset === 'number' && expansion.offset > 0) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARTIAL', args: [`offset ${expansion.offset}`] };
+ }
+ if (typeof expansion.total === 'number' && expansion.total > n) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARTIAL', args: [`${n} of ${expansion.total} codes`] };
+ }
+
+ // made with a text filter: only some of the value set
+ const storedFilter = (stored.get('filter') || [])[0];
+ if (storedFilter !== undefined) {
+ const same = expand && filterText && filterText.trim().toLowerCase() === storedFilter.trim().toLowerCase();
+ if (!same) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARAMETER', args: ['filter', storedFilter, expand && filterText ? filterText : ''] };
+ }
+ }
+
+ // made with a narrower selection than the request wants
+ for (const [name, requested] of [['activeOnly', params.activeOnly], ['excludeNotForUI', params.excludeNotForUI],
+ ['excludePostCoordinated', params.excludePostCoordinated]]) {
+ if (storedBool(stored, name) && !requested) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARAMETER', args: [name, 'true', String(!!requested)] };
+ }
+ }
+
+ // the code system versions it was made from
+ for (const rule of params.versionRules || []) {
+ if (rule.vs || !rule.system || !rule.version) {
+ continue;
+ }
+ const used = versionsUsed(expansion, stored, rule.system);
+ if (used.length === 0 || used.some(u => !versionMatches(rule.version, u))) {
+ const name = { default: 'system-version', override: 'force-system-version', check: 'check-system-version' }[rule.mode] || 'system-version';
+ return { msgId: 'VALUESET_STORED_EXPANSION_VERSION', args: [used.length ? used.join(', ') : '(none recorded)', rule.system, rule.version, name] };
+ }
+ }
+
+ if (!expand) {
+ // $validate-code checks displays against the code system: the rest doesn't matter
+ return null;
+ }
+
+ // the display language: a request for the language it's in (by default, the value set's,
+ // or the default, English) matches
+ const requested = params.hasDisplayLanguages ? params.DisplayLanguages : (params.hasHTTPLanguages ? params.HTTPLanguages : null);
+ const preferred = requested && requested.length > 0 ? requested.get(0) : null;
+ if (preferred && preferred.code !== '*') {
+ const storedLang = (stored.get('displayLanguage') || [])[0] || vs.language || '';
+ const first = storedLang.split(',')[0].split(';')[0].trim();
+ const lang = new Language(first);
+ if (!lang.matchesForDisplay(preferred) && !preferred.matchesForDisplay(first)) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARAMETER',
+ args: ['displayLanguage', first || '(none: the default, en)', preferred.code] };
+ }
+ }
+
+ // designations
+ if (params.includeDesignations && !storedBool(stored, 'includeDesignations')) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_PARAMETER', args: ['includeDesignations', 'false', 'true'] };
+ }
+ const storedDesignations = stored.get('designation') || [];
+ for (const d of params.designations || []) {
+ if (!storedDesignations.includes(d)) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_MISSING', args: ['designation', d] };
+ }
+ }
+
+ // properties: each one asked for must be one it has (by code or uri); '*' is all of them,
+ // which it can't be said to have unless it was made that way
+ const declared = expansion.property || [];
+ const storedProperties = stored.get('property') || [];
+ for (const p of params.properties || []) {
+ if (storedProperties.includes(p) || storedProperties.includes('*')) {
+ continue;
+ }
+ if (p === '*' || !declared.some(d => d.code === p || d.uri === p)) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_MISSING', args: ['property', p] };
+ }
+ }
+
+ // the supplements: each one the request (or the value set) uses must have been used
+ const used = stored.get('used-supplement') || [];
+ const wanted = new Set([...(params.supplements || [])]);
+ for (const ext of vs.extension || []) {
+ if (ext.url === SUPPLEMENT_EXT && (ext.valueCanonical || ext.valueUri)) {
+ wanted.add(ext.valueCanonical || ext.valueUri);
+ }
+ }
+ for (const s of wanted) {
+ const url = s.split('|')[0];
+ if (!used.some(u => u === s || u.split('|')[0] === url && !s.includes('|'))) {
+ return { msgId: 'VALUESET_STORED_EXPANSION_MISSING', args: ['supplement', s] };
+ }
+ }
+ return null;
+}
+
+/**
+ * storedExpansionProblem, as the issue that refuses the request (422)
+ * @param {Object} vs - the value set (JSON)
+ * @param {string} label - how the value set is named (url|version, or id)
+ * @param {TxParameters} params
+ * @param {string} purpose - 'expand' or 'validate'
+ * @param {Object} i18n - the worker's I18nSupport
+ * @param {string} [filterText]
+ * @returns {Issue|null}
+ */
+function storedExpansionIssue(vs, label, params, purpose, i18n, filterText = null) {
+ const problem = storedExpansionProblem(vs, params, purpose, filterText);
+ if (!problem) {
+ return null;
+ }
+ const message = i18n.translate(problem.msgId, params.HTTPLanguages, [label, ...problem.args]);
+ return new Issue('error', 'not-supported', null, problem.msgId, message, 'vs-invalid', 422).handleAsOO(422);
+}
+
+module.exports = { storedExpansionProblem, storedExpansionIssue, countContains };
diff --git a/tx/library/supplement-properties.js b/tx/library/supplement-properties.js
new file mode 100644
index 000000000..1d33a503a
--- /dev/null
+++ b/tx/library/supplement-properties.js
@@ -0,0 +1,37 @@
+//
+// The properties CodeSystem supplements in use give a concept
+//
+
+/**
+ * The properties the supplements in use (a provider's supplements) give a code, each with its
+ * definition from the supplement (CodeSystem.property: code, uri, type), as cs-cs.js gives a code
+ * system's own properties. Added by $expand (ValueSet expander) and $lookup after the provider has
+ * answered, so that every provider - FHIR CodeSystems, the built-in ones, sqlite-v2 - reports them
+ * the same way, whichever path an expansion takes (A12).
+ *
+ * @param {CodeSystem[]|null} supplements - the provider's supplements
+ * @param {string} code - the code, as the provider has it
+ * @returns {Object[]} the properties ({ code, value[x], definition }), in supplement order
+ */
+function supplementProperties(supplements, code) {
+ const result = [];
+ if (!supplements || code == null) {
+ return result;
+ }
+ for (const supplement of supplements) {
+ if (typeof supplement.getConceptByCode !== 'function') {
+ continue;
+ }
+ const concept = supplement.getConceptByCode(code);
+ if (!concept || !concept.property) {
+ continue;
+ }
+ const defs = (supplement.jsonObj && supplement.jsonObj.property) || [];
+ for (const p of concept.property) {
+ result.push({ ...p, definition: defs.find(d => d.code === p.code) });
+ }
+ }
+ return result;
+}
+
+module.exports = { supplementProperties };
diff --git a/tx/library/text-index-store.js b/tx/library/text-index-store.js
index f342c0457..4fe741297 100644
--- a/tx/library/text-index-store.js
+++ b/tx/library/text-index-store.js
@@ -238,53 +238,19 @@ class TextIndexStore {
}
} else {
fs.mkdirSync(path.dirname(this.file), { recursive: true });
- this.db = new Database(this.file);
- this.db.pragma('busy_timeout = 5000');
- const meta = this.db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'`).get();
- const version = meta ? this.db.prepare(`SELECT value FROM meta WHERE key = 'schema'`).get() : null;
- if (meta && (!version || Number(version.value) !== SCHEMA_VERSION)) {
- // another version's: start again
- this.db.close();
- for (const suffix of ['', '-wal', '-shm']) {
- fs.rmSync(this.file + suffix, { force: true });
+ try {
+ this.#openWritable();
+ } catch (e) {
+ if (!TextIndexStore.#damaged(e)) {
+ throw e;
}
- this.db = new Database(this.file);
- this.db.pragma('busy_timeout = 5000');
- }
- this.db.pragma('auto_vacuum = INCREMENTAL');
- this.db.pragma('journal_mode = WAL');
- this.db.pragma('synchronous = NORMAL');
- this.db.exec(`
- CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
- CREATE TABLE IF NOT EXISTS indexes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- hash TEXT NOT NULL UNIQUE,
- kind TEXT NOT NULL,
- url TEXT,
- version TEXT,
- lang TEXT,
- size INTEGER NOT NULL,
- names INTEGER NOT NULL,
- codes INTEGER NOT NULL,
- langs TEXT NOT NULL,
- first_row INTEGER,
- last_row INTEGER,
- complete INTEGER NOT NULL DEFAULT 0,
- built INTEGER NOT NULL,
- used INTEGER NOT NULL
- );
- CREATE VIRTUAL TABLE IF NOT EXISTS names USING fts5(key UNINDEXED, text UNINDEXED, scope, words, stems,
- tokenize = "${TEXT_INDEX_TOKENIZE}");
- CREATE TABLE IF NOT EXISTS codes (idx INTEGER NOT NULL, code TEXT NOT NULL, key);
- CREATE INDEX IF NOT EXISTS codes_by_idx ON codes (idx, code);
- `);
- this.db.prepare(`INSERT OR REPLACE INTO meta (key, value) VALUES ('schema', ?)`).run(String(SCHEMA_VERSION));
- // later than any run before (two starts in the same millisecond are still two runs)
- const last = this.db.prepare(`SELECT max(used) AS used FROM indexes`).get().used;
- this.run = Math.max(this.run, (last || 0) + 1);
- // an index whose build didn't finish (the server stopped part way through) is no use
- for (const row of this.db.prepare(`SELECT * FROM indexes WHERE complete = 0`).all()) {
- this.#drop(row);
+ // a damaged store (the machine stopped part way through a write, or its -wal was
+ // lost): it is only a cache of what can be built again, so start again
+ if (this.log) {
+ this.log.warn(`Text index store ${this.file} is damaged (${e.message}): starting it again`);
+ }
+ this.#discard();
+ this.#openWritable();
}
}
// a page cache of its own: the names table is searched by every text filter
@@ -296,6 +262,77 @@ class TextIndexStore {
return this;
}
+ /**
+ * Open the database to read and write, creating what isn't there (open)
+ */
+ #openWritable() {
+ this.db = new Database(this.file);
+ this.db.pragma('busy_timeout = 5000');
+ const meta = this.db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'`).get();
+ const version = meta ? this.db.prepare(`SELECT value FROM meta WHERE key = 'schema'`).get() : null;
+ if (meta && (!version || Number(version.value) !== SCHEMA_VERSION)) {
+ // another version's: start again
+ this.#discard();
+ this.db = new Database(this.file);
+ this.db.pragma('busy_timeout = 5000');
+ }
+ this.db.pragma('auto_vacuum = INCREMENTAL');
+ this.db.pragma('journal_mode = WAL');
+ this.db.pragma('synchronous = NORMAL');
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
+ CREATE TABLE IF NOT EXISTS indexes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ hash TEXT NOT NULL UNIQUE,
+ kind TEXT NOT NULL,
+ url TEXT,
+ version TEXT,
+ lang TEXT,
+ size INTEGER NOT NULL,
+ names INTEGER NOT NULL,
+ codes INTEGER NOT NULL,
+ langs TEXT NOT NULL,
+ first_row INTEGER,
+ last_row INTEGER,
+ complete INTEGER NOT NULL DEFAULT 0,
+ built INTEGER NOT NULL,
+ used INTEGER NOT NULL
+ );
+ CREATE VIRTUAL TABLE IF NOT EXISTS names USING fts5(key UNINDEXED, text UNINDEXED, scope, words, stems,
+ tokenize = "${TEXT_INDEX_TOKENIZE}");
+ CREATE TABLE IF NOT EXISTS codes (idx INTEGER NOT NULL, code TEXT NOT NULL, key);
+ CREATE INDEX IF NOT EXISTS codes_by_idx ON codes (idx, code);
+ `);
+ this.db.prepare(`INSERT OR REPLACE INTO meta (key, value) VALUES ('schema', ?)`).run(String(SCHEMA_VERSION));
+ // later than any run before (two starts in the same millisecond are still two runs)
+ const last = this.db.prepare(`SELECT max(used) AS used FROM indexes`).get().used;
+ this.run = Math.max(this.run, (last || 0) + 1);
+ // an index whose build didn't finish (the server stopped part way through) is no use
+ for (const row of this.db.prepare(`SELECT * FROM indexes WHERE complete = 0`).all()) {
+ this.#drop(row);
+ }
+ }
+
+ /** Close the database and delete its files */
+ #discard() {
+ if (this.db) {
+ try {
+ this.db.close();
+ } catch (e) {
+ // it's going anyway
+ }
+ this.db = null;
+ }
+ for (const suffix of ['', '-wal', '-shm']) {
+ fs.rmSync(this.file + suffix, { force: true });
+ }
+ }
+
+ /** Whether an error says the database file is damaged (or isn't a database at all) */
+ static #damaged(e) {
+ return !!e && typeof e.code === 'string' && /^SQLITE_(CORRUPT|NOTADB)/.test(e.code);
+ }
+
/** Whether an index is still in the store (and is the same one) */
_alive(index) {
const row = this._byId.get(index.id);
diff --git a/tx/library/ucum-parsers.js b/tx/library/ucum-parsers.js
index 8b8b86bd6..2a420d447 100644
--- a/tx/library/ucum-parsers.js
+++ b/tx/library/ucum-parsers.js
@@ -13,6 +13,16 @@ const {
const regexUtilities = require("../../library/utils/regex-utilities");
// Lexer for tokenizing UCUM expressions (port of Lexer.java)
+// as Utilities.truncate (Java): a value quoted in a message is cut short - a unit can be very long
+const MAX_MESSAGE_VALUE_LENGTH = 100;
+function truncate(s) {
+ if (s == null) {
+ return 'null';
+ }
+ s = String(s);
+ return s.length <= MAX_MESSAGE_VALUE_LENGTH ? s : s.substring(0, MAX_MESSAGE_VALUE_LENGTH) + '... (' + s.length + ' chars)';
+}
+
class Lexer {
static NO_CHAR = '\0';
@@ -44,7 +54,7 @@ class Lexer {
this._checkAnnotation(ch) ||
this._checkNumber(ch) ||
this._checkNumberOrSymbol(ch))) {
- throw new UcumException(`Error processing unit '${this.source}': unexpected character '${ch}' at character ${this.start+1}`);
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': unexpected character '${ch}' at character ${this.start+1}`);
}
}
}
@@ -61,7 +71,7 @@ class Lexer {
}
if (this.token.length === 1) {
- throw new UcumException(`Error processing unit '${this.source}': unexpected character '${ch}' at character ${this.start+1}: a + or - must be followed by at least one digit`);
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': unexpected character '${ch}' at character ${this.start+1}: a + or - must be followed by at least one digit`);
}
this.type = TokenType.NUMBER;
@@ -127,11 +137,15 @@ class Lexer {
let nextCh = this._nextChar();
while (nextCh !== '}') {
+ // (the end first: NO_CHAR is not an ASCII character either)
+ if (nextCh === Lexer.NO_CHAR && this.index > this.source.length) {
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': unterminated annotation`);
+ }
if (!Utilities.isAsciiChar(nextCh)) {
- throw new UcumException(`Error processing unit '${this.source}': Annotation contains non-ascii characters`);
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': Annotation contains non-ascii characters`);
}
- if (nextCh === Lexer.NO_CHAR) {
- throw new UcumException(`Error processing unit '${this.source}': unterminated annotation`);
+ if (nextCh === '{') {
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': an annotation can't contain '{'`);
}
b.push(nextCh);
nextCh = this._nextChar();
@@ -172,11 +186,16 @@ class Lexer {
}
error(errMsg) {
- throw new UcumException(`Error processing unit '${this.source}': ${errMsg} at character ${this.start+1}`);
+ throw new UcumException(`Error processing unit '${truncate(this.source)}': ${errMsg} at character ${this.start+1}`);
}
getTokenAsInt() {
- return this.token.charAt(0) === '+' ? parseInt(this.token.substring(1)) : parseInt(this.token);
+ const v = this.token.charAt(0) === '+' ? parseInt(this.token.substring(1)) : parseInt(this.token);
+ // (as Java's Integer.parseInt: a number that doesn't fit in 32 bits is not one)
+ if (!Number.isSafeInteger(v) || v > 2147483647 || v < -2147483648) {
+ this.error(`The number '${truncate(this.token)}' is not valid`);
+ }
+ return v;
}
finished() {
@@ -185,10 +204,17 @@ class Lexer {
}
// Expression parser for UCUM unit expressions (port of ExpressionParser.java)
-// A UCUM expression parses into a chain of Terms, one level per operator and per bracket, and
-// the parser and every walker of the result recurse along that chain. Bound it so that a hostile
-// unit is a clean error rather than a RangeError (stack overflow). Real units have a few terms.
-const MAX_UCUM_TERMS = 100;
+// Limits on the complexity of a unit expression, as ExpressionParser.java has them. Converting a
+// unit to canonical form multiplies exact decimal values together once per unit of exponent, so
+// without these a short hostile unit (km2000, a chain of Ym24) takes minutes of CPU; and a
+// UCUM expression parses into a chain of Terms, one level per operator and per bracket, which the
+// parser and every walker of the result recurse along. The limits are well beyond anything used in
+// practice (the largest real exponents are things like 10*23 or 10*-24).
+const MAX_EXPONENT = 30; // absolute value of any single exponent
+const MAX_TOTAL_EXPONENT = 60; // sum of absolute values of all exponents in the expression
+const MAX_COMPONENTS = 20; // number of symbols and numbers in the expression
+const MAX_NESTING = 10; // depth of nested brackets
+const MAX_TERMS = 50; // number of terms (including annotations) - each is a level of recursion
class ExpressionParser {
constructor(model) {
@@ -196,58 +222,83 @@ class ExpressionParser {
}
parse(code) {
+ this.componentCount = 0;
+ this.totalExponent = 0;
+ this.nesting = 0;
+ this.termCount = 0;
const lexer = new Lexer(code);
- this.terms = 0;
- const res = this._parseTerm(lexer, true);
-
- if (!lexer.finished()) {
- throw new UcumException('Expression was not parsed completely. Syntax Error?');
+ if (lexer.getType() === TokenType.NONE) {
+ throw new UcumException('The unit is empty'); // (unity is "1")
+ }
+ let res;
+ if (lexer.getType() === TokenType.SOLIDUS) {
+ // ::= "/" | : a leading "/" only here, for the whole expression
+ this.termCount++;
+ res = new Term();
+ res.op = Operator.DIVISION;
+ lexer.consume();
+ res.term = this._parseTerm(lexer);
+ } else {
+ res = this._parseTerm(lexer);
+ }
+ // every token used: a ")" that closes nothing is the token left over
+ if (lexer.getType() !== TokenType.NONE || !lexer.finished()) {
+ lexer.error(`Unexpected '${truncate(lexer.getToken())}': the unit was not parsed completely`);
}
-
return res;
}
- _parseTerm(lexer, first) {
- if (++this.terms > MAX_UCUM_TERMS) {
- lexer.error(`The unit has more than ${MAX_UCUM_TERMS} terms and brackets`);
+ /**
+ * ::= "." | "/" | , where a component
+ * may be an annotation, or have one after it - only one. The grammar has annotations only after a
+ * unit (with or without an exponent), but UCUM's own common units have them after a number
+ * (/100{WBC}) and a bracketed term (g/(8.h){shift}), so those are accepted too. The term is
+ * built right-recursively; the converter applies each operator to the component after it, left
+ * to right.
+ */
+ _parseTerm(lexer) {
+ if (++this.termCount > MAX_TERMS) {
+ lexer.error(`The unit expression is too complex (limit is ${MAX_TERMS} terms)`);
}
const res = new Term();
-
- if (first && lexer.getType() === TokenType.NONE) {
- res.comp = new Factor(1);
- } else if (lexer.getType() === TokenType.SOLIDUS) {
- res.op = Operator.DIVISION;
+ const annotation = lexer.getType() === TokenType.ANNOTATION;
+ if (annotation) {
+ res.comp = new Factor(1); // still lose the annotation
lexer.consume();
- res.term = this._parseTerm(lexer, false);
} else {
- if (lexer.getType() === TokenType.ANNOTATION) {
- res.comp = new Factor(1); // still lose the annotation
- lexer.consume();
- } else {
- res.comp = this._parseComp(lexer);
- }
+ res.comp = this._parseComp(lexer);
+ }
- if (lexer.getType() !== TokenType.NONE && lexer.getType() !== TokenType.CLOSE) {
- if (lexer.getType() === TokenType.SOLIDUS) {
- res.op = Operator.DIVISION;
- lexer.consume();
- } else if (lexer.getType() === TokenType.PERIOD) {
- res.op = Operator.MULTIPLICATION;
- lexer.consume();
- } else if (lexer.getType() === TokenType.ANNOTATION) {
- res.op = Operator.MULTIPLICATION; // implicit
- } else {
- lexer.error("Expected '/' or '.'");
+ if (lexer.getType() !== TokenType.NONE && lexer.getType() !== TokenType.CLOSE) {
+ if (lexer.getType() === TokenType.SOLIDUS) {
+ res.op = Operator.DIVISION;
+ lexer.consume();
+ } else if (lexer.getType() === TokenType.PERIOD) {
+ res.op = Operator.MULTIPLICATION;
+ lexer.consume();
+ } else if (lexer.getType() === TokenType.ANNOTATION) {
+ if (annotation) {
+ lexer.error("An annotation can't follow another annotation");
}
- res.term = this._parseTerm(lexer, false);
+ res.op = Operator.MULTIPLICATION; // implicit
+ } else {
+ lexer.error("Expected '/' or '.'");
}
+ res.term = this._parseTerm(lexer);
}
-
return res;
}
_parseComp(lexer) {
+ if (lexer.getType() === TokenType.NUMBER || lexer.getType() === TokenType.SYMBOL) {
+ if (++this.componentCount > MAX_COMPONENTS) {
+ lexer.error(`Too many components in the unit expression (limit is ${MAX_COMPONENTS})`);
+ }
+ }
if (lexer.getType() === TokenType.NUMBER) {
+ if (lexer.getToken().startsWith('+') || lexer.getToken().startsWith('-')) {
+ lexer.error("A number can't have a sign (only an exponent can)");
+ }
const fact = new Factor(lexer.getTokenAsInt());
lexer.consume();
return fact;
@@ -256,8 +307,12 @@ class ExpressionParser {
} else if (lexer.getType() === TokenType.NONE) {
lexer.error('unexpected end of expression looking for a symbol or a number');
} else if (lexer.getType() === TokenType.OPEN) {
+ if (++this.nesting > MAX_NESTING) {
+ lexer.error(`Brackets are nested too deeply (limit is ${MAX_NESTING})`);
+ }
lexer.consume();
- const res = this._parseTerm(lexer, true);
+ const res = this._parseTerm(lexer);
+ this.nesting--;
if (lexer.getType() === TokenType.CLOSE) {
lexer.consume();
} else {
@@ -296,17 +351,25 @@ class ExpressionParser {
if (unit != null) {
symbol.unit = unit;
} else if (sym !== '1') {
- lexer.error(`The unit '${sym}' is unknown`);
+ lexer.error(`The unit '${truncate(sym)}' is unknown`);
}
}
lexer.consume();
if (lexer.getType() === TokenType.NUMBER) {
- symbol.exponent = lexer.getTokenAsInt();
+ const exp = lexer.getTokenAsInt();
+ if (exp > MAX_EXPONENT || exp < -MAX_EXPONENT) {
+ lexer.error(`The exponent ${exp} is too large (limit is +/-${MAX_EXPONENT})`);
+ }
+ symbol.exponent = exp;
lexer.consume();
} else {
symbol.exponent = 1;
}
+ this.totalExponent += Math.abs(symbol.exponent);
+ if (this.totalExponent > MAX_TOTAL_EXPONENT) {
+ lexer.error(`The exponents in the unit expression are too large in total (limit is ${MAX_TOTAL_EXPONENT})`);
+ }
return symbol;
}
@@ -1044,5 +1107,9 @@ module.exports = {
Search,
Converter,
UcumValidator,
- MAX_UCUM_TERMS
+ MAX_EXPONENT,
+ MAX_TOTAL_EXPONENT,
+ MAX_COMPONENTS,
+ MAX_NESTING,
+ MAX_TERMS
};
\ No newline at end of file
diff --git a/tx/library/ucum-service.js b/tx/library/ucum-service.js
index 9ad35cb36..bfcbf9dee 100644
--- a/tx/library/ucum-service.js
+++ b/tx/library/ucum-service.js
@@ -14,6 +14,14 @@ const {
} = require('./ucum-parsers.js');
// UCUM Service - main service class for UCUM operations
+/**
+ * In arithmetic (canonical forms, conversion, multiplication...), no unit is unity: "" is "1", as
+ * in UcumEssenceService.java. validate() doesn't accept it - it is not a valid unit
+ */
+function unity(unit) {
+ return unit === '' ? '1' : unit;
+}
+
class UcumService {
constructor() {
this.model = null;
@@ -52,6 +60,7 @@ class UcumService {
* @throws {UcumException}
*/
getCanonicalUnits(unit) {
+ unit = unity(unit);
if (!unit || !unit.trim()) {
throw new UcumException("getCanonicalUnits: unit must not be null or empty");
}
@@ -65,7 +74,7 @@ class UcumService {
const convertedTerm = new Converter(this.model, this.handlers, true).convert(term);
return new ExpressionComposer().compose(convertedTerm, false);
} catch (e) {
- e.message = `Error processing ${unit}: ${e.message}`;
+ e.message = `Error processing ${unit.length > 100 ? unit.substring(0, 100) + '... (' + unit.length + ' chars)' : unit}: ${e.message}`;
throw e;
}
}
@@ -78,7 +87,7 @@ class UcumService {
* @throws {UcumException}
*/
isComparable(units1, units2) {
- if (!units1 || !units2) {
+ if (units1 == null || units2 == null) {
return false;
}
@@ -87,9 +96,7 @@ class UcumService {
const u2 = this.getCanonicalUnits(units2);
return u1 === u2;
} catch (e) {
- console.error('Error message:', e.message);
- console.error('Stack trace:', e.stack);
- return false;
+ return false; // a unit that isn't valid is comparable to nothing (no noise for bad input)
}
}
@@ -101,7 +108,7 @@ class UcumService {
* @throws {UcumException}
*/
multiply(o1, o2) {
- const res = new Pair(o1.getValue().multiply(o2.getValue()), o1.getCode() +"."+o2.getCode());
+ const res = new Pair(o1.getValue().multiply(o2.getValue()), unity(o1.getCode()) +"."+unity(o2.getCode()));
return this.getCanonicalForm(res);
}
/**
@@ -112,8 +119,8 @@ class UcumService {
* @throws {UcumException}
*/
divideBy(dividend, divisor) {
- const dividendCode = dividend.getCode();
- const divisorCode = divisor.getCode();
+ const dividendCode = unity(dividend.getCode());
+ const divisorCode = unity(divisor.getCode());
const resultValue = dividend.getValue().divide(divisor.getValue());
const resultCode = (dividendCode.includes("/") || dividendCode.includes("*") ?
@@ -136,7 +143,7 @@ class UcumService {
throw new UcumException("getCanonicalForm: value must not be null");
}
- const code = pair.getCode();
+ const code = unity(pair.getCode());
if (!code || !code.trim()) {
throw new UcumException("getCanonicalForm: value.code must not be null or empty");
}
@@ -268,6 +275,8 @@ class UcumService {
if (!value) {
throw new UcumException("convert: value must not be null");
}
+ sourceUnit = unity(sourceUnit);
+ destUnit = unity(destUnit);
if (!sourceUnit || !sourceUnit.trim()) {
throw new UcumException("convert: sourceUnit must not be null or empty");
}
diff --git a/tx/library/ucum-types.js b/tx/library/ucum-types.js
index 4200ea765..325736378 100644
--- a/tx/library/ucum-types.js
+++ b/tx/library/ucum-types.js
@@ -350,44 +350,15 @@ class Decimal {
s2 = s3;
}
- const s = new Array(s2.length);
-
- let t = 0;
- for (let i = s2.length - 1; i >= 0; i--) {
- s[i] = this._stringMultiply('0', s2.length - (i + 1));
- let c = 0;
- for (let j = s1.length - 1; j >= 0; j--) {
- t = c + (this._dig(s1.charAt(j)) * this._dig(s2.charAt(i)));
- s[i] = this._insert(String(this._cdig(t % 10)), s[i], 0);
- c = Math.floor(t / 10);
- }
- while (c > 0) {
- s[i] = this._insert(String(this._cdig(t % 10)), s[i], 0);
- c = Math.floor(t / 10);
- }
- }
-
- t = 0;
- for (const sv of s) {
- t = Math.max(t, sv.length);
- }
- for (let i = 0; i < s.length; i++) {
- s[i] = this._stringMultiply('0', t - s[i].length) + s[i];
- }
-
- let res = "";
- let c = 0;
- for (let i = t - 1; i >= 0; i--) {
- for (let j = 0; j < s.length; j++) {
- c = c + this._dig(s[j].charAt(i));
- }
- res = this._insert(String(this._cdig(c % 10)), res, 0);
- c = Math.floor(c / 10);
- }
-
- if (c > 0) {
+ // the product of the digits, as many digits as the long multiplication this replaces gave
+ // (s1.length + s2.length - 1, with leading zeros): BigInt, because multiplying digit strings
+ // one digit at a time is cubic in their length, and a unit like Ym30.Ym30 has thousands
+ const t = s1.length + s2.length - 1;
+ let res = (BigInt(s1) * BigInt(s2)).toString();
+ if (res.length > t) {
throw new Error("internal logic error");
}
+ res = res.padStart(t, '0');
let dec = res.length - ((s1.length - (max + 1)) * 2);
diff --git a/tx/params.js b/tx/params.js
index 85f8fc21d..624efe235 100644
--- a/tx/params.js
+++ b/tx/params.js
@@ -545,10 +545,11 @@ class TxParameters {
}
// The code system version the request's version rules ask for - force-system-version,
- // else system-version, else check-system-version - or null when they name none
+ // else system-version - or null when they name none. check-system-version doesn't choose
+ // a version: it only checks the one that was chosen
requestedSystemVersion(systemURI) {
const rules = this.rulesForSystem(systemURI).filter(t => !t.vs);
- for (const mode of ['override', 'default', 'check']) {
+ for (const mode of ['override', 'default']) {
const rule = rules.find(t => t.mode === mode);
if (rule) {
return rule.version;
diff --git a/tx/provider.js b/tx/provider.js
index ff5c7a090..80c6c25a2 100644
--- a/tx/provider.js
+++ b/tx/provider.js
@@ -410,7 +410,9 @@ class Provider {
const json = await contentLoader.loadFile(resource, contentLoader.fhirVersion());
// narrative is shown as-is in a page, so it must not carry script (see narrative-check.js)
assertNoActiveContent(json);
- cs = new CodeSystem(json);
+ // R3 code systems are converted (codesystem-subsumes becomes a child property); the others
+ // are read as they are
+ cs = new CodeSystem(json, VersionUtilities.isR3Ver(contentLoader.fhirVersion()) ? contentLoader.fhirVersion() : undefined);
} catch (e) {
// one unacceptable resource (e.g. contained resources the server doesn't support)
// must not stop the rest of the package loading
diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md
index dd78b13dc..994b4d44c 100644
--- a/tx/sqlite-v2/README.md
+++ b/tx/sqlite-v2/README.md
@@ -160,7 +160,7 @@ system's text-search names and ranking; the $lookup property lists and order.
## Importers
```
-node tx/importers/tx-import.js snomed-v2 import -s -d sct-intl-20260701.db -e 900000000000207008 --snomed-version 20260701
+node tx/importers/tx-import.js snomed-v2 import -s -d sct-intl-20260701.db -e 900000000000207008 -v 20260701
node tx/importers/tx-import.js snomed-v2-from-cache import -s sct_uk_20261021.cache -d sct-uk-20261021.db
node tx/importers/tx-import.js snomed-v2-from-cache inspect
node tx/importers/tx-import.js loinc-v2 import -s -d loinc-2.83.db -v 2.83
@@ -168,6 +168,10 @@ node tx/importers/tx-import.js loinc-v2-classic import -s loinc-2.77-a.db -d loi
node tx/importers/tx-import.js rxnorm-v2 import -s -d rxnorm-03022026.db -v 03022026 [--atom-relationships]
```
+Every importer takes `-v, --version` for the release's version (not `snomed-v2-from-cache`, which
+reads it from the cache) and `-y, --yes` to replace an existing destination; see
+[tx/importers/readme.md](../importers/readme.md#sqlite-v2-terminology-files) for all the options.
+
`snomed-v2-from-cache` and `loinc-v2-classic` reverse-load the files main's providers use, for
releases that are not at hand. Every importer stages into `.stage` beside the destination,
then numbers the concepts, writes the fact tables in key order, builds the indexes, and VACUUMs.
diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js
index 697ef4221..0b4e03183 100644
--- a/tx/sqlite-v2/provider.js
+++ b/tx/sqlite-v2/provider.js
@@ -100,13 +100,14 @@ class SqliteV2Provider extends BaseCSServices {
defLang() { return this.f.defLang(); }
totalCount() { return this.f.totalCount(); }
/**
- * expand.js asks this for count=0 of a whole code system. cs-snomed.js counts the active concepts
- * for a compose without inactive codes; cs-loinc.js and cs-rxnorm.js don't override cs-api's
- * default, which ignores the flag (totalCount)
+ * expand.js asks this for count=0 of a whole code system: the codes iteratorAll walks (for RxNorm,
+ * the live ones - not the archived), but the inactive ones when excludeInactive, as main's
+ * providers count them (A9)
*/
async countAllCodes(excludeInactive) {
- if (this.dialect.name === 'loinc' || this.dialect.name === 'rxnorm') return this.totalCount();
- return excludeInactive ? this.store.active().size : this.totalCount();
+ if (!excludeInactive) return this.totalCount();
+ const walked = this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all();
+ return walked.andCardinality(this.store.active());
}
hasParents() { return !!this.store.hierarchy || this.dialect.name === 'rxnorm'; }
isNotClosed() { return !!this.store.notClosed; }
@@ -394,12 +395,13 @@ class SqliteV2Provider extends BaseCSServices {
if (!c) return null;
const s = this._displayFromSupplements(c.code);
if (s) return s;
- if (this.dialect.name === 'loinc' && this.opContext.langs && !this.opContext.langs.isEnglishOrNothing()) {
+ const displayLangs = this.displayLanguages();
+ if (this.dialect.name === 'loinc' && displayLangs && !displayLangs.isEnglishOrNothing()) {
this._needDesigs(c);
const types = ['LONG_COMMON_NAME', 'SHORTNAME', 'DisplayName'];
const cands = [{ language: 'en-US', term: c.row.display }]
.concat(c.desigs.filter((d) => d.use && types.includes(d.use.code)).sort((a, b) => types.indexOf(a.use.code) - types.indexOf(b.use.code)));
- const langs = this.opContext.langs.languages || [];
+ const langs = displayLangs.languages || [];
for (const exact of [true, false]) {
for (const l of langs) for (const d of cands) if (l.matches(d.language, exact)) return d.term;
}
@@ -1220,15 +1222,15 @@ class SqliteV2Provider extends BaseCSServices {
set.complete = result.complete;
set.result = result;
if (trace) trace.annotate({ codesReturned: page.length, total: result.complete ? result.total : null });
- // count=0 on the whole system: what expand.js asks the built-in provider for (countAllCodes:
- // cs-snomed.js the concepts, or the active ones for a compose without inactive codes; cs-loinc.js
- // every code), not the walk's count (activeOnly does not change it; SNOMED CT's walk does not
- // reach the inactive concepts)
- // (RxNorm: its whole system is the RXNCONSO concepts, a set, not the walk; the include is the
- // whole system whatever activeOnly or compose.inactive say, as expand.js counts it)
+ // count=0 on the whole system: what expand.js asks the built-in provider for (countAllCodes), not
+ // the walk's count (SNOMED CT's walk does not reach the inactive concepts): every code, or the
+ // active ones when the compose or activeOnly leaves the inactive ones out (A9). Not with
+ // excludeNotForUI, which expand.js doesn't count this way either (no provider counts abstract codes)
+ // (RxNorm: its whole system is the RXNCONSO concepts, a set, not the walk)
const whole = result.wholeSystem || (this.dialect.name === 'rxnorm' && includes.length === 1 && !excludes.length
&& ['filter', 'concept', 'valueSet'].every((k) => !(includes[0][k] || []).length));
- const total = count === 0 && whole ? await this.countAllCodes(excludeInactive) : result.total;
+ const total = count === 0 && whole && !(params && params.excludeNotForUI)
+ ? await this.countAllCodes(excludeInactive || !!(params && params.activeOnly)) : result.total;
return { sets: [set], total: result.complete ? total : -1, notClosed: await this._selectionNotClosed(includes, excludes) };
}
diff --git a/tx/tx.fhir.org.yml b/tx/tx.fhir.org.yml
index 78dca2ed2..81a3712b4 100644
--- a/tx/tx.fhir.org.yml
+++ b/tx/tx.fhir.org.yml
@@ -21,7 +21,7 @@ sources:
- ucum:tx/data/ucum-essence.xml
- loinc:loinc-2.77-c.db
- loinc!:Loinc_2.83f.db
- - rxnorm:rxnorm-11022026.db
+ - rxnorm-v2:rxnorm-11022026-v2.db
- ndc:ndc-20261117.db
- unii:unii_20240622.db
- snomed:sct_intl_20250201-21.cache
diff --git a/tx/tx.js b/tx/tx.js
index fc9d91f24..27cd91fac 100644
--- a/tx/tx.js
+++ b/tx/tx.js
@@ -86,6 +86,7 @@ const {BundleXML} = require("./xml/bundle-xml");
const ConceptUsageTracker = require("./usage-tracker");
const ProblemFinder = require("./problems");
const { buildOperationOutcome, outcomeFromError } = require('./library/operation-outcome');
+const { Extensions } = require('./library/extensions');
const txOpenApi = require('./openapi');
const { SyndicationStore } = require('./syndication/syndication-store');
const syndicationFeed = require('./syndication/syndication-feed');
@@ -1037,6 +1038,13 @@ class TXModule {
} catch (e) {
return next(e);
}
+ // a parameter with a modifier extension the server doesn't understand: every operation
+ // refuses it (the resources in the parameters are checked where they're used)
+ try {
+ Extensions.checkNoParameterModifiers(req.body);
+ } catch (e) {
+ return res.status(e.statusCode || 400).json(outcomeFromError(e));
+ }
next();
};
diff --git a/tx/vs/vs-database.js b/tx/vs/vs-database.js
index 32482ede9..ce5284ef7 100644
--- a/tx/vs/vs-database.js
+++ b/tx/vs/vs-database.js
@@ -1,6 +1,6 @@
const fs = require('fs').promises;
const crypto = require('crypto');
-const sqlite3 = require('sqlite3').verbose();
+const sqlite3 = require('sqlite3');
const { VersionUtilities } = require('../../library/fhir/version-utilities');
const ValueSet = require("../library/valueset");
const { guarded } = require('../library/sqlite-utilities');
diff --git a/tx/workers/compare.js b/tx/workers/compare.js
index 93397d5e3..24ec45151 100644
--- a/tx/workers/compare.js
+++ b/tx/workers/compare.js
@@ -89,15 +89,15 @@ class CompareWorker extends TerminologyWorker {
async handleTypeLevelCompare(req, res) {
this.deadCheck('compare-type-level');
- let params = req.body;
- this.addHttpParams(req, params);
+ // a GET's query (or a form post) as a Parameters resource, as the other operations do
+ let params = this.buildParameters(req);
await this.setupAdditionalResources(params);
let txp = new TxParameters(this.opContext.i18n.languageDefinitions, this.opContext.i18n, false);
txp.readParams(params);
this.params = txp;
- let thisVS = await this.readValueSet(res, "this", params, txp);
- let otherVS = await this.readValueSet(res, "other", params, txp);
+ let thisVS = await this.readValueSet("this", params);
+ let otherVS = await this.readValueSet("other", params);
const result = await this.doCompare(txp, thisVS, otherVS);
return res.json(result);
@@ -110,8 +110,8 @@ class CompareWorker extends TerminologyWorker {
async handleInstanceLevelCompare(req, res) {
this.deadCheck('compare-instance-level');
- let params = req.body;
- this.addHttpParams(req, params);
+ // a GET's query (or a form post) as a Parameters resource, as the other operations do
+ let params = this.buildParameters(req);
await this.setupAdditionalResources(params);
let txp = new TxParameters(this.opContext.i18n.languageDefinitions, this.opContext.i18n, false);
txp.readParams(params);
@@ -123,7 +123,7 @@ class CompareWorker extends TerminologyWorker {
return res.status(404).json(this.operationOutcome('error', 'not-found',
`ValueSet/${id} not found`));
}
- let otherVS = await this.readValueSet(res, "other", params, txp);
+ let otherVS = await this.readValueSet("other", params);
const result = await this.doCompare(txp, thisVS, otherVS);
return res.json(result);
@@ -141,7 +141,14 @@ class CompareWorker extends TerminologyWorker {
return buildOperationOutcome(severity, code, message, txIssueType);
}
- async readValueSet(res, prefix, params) {
+ /**
+ * The value set to compare: the {prefix}ValueSet parameter, or the one {prefix}Url names
+ * (thrown as an OperationOutcome, 400 or 404, if there's neither or it isn't found)
+ * @param {string} prefix - this or other
+ * @param {Object} params - the Parameters resource
+ * @returns {Promise}
+ */
+ async readValueSet(prefix, params) {
const valueSetParam = this.findParameter(params, prefix+'ValueSet');
if (valueSetParam && valueSetParam.resource) {
let valueSet = new ValueSet(valueSetParam.resource);
@@ -153,8 +160,8 @@ class CompareWorker extends TerminologyWorker {
const versionParam = this.findParameter(params, 'valueSetVersion');
if (!urlParam) {
- return res.status(400).json(this.operationOutcome('error', 'invalid',
- `Must provide either a ${prefix}ValueSet resource or a ${prefix}Url parameter`));
+ throw new Issue('error', 'required', null, null,
+ `Must provide either a ${prefix}ValueSet resource or a ${prefix}Url parameter`, 'invalid-data').handleAsOO(400);
}
const url = this.getParameterValue(urlParam);
@@ -163,11 +170,10 @@ class CompareWorker extends TerminologyWorker {
let valueSet = await this.findValueSet(url, version, null);
this.seeSourceVS(valueSet, url);
if (!valueSet) {
- return res.status(404).json(this.operationOutcome('error', 'not-found',
- version ? `ValueSet not found: ${url} version ${version}` : `ValueSet not found: ${url}`));
- } else {
- return valueSet;
+ throw new Issue('error', 'not-found', null, null,
+ version ? `ValueSet not found: ${url} version ${version}` : `ValueSet not found: ${url}`, 'not-found').handleAsOO(404);
}
+ return valueSet;
}
async doCompare(txp, thisVS, otherVS) {
@@ -181,12 +187,12 @@ class CompareWorker extends TerminologyWorker {
if (!thisC) {
return this.makeOutcome("indeterminate", `The ValueSet ${thisVS.vurl} has no compose`);
}
- Extensions.checkNoModifiers(thisC, 'CompareWorker.doCompare', 'ValueSet.compose', thisVS.vurl)
+ Extensions.checkNoModifiersAnywhere(thisVS, 'VALUESET_MODIFIER_EXTENSION_UNKNOWN', 'value set', thisVS.vurl);
this.checkNoLockedDate(thisVS.vurl, thisC);
if (!otherC) {
return this.makeOutcome("indeterminate", `The ValueSet ${otherVS.vurl} has no compose`);
}
- Extensions.checkNoModifiers(otherC, 'CompareWorker.doCompare', 'ValueSet.compose', otherVS.vurl)
+ Extensions.checkNoModifiersAnywhere(otherVS, 'VALUESET_MODIFIER_EXTENSION_UNKNOWN', 'value set', otherVS.vurl);
this.checkNoLockedDate(otherVS.vurl, otherC);
let systems = new Map(); // tracks whether the comparison is version dependent or not
diff --git a/tx/workers/expand.js b/tx/workers/expand.js
index 6bb92e664..34fc4c002 100644
--- a/tx/workers/expand.js
+++ b/tx/workers/expand.js
@@ -8,9 +8,11 @@
// POST /ValueSet/$expand (body is Parameters with valueSet parameter)
//
+const { supplementProperties } = require('../library/supplement-properties');
const { TerminologyWorker } = require('./worker');
const {TxParameters} = require("../params");
const {Designations, SearchFilterText} = require("../library/designations");
+const { storedExpansionIssue } = require("../library/stored-expansion");
const {Extensions} = require("../library/extensions");
const {getValuePrimitive, getValueName, validateParameter} = require("../../library/utils/utilities");
const {div} = require("../../library/html/html");
@@ -727,6 +729,11 @@ class ValueSetExpander {
* @param {Issue|Issue[]} issue the issue (or issues, reported in one OperationOutcome)
*/
addExpansionIssue(vs, exp, issue) {
+ this.#addExpansionIssueJson(vs, exp, (Array.isArray(issue) ? issue : [issue]).map(i => i.asIssue()));
+ }
+
+ /** addExpansionIssue, with the OperationOutcome's issues as they are in JSON */
+ #addExpansionIssueJson(vs, exp, issues) {
if (!vs.contained) {
vs.contained = [];
}
@@ -735,13 +742,68 @@ class ValueSetExpander {
n++;
}
const id = 'oo' + n;
- vs.contained.push({ resourceType: 'OperationOutcome', id, issue: (Array.isArray(issue) ? issue : [issue]).map(i => i.asIssue()) });
+ vs.contained.push({ resourceType: 'OperationOutcome', id, issue: issues });
if (!exp.extension) {
exp.extension = [];
}
exp.extension.push({ url: 'http://hl7.org/fhir/StructureDefinition/expansion-issue', valueReference: { reference: '#' + id } });
}
+ /**
+ * The issues an imported value set's expansion reported (each expansion-issue refers to a contained
+ * OperationOutcome), kept to be reported by this expansion too: a problem in an import is a problem
+ * in the expansion that uses it, whether the import adds codes or only says which (A11). An import
+ * that imports others has already taken theirs
+ */
+ #collectImportedIssues(result) {
+ const exp = result.expansion;
+ for (const ext of (exp && exp.extension) || []) {
+ if (ext.url !== 'http://hl7.org/fhir/StructureDefinition/expansion-issue' || !ext.valueReference || !ext.valueReference.reference) {
+ continue;
+ }
+ const id = ext.valueReference.reference.replace(/^#/, '');
+ const oo = (result.contained || []).find(r => r.resourceType === 'OperationOutcome' && r.id === id);
+ if (oo && oo.issue && oo.issue.length > 0) {
+ if (!this.importedIssues) {
+ this.importedIssues = [];
+ }
+ this.importedIssues.push(oo.issue);
+ }
+ }
+ }
+
+ /**
+ * The imported value sets' issues (see #collectImportedIssues), after this expansion's own: each
+ * reported once - an import used twice, or two imports with the same problem, or one this
+ * expansion has found itself (e.g. a request supplement's), is not reported again
+ */
+ #addImportedIssues(vs, exp) {
+ if (!this.importedIssues) {
+ return;
+ }
+ const seen = new Set();
+ for (const r of vs.contained || []) {
+ if (r.resourceType === 'OperationOutcome') {
+ for (const i of r.issue || []) {
+ seen.add(JSON.stringify(i));
+ }
+ }
+ }
+ for (const group of this.importedIssues) {
+ const fresh = group.filter(i => {
+ const key = JSON.stringify(i);
+ if (seen.has(key)) {
+ return false;
+ }
+ seen.add(key);
+ return true;
+ });
+ if (fresh.length > 0) {
+ this.#addExpansionIssueJson(vs, exp, fresh);
+ }
+ }
+ }
+
/**
* Before the page of a paged expansion (count and offset, see handleCompose), a code that would
* be included is only counted: its key is kept, for deduplication, and nothing is read or built.
@@ -830,8 +892,18 @@ class ValueSetExpander {
* other include, no exclude), and no code in the selection is left out (inactive ones, or over
* the code system's cap on how many codes it contributes)
*/
+ /**
+ * Whether a code passes the request's activeOnly and excludeNotForUI: it isn't inactive (with
+ * activeOnly), and isn't abstract (with excludeNotForUI) - however it came to be in the value
+ * set: the whole code system, a filter, or listed (A9: excludeNotForUI was only applied to a
+ * walk of the whole code system)
+ */
+ async #passesStatus(cs, context) {
+ return (!this.params.activeOnly || !await cs.isInactive(context)) && (!this.params.excludeNotForUI || !await cs.isAbstract(context));
+ }
+
#sizeIsTotal(compose, cs, excludeInactive) {
- return !excludeInactive && !this.params.activeOnly && !this.hasExclusions
+ return !excludeInactive && !this.params.activeOnly && !this.params.excludeNotForUI && !this.hasExclusions
&& (compose.include || []).length === 1 && (compose.exclude || []).length === 0
&& !(cs.expandLimitation() > 0);
}
@@ -930,6 +1002,7 @@ class ValueSetExpander {
if (Extensions.has(result.expansion, 'http://hl7.org/fhir/params/questionnaire-extensions#closed')) {
notClosed.value = true;
}
+ this.#collectImportedIssues(result);
return result;
}
@@ -1330,12 +1403,20 @@ class ValueSetExpander {
notClosed.value = true;
}
- if (this.count === 0 && filters.length === 0 && valueSets.length === 0 && !this.hasExclusions) {
+ let counted = null;
+ if (this.count === 0 && filters.length === 0 && valueSets.length === 0 && !this.hasExclusions
+ && (compose.include || []).length === 1 && !this.params.excludeNotForUI) {
// count=0 (count only) with a single whole-code-system include and no
// additional filters: report the code count directly rather than
// enumerating - which for a poly-hierarchy (e.g. SNOMED) is both
- // expensive and pointless when no codes are being materialised.
- this.addToTotal(await cs.countAllCodes(excludeInactive));
+ // expensive and pointless when no codes are being materialised. Only when it is
+ // the value set's only include (another could include the same codes again), and
+ // nothing but inactive codes is left out (activeOnly: the provider counts those) (A9)
+ // (null: the provider can't count without the inactive codes, so walk them)
+ counted = await cs.countAllCodes(excludeInactive || this.params.activeOnly);
+ }
+ if (counted != null) {
+ this.addToTotal(counted);
} else {
const iter = await cs.iterator(null);
if (valueSets.length === 0 && this.count !== 0 && this.limitCount > 0 && (iter && iter.total > this.limitCount) && this.offset < 0) {
@@ -1369,7 +1450,8 @@ class ValueSetExpander {
// a code system that caps how many of its codes an expansion may list (e.g. CPT): the
// cap limits which codes can be on a page, not how many the value set has, so the
// total is all of them, as for count=0 (and the walk stopped at the cap)
- this.addToTotal(await cs.countAllCodes(excludeInactive));
+ const all = await cs.countAllCodes(excludeInactive);
+ this.addToTotal(all != null ? all : tcount);
} else {
this.addToTotal(tcount);
}
@@ -1383,17 +1465,23 @@ class ValueSetExpander {
const ctxt = await cs.searchFilter(prep, filter, true);
this.#reportSearchSupplements(prep);
let set = await cs.executeFilters(prep);
- if (this.count === 0 && valueSets.length === 0) {
+ if (this.count === 0 && valueSets.length === 0 && (compose.include || []).length === 1 && !this.hasExclusions
+ && !excludeInactive && !this.params.activeOnly && !this.params.excludeNotForUI) {
// count=0 (count only): report the filtered size directly without
- // materialising the codes.
+ // materialising the codes - when that size is the answer: the only include, and
+ // nothing left out of it (A9)
this.addToTotal(await cs.filterSize(ctxt, set[0]));
} else {
- this.noTotal();
+ if (this.count > 0) {
+ // a page of the matches: the rest aren't read, so there's no total. Unpaged, or count=0
+ // (which asks for the total), the matches that pass are all counted below (A9)
+ this.noTotal();
+ }
this.worker.opContext.log('iterate filters');
while (await cs.filterMore(ctxt, set[0])) {
await this.worker.checkAndYield('processCodes#4');
const c = await cs.filterConcept(ctxt, set[0]);
- if (await this.passesFilters(cs, c, prep, set, 1)) {
+ if (await this.#passesStatus(cs, c) && await this.passesFilters(cs, c, prep, set, 1)) {
const walked = await this.#beforePage(cs, await cs.system(), await cs.version(), await cs.code(c), await cs.isInactive(c), excludeInactive, valueSets);
if (walked !== null) {
// (no total on this path: once the page is full there's nothing to count)
@@ -1483,7 +1571,7 @@ class ValueSetExpander {
this.#unknownListedCode(cs, cc.code);
continue;
}
- if ((!this.params.activeOnly || !await cs.isInactive(cctxt.context)) && await this.passesFilters(cs, cctxt.context, prep, filters, 0)) {
+ if (await this.#passesStatus(cs, cctxt.context) && await this.passesFilters(cs, cctxt.context, prep, filters, 0)) {
let added;
const ecode = await cs.expansionCode(cctxt.context, cc.code);
const walked = await this.#beforePage(cs, cs.system(), cs.version(), ecode, await cs.isInactive(cctxt.context), excludeInactive, valueSets);
@@ -1638,7 +1726,7 @@ class ValueSetExpander {
while (!countOnly && await cs.filterMore(prep, fset[0])) {
await this.worker.checkAndYield('processCodes#5');
const c = await cs.filterConcept(prep, fset[0]);
- const ok = (!this.params.activeOnly || !await cs.isInactive(c)) && (await this.passesFilters(cs, c, prep, fset, 1))
+ const ok = await this.#passesStatus(cs, c) && (await this.passesFilters(cs, c, prep, fset, 1))
&& (await this.#passesSupplementFilters(cs, c, suppFilters));
if (ok) {
await addFound(c);
@@ -1648,7 +1736,7 @@ class ValueSetExpander {
// only filters on supplement properties: the codes are those the supplements list
for (const c of await this.#supplementFilterConcepts(cs, suppFilters, path)) {
await this.worker.checkAndYield('processCodes#5');
- if ((!this.params.activeOnly || !await cs.isInactive(c)) && (filter.isNull || filter.passesCode(await cs.code(c)) || await this.#displayPasses(filter, cs, c))) {
+ if (await this.#passesStatus(cs, c) && (filter.isNull || filter.passesCode(await cs.code(c)) || await this.#displayPasses(filter, cs, c))) {
await addFound(c);
}
}
@@ -2108,6 +2196,89 @@ class ValueSetExpander {
return false;
}
+ /**
+ * The codes of a stored expansion, as handleCompose adds a compose's: the request's filter,
+ * activeOnly and excludeNotForUI applied (a code that doesn't pass is left out, and what's
+ * under it moves up to its parent); the rest - count, offset, excludeNested, the total - as for
+ * any expansion. The parameters it was made with are carried over (what this request sets is
+ * this request's), and so are its extensions and property declarations
+ * (storedExpansionIssue has already said it can answer the request)
+ * @param {ValueSet} source
+ * @param {Object} stored - its expansion
+ * @param {SearchFilterText} filter
+ * @param {Object} exp - the expansion being made
+ * @param {{value: boolean}} notClosed
+ */
+ async handleStored(source, stored, filter, exp, notClosed) {
+ const own = new Set(['count', 'offset', 'filter', ...(exp.parameter || []).map(p => p.name)]);
+ for (const p of stored.parameter || []) {
+ const vn = getValueName(p);
+ if (vn && !own.has(p.name)) {
+ this.addParam(exp, p.name, vn, getValuePrimitive(p));
+ }
+ }
+ for (const ext of stored.extension || []) {
+ if (ext.url === 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed') {
+ notClosed.value = true;
+ } else {
+ exp.extension = [...(exp.extension || []), ext];
+ }
+ }
+ if (Array.isArray(stored.property) && stored.property.length > 0) {
+ exp.property = structuredClone(stored.property);
+ }
+ // the supplements it was made with are used: a required one is (storedExpansionIssue checked
+ // it was), though no code system is read here
+ const madeWith = (stored.parameter || []).filter(p => p.name === 'used-supplement').map(p => String(getValuePrimitive(p)));
+ for (const s of this.requiredSupplements) {
+ if (madeWith.some(u => u === s || u.split('|')[0] === s.split('|')[0])) {
+ this.usedSupplements.add(s);
+ }
+ }
+ const passes = (c) => {
+ if (this.params.activeOnly && c.inactive) {
+ return false;
+ }
+ if (this.params.excludeNotForUI && c.abstract) {
+ return false;
+ }
+ if (filter && !filter.isNull) {
+ const names = [c.display, ...(c.designation || []).map(d => d.value)].filter(v => typeof v === 'string' && v);
+ return (c.code && filter.passesCode(c.code)) || names.some(v => filter.passes(v));
+ }
+ return true;
+ };
+ const walk = async (list, parent) => {
+ for (const c of list || []) {
+ await this.worker.checkAndYield('handleStored');
+ let under = parent;
+ if (c.code && passes(c)) {
+ const key = this.keyC(c);
+ if (!this.map.has(key)) {
+ this.#checkLimit(source.vurl);
+ const n = structuredClone({ ...c, contains: undefined });
+ delete n.contains;
+ this.fullList.push(n);
+ this.map.set(key, n);
+ if (parent != null && !this.noDetails) {
+ if (!parent.contains) {
+ parent.contains = [];
+ }
+ parent.contains.push(n);
+ } else {
+ this.rootList.push(n);
+ }
+ under = n;
+ } else {
+ this.canBeHierarchy = false;
+ }
+ }
+ await walk(c.contains, under);
+ }
+ };
+ await walk(stored.contains, null);
+ }
+
/**
* How a value set is named in a message: by the url (|version) given, else as the value set this
* expander is expanding - its url|version, else its id - else null, for one with neither (a value
@@ -2173,7 +2344,8 @@ class ValueSetExpander {
async expand(source, filter, noCacheThisOne) {
Extensions.checkNoImplicitRules(source,'ValueSetExpander.Expand', 'ValueSet', source.vurl);
- Extensions.checkNoModifiers(source,'ValueSetExpander.Expand', 'ValueSet', source.vurl);
+ // the whole value set: there's nowhere in it a modifier extension doesn't matter
+ Extensions.checkNoModifiersAnywhere(source, 'VALUESET_MODIFIER_EXTENSION_UNKNOWN', 'value set', source.vurl);
// circular reference detection: this value set is in the chain being processed until
// its expansion is done
this.worker.seeValueSet(source, this.params);
@@ -2212,14 +2384,24 @@ class ValueSetExpander {
this.requiredSupplements.add(getValuePrimitive(ext));
}
+ // A stored expansion is used when the compose can't be (see useStoredExpansion) - as an
+ // expansion made with the parameters it records: the request's count, offset, filter,
+ // activeOnly, excludeNotForUI and excludeNested are applied to it, and the rest must match
+ // (stored-expansion.js). If they don't, there's no answer: the request is refused
+ let stored = null;
if (result.expansion) {
if (await this.useStoredExpansion(source.jsonObj)) {
- return result; // just return the expansion
+ const issue = storedExpansionIssue(source.jsonObj, this.vsLabel(source.vurl) || 'in the request', this.params, 'expand', this.worker.i18n,
+ filter && !filter.isNull ? filter.filter : null);
+ if (issue) {
+ throw issue;
+ }
+ stored = source.jsonObj.expansion;
}
- // otherwise it's expanded from the compose, as if it had no expansion
+ // either way, the expansion is made again: from the stored one, or from the compose
result.expansion = undefined;
}
- if (!source.jsonObj.compose) {
+ if (!source.jsonObj.compose && !stored) {
throw new Issue('error', 'invalid', null, 'VALUESET_NO_COMPOSE',
this.worker.i18n.translate('VALUESET_NO_COMPOSE', this.params.httpLanguages, [source.contextKey || source.vurlOrMsg]), 'vs-invalid', 422);
}
@@ -2309,9 +2491,12 @@ class ValueSetExpander {
let notClosed = { value : false};
- let vsInfo = this.scanValueSet(source.jsonObj.compose);
+ let vsInfo = stored ? { isSimple: false, hasExcludes: false, csset: new Set(), csDoExcludes: false, csDoOffset: false }
+ : this.scanValueSet(source.jsonObj.compose);
try {
- if (source.jsonObj.compose && Extensions.checkNoModifiers(source.jsonObj.compose, 'ValueSetExpander.Expand', 'ValueSet.compose', source.vurl)
+ if (stored) {
+ await this.handleStored(source, stored, filter, exp, notClosed);
+ } else if (source.jsonObj.compose && Extensions.checkNoModifiers(source.jsonObj.compose, 'ValueSetExpander.Expand', 'ValueSet.compose', source.vurl)
&& this.worker.checkNoLockedDate(source.url, source.jsonObj.compose)) {
await this.handleCompose(source, filter, exp, notClosed, vsInfo);
}
@@ -2361,6 +2546,7 @@ class ValueSetExpander {
this.addExpansionIssue(result, exp, new Issue('warning', 'business-rule', null, 'VALUESET_EXPANSION_CODESYSTEM_LIMITED',
this.worker.i18n.translate('VALUESET_EXPANSION_CODESYSTEM_LIMITED', this.params.httpLanguages, [this.capCut.system, this.capCut.limit]), 'business-rule'));
}
+ this.#addImportedIssues(result, exp);
this.worker.opContext.log('finish up');
@@ -2882,7 +3068,8 @@ class ValueSetExpander {
continue;
}
const inactive = await cs.isInactive(cctxt.context);
- if ((this.params.activeOnly && inactive) || !(await this.passesFilters(cs, cctxt.context, prep, filters, 0))) {
+ if ((this.params.activeOnly && inactive) || (this.params.excludeNotForUI && await cs.isAbstract(cctxt.context))
+ || !(await this.passesFilters(cs, cctxt.context, prep, filters, 0))) {
continue;
}
const code = await cs.expansionCode(cctxt.context, cc.code);
@@ -2934,7 +3121,16 @@ class ValueSetExpander {
names.push(pn);
}
}
- return await cs.properties(context, names);
+ const props = await cs.properties(context, names);
+ // and the properties the supplements in use give the code, whatever the provider (A12): which
+ // of these are reported is decided as for the provider's (#addDetails)
+ if (cs.supplements && cs.supplements.length > 0) {
+ const extra = supplementProperties(cs.supplements, await cs.code(context));
+ if (extra.length > 0) {
+ return [...(props || []), ...extra];
+ }
+ }
+ return props;
}
getPropUrl(cs, pn, cp) {
diff --git a/tx/workers/lookup.js b/tx/workers/lookup.js
index 6afc725f9..f6d4baf9b 100644
--- a/tx/workers/lookup.js
+++ b/tx/workers/lookup.js
@@ -7,6 +7,7 @@
// POST /CodeSystem/{id}/$lookup
//
+const { supplementProperties } = require('../library/supplement-properties');
const { TerminologyWorker, Unknown_Code_in_VersionSCT, SCTVersion } = require('./worker');
const { FhirCodeSystemProvider } = require('../cs/cs-cs');
const { Designations} = require("../library/designations");
@@ -298,6 +299,10 @@ class LookupWorker extends TerminologyWorker {
});
}
+ // displays - this one, and the descriptions of related codes (parent, child, ...) - are in the
+ // language asked for, displayLanguage or else Accept-Language, as the preferred designation is (A14)
+ csProvider.useDisplayLanguages(params.workingLanguages());
+
// display (required)
const display = await csProvider.display(ctxt);
const designations = new Designations(this.languages);
@@ -433,6 +438,19 @@ class LookupWorker extends TerminologyWorker {
}
checkAddedParameters(responseParams, providerParamsFrom, providerName);
+ // the properties the supplements in use give the code, whatever the provider (A12): each one
+ // asked for by its code, or by 'property' (or '*', or nothing asked for), as cs-cs.js reports
+ // a code system's own
+ for (const p of supplementProperties(csProvider.supplements, await csProvider.code(ctxt))) {
+ if (!hasProp(p.code, true) && !hasProp('property', true)) {
+ continue;
+ }
+ const vn = Object.keys(p).find(k => k.startsWith('value'));
+ if (vn) {
+ responseParams.push({ name: 'property', part: [{ name: 'code', valueCode: p.code }, { name: 'value', [vn]: p[vn] }] });
+ }
+ }
+
// notSelectable, the property: present (true) for every concept that is not selectable;
// for a selectable one only when asked for (false), and taken out if a provider added it
// anyway
diff --git a/tx/workers/subsumes.js b/tx/workers/subsumes.js
index e48800b62..ec930a9bb 100644
--- a/tx/workers/subsumes.js
+++ b/tx/workers/subsumes.js
@@ -164,7 +164,7 @@ class SubsumesWorker extends TerminologyWorker {
const codeSystem = await this.provider.getCodeSystemById(this.opContext, id);
if (!codeSystem) {
- throw new Issue('error', 'not found', null, null, `CodeSystem/${id} not found`, null, 404);
+ throw new Issue('error', 'not-found', null, null, `CodeSystem/${id} not found`, null, 404);
}
// See handleTypeLevelSubsumes: parse first, so a GET reaches the cache-id handling too
diff --git a/tx/workers/translate.js b/tx/workers/translate.js
index 68c4028b4..348f1b1be 100644
--- a/tx/workers/translate.js
+++ b/tx/workers/translate.js
@@ -13,6 +13,10 @@ const { Parameters } = require('../library/parameters');
const { Issue, OperationOutcome, buildOperationOutcome, outcomeFromError } = require('../library/operation-outcome');
const {ConceptMap} = require("../library/conceptmap");
const {Extensions} = require("../library/extensions");
+const { equivalenceOf, EXT_OLD_CONCEPTMAP_EQUIVALENCE } = require("../library/conceptmap");
+
+// the modifier extensions $translate understands, and the one element each is understood on
+const CONCEPTMAP_KNOWN_MODIFIERS = [['ConceptMap.group.element.target', EXT_OLD_CONCEPTMAP_EQUIVALENCE]];
const {VersionUtilities} = require("../../library/fhir/version-utilities");
const {debugLog} = require("../operation-context");
const {ValueSetChecker, ValidationCheckMode} = require("./validate");
@@ -33,6 +37,43 @@ function elementComment(em) {
return em.comment || Extensions.readString(em, EXT_ELEMENT_COMMENT);
}
+/**
+ * A target's product as a $translate match.product, in R5's form: attribute (a uri) and value[x]
+ * (for R4, xv-parameters.js makes it element and concept). The stored map may have R5's form
+ * (attribute - a code, defined in additionalAttribute - and value[x]) or R4's (property, system,
+ * value, display): the internal form keeps R4's (tx/xversion). As the Java convertors do, an R4
+ * value with a system is a Coding, and without one a string.
+ * @param {Object} prod - ConceptMap.group.element.target.product
+ * @param {Object} cm - the ConceptMap (its additionalAttribute say what the attribute codes are)
+ * @returns {Object} the product parameter
+ */
+function productParameter(prod, cm) {
+ const parts = [];
+ let attribute = prod.property;
+ if (prod.attribute !== undefined) {
+ const def = (cm.jsonObj.additionalAttribute || []).find(a => a.code === prod.attribute);
+ attribute = (def && def.uri) || prod.attribute;
+ }
+ if (attribute) {
+ parts.push({ name: 'attribute', valueUri: attribute });
+ }
+ const valueName = Object.keys(prod).find(k => /^value[A-Z]/.test(k) && k !== 'valueSet');
+ if (valueName) {
+ parts.push({ name: 'value', [valueName]: prod[valueName] });
+ } else if (prod.value !== undefined) {
+ if (prod.system) {
+ const coding = { system: prod.system, code: prod.value };
+ if (prod.display) {
+ coding.display = prod.display;
+ }
+ parts.push({ name: 'value', valueCoding: coding });
+ } else {
+ parts.push({ name: 'value', valueString: prod.value });
+ }
+ }
+ return { name: 'product', part: parts };
+}
+
// marks a match whose target came from the code system itself (translateUsingCodeSystem), so
// checkTargetConcepts leaves it alone. A symbol key, so it never reaches the JSON output
const TRUSTED_TARGET = Symbol('trustedTarget');
@@ -450,6 +491,8 @@ class TranslateWorker extends TerminologyWorker {
}
async translateUsingGroupsForwards(cm, coding, targetScope, targetSystem, params, output, origin, visited) {
+ // everything in a map is about translating: one it doesn't understand can't be used (A5)
+ Extensions.checkNoModifiersAnywhere(cm, 'CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN', 'concept map', cm.vurl, CONCEPTMAP_KNOWN_MODIFIERS);
let result = false;
// originMap names where the chain of maps started, not the map that happened to
// supply the answer; any other map consulted along the way is a used-conceptmap.
@@ -516,8 +559,9 @@ class TranslateWorker extends TerminologyWorker {
}
for (const map of em.target || []) {
let ok = false;
- if (map.equivalence) { // R4 mode
- ok = ['null', 'relatedto', 'equivalent', 'equal', 'wider', 'subsumes', 'narrower', 'specializes', 'inexact', 'unmatched', 'disjoint'].includes(map.equivalence);
+ const equivalence = equivalenceOf(map);
+ if (equivalence) { // R4 mode
+ ok = ['null', 'relatedto', 'equivalent', 'equal', 'wider', 'subsumes', 'narrower', 'specializes', 'inexact', 'unmatched', 'disjoint'].includes(equivalence);
} else {
ok = ['null', 'related-to', 'equivalent', 'source-is-narrower-than-target', 'source-is-broader-than-target', 'not-related-to'].includes(map.relationship);
}
@@ -544,10 +588,10 @@ class TranslateWorker extends TerminologyWorker {
valueCode: map.relationship
});
// equivalence vs relationship will be sorted out in the version transform for parameters
- if (map.equivalence) {
+ if (equivalence) {
matchParts.push({
name: 'equivalence',
- valueCode: map.equivalence
+ valueCode: equivalence
});
}
// ConceptMap.group.element.comment is about the source concept,
@@ -566,22 +610,7 @@ class TranslateWorker extends TerminologyWorker {
});
}
for (const prod of map.product || []) {
- const productParts = [];
- productParts.push({
- name: 'element',
- valueString: prod.property
- });
- productParts.push({
- name: 'concept',
- valueCoding: {
- system: prod.system,
- code: prod.value
- }
- });
- matchParts.push({
- name: 'product',
- part: productParts
- });
+ matchParts.push(productParameter(prod, cm));
}
matchParts.push({
name: 'originMap',
@@ -606,6 +635,7 @@ class TranslateWorker extends TerminologyWorker {
}
async translateUsingGroupsReverse(cm, coding, targetScope, targetSystem, params, output) {
+ Extensions.checkNoModifiersAnywhere(cm, 'CONCEPTMAP_MODIFIER_EXTENSION_UNKNOWN', 'concept map', cm.vurl, CONCEPTMAP_KNOWN_MODIFIERS);
let result = false;
const matches = cm.listTranslationsReverse(coding, targetScope, targetSystem);
// ConceptMap.group.element.target.valueSet: in reverse, the code is a target if it's in the
@@ -624,8 +654,9 @@ class TranslateWorker extends TerminologyWorker {
const em = match.match;
const map = match.target;
let ok = false;
- if (map.equivalence) { // R4 mode
- ok = ['null', 'relatedto', 'equivalent', 'equal', 'wider', 'subsumes', 'narrower', 'specializes', 'inexact', 'unmatched', 'disjoint'].includes(map.equivalence);
+ const equivalence = equivalenceOf(map);
+ if (equivalence) { // R4 mode
+ ok = ['null', 'relatedto', 'equivalent', 'equal', 'wider', 'subsumes', 'narrower', 'specializes', 'inexact', 'unmatched', 'disjoint'].includes(equivalence);
} else {
ok = ['null', 'related-to', 'equivalent', 'source-is-narrower-than-target', 'source-is-broader-than-target', 'not-related-to'].includes(map.relationship);
}
@@ -661,10 +692,10 @@ class TranslateWorker extends TerminologyWorker {
valueCode: map.relationship
});
// equivalence vs relationship will be sorted out in the version transform for parameters
- if (map.equivalence) {
+ if (equivalence) {
matchParts.push({
name: 'equivalence',
- valueCode: map.equivalence
+ valueCode: equivalence
});
}
// as above: element.comment describes the source concept, and
@@ -683,22 +714,7 @@ class TranslateWorker extends TerminologyWorker {
});
}
for (const prod of map.product || []) {
- const productParts = [];
- productParts.push({
- name: 'element',
- valueString: prod.property
- });
- productParts.push({
- name: 'concept',
- valueCoding: {
- system: prod.system,
- code: prod.value
- }
- });
- matchParts.push({
- name: 'product',
- part: productParts
- });
+ matchParts.push(productParameter(prod, cm));
}
matchParts.push({
name: 'originMap',
diff --git a/tx/workers/validate.js b/tx/workers/validate.js
index fa003d624..59ed5c745 100644
--- a/tx/workers/validate.js
+++ b/tx/workers/validate.js
@@ -11,10 +11,12 @@
// POST /ValueSet/{id}/$validate-code
//
+const { VCL_URI } = require('../../vcl/vcl-parser');
const { TerminologyWorker, Unknown_Code_in_VersionSCT, SCTVersion } = require('./worker');
const { splitFilters, supplementFilter } = require('./supplement-filters');
const {Languages, Language} = require("../../library/i18n/languages");
const {Extensions} = require("../library/extensions");
+const { storedExpansionIssue } = require("../library/stored-expansion");
const {validateParameter, isAbsoluteUrl, validateOptionalParameter, getValuePrimitive} = require("../../library/utils/utilities");
const {TxParameters} = require("../params");
const { OperationOutcome, Issue, buildOperationOutcome } = require('../library/operation-outcome');
@@ -346,7 +348,17 @@ class ValueSetChecker {
}
Extensions.checkNoImplicitRules(this.valueSet, 'ValueSetChecker.prepare', 'ValueSet');
- Extensions.checkNoModifiers(this.valueSet, 'ValueSetChecker.prepare', 'ValueSet', this.valueSet.vurl);
+ // the whole value set: there's nowhere in it a modifier extension doesn't matter
+ Extensions.checkNoModifiersAnywhere(this.valueSet, 'VALUESET_MODIFIER_EXTENSION_UNKNOWN', 'value set', this.valueSet.vurl);
+ // with no compose, membership is the stored expansion's: only if it was made the way this
+ // request needs (stored-expansion.js). If it wasn't, there's no answer: the request is refused
+ if (!this.valueSet.jsonObj.compose && this.valueSet.jsonObj.expansion) {
+ const issue = storedExpansionIssue(this.valueSet.jsonObj, this.valueSet.vurl || this.valueSet.jsonObj.id || 'in the request',
+ this.params, 'validate', this.worker.i18n);
+ if (issue) {
+ throw issue;
+ }
+ }
this.allValueSet = this.valueSet.url === 'http://hl7.org/fhir/ValueSet/@all';
@@ -995,6 +1007,12 @@ class ValueSetChecker {
let msg = '';
if ((system === '%%null%%' || cs.system() === system) && await this.checkExpansion(path, cs, ccc, code, displays, this.valueSet, msg, inactive, vstatus, op)) {
result = true;
+ // activeOnly: an inactive code isn't in the value set as expanded with activeOnly
+ if (this.params.activeOnly && (ccc.inactive || inactive.value)) {
+ result = false;
+ const loc = await cs.locate(code);
+ await this.#excludedByActiveOnly(cs, loc ? loc.context : null, code, path, 'in', op, messages, inactive, vstatus);
+ }
} else {
result = false;
}
@@ -1246,7 +1264,9 @@ class ValueSetChecker {
op.addIssue(new Issue('error', 'invalid', addToPath(path, 'system'), 'CODESYSTEM_CS_NO_SUPPLEMENT', m, 'invalid-data'));
cause.value = 'invalid';
} else {
- let prov2 = await this.worker.findCodeSystem(ws, '', this.params, ['complete', 'fragment'], op,true, true, false, this.worker.requiredSupplements);
+ // only whether the system is known at all: no version was chosen here, so there's
+ // nothing for check-system-version to check
+ let prov2 = await this.worker.findCodeSystem(ws, '', this.params, ['complete', 'fragment'], op,true, false, false, this.worker.requiredSupplements);
let bAdd = true;
let m, mid, vn;
if (prov2 === null && !lookupVersion) {
@@ -2633,6 +2653,12 @@ class ValidateWorker extends TerminologyWorker {
if (fromAdditional) {
return fromAdditional;
}
+ // an implicit VCL value set (worker.findValueSet)
+ if (url.startsWith(VCL_URI)) {
+ const vs = this.implicitVclValueSet(url);
+ this.seeSourceVS(vs, url);
+ return vs;
+ }
// an implicit value set in the generic form is drawn from the code system version the
// request asks for (system-version and the like)
diff --git a/tx/workers/worker.js b/tx/workers/worker.js
index abbaac15a..84c24e2cd 100644
--- a/tx/workers/worker.js
+++ b/tx/workers/worker.js
@@ -1,4 +1,5 @@
const { TerminologyError} = require('../library/errors');
+const { parseVCL, vclFromImplicitUrl, VCL_URI } = require('../../vcl/vcl-parser');
const { CodeSystem } = require('../library/codesystem');
const ValueSet = require('../library/valueset');
const {VersionUtilities} = require("../../library/fhir/version-utilities");
@@ -487,6 +488,12 @@ class TerminologyWorker {
return null;
}
+ // an implicit VCL value set (http://fhir.org/VCL?v1={expression}): the value set the expression is.
+ // Before the url|version split: the expression is percent-encoded, but a client may not have
+ if (url.startsWith(VCL_URI) && !this.findInAdditionalResources(url, version, 'ValueSet', false)) {
+ return this.implicitVclValueSet(url);
+ }
+
// Parse URL|version format
let effectiveUrl = url;
let effectiveVersion = version;
@@ -519,6 +526,25 @@ class TerminologyWorker {
return null;
}
+ /**
+ * The value set an implicit VCL value set URL is: its compose, from the expression (A16)
+ * @param {string} url - http://fhir.org/VCL?v1={percent-encoded expression}
+ */
+ implicitVclValueSet(url) {
+ let vs;
+ try {
+ vs = parseVCL(vclFromImplicitUrl(url));
+ } catch (e) {
+ const langs = this.params && this.params.httpLanguages ? this.params.httpLanguages : this.opContext.langs;
+ throw new Issue('error', 'invalid', null, 'VALUESET_VCL_INVALID',
+ this.i18n.translate('VALUESET_VCL_INVALID', langs, [url, e.message]), 'vs-invalid', 400);
+ }
+ vs.url = url;
+ vs.status = 'active';
+ vs.name = 'VCL';
+ return this.wrapRawResource(vs);
+ }
+
/**
* Apply version pinning rules from parameters
* @param {string} url - ValueSet URL
@@ -1196,17 +1222,18 @@ class TerminologyWorker {
}
}
}
- for (let t of list) {
- if (t.mode === 'check') {
- if (!result) {
+ // check-system-version never influences which version of the code system is used: the
+ // version is chosen as if it weren't there, and then checkVersion fails the operation if
+ // the chosen version doesn't match (community decision, Dec 2026: Zulip, Terminology Service
+ // Test Cases, 'check-system-version semantics'). check-valueset-version still names the
+ // value set version when nothing else does - nothing checks a value set version afterwards
+ if (!result) {
+ for (let t of list) {
+ if (t.mode === 'check' && t.vs) {
result = t.version;
this.foundParameters.push(t.asParam());
+ break;
}
- // if we decide to allow check to guide the selection.
- // waiting for discussion
- //else if (TFHIRVersions.isSubset(result, t.version)) {
- // result = t.version;
- //}
}
}
return result;
@@ -1216,7 +1243,7 @@ class TerminologyWorker {
if (params) {
let list = params.rulesForSystem(url);
for (let t of list) {
- if (t.mode === 'check') {
+ if (t.mode === 'check' && !t.vs) {
if (!VersionUtilities.versionMatchesByAlgorithm(t.version, version, versionAlgorithm)) {
let issue = new Issue("error", "exception", null, 'VALUESET_VERSION_CHECK', this.i18n.translate('VALUESET_VERSION_CHECK', params.FHTTPLanguages, [url, version, t.version]), 'version-error', 400);
if (op) {
diff --git a/tx/xversion/xv-codesystem.js b/tx/xversion/xv-codesystem.js
index 6d4fa08f0..7ee3c89c9 100644
--- a/tx/xversion/xv-codesystem.js
+++ b/tx/xversion/xv-codesystem.js
@@ -1,5 +1,5 @@
const {VersionUtilities} = require("../../library/fhir/version-utilities");
-const { mapShared, designationsFromR5, convertOnce, CS_ADDITIONAL_USE_EXT } = require("./xv-shared");
+const { mapShared, designationsFromR5, convertOnce, elementsToExtensions, canonicalMetadataSpecs, CS_ADDITIONAL_USE_EXT } = require("./xv-shared");
/**
* Converts input CodeSystem to R5 format (modifies input object for performance)
@@ -19,6 +19,7 @@ function codeSystemToR5(jsonObj, version) {
if (jsonObj.identifier && !Array.isArray(jsonObj.identifier)) {
jsonObj.identifier = [jsonObj.identifier];
}
+ subsumesToChildProperty(jsonObj);
return jsonObj;
}
@@ -30,6 +31,53 @@ function codeSystemToR5(jsonObj, version) {
throw new Error(`Unsupported FHIR version: ${version}`);
}
+// R3's way of saying a concept has another parent: on the parent, a modifier extension naming a
+// code declared elsewhere in the code system that it also subsumes (the v3 code systems in R3 core
+// use it). It's an is-a link, as much as the nesting is - the hierarchy carries meaning, which is
+// why it's a modifier. R4 and later say it with a property, and the tx module supports the child
+// property (CodeSystem._buildHierarchyMaps), so it becomes one
+const EXT_R3_SUBSUMES = 'http://hl7.org/fhir/StructureDefinition/codesystem-subsumes';
+const CHILD_PROPERTY_URI = 'http://hl7.org/fhir/concept-properties#child';
+
+/**
+ * Each codesystem-subsumes modifier extension in an R3 code system as a child property (declared,
+ * if the code system doesn't declare one already). Changes the code system.
+ * @param {Object} cs - the code system (R3, being converted)
+ * @private
+ */
+function subsumesToChildProperty(cs) {
+ let code = null;
+ const propertyCode = () => {
+ if (code === null) {
+ cs.property = cs.property || [];
+ const declared = cs.property.find(p => p.uri === CHILD_PROPERTY_URI);
+ if (declared) {
+ code = declared.code;
+ } else {
+ code = cs.property.some(p => p.code === 'child') ? 'subsumes' : 'child';
+ cs.property.push({ code, uri: CHILD_PROPERTY_URI, description: 'A concept this concept subsumes, other than those nested under it', type: 'code' });
+ }
+ }
+ return code;
+ };
+ const walk = concepts => {
+ for (const concept of concepts || []) {
+ if (Array.isArray(concept.modifierExtension)) {
+ const subsumes = concept.modifierExtension.filter(e => e.url === EXT_R3_SUBSUMES && e.valueCode);
+ if (subsumes.length > 0) {
+ concept.property = [...(concept.property || []), ...subsumes.map(e => ({ code: propertyCode(), valueCode: e.valueCode }))];
+ concept.modifierExtension = concept.modifierExtension.filter(e => e.url !== EXT_R3_SUBSUMES);
+ if (concept.modifierExtension.length === 0) {
+ delete concept.modifierExtension;
+ }
+ }
+ }
+ walk(concept.concept);
+ }
+ };
+ walk(cs.concept);
+}
+
/**
* Converts R5 CodeSystem to target version format (without changing the original: see xv-shared.js)
* @param {Object} r5Obj - The R5 format CodeSystem object
@@ -106,13 +154,8 @@ function conceptFromR5(concept, r3) {
* @private
*/
function codeSystemR5ToR4(r5Obj) {
- // Remove R5-specific elements that don't exist in R4
- if (r5Obj.versionAlgorithmString) {
- delete r5Obj.versionAlgorithmString;
- }
- if (r5Obj.versionAlgorithmCoding) {
- delete r5Obj.versionAlgorithmCoding;
- }
+ // R5 elements R4 doesn't have go into their cross-version extensions
+ elementsToExtensions(r5Obj, canonicalMetadataSpecs('CodeSystem'));
// Filter out R5-only filter operators
if (r5Obj.filter && Array.isArray(r5Obj.filter)) {
diff --git a/tx/xversion/xv-conceptmap.js b/tx/xversion/xv-conceptmap.js
index 904f97cba..6265ac8e0 100644
--- a/tx/xversion/xv-conceptmap.js
+++ b/tx/xversion/xv-conceptmap.js
@@ -1,10 +1,45 @@
const {VersionUtilities} = require("../../library/fhir/version-utilities");
-const { mapShared, convertOnce } = require("./xv-shared");
+const { mapShared, convertOnce, elementsToExtensions, renameElement, canonicalMetadataSpecs } = require("./xv-shared");
// R4/R3 have no ConceptMap.group.unmapped.valueSet or .relationship. The Java version
// convertors carry them across as these cross-version extensions, so read them back.
const EXT_UNMAPPED_VALUESET = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ConceptMap.group.unmapped.valueSet';
const EXT_UNMAPPED_RELATIONSHIP = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ConceptMap.group.unmapped.relationship';
+const EXT_UNMAPPED_COMMENT = 'http://hl7.org/fhir/6.0/StructureDefinition/extension-ConceptMap.group.unmapped.comment';
+
+// R4's way of saying "no map" is a target with no code and equivalence 'unmatched'; it becomes
+// element.noMap (see conceptMapToR5). The target's comment becomes element.comment (R6, which
+// $translate reads), and its products and dependsOn - which R5 has no place for on a noMap -
+// travel on the element as these extensions (the Java convertors' urls), and are put back for R4
+const EXT_R4_TARGET_PRODUCT = 'http://hl7.org/fhir/4.0/StructureDefinition/extension-ConceptMap.group.element.target.product';
+const EXT_R4_TARGET_DEPENDSON = 'http://hl7.org/fhir/4.0/StructureDefinition/extension-ConceptMap.group.element.target.dependsOn';
+
+// R5 (and R6) elements R4 doesn't have, as the Java convertors carry them
+const V5 = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ConceptMap.';
+const EXT_ELEMENT_COMMENT = 'http://hl7.org/fhir/6.0/StructureDefinition/extension-ConceptMap.group.element.comment';
+
+/** An R4 dependsOn or product as the complex extension that carries it @private */
+function r4OtherElementToExtension(url, d) {
+ const ext = { url, extension: [] };
+ for (const [name, type] of [['property', 'Uri'], ['system', 'Canonical'], ['value', 'String'], ['display', 'String']]) {
+ if (d[name] !== undefined) {
+ ext.extension.push({ url: name, ['value' + type]: d[name] });
+ }
+ }
+ return ext;
+}
+
+/** The inverse of r4OtherElementToExtension @private */
+function r4OtherElementFromExtension(ext) {
+ const d = {};
+ for (const e of ext.extension || []) {
+ const v = e.valueUri ?? e.valueCanonical ?? e.valueString;
+ if (['property', 'system', 'value', 'display'].includes(e.url) && v !== undefined) {
+ d[e.url] = v;
+ }
+ }
+ return d;
+}
/**
* R4 spells group.unmapped differently: the target map is 'url' rather than 'otherMap',
@@ -18,8 +53,7 @@ function unmappedToR5(unmapped) {
unmapped.mode = 'use-source-code';
}
if (unmapped.url !== undefined && unmapped.otherMap === undefined) {
- unmapped.otherMap = unmapped.url;
- delete unmapped.url;
+ renameElement(unmapped, 'url', 'otherMap');
}
for (const ext of unmapped.extension || []) {
if (ext.url === EXT_UNMAPPED_VALUESET && unmapped.valueSet === undefined) {
@@ -40,7 +74,8 @@ function unmappedToR5(unmapped) {
/** The inverse of unmappedToR5. */
function unmappedFromR5(unmapped) {
if (!unmapped || !(unmapped.mode === 'use-source-code' || unmapped.otherMap !== undefined ||
- unmapped.valueSet !== undefined || unmapped.relationship !== undefined)) {
+ unmapped.valueSet !== undefined || unmapped.relationship !== undefined || unmapped.comment !== undefined ||
+ unmapped._otherMap !== undefined || unmapped._valueSet !== undefined || unmapped._relationship !== undefined || unmapped._comment !== undefined)) {
return unmapped;
}
// a copy: the stored map is not changed (copy on write, see conceptMapFromR5)
@@ -48,21 +83,10 @@ function unmappedFromR5(unmapped) {
if (copy.mode === 'use-source-code') {
copy.mode = 'provided';
}
- if (copy.otherMap !== undefined) {
- copy.url = copy.otherMap;
- delete copy.otherMap;
- }
- if (copy.valueSet !== undefined || copy.relationship !== undefined) {
- copy.extension = [...(copy.extension || [])];
- }
- if (copy.valueSet !== undefined) {
- copy.extension.push({url: EXT_UNMAPPED_VALUESET, valueCanonical: copy.valueSet});
- delete copy.valueSet;
- }
- if (copy.relationship !== undefined) {
- copy.extension.push({url: EXT_UNMAPPED_RELATIONSHIP, valueCode: copy.relationship});
- delete copy.relationship;
- }
+ renameElement(copy, 'otherMap', 'url');
+ // valueSet and relationship are R5, comment R6
+ elementsToExtensions(copy, [['valueSet', EXT_UNMAPPED_VALUESET, 'Canonical'], ['relationship', EXT_UNMAPPED_RELATIONSHIP, 'Code'],
+ ['comment', EXT_UNMAPPED_COMMENT, 'String']]);
return copy;
}
@@ -129,6 +153,13 @@ function conceptMapToR5(jsonObj, sourceVersion) {
if (comment && !element.comment) {
element.comment = comment.comment;
}
+ // R5 has no place for these on a noMap: they travel as extensions (A3: they were lost)
+ const carried = noMapTargets.flatMap(t => [
+ ...(t.dependsOn || []).map(d => r4OtherElementToExtension(EXT_R4_TARGET_DEPENDSON, d)),
+ ...(t.product || []).map(d => r4OtherElementToExtension(EXT_R4_TARGET_PRODUCT, d))]);
+ if (carried.length > 0) {
+ element.extension = [...(element.extension || []), ...carried];
+ }
element.target = element.target.filter(t => !(t.equivalence === 'unmatched' && !t.code));
if (element.target.length === 0) {
delete element.target;
@@ -174,19 +205,27 @@ function conceptMapFromR5(r5Obj, targetVersion) {
const out = { ...r5Obj };
// Remove R5-specific elements
- delete out.versionAlgorithmString;
- delete out.versionAlgorithmCoding;
delete out.property;
delete out.additionalAttribute;
+ // the rest of the R5 metadata R4 doesn't have go into their cross-version extensions
+ elementsToExtensions(out, canonicalMetadataSpecs('ConceptMap'));
- // Convert identifier array back to single object
+ // R4 has one identifier: the others go into the cross-version extension
if (Array.isArray(r5Obj.identifier)) {
- if (r5Obj.identifier.length > 0) {
- out.identifier = r5Obj.identifier[0]; // Take first identifier
- } else {
+ if (r5Obj.identifier.length === 0) {
delete out.identifier;
+ } else {
+ out.identifier = r5Obj.identifier[0];
+ if (r5Obj.identifier.length > 1) {
+ out.extension = [...(out.extension || []), ...r5Obj.identifier.slice(1).map(id => ({ url: V5 + 'identifier', valueIdentifier: id }))];
+ }
}
}
+ // R5 renamed source[x] and target[x] to sourceScope[x] and targetScope[x]
+ renameElement(out, 'sourceScopeUri', 'sourceUri');
+ renameElement(out, 'sourceScopeCanonical', 'sourceCanonical');
+ renameElement(out, 'targetScopeUri', 'targetUri');
+ renameElement(out, 'targetScopeCanonical', 'targetCanonical');
// Convert sourceScope/targetScope back to source/target + version
if (r5Obj.sourceScope) {
@@ -208,15 +247,17 @@ function conceptMapFromR5(r5Obj, targetVersion) {
// Convert relationship back to equivalence in group.element.target
if (Array.isArray(r5Obj.group)) {
- out.group = convertOnce(r5Obj.group, 'cm-r4', groups => mapShared(groups, groupFromR5));
+ // an R5 dependsOn/product names its attribute by code: R4's property is the attribute's uri
+ const attributes = new Map((r5Obj.additionalAttribute || []).filter(a => a.code && a.uri).map(a => [a.code, a.uri]));
+ out.group = convertOnce(r5Obj.group, 'cm-r4', groups => mapShared(groups, g => groupFromR5(g, attributes)));
}
return out;
}
/** A group (the same object if nothing in it changes) @private */
-function groupFromR5(group) {
+function groupFromR5(group, attributes) {
const unmapped = unmappedFromR5(group.unmapped);
- const element = Array.isArray(group.element) ? mapShared(group.element, elementFromR5) : group.element;
+ const element = Array.isArray(group.element) ? mapShared(group.element, e => elementFromR5(e, attributes)) : group.element;
if (unmapped === group.unmapped && element === group.element) {
return group;
}
@@ -231,31 +272,64 @@ function groupFromR5(group) {
}
/** An element (the same object if none of its targets changes) @private */
-function elementFromR5(element) {
+function elementFromR5(element, attributes) {
if (element.noMap === true) {
// The inverse of conceptMapToR5: R3/R4 have no element.noMap or element.comment, and say
// "no map" with a target-less target whose equivalence is 'unmatched'.
const copy = { ...element };
delete copy.noMap;
+ delete copy._noMap;
delete copy.comment;
+ delete copy._comment;
const unmatched = { equivalence: 'unmatched' };
if (element.comment !== undefined) {
unmatched.comment = element.comment;
}
- const target = Array.isArray(element.target) ? mapShared(element.target, targetFromR5) : [];
+ // the R4 target's dependsOn and products, carried on the element
+ if (Array.isArray(element.extension)) {
+ const dependsOn = element.extension.filter(e => e.url === EXT_R4_TARGET_DEPENDSON).map(r4OtherElementFromExtension);
+ const product = element.extension.filter(e => e.url === EXT_R4_TARGET_PRODUCT).map(r4OtherElementFromExtension);
+ if (dependsOn.length > 0) {
+ unmatched.dependsOn = dependsOn;
+ }
+ if (product.length > 0) {
+ unmatched.product = product;
+ }
+ const rest = element.extension.filter(e => e.url !== EXT_R4_TARGET_DEPENDSON && e.url !== EXT_R4_TARGET_PRODUCT);
+ if (rest.length > 0) {
+ copy.extension = rest;
+ } else {
+ delete copy.extension;
+ }
+ }
+ elementsToExtensions(copy, [['valueSet', V5 + 'group.element.valueSet', 'Canonical']]);
+ const target = Array.isArray(element.target) ? mapShared(element.target, t => targetFromR5(t, attributes)) : [];
copy.target = [...target, unmatched];
return copy;
}
- if (!Array.isArray(element.target)) {
+ const target = Array.isArray(element.target) ? mapShared(element.target, t => targetFromR5(t, attributes)) : element.target;
+ // R5's element.valueSet and R6's element.comment have no R4 element; noMap false says nothing
+ const r5Only = element.valueSet !== undefined || element._valueSet !== undefined || element.comment !== undefined ||
+ element._comment !== undefined || element.noMap !== undefined || element._noMap !== undefined;
+ if (target === element.target && !r5Only) {
return element;
}
- const target = mapShared(element.target, targetFromR5);
- return target === element.target ? element : { ...element, target };
+ const copy = { ...element };
+ if (target !== element.target) {
+ copy.target = target;
+ }
+ delete copy.noMap;
+ delete copy._noMap;
+ elementsToExtensions(copy, [['valueSet', V5 + 'group.element.valueSet', 'Canonical'], ['comment', EXT_ELEMENT_COMMENT, 'String']]);
+ return copy;
}
/** A target: relationship becomes equivalence (the same object if it has no relationship) @private */
-function targetFromR5(target) {
- if (target.relationship === undefined) {
+function targetFromR5(target, attributes) {
+ const dependsOn = Array.isArray(target.dependsOn) ? mapShared(target.dependsOn, d => otherElementFromR5(d, 'dependsOn', attributes)) : target.dependsOn;
+ const product = Array.isArray(target.product) ? mapShared(target.product, d => otherElementFromR5(d, 'product', attributes)) : target.product;
+ if (target.relationship === undefined && target._relationship === undefined && dependsOn === target.dependsOn &&
+ product === target.product && target.valueSet === undefined && target._valueSet === undefined && target.property === undefined) {
return target;
}
const copy = { ...target };
@@ -265,9 +339,69 @@ function targetFromR5(target) {
}
// Remove R5-only relationship field
delete copy.relationship;
+ delete copy._relationship;
+ if (dependsOn !== target.dependsOn) {
+ copy.dependsOn = dependsOn;
+ }
+ if (product !== target.product) {
+ copy.product = product;
+ }
+ elementsToExtensions(copy, [['valueSet', V5 + 'group.element.target.valueSet', 'Canonical']]);
+ if (Array.isArray(target.property)) {
+ copy.extension = [...(copy.extension || []), ...target.property.map(p => {
+ const ext = { url: V5 + 'group.element.target.property', extension: [{ url: 'code', valueCode: p.code }] };
+ const vn = Object.keys(p).find(k => k.startsWith('value'));
+ if (vn) {
+ ext.extension.push({ url: 'value', [vn]: p[vn] });
+ }
+ return ext;
+ })];
+ delete copy.property;
+ }
return copy;
}
+/**
+ * An R5 dependsOn or product (attribute, value[x], valueSet) as R4 has it (property, system,
+ * value, display); the same object if it's already R4's (the internal form keeps R4's)
+ * @param {Object} d
+ * @param {string} kind - dependsOn or product
+ * @param {Map} attributes - additionalAttribute code -> uri
+ * @private
+ */
+function otherElementFromR5(d, kind, attributes) {
+ const r5 = Object.keys(d).some(k => k === 'attribute' || k === '_attribute' || k === 'valueSet' || k === '_valueSet' ||
+ (k.replace(/^_/, '').startsWith('value') && k.replace(/^_/, '') !== 'value'));
+ if (!r5) {
+ return d;
+ }
+ const out = { ...d };
+ if (out.attribute !== undefined) {
+ out.property = attributes.get(out.attribute) || out.attribute;
+ delete out.attribute;
+ }
+ renameElement(out, '_attribute', '_property');
+ if (out.valueCoding) {
+ if (out.valueCoding.system !== undefined) {
+ out.system = out.valueCoding.system;
+ }
+ if (out.valueCoding.code !== undefined) {
+ out.value = out.valueCoding.code;
+ }
+ if (out.valueCoding.display !== undefined) {
+ out.display = out.valueCoding.display;
+ }
+ delete out.valueCoding;
+ delete out._valueCoding;
+ }
+ renameElement(out, 'valueCode', 'value');
+ renameElement(out, 'valueString', 'value');
+ // any other value type, and valueSet, R4 can't say: the cross-version extensions
+ const others = Object.keys(out).filter(k => /^value[A-Z]/.test(k) && k !== 'valueSet').map(k => [k, V5 + `group.element.target.${kind}.value`, k.slice(5)]);
+ elementsToExtensions(out, [...others, ['valueSet', V5 + `group.element.target.${kind}.valueSet`, 'Canonical']]);
+ return out;
+}
+
/**
* Converts R3/R4 equivalence to R5 relationship
* @param {string} equivalence - R3/R4 equivalence value
diff --git a/tx/xversion/xv-namingsystem.js b/tx/xversion/xv-namingsystem.js
index 6fb77802e..00f21b0bb 100644
--- a/tx/xversion/xv-namingsystem.js
+++ b/tx/xversion/xv-namingsystem.js
@@ -1,3 +1,4 @@
+const { elementsToExtensions, canonicalMetadataSpecs } = require("./xv-shared");
const {VersionUtilities} = require("../../library/fhir/version-utilities");
/**
@@ -59,11 +60,21 @@ function namingSystemFromR5(r5Obj, targetVersion) {
* @private
*/
function namingSystemR5ToR4(r5Obj) {
- if (r5Obj.versionAlgorithmString) {
- delete r5Obj.versionAlgorithmString;
- }
- if (r5Obj.versionAlgorithmCoding) {
- delete r5Obj.versionAlgorithmCoding;
+ // R4 NamingSystem isn't a canonical resource: no url, identifier, version, title and so on.
+ // They go into their cross-version extensions, as the Java convertors do
+ const v5 = name => `http://hl7.org/fhir/5.0/StructureDefinition/extension-NamingSystem.${name}`;
+ elementsToExtensions(r5Obj, [
+ ['url', v5('url'), 'Uri'],
+ ['identifier', v5('identifier'), 'Identifier'],
+ ['version', v5('version'), 'String'],
+ ['title', v5('title'), 'String'],
+ ['experimental', v5('experimental'), 'Boolean'],
+ ['purpose', v5('purpose'), 'Markdown'],
+ ['copyright', v5('copyright'), 'Markdown'],
+ ...canonicalMetadataSpecs('NamingSystem')
+ ]);
+ for (const uid of r5Obj.uniqueId || []) {
+ elementsToExtensions(uid, [['authoritative', v5('uniqueId.authoritative'), 'Boolean']]);
}
return r5Obj;
diff --git a/tx/xversion/xv-parameters.js b/tx/xversion/xv-parameters.js
index c7c0ef360..8b598aece 100644
--- a/tx/xversion/xv-parameters.js
+++ b/tx/xversion/xv-parameters.js
@@ -85,12 +85,16 @@ function parameterR5ToR3(p, topLevel) {
copy = { ...copy, resource };
}
}
+ if (topLevel && p.name == 'match' && p.part) {
+ // R3's $translate match has the same shape as R4's
+ copy = { ...copy, part: matchPartsFor4(p.part) };
+ }
if (p.valueCanonical) {
copy = { ...copy, valueUri: p.valueCanonical };
delete copy.valueCanonical;
}
- if (Array.isArray(p.part)) {
- const part = mapShared(p.part, pp => parameterR5ToR3(pp, false));
+ if (Array.isArray(copy.part)) {
+ const part = mapShared(copy.part, pp => parameterR5ToR3(pp, false));
if (part !== p.part) {
copy = { ...copy, part };
}
@@ -149,7 +153,33 @@ function matchPartsFor4(parts) {
out.push(pp);
}
}
- return out.filter(pp => pp.name !== 'relationship');
+ return out.filter(pp => pp.name !== 'relationship').map(pp => pp.name === 'product' ? productFor4(pp) : pp);
+}
+
+/**
+ * A match.product, for R4 (and R3): R5's attribute and value[x] are R4's element and concept (a
+ * Coding). As the Java convertors do, a value that isn't a Coding is the code; a value with no
+ * code at all (a Quantity) has no concept. A new part (the part given is not changed).
+ */
+function productFor4(product) {
+ const part = [];
+ for (const pp of product.part || []) {
+ if (pp.name === 'attribute') {
+ part.push({ name: 'element', valueUri: pp.valueUri ?? pp.valueCanonical ?? pp.valueString });
+ } else if (pp.name === 'value') {
+ if (pp.valueCoding) {
+ part.push({ name: 'concept', valueCoding: pp.valueCoding });
+ } else {
+ const v = pp.valueCode ?? pp.valueString ?? pp.valueBoolean ?? pp.valueInteger;
+ if (v !== undefined) {
+ part.push({ name: 'concept', valueCoding: { code: String(v) } });
+ }
+ }
+ } else {
+ part.push(pp);
+ }
+ }
+ return { ...product, part };
}
module.exports = { parametersToR5, parametersFromR5 };
\ No newline at end of file
diff --git a/tx/xversion/xv-resource.js b/tx/xversion/xv-resource.js
index 5c73ea56b..84c0ec554 100644
--- a/tx/xversion/xv-resource.js
+++ b/tx/xversion/xv-resource.js
@@ -6,6 +6,7 @@ const {conceptMapFromR5, conceptMapToR5} = require("./xv-conceptmap");
const {parametersFromR5, parametersToR5} = require("./xv-parameters");
const {operationOutcomeFromR5, operationOutcomeToR5} = require("./xv-operationoutcome");
const {bundleFromR5, bundleToR5} = require("./xv-bundle");
+const {namingSystemFromR5, namingSystemToR5} = require("./xv-namingsystem");
function convertResourceToR5(data, sourceVersion) {
@@ -18,6 +19,7 @@ function convertResourceToR5(data, sourceVersion) {
case "TerminologyCapabilities": return terminologyCapabilitiesToR5(data, sourceVersion);
case "ValueSet": return valueSetToR5(data, sourceVersion);
case "ConceptMap": return conceptMapToR5(data, sourceVersion);
+ case "NamingSystem": return namingSystemToR5(data, sourceVersion);
case "Parameters": return parametersToR5(data, sourceVersion);
case "OperationOutcome": return operationOutcomeToR5(data, sourceVersion);
case "Bundle": return bundleToR5(data, sourceVersion);
@@ -35,6 +37,7 @@ function convertResourceFromR5(data, targetVersion) {
case "TerminologyCapabilities": return terminologyCapabilitiesFromR5(data, targetVersion);
case "ValueSet": return valueSetFromR5(data, targetVersion);
case "ConceptMap": return conceptMapFromR5(data, targetVersion);
+ case "NamingSystem": return namingSystemFromR5(data, targetVersion);
case "Parameters": return parametersFromR5(data, targetVersion);
case "OperationOutcome": return operationOutcomeFromR5(data, targetVersion);
case "Bundle": return bundleFromR5(data, targetVersion);
diff --git a/tx/xversion/xv-shared.js b/tx/xversion/xv-shared.js
index e64f75158..340939fe4 100644
--- a/tx/xversion/xv-shared.js
+++ b/tx/xversion/xv-shared.js
@@ -92,4 +92,84 @@ function convertOnce(array, key, convert) {
return result;
}
-module.exports = { mapShared, designationFromR5, designationsFromR5, convertOnce, CS_ADDITIONAL_USE_EXT, VS_ADDITIONAL_USE_EXT };
+/**
+ * Elements that R4 doesn't have, moved into the cross-version extensions the Java convertors
+ * use for them, so what goes out as R4 is R4. Each value (each item, for a repeating element)
+ * becomes an extension; its id and extensions (the _name of a primitive) go with it.
+ * @param {Object} out - a copy of the object being converted (changed: the elements are removed
+ * and the extensions added)
+ * @param {Array>} specs - [element name, extension url, value type (e.g. 'String')]
+ * @returns {Object} out
+ */
+function elementsToExtensions(out, specs) {
+ const exts = [];
+ for (const [name, url, type] of specs) {
+ const v = out[name];
+ const prim = out['_' + name];
+ if (v === undefined && prim === undefined) {
+ continue;
+ }
+ const values = Array.isArray(v) ? v : (Array.isArray(prim) ? prim.map(() => null) : [v]);
+ values.forEach((value, i) => {
+ const ext = { url };
+ if (value !== null && value !== undefined) {
+ ext['value' + type] = value;
+ }
+ const p = Array.isArray(prim) ? prim[i] : prim;
+ if (p) {
+ ext['_value' + type] = p;
+ }
+ exts.push(ext);
+ });
+ delete out[name];
+ delete out['_' + name];
+ }
+ if (exts.length > 0) {
+ out.extension = [...(out.extension || []), ...exts];
+ }
+ return out;
+}
+
+/**
+ * Renames an element (and its _name), for elements R5 renamed: e.g. sourceScopeUri to sourceUri
+ * @param {Object} out - a copy (changed)
+ */
+function renameElement(out, from, to) {
+ if (out[from] !== undefined) {
+ out[to] = out[from];
+ delete out[from];
+ }
+ if (out['_' + from] !== undefined) {
+ out['_' + to] = out['_' + from];
+ delete out['_' + from];
+ }
+}
+
+const VERSION_ALGORITHM_EXT = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-CanonicalResource.versionAlgorithm';
+
+/**
+ * The canonical resource metadata R5 added (versionAlgorithm, copyrightLabel, the review and
+ * approval dates, topic, the contributors, relatedArtifact), for elementsToExtensions: R4
+ * CodeSystem, ValueSet, ConceptMap, NamingSystem and TerminologyCapabilities have none of them
+ * @param {string} type - the resource type, for the extension urls
+ */
+function canonicalMetadataSpecs(type) {
+ const v5 = name => `http://hl7.org/fhir/5.0/StructureDefinition/extension-${type}.${name}`;
+ return [
+ ['versionAlgorithmString', VERSION_ALGORITHM_EXT, 'String'],
+ ['versionAlgorithmCoding', VERSION_ALGORITHM_EXT, 'Coding'],
+ ['copyrightLabel', v5('copyrightLabel'), 'String'],
+ ['approvalDate', 'http://hl7.org/fhir/StructureDefinition/resource-approvalDate', 'Date'],
+ ['lastReviewDate', 'http://hl7.org/fhir/StructureDefinition/resource-lastReviewDate', 'Date'],
+ ['effectivePeriod', 'http://hl7.org/fhir/StructureDefinition/resource-effectivePeriod', 'Period'],
+ ['topic', v5('topic'), 'CodeableConcept'],
+ ['author', v5('author'), 'ContactDetail'],
+ ['editor', v5('editor'), 'ContactDetail'],
+ ['reviewer', v5('reviewer'), 'ContactDetail'],
+ ['endorser', v5('endorser'), 'ContactDetail'],
+ ['relatedArtifact', v5('relatedArtifact'), 'RelatedArtifact']
+ ];
+}
+
+module.exports = { mapShared, designationFromR5, designationsFromR5, convertOnce, elementsToExtensions, renameElement,
+ canonicalMetadataSpecs, CS_ADDITIONAL_USE_EXT, VS_ADDITIONAL_USE_EXT };
diff --git a/tx/xversion/xv-terminologyCapabilities.js b/tx/xversion/xv-terminologyCapabilities.js
index fbb1aa7e5..6191597af 100644
--- a/tx/xversion/xv-terminologyCapabilities.js
+++ b/tx/xversion/xv-terminologyCapabilities.js
@@ -1,5 +1,6 @@
const {VersionUtilities} = require("../../library/fhir/version-utilities");
const {Extensions} = require("../library/extensions");
+const { elementsToExtensions, canonicalMetadataSpecs } = require("./xv-shared");
/**
* Converts input TerminologyCapabilities to R5 format (modifies input object for performance)
@@ -134,21 +135,13 @@ function terminologyCapabilitiesFromR5(r5Obj, targetVersion) {
* @private
*/
function terminologyCapabilitiesR5ToR4(r5Obj) {
-
- if (r5Obj.versionAlgorithmString) {
- delete r5Obj.versionAlgorithmString;
- }
- if (r5Obj.versionAlgorithmCoding) {
- delete r5Obj.versionAlgorithmCoding;
- }
+ // R5 elements R4 doesn't have go into their cross-version extensions
+ elementsToExtensions(r5Obj, [
+ ['identifier', 'http://hl7.org/fhir/5.0/StructureDefinition/extension-TerminologyCapabilities.identifier', 'Identifier'],
+ ...canonicalMetadataSpecs('TerminologyCapabilities')
+ ]);
for (const cs of r5Obj.codeSystem || []) {
- if (cs.content) {
- if (!cs.extension) {
- cs.extension = [];
- }
- cs.extension.push({"url" : "http://hl7.org/fhir/5.0/StructureDefinition/extension-TerminologyCapabilities.codeSystem.content", valueCode : cs.content});
- delete cs.content;
- }
+ elementsToExtensions(cs, [['content', 'http://hl7.org/fhir/5.0/StructureDefinition/extension-TerminologyCapabilities.codeSystem.content', 'Code']]);
}
return r5Obj;
diff --git a/tx/xversion/xv-valueset.js b/tx/xversion/xv-valueset.js
index c912e3db9..6cbfde918 100644
--- a/tx/xversion/xv-valueset.js
+++ b/tx/xversion/xv-valueset.js
@@ -1,7 +1,7 @@
const {VersionUtilities} = require("../../library/fhir/version-utilities");
const {getValueName, getValuePrimitive} = require("../../library/utils/utilities");
const {Extensions} = require("../library/extensions");
-const { mapShared, designationsFromR5, convertOnce, VS_ADDITIONAL_USE_EXT } = require("./xv-shared");
+const { mapShared, designationsFromR5, convertOnce, elementsToExtensions, canonicalMetadataSpecs, VS_ADDITIONAL_USE_EXT } = require("./xv-shared");
// ValueSet.compose.property is R5 and up - it is how a client says which properties it wants
// back in an expansion. R4 and R3 have nowhere to put it, so it travels as a cross-version
@@ -28,6 +28,7 @@ function valueSetToR5(jsonObj, sourceVersion) {
valueSetIncludeToR5(inc);
}
composePropertyToR5(jsonObj.compose);
+ expansionToR5(jsonObj.expansion);
if (VersionUtilities.isR4Ver(sourceVersion)) {
return jsonObj; // No conversion needed
}
@@ -63,6 +64,85 @@ function composePropertyToR5(compose) {
}
}
+const EXP_PROPERTY_EXT = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.property';
+const EXP_CONTAINS_PROPERTY_EXT = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.contains.property';
+const EXP_NEXT_EXT = 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.next';
+
+/**
+ * Calls fn with each extension on obj with the url, and takes them off obj. Changes obj.
+ * @private
+ */
+function takeExtensions(obj, url, fn) {
+ if (!obj || !Array.isArray(obj.extension) || !obj.extension.some(ext => ext.url === url)) {
+ return;
+ }
+ for (const ext of obj.extension) {
+ if (ext.url === url) {
+ fn(ext);
+ }
+ }
+ obj.extension = obj.extension.filter(ext => ext.url !== url);
+ if (obj.extension.length === 0) {
+ delete obj.extension;
+ }
+}
+
+/** the value of the sub-extension of ext with the url, or undefined @private */
+function subExtension(ext, url) {
+ return Array.isArray(ext.extension) ? ext.extension.find(e => e.url === url) : undefined;
+}
+
+/**
+ * ValueSet.expansion from R4 or R3 (a stored expansion a client sends): the R5 elements back out of
+ * the cross-version extensions valueSetFromR5 (and the Java convertors) put them in - expansion.next,
+ * expansion.property, contains.property and designation.additionalUse. Without this, a stored
+ * expansion sent as R4 doesn't declare the properties it carries (and so can't be reused for a
+ * request that asks for them). Changes the expansion.
+ * @private
+ */
+function expansionToR5(expansion) {
+ if (!expansion) {
+ return;
+ }
+ takeExtensions(expansion, EXP_NEXT_EXT, ext => {
+ if (ext.valueUri !== undefined) {
+ expansion.next = ext.valueUri;
+ }
+ });
+ takeExtensions(expansion, EXP_PROPERTY_EXT, ext => {
+ const code = getValuePrimitive(subExtension(ext, 'code'));
+ if (code) {
+ const prop = { code };
+ const uri = getValuePrimitive(subExtension(ext, 'uri'));
+ if (uri) {
+ prop.uri = uri;
+ }
+ (expansion.property = expansion.property || []).push(prop);
+ }
+ });
+ const walk = (contains) => {
+ for (const item of contains || []) {
+ takeExtensions(item, EXP_CONTAINS_PROPERTY_EXT, ext => {
+ const code = getValuePrimitive(subExtension(ext, 'code'));
+ const value = subExtension(ext, 'value');
+ const vn = value ? getValueName(value) : null;
+ if (code && vn) {
+ (item.property = item.property || []).push({ code, [vn]: value[vn] });
+ }
+ });
+ for (const d of item.designation || []) {
+ takeExtensions(d, VS_ADDITIONAL_USE_EXT, ext => {
+ if (ext.valueCoding) {
+ (d.additionalUse = d.additionalUse || []).push(ext.valueCoding);
+ }
+ });
+ }
+ walk(item.contains);
+ }
+ };
+ walk(expansion.contains);
+}
+
function valueSetIncludeToR5(inc) {
for (const filter of inc.filter || []) {
if (filter._op) {
@@ -95,12 +175,8 @@ function valueSetFromR5(r5Obj, targetVersion) {
}
const out = { ...r5Obj };
- if (out.versionAlgorithmString) {
- delete out.versionAlgorithmString;
- }
- if (out.versionAlgorithmCoding) {
- delete out.versionAlgorithmCoding;
- }
+ // R5 elements R4 doesn't have go into their cross-version extensions
+ elementsToExtensions(out, canonicalMetadataSpecs('ValueSet'));
if (out.compose) {
out.compose = composeFromR5(out.compose, r3);
}
@@ -119,9 +195,8 @@ function valueSetFromR5(r5Obj, targetVersion) {
function composeFromR5(compose, r3) {
const out = { ...compose };
// ValueSet.compose.property has no home in R4, so it goes into the extension
- if (Array.isArray(compose.property) && compose.property.length > 0) {
- out.extension = [...(compose.extension || []), ...compose.property.map(prop => ({ url: COMPOSE_PROPERTY_EXT, valueString: prop }))];
- delete out.property;
+ if ((Array.isArray(compose.property) && compose.property.length > 0) || compose._property !== undefined) {
+ elementsToExtensions(out, [['property', COMPOSE_PROPERTY_EXT, 'String']]);
}
if (compose.include) {
out.include = compose.include.map(inc => includeFromR5(inc, r3));
@@ -141,10 +216,12 @@ function includeFromR5(inc, r3) {
return designation === c.designation ? c : { ...c, designation };
})
: inc.concept;
- if (filter === inc.filter && concept === inc.concept) {
+ if (filter === inc.filter && concept === inc.concept && inc.copyright === undefined && inc._copyright === undefined) {
return inc;
}
const out = { ...inc };
+ // include.copyright is R5 (the Java convertors use the include url for an exclude too)
+ elementsToExtensions(out, [['copyright', 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.compose.include.copyright', 'String']]);
if (filter !== inc.filter) {
out.filter = filter;
}
@@ -183,10 +260,13 @@ function filterOpExtension(op) {
*/
function expansionFromR5(expansion, r3) {
const out = { ...expansion };
+ // expansion.next (paging) is R5
+ elementsToExtensions(out, [['next', 'http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.next', 'Uri']]);
if (expansion.property && expansion.property.length > 0) {
// uri is 0..1: a property without one (a provider that doesn't declare its properties)
// must not produce an empty uri extension, which is not valid
- out.extension = [...(expansion.extension || []), ...expansion.property.map(prop => {
+ // (out.extension, not expansion.extension: it may already have the expansion.next extension)
+ out.extension = [...(out.extension || []), ...expansion.property.map(prop => {
const ext = [{ url: "code", valueCode: prop.code }];
if (prop.uri) {
ext.push({ url: "uri", valueUri: prop.uri });
diff --git a/vcl/vcl-parser.js b/vcl/vcl-parser.js
index e0017d952..608b7970c 100644
--- a/vcl/vcl-parser.js
+++ b/vcl/vcl-parser.js
@@ -5,9 +5,34 @@
//
/**
- * Value Set Composition Language (VCL) Parser for JavaScript FHIR
- * Based on the Java VCL parser but adapted for JavaScript
- * Compatible with ES6+ and both Node.js and browser environments
+ * ValueSet Compose Language (VCL) parser: https://build.fhir.org/ig/FHIR/ig-guidance/en/vcl.html
+ *
+ * An expression is parsed by the grammar into a tree, and the tree is then written as a
+ * ValueSet.compose. Kept in step with the Java parser in org.hl7.fhir.core (VCLParser, in
+ * org.hl7.fhir.r5 and org.hl7.fhir.model); both are tested by the shared cases in
+ * fhir-test-cases/vcl (tests/vcl/vcl-test-cases.test.js), whose readme sets out these rules.
+ *
+ * Parsing follows the grammar, with the lexer taking the longest match (so A-B is one code), and
+ * these differences:
+ * - a URI doesn't contain ';', ',' or '^' (the grammar's character set has them, so that
+ * ^http://a/vs1;^http://a/vs2 would be one URI)
+ * - a version (uri|version) ends at '|', '(', ')', ';', ',' or white space (the grammar's
+ * ~[|()]* would run on to the end of ^vs|1;^vs2)
+ * Newlines are not allowed (white space is spaces and tabs), and a quoted value escapes only " and \.
+ *
+ * Meaning, and the compose it gives:
+ * - a (system) scope applies to the sub-expression after it, and carries into brackets inside it,
+ * unless they have a scope of their own
+ * - ';' is a union: each part its own include (parts that are only codes, in the same system and
+ * version, are one include)
+ * - ',' is an intersection: one include, with the parts' system, codes (intersected), filters and
+ * value sets (all of which an include requires a code to be in)
+ * - '-' at the top is compose.exclude
+ * - anything an include can't hold - a union, or an exclusion, inside an intersection; an
+ * exclusion anywhere but the top; a part in another system; codes no other part has - is an
+ * include of the implicit value set for that sub-expression (include.valueSet:
+ * http://fhir.org/VCL?v1={the sub-expression, with its system, percent-encoded})
+ * - (system)* is all of the system: an include with just the system
*/
class VCLParseException extends Error {
@@ -59,6 +84,26 @@ const FilterOperator = {
EXISTS: 'exists'
};
+// the operator tokens: their symbol, and the filter operator
+const OPERATORS = {
+ [TokenType.EQ]: ['=', FilterOperator.EQUAL],
+ [TokenType.IS_A]: ['<<', FilterOperator.IS_A],
+ [TokenType.IS_NOT_A]: ['~<<', FilterOperator.IS_NOT_A],
+ [TokenType.DESC_OF]: ['<', FilterOperator.DESCENDENT_OF],
+ [TokenType.REGEX]: ['/', FilterOperator.REGEX],
+ [TokenType.IN]: ['^', FilterOperator.IN],
+ [TokenType.NOT_IN]: ['~^', FilterOperator.NOT_IN],
+ [TokenType.GENERALIZES]: ['>>', FilterOperator.GENERALIZES],
+ [TokenType.CHILD_OF]: [' this.pos && this.input[p] === ':';
+ }
+
tokenize() {
const tokens = [];
-
+ const single = { '-': TokenType.DASH, '(': TokenType.OPEN, ')': TokenType.CLOSE, '{': TokenType.LCRLY, '}': TokenType.RCRLY,
+ ';': TokenType.SEMI, ',': TokenType.COMMA, '.': TokenType.DOT, '*': TokenType.STAR, '=': TokenType.EQ, '/': TokenType.REGEX,
+ '^': TokenType.IN, '?': TokenType.EXISTS };
while (this.pos < this.input.length) {
- this.skipWhitespace();
- if (this.pos >= this.input.length) break;
-
- const startPos = this.pos;
const ch = this.input[this.pos];
-
- switch (ch) {
- case '-':
- tokens.push(new Token(TokenType.DASH, '-', startPos));
- this.pos++;
- break;
- case '(':
- tokens.push(new Token(TokenType.OPEN, '(', startPos));
- this.pos++;
- break;
- case ')':
- tokens.push(new Token(TokenType.CLOSE, ')', startPos));
- this.pos++;
- break;
- case '{':
- tokens.push(new Token(TokenType.LCRLY, '{', startPos));
- this.pos++;
- break;
- case '}':
- tokens.push(new Token(TokenType.RCRLY, '}', startPos));
- this.pos++;
- break;
- case ';':
- tokens.push(new Token(TokenType.SEMI, ';', startPos));
- this.pos++;
- break;
- case ',':
- tokens.push(new Token(TokenType.COMMA, ',', startPos));
- this.pos++;
- break;
- case '.':
- tokens.push(new Token(TokenType.DOT, '.', startPos));
- this.pos++;
- break;
- case '*':
- tokens.push(new Token(TokenType.STAR, '*', startPos));
- this.pos++;
- break;
- case '=':
- tokens.push(new Token(TokenType.EQ, '=', startPos));
- this.pos++;
- break;
- case '/':
- tokens.push(new Token(TokenType.REGEX, '/', startPos));
- this.pos++;
- break;
- case '^':
- tokens.push(new Token(TokenType.IN, '^', startPos));
- this.pos++;
- break;
- case '>':
- if (this.peek() === '>') {
- tokens.push(new Token(TokenType.GENERALIZES, '>>', startPos));
- this.pos += 2;
- } else {
- throw new VCLParseException(`Unexpected character: ${ch}`, this.pos);
- }
- break;
- case '<':
- if (this.peek() === '<') {
- tokens.push(new Token(TokenType.IS_A, '<<', startPos));
- this.pos += 2;
- } else if (this.peek() === '!') {
- tokens.push(new Token(TokenType.CHILD_OF, '' && this.peek() === '>') {
+ tokens.push(new Token(TokenType.GENERALIZES, '>>', startPos));
+ this.pos += 2;
+ } else if (ch === '<' && this.peek() === '<') {
+ tokens.push(new Token(TokenType.IS_A, '<<', startPos));
+ this.pos += 2;
+ } else if (ch === '<' && this.peek() === '!') {
+ tokens.push(new Token(TokenType.CHILD_OF, '= 0) {
- conceptSet.system = systemUri.substring(0, pipePos);
- conceptSet.version = systemUri.substring(pipePos + 1);
- } else {
- conceptSet.system = systemUri;
+ return { t: type === TokenType.COMMA ? 'and' : 'or', parts };
+ } else if (type === TokenType.DASH) {
+ this.consume(TokenType.DASH);
+ const b = this.parseSubExpr();
+ if ([TokenType.COMMA, TokenType.SEMI, TokenType.DASH].includes(this.current().type)) {
+ throw new VCLParseException('Use brackets to mix \',\', \';\' and \'-\'', this.current().position);
}
+ return { t: 'minus', a: first, b };
}
-
- if (isExclusion) {
- this.valueSet.compose.exclude.push(conceptSet);
- } else {
- this.valueSet.compose.include.push(conceptSet);
- }
-
- return conceptSet;
- }
-
- getCurrentConceptSet(isExclusion) {
- const list = isExclusion ? this.valueSet.compose.exclude : this.valueSet.compose.include;
- return list.length > 0 ? list[list.length - 1] : this.createConceptSet('', isExclusion);
- }
-
- toImplicitVcl(system, expression) {
- return 'http://fhir.org/VCL?v1='
- + encodeURIComponent(`(${system})(${expression})`)
- .replace(/\(/g, '%28')
- .replace(/\)/g, '%29'); // need to encode parentheses for VCL as well
+ return first;
}
- parseExpr() {
- this.parseSubExpr(false);
-
- switch (this.current().type) {
- case TokenType.COMMA:
- this.parseConjunction();
- break;
- case TokenType.SEMI:
- this.parseDisjunction();
- break;
- case TokenType.DASH:
- this.parseExclusion();
- break;
+ // subExpr : systemUri? (simpleExpr | OPEN expr CLOSE)
+ parseSubExpr() {
+ let scope = null;
+ if (this.isSystemUri()) {
+ scope = this.parseSystemUri();
}
- }
-
- parseSubExpr(isExclusion) {
- let systemUri = '';
-
- // Check for system URI in parentheses
- if (this.current().type === TokenType.OPEN && this.peek().type === TokenType.URI) {
- this.consume(TokenType.OPEN);
- systemUri = this.current().value;
- this.consume(TokenType.URI);
- this.consume(TokenType.CLOSE);
- }
-
+ let e;
if (this.current().type === TokenType.OPEN) {
- this.consume(TokenType.OPEN);
+ const open = this.consume(TokenType.OPEN);
if (++this.depth > MAX_VCL_DEPTH) {
- throw new VCLParseException(`The expression nests more than ${MAX_VCL_DEPTH} levels deep`, this.current().position);
- }
-
- // Check for nested system URI
- if (this.current().type === TokenType.OPEN && this.peek().type === TokenType.URI) {
- this.consume(TokenType.OPEN);
- systemUri = this.current().value;
- this.consume(TokenType.URI);
- this.consume(TokenType.CLOSE);
- }
-
- if (this.isSimpleCodeList()) {
- this.parseSimpleCodeList(systemUri, isExclusion);
- } else {
- this.parseExprWithinParentheses(isExclusion);
+ throw new VCLParseException(`The expression nests more than ${MAX_VCL_DEPTH} levels deep`, open.position);
}
-
- // This should fail for unmatched parentheses
+ e = this.parseExpr();
this.consume(TokenType.CLOSE);
this.depth--;
} else {
- this.parseSimpleExpr(systemUri, isExclusion);
+ e = this.parseSimpleExpr();
}
+ return scope ? { t: 'scope', system: scope.system, version: scope.version, e } : e;
}
- parseSimpleCodeList(systemUri, isExclusion) {
- const conceptSet = this.createConceptSet(systemUri, isExclusion);
-
- if (this.current().type === TokenType.STAR) {
- this.consume(TokenType.STAR);
- conceptSet.filter.push({
- property: 'concept',
- op: FilterOperator.EXISTS,
- value: 'true'
- });
- return;
- } else if (this.current().type === TokenType.IN) {
- this.parseIncludeVs(conceptSet);
- return;
- } else {
- const code = this.parseCode();
- conceptSet.concept.push({code});
- }
-
- while ([TokenType.SEMI, TokenType.COMMA].includes(this.current().type)) {
- this.consume(this.current().type);
+ isSystemUri() {
+ return this.current().type === TokenType.OPEN && this.peek().type === TokenType.URI && this.peek(2).type === TokenType.CLOSE;
+ }
- if (this.current().type === TokenType.STAR) {
- this.consume(TokenType.STAR);
- conceptSet.filter.push({
- property: 'concept',
- op: FilterOperator.EXISTS,
- value: 'true'
- });
- } else if (this.current().type === TokenType.IN) {
- this.parseIncludeVs(conceptSet);
- } else {
- const code = this.parseCode();
- conceptSet.concept.push({code});
- }
- }
+ // systemUri : OPEN URI CLOSE
+ parseSystemUri() {
+ this.consume(TokenType.OPEN);
+ const uri = this.consume(TokenType.URI).value;
+ this.consume(TokenType.CLOSE);
+ return splitSystemUri(uri);
}
- parseSimpleExpr(systemUri, isExclusion) {
- const conceptSet = this.createConceptSet(systemUri, isExclusion);
-
- if (this.peek().type === TokenType.DOT) {
- this.parseOf(systemUri, conceptSet);
- } else if (this.current().type === TokenType.STAR) {
- this.consume(TokenType.STAR);
- conceptSet.filter.push({
- property: 'concept',
- op: FilterOperator.EXISTS,
- value: 'true'
- });
- } else if ([TokenType.SCODE, TokenType.QUOTED_VALUE].includes(this.current().type)) {
- if (this.current().type === TokenType.SCODE && this.current().value.includes('.')) {
- this.parseOf(systemUri, conceptSet);
- } else {
+ // simpleExpr : STAR | code | filter | includeVs
+ parseSimpleExpr() {
+ const tok = this.current();
+ switch (tok.type) {
+ case TokenType.STAR:
+ this.consume(TokenType.STAR);
+ if (this.current().type === TokenType.DOT) {
+ return this.parseOfRest({ star: true });
+ }
+ return { t: 'star' };
+ case TokenType.IN:
+ return this.parseIncludeVs();
+ case TokenType.SCODE:
+ case TokenType.QUOTED_VALUE: {
const code = this.parseCode();
-
if (this.isFilterOperator(this.current().type)) {
- this.parseFilter(conceptSet, code);
- } else {
- conceptSet.concept.push({ code });
- }
- }
- } else if (this.current().type === TokenType.IN) {
- this.parseIncludeVs(conceptSet);
- } else {
- this.parseOf(systemUri, conceptSet);
- }
- }
-
- parseOf(systemUri, conceptSet) {
- let isVcl = false;
- const sb = [];
-
- switch (this.current().type) {
- case TokenType.LCRLY: {
- // codeList or filterList
- this.consume(TokenType.LCRLY);
- if (this.peek().type === TokenType.COMMA) {
- sb.push(this.parseCode());
- while (this.current().type === TokenType.COMMA) {
- this.consume(TokenType.COMMA);
- sb.push(this.parseCode());
- }
- } else {
- isVcl = true;
- this.parseFilterList(sb);
+ return this.parseFilterRest(code);
+ } else if (this.current().type === TokenType.DOT) {
+ return this.parseOfRest({ code });
}
- this.consume(TokenType.RCRLY);
- break;
- }
- case TokenType.STAR: {
- sb.push(this.current().value);
- this.consume(TokenType.STAR);
- break;
+ return { t: 'code', code };
}
case TokenType.URI: {
- sb.push(this.current().value);
- this.consume(TokenType.URI);
- break;
+ const uri = this.consume(TokenType.URI).value;
+ if (this.current().type !== TokenType.DOT) {
+ throw new VCLParseException('A URI here must be followed by \'.\' and a property', this.current().position);
+ }
+ return this.parseOfRest({ uri });
}
- case TokenType.SCODE:
- case TokenType.QUOTED_VALUE: {
- sb.push(this.current().value);
- this.parseCode();
- break;
+ case TokenType.LCRLY: {
+ const value = this.parseCodeOrFilterList();
+ if (this.current().type !== TokenType.DOT) {
+ throw new VCLParseException('A list here must be followed by \'.\' and a property', this.current().position);
+ }
+ return this.parseOfRest(value);
}
default:
- throw new VCLParseException("Expected code, codeList, STAR, URI or filterList", this.current().position);
+ throw new VCLParseException('Expected a code, a filter, \'*\', \'^\' or \'(\'', tok.position);
}
-
- this.consume(TokenType.DOT);
-
- const property = this.parseCode();
- const implicitVcl = isVcl ? this.toImplicitVcl(systemUri, sb.join(',')) : sb.join(',');
-
- conceptSet.filter.push({
- property: property,
- op: FilterOperator.EQUAL, // FIXME: Is this really the value to use?
- _op: {
- extension: [{
- // WARNING: pre-adopting an extension that may change in before R6
- url: 'http://hl7.org/fhir/6.0/StructureDefinition/extension-ValueSet.compose.include.filter.op',
- valueString: 'of'
- }]
- },
- value: implicitVcl,
- });
}
- parseExprWithinParentheses(isExclusion) {
- this.parseSubExpr(isExclusion);
-
- while ([TokenType.COMMA, TokenType.SEMI, TokenType.DASH].includes(this.current().type)) {
- switch (this.current().type) {
- case TokenType.COMMA:
- this.parseConjunctionWithFlag(isExclusion);
- break;
- case TokenType.SEMI:
- this.parseDisjunctionWithFlag(isExclusion);
- break;
- case TokenType.DASH:
- this.parseExclusion();
- break;
- }
+ // includeVs : IN (URI | systemUri)
+ parseIncludeVs() {
+ this.consume(TokenType.IN);
+ if (this.current().type === TokenType.URI) {
+ return { t: 'vs', uri: this.consume(TokenType.URI).value };
+ } else if (this.isSystemUri()) {
+ this.consume(TokenType.OPEN);
+ const uri = this.consume(TokenType.URI).value;
+ this.consume(TokenType.CLOSE);
+ return { t: 'vs', uri };
}
+ throw new VCLParseException('Expected a URI after \'^\'', this.current().position);
}
- parseFilter(conceptSet, propertyCode) {
- const op = this.current().type;
- this.consume(op);
-
- const filter = {
- property: propertyCode,
- op: this.tokenTypeToFilterOperator(op)
- };
-
- switch (op) {
- case TokenType.EQ:
- case TokenType.IS_A:
- case TokenType.IS_NOT_A:
- case TokenType.DESC_OF:
- case TokenType.GENERALIZES:
- case TokenType.CHILD_OF:
- case TokenType.DESC_LEAF:
- case TokenType.EXISTS:
- filter.value = this.parseCode();
- break;
+ // filter: property op value
+ parseFilterRest(property) {
+ const opTok = this.current();
+ this.pos++;
+ const op = OPERATORS[opTok.type][1];
+ let value;
+ switch (opTok.type) {
case TokenType.REGEX:
- filter.value = this.parseQuotedString();
+ if (this.current().type !== TokenType.QUOTED_VALUE) {
+ throw new VCLParseException('A regex must be a quoted value', this.current().position);
+ }
+ value = { str: this.consume(TokenType.QUOTED_VALUE).value };
break;
case TokenType.IN:
case TokenType.NOT_IN:
- filter.value = this.parseFilterValue(conceptSet.system);
+ if (this.current().type === TokenType.URI) {
+ value = { uri: this.consume(TokenType.URI).value };
+ } else if (this.current().type === TokenType.LCRLY) {
+ value = this.parseCodeOrFilterList();
+ } else {
+ throw new VCLParseException('Expected a list of codes or filters, or a URI', this.current().position);
+ }
+ break;
+ case TokenType.EXISTS: {
+ const pos = this.current().position;
+ const code = this.parseCode();
+ if (code !== 'true' && code !== 'false') {
+ throw new VCLParseException('\'?\' takes true or false', pos);
+ }
+ value = { code };
break;
+ }
default:
- throw new VCLParseException(`Unexpected filter operator: ${op}`, this.current().position);
+ value = { code: this.parseCode() };
}
+ return { t: 'filter', property, op, value };
+ }
- conceptSet.filter.push(filter);
+ // (code | codeList | STAR | URI | filterList) DOT property
+ parseOfRest(source) {
+ this.consume(TokenType.DOT);
+ return { t: 'of', source, property: this.parseCode() };
+ }
+
+ // codeList : { code (, code)+ } filterList : { filter (, filter)* }
+ parseCodeOrFilterList() {
+ const open = this.consume(TokenType.LCRLY);
+ // a filter starts with a code and an operator, or is an "of": something, then '.'
+ const t1 = this.current().type;
+ const t2 = this.peek().type;
+ const isFilter = t1 === TokenType.LCRLY || t1 === TokenType.STAR || t1 === TokenType.URI
+ || ((t1 === TokenType.SCODE || t1 === TokenType.QUOTED_VALUE) && (this.isFilterOperator(t2) || t2 === TokenType.DOT));
+ if (isFilter) {
+ if (++this.depth > MAX_VCL_DEPTH) {
+ throw new VCLParseException(`The expression nests more than ${MAX_VCL_DEPTH} levels deep`, open.position);
+ }
+ const filters = [this.parseListFilter()];
+ while (this.current().type === TokenType.COMMA) {
+ this.consume(TokenType.COMMA);
+ filters.push(this.parseListFilter());
+ }
+ this.consume(TokenType.RCRLY);
+ this.depth--;
+ return { filters };
+ }
+ const codes = [this.parseCode()];
+ while (this.current().type === TokenType.COMMA) {
+ this.consume(TokenType.COMMA);
+ codes.push(this.parseCode());
+ }
+ if (codes.length < 2) {
+ throw new VCLParseException('A list of codes has at least two', open.position);
+ }
+ this.consume(TokenType.RCRLY);
+ return { codes };
}
- parseIncludeVs(conceptSet) {
- this.consume(TokenType.IN);
+ parseListFilter() {
+ const e = this.parseSimpleExpr();
+ if (e.t !== 'filter' && e.t !== 'of') {
+ throw new VCLParseException('Expected a filter', this.current().position);
+ }
+ return e;
+ }
- let uri;
- if (this.current().type === TokenType.URI) {
- uri = this.current().value;
- this.consume(TokenType.URI);
- } else if (this.current().type === TokenType.OPEN) {
- this.consume(TokenType.OPEN);
- uri = this.current().value;
- this.consume(TokenType.URI);
- this.consume(TokenType.CLOSE);
- } else {
- throw new VCLParseException('Expected URI after ^', this.current().position);
+ parseCode() {
+ const tok = this.current();
+ if (tok.type === TokenType.SCODE || tok.type === TokenType.QUOTED_VALUE) {
+ this.pos++;
+ return tok.value;
}
+ throw new VCLParseException('Expected code', tok.position);
+ }
- conceptSet.valueSet.push(uri);
+ // ---- the compose -------------------------------------------------------------------------
+
+ parse() {
+ try {
+ const tree = this.parseExpr();
+ if (this.current().type !== TokenType.EOF) {
+ throw new VCLParseException(`Expected EOF but got ${this.current().type}`, this.current().position);
+ }
+ const valueSet = this.createValueSet();
+ const compose = toCompose(tree);
+ valueSet.compose.include = compose.include;
+ valueSet.compose.exclude = compose.exclude;
+ return cleanupEmptyArrays(valueSet);
+ } catch (error) {
+ if (error instanceof VCLParseException) {
+ throw error;
+ }
+ throw new VCLParseException(`Parse error: ${error.message}`);
+ }
}
+}
- parseConjunction() {
- const currentConceptSet = this.getCurrentConceptSet(false);
+// ---- tree -> compose ---------------------------------------------------------------------------
- while (this.current().type === TokenType.COMMA) {
- this.consume(TokenType.COMMA);
+const NO_SCOPE = { system: '', version: '' };
- if ([TokenType.SCODE, TokenType.QUOTED_VALUE].includes(this.current().type)) {
- const code = this.parseCode();
- if (this.isFilterOperator(this.current().type)) {
- this.parseFilter(currentConceptSet, code);
- } else {
- currentConceptSet.concept.push({code});
+/** the compose: a top-level exclusion is the excludes */
+function toCompose(tree) {
+ let e = tree;
+ let scope = NO_SCOPE;
+ while (e.t === 'scope') {
+ scope = { system: e.system, version: e.version };
+ e = e.e;
+ }
+ if (e.t === 'minus') {
+ return { include: includes(e.a, scope), exclude: includes(e.b, scope) };
+ }
+ return { include: includes(e, scope), exclude: [] };
+}
+
+/** the includes whose union is e */
+function includes(e, scope) {
+ switch (e.t) {
+ case 'scope':
+ return includes(e.e, { system: e.system, version: e.version });
+ case 'or': {
+ const list = [];
+ // codes only, in the same system and version: one include. Found by key, and the codes
+ // de-duplicated with a set, so a long list of codes doesn't take quadratic time
+ const codesOnly = new Map(); // system|version -> { cs, seen }
+ for (const p of e.parts) {
+ for (const cs of includes(p, scope)) {
+ const key = isCodesOnly(cs) ? (cs.system || '') + '|' + (cs.version || '') : null;
+ const same = key !== null ? codesOnly.get(key) : undefined;
+ if (same) {
+ for (const c of cs.concept) {
+ if (!same.seen.has(c.code)) {
+ same.seen.add(c.code);
+ same.cs.concept.push(c);
+ }
+ }
+ } else {
+ list.push(cs);
+ if (key !== null) {
+ codesOnly.set(key, { cs, seen: new Set(cs.concept.map(c => c.code)) });
+ }
+ }
}
- } else {
- this.parseSubExpr(false);
}
+ return list;
}
+ case 'minus':
+ return [implicitSet(e, scope)];
+ default:
+ return [single(e, scope)];
}
+}
- parseConjunctionWithFlag(isExclusion) {
- const currentConceptSet = this.getCurrentConceptSet(isExclusion);
+function isCodesOnly(cs) {
+ return cs.concept.length > 0 && cs.filter.length === 0 && cs.valueSet.length === 0;
+}
- while (this.current().type === TokenType.COMMA) {
- this.consume(TokenType.COMMA);
+function newSet(scope) {
+ // (in the order FHIR has them)
+ return { system: scope.system, version: scope.version || undefined, concept: [], filter: [], valueSet: [] };
+}
- if ([TokenType.SCODE, TokenType.QUOTED_VALUE].includes(this.current().type)) {
- const code = this.parseCode();
- if (this.isFilterOperator(this.current().type)) {
- this.parseFilter(currentConceptSet, code);
- } else {
- currentConceptSet.concept.push({code});
+/** an include of the implicit value set for e */
+function implicitSet(e, scope) {
+ const cs = newSet(NO_SCOPE);
+ cs.valueSet.push(implicitUrl(e, scope));
+ return cs;
+}
+
+/** one include for e (a leaf, or an intersection, or a union of codes in one system) */
+function single(e, scope) {
+ switch (e.t) {
+ case 'scope':
+ return single(e.e, { system: e.system, version: e.version });
+ case 'star':
+ return newSet(scope);
+ case 'code': {
+ const cs = newSet(scope);
+ cs.concept.push({ code: e.code });
+ return cs;
+ }
+ case 'filter': {
+ const cs = newSet(scope);
+ cs.filter.push({ property: e.property, op: e.op, value: filterValue(e.value, scope) });
+ return cs;
+ }
+ case 'of': {
+ const cs = newSet(scope);
+ cs.filter.push(ofFilter(e, scope));
+ return cs;
+ }
+ case 'vs': {
+ const cs = newSet(scope);
+ cs.valueSet.push(e.uri);
+ return cs;
+ }
+ case 'and': {
+ let acc = null;
+ for (const p of e.parts) {
+ const cs = asSingle(p, scope);
+ if (acc === null) {
+ acc = cs || implicitSet(p, scope);
+ } else if (!cs || !merge(acc, cs)) {
+ acc.valueSet.push(implicitUrl(p, scope));
}
- } else {
- this.parseSubExpr(isExclusion);
}
+ return acc;
}
+ default: // or, minus: one include only as the implicit value set
+ return implicitSet(e, scope);
}
+}
- parseDisjunction() {
- while (this.current().type === TokenType.SEMI) {
- this.consume(TokenType.SEMI);
- this.parseSubExpr(false);
- }
+/** e as one include, if it is one (a union is, only if it is codes in one system) */
+function asSingle(e, scope) {
+ if (e.t === 'scope') {
+ return asSingle(e.e, { system: e.system, version: e.version });
}
-
- parseDisjunctionWithFlag(isExclusion) {
- while (this.current().type === TokenType.SEMI) {
- this.consume(TokenType.SEMI);
- this.parseSubExpr(isExclusion);
- }
+ if (e.t === 'minus') {
+ return null;
}
-
- parseExclusion() {
- this.consume(TokenType.DASH);
- this.parseSubExpr(true);
+ if (e.t === 'or') {
+ const list = includes(e, scope);
+ return list.length === 1 && isCodesOnly(list[0]) ? list[0] : null;
}
+ return single(e, scope);
+}
- parseCode() {
- if (this.current().type === TokenType.SCODE) {
- const code = this.current().value;
- this.consume(TokenType.SCODE);
- return code;
- } else if (this.current().type === TokenType.QUOTED_VALUE) {
- const code = this.current().value;
- this.consume(TokenType.QUOTED_VALUE);
- return code;
- } else {
- throw new VCLParseException('Expected code', this.current().position);
- }
+/** adds cs to acc (an intersection), if one include can hold both */
+function merge(acc, cs) {
+ if (cs.system && acc.system && (cs.system !== acc.system || (cs.version || '') !== (acc.version || ''))) {
+ return false;
}
-
- parseQuotedString() {
- if (this.current().type === TokenType.QUOTED_VALUE) {
- const value = this.current().value;
- this.consume(TokenType.QUOTED_VALUE);
- return value;
- } else {
- throw new VCLParseException('Expected quoted string', this.current().position);
+ if (cs.concept.length > 0 && acc.concept.length > 0) {
+ const codes = new Set(cs.concept.map(c => c.code));
+ const both = acc.concept.filter(c => codes.has(c.code));
+ if (both.length === 0) {
+ return false; // nothing in common: the implicit value set says so (an include can't be empty)
}
+ acc.concept = both;
+ } else if (cs.concept.length > 0) {
+ acc.concept = cs.concept;
}
-
- cleanupEmptyArrays(obj) {
- if (Array.isArray(obj)) {
- return obj.map(item => this.cleanupEmptyArrays(item));
- } else if (obj && typeof obj === 'object') {
- const cleaned = {};
- for (const [key, value] of Object.entries(obj)) {
- if (Array.isArray(value)) {
- if (value.length > 0) {
- cleaned[key] = this.cleanupEmptyArrays(value);
- }
- } else if (value && typeof value === 'object') {
- cleaned[key] = this.cleanupEmptyArrays(value);
- } else if (value !== undefined && value !== null && value !== '') {
- cleaned[key] = value;
- }
- }
- return cleaned;
- }
- return obj;
+ if (cs.system && !acc.system) {
+ acc.system = cs.system;
+ acc.version = cs.version;
}
+ acc.filter.push(...cs.filter);
+ acc.valueSet.push(...cs.valueSet);
+ return true;
+}
- parseFilterValue(systemUri) {
- if (this.current().type === TokenType.LCRLY) {
- this.consume(TokenType.LCRLY);
- const codes = [this.parseCode()];
+function filterValue(value, scope) {
+ if (value.code !== undefined) {
+ return value.code;
+ } else if (value.str !== undefined) {
+ return value.str;
+ } else if (value.codes) {
+ return value.codes.join(',');
+ } else if (value.uri) {
+ return value.uri;
+ } else if (value.filters) {
+ // the codes that pass the filters: their implicit value set
+ return implicitUrl({ t: 'and', parts: value.filters }, scope);
+ }
+ return '';
+}
- if (this.isFilterOperator(this.current().type)) {
- this.parseFilterList(codes);
- this.consume(TokenType.RCRLY);
- return this.toImplicitVcl(systemUri, codes.join(''));
- } else {
- while (this.current().type === TokenType.COMMA) {
- this.consume(TokenType.COMMA);
- codes.push(this.parseCode());
- }
+function ofFilter(e, scope) {
+ return {
+ property: e.property,
+ op: FilterOperator.EQUAL,
+ _op: {
+ extension: [{
+ // WARNING: pre-adopting an extension that may change before R6
+ url: OF_EXTENSION,
+ valueCode: 'of'
+ }]
+ },
+ value: e.source.star ? '*' : filterValue(e.source, scope)
+ };
+}
- this.consume(TokenType.RCRLY);
- return codes.join(',');
- }
- } else if (this.current().type === TokenType.URI) {
- const uri = this.current().value;
- this.consume(TokenType.URI);
- return uri;
- } else {
- return this.parseCode();
- }
+// ---- implicit value sets -------------------------------------------------------------------------
+
+/**
+ * The implicit value set URL for e: its canonical VCL, with its system, percent-encoded.
+ *
+ * Rendering is memoised on the tree, and the encoded form is built from the encoded forms of the
+ * parts (percent-encoding a concatenation is the concatenation of the encodings), so that building
+ * the URLs for nested sub-expressions doesn't take time in proportion to their depth times their size.
+ */
+function implicitUrl(e, scope) {
+ if (scope.system && e.t !== 'scope') {
+ return VCL_URI + percentEncode('(' + scope.system + (scope.version ? '|' + scope.version : '') + ')(') + render(e, true) + percentEncode(')');
}
+ return VCL_URI + render(e, true);
+}
- parseFilterList(terms) {
- let depth = 1;
- while (depth > 0) {
- const tokenType = this.current().type;
-
- switch (tokenType) {
- case TokenType.EOF:
- // current() answers EOF forever once the tokens run out, so without this an
- // unterminated "{" looped here until the terms array overflowed
- throw new VCLParseException("Expected '}' to close the filter list", this.current().position);
- case TokenType.LCRLY:
- depth++;
- break;
- case TokenType.RCRLY:
- depth--;
- break;
- default:
- // do nothing
- }
+/** every character but the unreserved ones (RFC 3986: A-Z a-z 0-9 - . _ ~) as %XX, UTF-8 */
+function percentEncode(s) {
+ // encodeURIComponent leaves ! ' ( ) * as they are; a lone surrogate becomes U+FFFD
+ const wf = typeof s.toWellFormed === 'function' ? s.toWellFormed() : s;
+ return encodeURIComponent(wf).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
+}
- if (depth > 0) {
- terms.push(this.current().value);
- this.consume(tokenType);
- }
+const SIMPLE_CODE = /^[a-zA-Z0-9][-_a-zA-Z0-9]*$/;
+
+function quote(s) {
+ return '"' + s.replace(/[\\"]/g, m => '\\' + m) + '"';
+}
+
+function renderCode(code) {
+ return SIMPLE_CODE.test(code) ? code : quote(code);
+}
+
+function renderValue(v, enc) {
+ const L = enc ? percentEncode : (x => x);
+ if (v.code !== undefined) {
+ return L(renderCode(v.code));
+ } else if (v.str !== undefined) {
+ return L(quote(v.str));
+ } else if (v.codes) {
+ return L('{' + v.codes.map(renderCode).join(',') + '}');
+ } else if (v.uri) {
+ return L(v.uri);
+ } else if (v.filters) {
+ return L('{') + v.filters.map(f => render(f, enc)).join(L(',')) + L('}');
+ } else if (v.star) {
+ return L('*');
+ }
+ return '';
+}
+
+function opSymbol(op) {
+ for (const [sym, fop] of Object.values(OPERATORS)) {
+ if (fop === op) {
+ return sym;
}
}
+ return op;
+}
- parse() {
- try {
- this.parseExpr();
- this.expect(TokenType.EOF);
- return this.cleanupEmptyArrays(this.valueSet);
- } catch (error) {
- // Make sure we're throwing VCLParseException for any parsing error
- if (error instanceof VCLParseException) {
- throw error;
- } else {
- throw new VCLParseException(`Parse error: ${error.message}`);
+const COMPOUND = ['or', 'and', 'minus'];
+
+/**
+ * canonical VCL for e: no white space; a union, intersection or exclusion inside another in brackets;
+ * each side of an exclusion in brackets. enc: percent-encoded. Memoised on the node.
+ */
+function render(e, enc = false) {
+ const key = enc ? '_vclEnc' : '_vcl';
+ if (e[key] !== undefined) {
+ return e[key];
+ }
+ const L = enc ? percentEncode : (x => x);
+ const bracketed = (p) => L('(') + render(p, enc) + L(')');
+ const inner = (p) => (COMPOUND.includes(p.t) ? bracketed(p) : render(p, enc));
+ let r;
+ switch (e.t) {
+ case 'or':
+ r = e.parts.map(inner).join(L(';'));
+ break;
+ case 'and':
+ r = e.parts.map(inner).join(L(','));
+ break;
+ case 'minus':
+ r = bracketed(e.a) + L('-') + bracketed(e.b);
+ break;
+ case 'scope':
+ r = L('(' + e.system + (e.version ? '|' + e.version : '') + ')') + (COMPOUND.includes(e.e.t) || e.e.t === 'scope' ? bracketed(e.e) : render(e.e, enc));
+ break;
+ case 'star':
+ r = L('*');
+ break;
+ case 'code':
+ r = L(renderCode(e.code));
+ break;
+ case 'filter':
+ r = L(renderCode(e.property) + opSymbol(e.op)) + renderValue(e.value, enc);
+ break;
+ case 'of':
+ r = renderValue(e.source, enc) + L('.' + renderCode(e.property));
+ break;
+ case 'vs':
+ r = L('^' + e.uri);
+ break;
+ default:
+ r = '';
+ }
+ e[key] = r;
+ return r;
+}
+
+function cleanupEmptyArrays(obj) {
+ if (Array.isArray(obj)) {
+ return obj.map(item => cleanupEmptyArrays(item));
+ } else if (obj && typeof obj === 'object') {
+ const cleaned = {};
+ for (const [key, value] of Object.entries(obj)) {
+ if (Array.isArray(value)) {
+ if (value.length > 0) {
+ cleaned[key] = cleanupEmptyArrays(value);
+ }
+ } else if (value && typeof value === 'object') {
+ cleaned[key] = cleanupEmptyArrays(value);
+ } else if (value !== undefined && value !== null && value !== '') {
+ cleaned[key] = value;
}
}
+ return cleaned;
}
+ return obj;
}
-// Main parsing functions
+// ---- the API ---------------------------------------------------------------------------------------
+
function parseVCL(vclExpression, fhirFactory = null) {
- if (!vclExpression || vclExpression.trim() === '') {
+ if (typeof vclExpression !== 'string') {
+ // e.g. a repeated request parameter, which arrives as an array
+ throw new VCLParseException('VCL expression must be a string');
+ }
+ if (vclExpression.trim() === '') {
throw new VCLParseException('VCL expression cannot be empty');
}
-
- const lexer = new VCLLexer(vclExpression);
- const tokens = lexer.tokenize();
-
- const parser = new VCLParserClass(tokens, fhirFactory);
- const result = parser.parse();
-
+ const tokens = new VCLLexer(vclExpression).tokenize();
+ const result = new VCLParserClass(tokens, fhirFactory).parse();
if (!result) {
throw new VCLParseException('Parser returned null result');
}
-
return result;
}
function parseVCLAndSetId(vclExpression, fhirFactory = null) {
- // Use the same parsing logic as parseVCL to avoid scope issues
- if (!vclExpression || vclExpression.trim() === '') {
- throw new VCLParseException('VCL expression cannot be empty');
- }
-
- const lexer = new VCLLexer(vclExpression);
- const tokens = lexer.tokenize();
- const parser = new VCLParserClass(tokens, fhirFactory);
- const valueSet = parser.parse();
-
- if (!valueSet) {
- throw new VCLParseException('Failed to create ValueSet');
- }
+ const valueSet = parseVCL(vclExpression, fhirFactory);
+ // a hash of the content (as the Java version): the same expression always has the same url
+ valueSet.url = `cid:${simpleHash(JSON.stringify(valueSet))}`;
+ return valueSet;
+}
- // Generate hash-based ID (similar to Java version)
- const jsonString = JSON.stringify(valueSet);
- if (!jsonString) {
- throw new VCLParseException('Failed to serialize ValueSet to JSON');
+/**
+ * The VCL expression of an implicit VCL value set URL (http://fhir.org/VCL?v1=...), percent-decoded,
+ * or null if the url isn't one
+ */
+function vclFromImplicitUrl(url) {
+ if (typeof url !== 'string' || !url.startsWith(VCL_URI)) {
+ return null;
}
-
- // Create hash directly inline to avoid scoping issues
- let hash = 0;
- for (let i = 0; i < jsonString.length; i++) {
- const char = jsonString.charCodeAt(i);
- hash = ((hash << 5) - hash) + char;
- hash = hash & hash; // Convert to 32-bit integer
+ try {
+ return decodeURIComponent(url.substring(VCL_URI.length));
+ } catch (e) {
+ throw new VCLParseException('The VCL in the URL is not validly percent-encoded');
}
- const hashCode = Math.abs(hash);
-
- valueSet.url = `cid:${hashCode}`;
-
- return valueSet;
}
-// Utility functions
function validateVCLExpression(vclExpression) {
- if (!vclExpression || vclExpression.trim() === '') {
- return false;
- }
-
try {
- // Make sure we call the same parseVCL function that's being exported
- const lexer = new VCLLexer(vclExpression);
- const tokens = lexer.tokenize();
- const parser = new VCLParserClass(tokens, null);
- parser.parse();
+ parseVCL(vclExpression);
return true;
} catch (e) {
- // Return false for any parsing error, regardless of type
return false;
}
}
@@ -963,66 +921,34 @@ function createVCLValueSet(id, name, description) {
exclude: []
}
};
-
if (id) valueSet.id = id;
if (name) valueSet.name = name;
if (description) valueSet.description = description;
-
return valueSet;
}
function splitSystemUri(systemUri) {
const pipePos = systemUri.indexOf('|');
if (pipePos >= 0) {
- return {
- system: systemUri.substring(0, pipePos),
- version: systemUri.substring(pipePos + 1)
- };
+ return { system: systemUri.substring(0, pipePos), version: systemUri.substring(pipePos + 1) };
}
- return {
- system: systemUri,
- version: ''
- };
+ return { system: systemUri, version: '' };
}
function isVCLCompatible(valueSet) {
if (!valueSet.compose) {
return false;
}
-
- const supportedOps = [
- FilterOperator.EQUAL, FilterOperator.IS_A, FilterOperator.IS_NOT_A,
- FilterOperator.DESCENDENT_OF, FilterOperator.REGEX, FilterOperator.IN,
- FilterOperator.NOT_IN, FilterOperator.GENERALIZES, FilterOperator.CHILD_OF,
- FilterOperator.DESCENDENT_LEAF, FilterOperator.EXISTS
- ];
-
- // Check includes
- if (valueSet.compose.include) {
- for (const include of valueSet.compose.include) {
- if (include.filter) {
- for (const filter of include.filter) {
- if (!supportedOps.includes(filter.op)) {
- return false;
- }
- }
- }
- }
- }
-
- // Check excludes
- if (valueSet.compose.exclude) {
- for (const exclude of valueSet.compose.exclude) {
- if (exclude.filter) {
- for (const filter of exclude.filter) {
- if (!supportedOps.includes(filter.op)) {
- return false;
- }
+ const supportedOps = Object.values(FilterOperator);
+ for (const list of [valueSet.compose.include || [], valueSet.compose.exclude || []]) {
+ for (const cs of list) {
+ for (const filter of cs.filter || []) {
+ if (!supportedOps.includes(filter.op)) {
+ return false;
}
}
}
}
-
return true;
}
@@ -1037,77 +963,20 @@ function simpleHash(str) {
return Math.abs(hash);
}
-// Export for different module systems
-if (typeof module !== 'undefined' && module.exports) {
- // Node.js
- module.exports = {
- parseVCL,
- parseVCLAndSetId,
- validateVCLExpression,
- createVCLValueSet,
- splitSystemUri,
- isVCLCompatible,
- VCLParseException,
- MAX_VCL_DEPTH,
- TokenType,
- FilterOperator,
- // Export classes for debugging
- VCLLexer,
- VCLParserClass,
- // Export utility functions
- simpleHash
- };
-} else if (typeof window !== 'undefined') {
- // Browser - attach everything to window.VCLParser
- window.VCLParser = {
- parseVCL,
- parseVCLAndSetId,
- validateVCLExpression,
- createVCLValueSet,
- splitSystemUri,
- isVCLCompatible,
- VCLParseException,
- MAX_VCL_DEPTH,
- TokenType,
- FilterOperator,
- // Export classes for debugging
- VCLLexer,
- VCLParserClass,
- // Export utility functions
- simpleHash
- };
-
- // Also make classes available globally for debugging
- window.VCLLexer = VCLLexer;
- window.VCLParseException = VCLParseException;
-}
-
-// Examples of usage:
-/*
-// Basic parsing
-const valueSet = parseVCL('(http://snomed.info/sct) 123456789; 987654321');
-
-// With filters
-const valueSet2 = parseVCL('(http://snomed.info/sct) 123456789 << 64572001');
-
-// With version and exclusions
-const valueSet3 = parseVCL('(http://snomed-alike.info/sct|20210131) * - 123456789');
-
-// With auto-generated ID
-const valueSet4 = parseVCLAndSetId('(http://snomed.info/sct) 123456789');
-
-// Validation
-if (validateVCLExpression(myExpression)) {
- const valueSet = parseVCL(myExpression);
-}
-
-// With custom FHIR factory
-const customFactory = {
- createValueSet: () => ({
- resourceType: 'ValueSet',
- status: 'active', // Different default
- compose: { include: [], exclude: [] }
- })
+module.exports = {
+ parseVCL,
+ parseVCLAndSetId,
+ validateVCLExpression,
+ vclFromImplicitUrl,
+ createVCLValueSet,
+ splitSystemUri,
+ isVCLCompatible,
+ VCLParseException,
+ MAX_VCL_DEPTH,
+ VCL_URI,
+ TokenType,
+ FilterOperator,
+ VCLLexer,
+ VCLParserClass,
+ simpleHash
};
-const valueSet5 = parseVCL('(http://snomed.info/sct) 123456789', customFactory);
-*/
\ No newline at end of file
diff --git a/vcl/vcl.js b/vcl/vcl.js
index 9225092c0..1fefedcaf 100644
--- a/vcl/vcl.js
+++ b/vcl/vcl.js
@@ -5,7 +5,7 @@
//
const express = require('express');
-const {parseVCLAndSetId, validateVCLExpression, VCLParseException} = require('./vcl-parser.js');
+const {parseVCLAndSetId, vclFromImplicitUrl, VCLParseException, VCL_URI} = require('./vcl-parser.js');
const Logger = require('../library/server/logger');
const vclLog = Logger.getInstance().child({ module: 'vcl' });
@@ -112,45 +112,6 @@ class VCLModule {
};
}
- // VCL expression validation
- validateVCLInput(vcl) {
- if (!vcl || typeof vcl !== 'string') {
- throw new Error('VCL expression must be a non-empty string');
- }
-
- // Length validation
- if (vcl.length > 10000) {
- throw new Error('VCL expression too long (max 10000 characters)');
- }
-
- // Basic character validation - allow VCL-specific characters
- // VCL expressions can contain: letters, numbers, dots, hyphens, underscores,
- // colons, slashes, pipes, parentheses, square brackets, equals, commas, spaces
- const allowedCharsPattern = /^[a-zA-Z0-9.\-_:/|()[\]=, \t\r\n]*$/;
- if (!allowedCharsPattern.test(vcl)) {
- throw new Error('VCL expression contains invalid characters');
- }
-
- // Check for potential injection patterns
- const suspiciousPatterns = [
- /