From 0cb2486b3e444a850693738e5bf7a74b96888455 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:05:41 +1100 Subject: [PATCH 1/8] put xig in template --- library/security/auth/auth.js | 24 ++++++++++++++++++++++++ library/security/auth/pages.js | 9 ++++++++- xig/xig-template.html | 2 +- xig/xig.js | 25 +++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 2 deletions(-) diff --git a/library/security/auth/auth.js b/library/security/auth/auth.js index a42b07953..aa05110ee 100644 --- a/library/security/auth/auth.js +++ b/library/security/auth/auth.js @@ -189,6 +189,8 @@ class Auth { this.mailer = null; this.roleDefs = new Map(); // module -> [{role, label, description, scope: {label, values()}}] this.moduleInfo = new Map(); // module -> {title, path, adminPages: [{label, path, description}]} + // notes the login pages show when the page being returned to is under a path (addLoginNote) + this.loginNotes = []; // [{path, html, text}] // the request a page is being made for, so the template's [%account%] can say who is logged in this.pageRequests = new AsyncLocalStorage(); this.internalSecret = crypto.randomBytes(32).toString('base64url'); @@ -970,6 +972,25 @@ class Auth { return (LOGIN_FOR[kind] || 'this').replace('{n}', this.anonymousMaxRows().toLocaleString('en-US')).replace('{old}', tools); } + /** + * A note for the login pages (the page asking someone to log in, and /auth/login) when the page + * they'll come back to is under path: e.g. the XIG says the whole index can be downloaded instead. + * Software told to log in (refuseAnonymous, not HTML) gets the text + * @param {string} path - a path on this server ('/xig': /xig and everything under it) + * @param {string} html - the note, as HTML (the module's own text: not escaped) + * @param {string} text - the same as plain text, for software + */ + addLoginNote(path, html, text) { + this.loginNotes = this.loginNotes.filter(n => n.path !== path); + this.loginNotes.push({ path, html, text }); + } + + /** The login notes for a page on this server (addLoginNote) */ + loginNotesFor(url) { + const path = String(url || '').split(/[?#]/)[0]; + return this.loginNotes.filter(n => path === n.path || path.startsWith(n.path.endsWith('/') ? n.path : n.path + '/')); + } + /** Why a kind of request needs a login, in a sentence */ whyLoginFor(kind) { if (kind === 'old-tool') { @@ -1018,6 +1039,9 @@ class Auth { text = `To get ${what} from this server, log in: send an API token (Authorization: Bearer {token}). ${this.whyLoginFor(kind)} ${how}`; } text += hint ? `. ${hint}` : ''; + for (const n of this.loginNotesFor(req.originalUrl)) { + text += ` ${n.text}`; + } if (as === 'fhir-xml') { res.setHeader('Content-Type', 'application/fhir+xml'); return res.send('\n' + diff --git a/library/security/auth/pages.js b/library/security/auth/pages.js index 7ab0afb59..14d93397a 100644 --- a/library/security/auth/pages.js +++ b/library/security/auth/pages.js @@ -326,6 +326,7 @@ function sendLogin(auth, req, res, status, error) { '   ' + `Forgotten your password?`; h += `

How logging in works

`; + h += loginNotes(auth, ret); render(auth, req, res, 'Log in', h, status); } @@ -333,6 +334,11 @@ function sendLogin(auth, req, res, status, error) { const WHY_LOGIN_PATH = '/auth/why-login'; +/** The notes modules added for the page being returned to (Auth.addLoginNote), as HTML */ +function loginNotes(auth, ret) { + return auth.loginNotesFor(ret).map(n => `
${n.html}
`).join(''); +} + /** The ways to log in, as buttons, coming back to `back` (a path on this server) */ function loginButtons(auth, back) { const q = back ? `?return=${escape(encodeURIComponent(back))}` : ''; @@ -358,7 +364,8 @@ function sendLoginNeeded(auth, req, res, what, back) { ? `

Any ${escape(providers.join(' or '))} account will do. The first time, it makes you an account here; nothing else is needed.

` : '') + (back ? `

Back to what you can see without logging in

` : '') + - `

What needs a login, and why

`; + `

What needs a login, and why

` + + loginNotes(auth, ret); render(auth, req, res, 'Please log in', h, 401); } diff --git a/xig/xig-template.html b/xig/xig-template.html index 943a16dce..6cc4f8bba 100644 --- a/xig/xig-template.html +++ b/xig/xig-template.html @@ -81,7 +81,7 @@

FHIRsmith Logo FHIRsmith [%ver%] © HealthIntersections.com.au 2023+  |  - XIG built as of [%download-date%]  |  [%total-resources%] resources in [%total-packages%] packages  | + XIG built as of [%download-date%]  |  [%total-resources%] resources in [%total-packages%] packages  |   ([%ms%] ms) [%sponsorMessage%]

diff --git a/xig/xig.js b/xig/xig.js index 0c82ccac9..b66abb946 100644 --- a/xig/xig.js +++ b/xig/xig.js @@ -33,6 +33,30 @@ const XIG_DB_URL = 'https://fhir.org/guides/stats/xig.db'; const XIG_DB_PATH = folders.filePath('xig', 'xig.db'); const TEMPLATE_PATH = path.join(__dirname, 'xig-template.html'); +// For the login pages (auth.addLoginNote): someone who wants the whole index should download it +// once, not page through /xig (much cheaper for the server; npm.fhir.org, 2026-12) +const XIG_DOWNLOAD_NOTE_HTML = + '

Want the whole index? Rather than paging through it here, download it once: ' + + `xig.db is the whole XIG as one SQLite database (a few GB), and any SQLite ` + + 'client can query it locally. No login needed.

' + + '

The main tables:

    ' + + '
  • Packages: one row per package version (PackageKey, PID = id#version, ' + + 'Title, Canonical, Web, Realm, Auth, and the FHIR version flags R2..R6)
  • ' + + '
  • Resources: one row per resource in those packages (ResourceKey, PackageKey, ' + + 'ResourceType, Id, Url, Version, Name, Title, Status, ' + + 'Type, Kind, Description, Web (its page), Realm, Authority)
  • ' + + '
  • Contents: the resource itself (ResourceKey, Json: gzipped JSON)
  • ' + + '
  • DependencyList: which resources use which (the resource SourceKey uses TargetKey)
  • ' + + '
  • Categories: (ResourceKey, Mode, Code), where Mode 1 is a terminology ' + + 'source, 2 an extension context and 3 an extension type
  • ' + + '
  • ExtensionDefns, ExtensionUsers and ExtensionUsages: where each extension is used
  • ' + + '

For example, every extension and the package it is in:
SELECT p.PID, r.Url FROM Resources r JOIN Packages p ' + + 'ON p.PackageKey = r.PackageKey WHERE r.ResourceType = \'StructureDefinition\' AND r.Type = \'Extension\'

'; +const XIG_DOWNLOAD_NOTE_TEXT = `To go through the whole XIG, download it once instead of paging: ${XIG_DB_URL} is the whole index as ` + + 'one SQLite database (no login needed). Main tables: Packages (one row per package version), Resources (one row per resource, ' + + 'PackageKey to Packages), Contents (Json: the resource, gzipped), DependencyList (SourceKey uses TargetKey), ' + + 'Categories (Mode 1 terminology source, 2 extension context, 3 extension type).'; + // Global database instance let xigDb = null; @@ -3368,6 +3392,7 @@ async function initializeXigModule(stats, xigConfig) { globalStats = stats; setXigSettings(xigConfig); loadTemplate(); + auth.addLoginNote('/xig', XIG_DOWNLOAD_NOTE_HTML, XIG_DOWNLOAD_NOTE_TEXT); await initializeDatabase(); From ed68bfd5a544889f8f056bc062e92fb19c4545e4 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:05:52 +1100 Subject: [PATCH 2/8] VCL parser fix --- vcl/vcl-parser.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vcl/vcl-parser.js b/vcl/vcl-parser.js index ec413c854..ca915d84e 100644 --- a/vcl/vcl-parser.js +++ b/vcl/vcl-parser.js @@ -440,6 +440,10 @@ class VCLParserClass { if (this.current().type !== TokenType.QUOTED_VALUE) { throw new VCLParseException('A regex must be a quoted value', this.current().position); } + if (this.current().value === '') { + // as for a quoted code or value (parseCode): the filter would have no value + throw new VCLParseException("A regex can't be empty", this.current().position); + } value = { str: this.consume(TokenType.QUOTED_VALUE).value }; break; case TokenType.IN: From 4be18cdf664f91c382c32a1e19e6fb95ed7c88a0 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:07:39 +1100 Subject: [PATCH 3/8] fix ecosystem for revised terminology capabilities usage --- README.md | 27 +++++++ registry/api.js | 44 +++++++----- .../library/auth-login-for-expensive.test.js | 18 +++++ tests/registry/registry-choose-server.test.js | 21 +++++- tests/tx/ecosystem-resolver.test.js | 26 +++---- tests/tx/metadata-codesystems.test.js | 71 +++++++++++++++++++ tx/ecosystem-resolver.js | 31 ++++---- tx/workers/metadata.js | 22 ++++-- tx/workers/validate.js | 62 ++++++++++++++-- 9 files changed, 258 insertions(+), 64 deletions(-) create mode 100644 tests/tx/metadata-codesystems.test.js diff --git a/README.md b/README.md index ae85a410e..23276a081 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,33 @@ Available tags: - `vX.Y.Z`: Specific version (e.g., `v1.0.0`) - `cibuild`: Latest build from the main branch +### Clone-and-Run + +```bash +git clone https://github.com/HealthIntersections/FHIRsmith +cd FHIRsmith + +# Install the dependencies a server needs +npm ci --omit=dev + +# Create a data directory +mkdir -p /var/lib/fhirsmith +cp config-template.json /var/lib/fhirsmith/config.json +# Edit config.json as needed + +export FHIRSMITH_DATA_DIR=/var/lib/fhirsmith +npm run check # check the configuration +npm start +``` + +To update: `git pull`, then `npm ci --omit=dev` again. + +`npm ci` installs exactly what `package-lock.json` lists. `--omit=dev` leaves out the +devDependencies (jest, ESLint and what they bring in), which only the tests and the linter use. +A plain `npm install` works too, but installs all of those as well, and npm then warns about +install scripts in some of them (`allowScripts` in package.json says none of them need to run). +The npm global install and the Docker image never include the devDependencies. + ### Windows Installation You can install as a windows service using [windows-install.js](utilities/windows-install.js). You might need to diff --git a/registry/api.js b/registry/api.js index 282cf1dd5..362ddc4bc 100644 --- a/registry/api.js +++ b/registry/api.js @@ -637,9 +637,9 @@ class RegistryAPI { * - language: only for language sensitive requests (see resolveCodeSystem). * * Differences from the Java code: - * - 'Does a candidate really have the code system' is answered from the content mode the - * server reported in its TerminologyCapabilities, not by searching the server. If it - * didn't report one, the candidate is assumed to be usable. + * - 'Does a candidate really have the code system' is answered by its TerminologyCapabilities: + * a server that lists a code system (version) there supports it, whatever content mode it + * reports. The content mode only ranks candidates: one with a fragment comes after the others. * - The 'primary server' for the systems tx.fhir.org handles specially is the default. * - The value set's source server is found by resolving the value set here. * - Ties are broken by order (the first system, then registration order), not hash order. @@ -721,16 +721,28 @@ class RegistryAPI { } // 4. a server that's a candidate for all of them (again, systems no server is known for - // don't constrain the choice), and that has a usable copy of the code systems + // don't constrain the choice). Being a candidate means it lists the code system in its + // TerminologyCapabilities, which says it supports it, whatever content it reports; but one + // with the whole of each code system is preferred over one that has only a fragment of some + let fragmentOnly = null; for (const c of choices) { for (const s of c.candidates) { - if (choices.every(t => unresolved(t) || t.candidates.includes(s)) && - this._supportsAll(s, choices, unresolved, log)) { - log.push(`Found candidate server ${s}`); - return s; + if (choices.every(t => unresolved(t) || t.candidates.includes(s))) { + const fragment = this._fragmentOf(s, choices, unresolved); + if (!fragment) { + log.push(`Found candidate server ${s}`); + return s; + } + if (!fragmentOnly) { + fragmentOnly = { server: s, system: fragment }; + } } } } + if (fragmentOnly) { + log.push(`Found candidate server ${fragmentOnly.server} (it has only a fragment of ${fragmentOnly.system})`); + return fragmentOnly.server; + } // 5. no agreement - take the one that is most authoritative const counts = new Map(); @@ -766,24 +778,22 @@ class RegistryAPI { } /** - * Whether a candidate server has a usable copy (complete or fragment) of each code system - * it's a candidate for. Systems for which tx.fhir.org is a candidate aren't checked + * The first code system that a candidate server says it has only a fragment of, or null if + * there isn't one. Systems for which tx.fhir.org is a candidate aren't checked */ - _supportsAll(server, choices, unresolved, log) { + _fragmentOf(server, choices, unresolved) { if (isTxFhirOrg(server)) { - return true; + return null; } for (const t of choices) { if (unresolved(t) || !t.candidates.includes(server) || t.candidates.some(isTxFhirOrg)) { continue; } - const content = t.content[server]; - if (content && content !== 'complete' && content !== 'fragment') { - log.push(`Candidate server ${server} dropped for ${t.system}: its copy of the code system is '${content}'`); - return false; + if (t.content[server] === 'fragment') { + return t.system; } } - return true; + return null; } /** diff --git a/tests/library/auth-login-for-expensive.test.js b/tests/library/auth-login-for-expensive.test.js index 502846bac..3b31b136e 100644 --- a/tests/library/auth-login-for-expensive.test.js +++ b/tests/library/auth-login-for-expensive.test.js @@ -76,6 +76,24 @@ describe('login for expensive operations', () => { expect(plain.body.message).toContain('a filtered XIG list past its first page'); }); + test('a module\'s note for its pages is on the login pages that come back to them, and in what software reads', async () => { + auth.addLoginNote('/expensive', '

Download all.db instead

', 'Download https://example.org/all.db instead.'); + try { + const page = await request(app).get('/expensive?_offset=20'); + expect(page.text).toContain('all.db'); + const loginPage = await request(app).get('/auth/login?return=%2Fexpensive%3F_offset%3D20'); + expect(loginPage.text).toContain('all.db'); + const json = await request(app).get('/expensive?kind=xig-page&as=json'); + expect(json.body.message).toContain('Download https://example.org/all.db instead.'); + // not for other pages, or for a path that only starts the same + expect((await request(app).get('/auth/login?return=%2Fother')).text).not.toContain('all.db'); + expect(auth.loginNotesFor('/expensive-too')).toEqual([]); + expect(auth.loginNotesFor('/expensive/sub?x=1')).toHaveLength(1); + } finally { + auth.loginNotes = []; + } + }); + test('/auth/why-login says what needs a login, and how software logs in', async () => { const res = await request(app).get('/auth/why-login'); expect(res.status).toBe(200); diff --git a/tests/registry/registry-choose-server.test.js b/tests/registry/registry-choose-server.test.js index 3f1c2e0f9..14ad8fafa 100644 --- a/tests/registry/registry-choose-server.test.js +++ b/tests/registry/registry-choose-server.test.js @@ -39,7 +39,9 @@ const DATA = { 'https://au.example/CodeSystem/a', 'https://au.example/CodeSystem/b', 'http://terminology.hl7.org/CodeSystem/v2-0203', { uri: 'http://example.org/cs/shared', content: 'complete' }, - { uri: 'http://example.org/cs/frag', content: 'not-present' } + { uri: 'http://example.org/cs/frag', content: 'fragment' }, + { uri: 'http://example.org/cs/fragonly', content: 'fragment' }, + { uri: 'http://example.org/cs/stub', content: 'not-present' } ]), server('nz', NZ, 'https://nz.example/CodeSystem*', [ 'https://nz.example/CodeSystem/x', @@ -120,13 +122,26 @@ describe('RegistryAPI.chooseServer', () => { expect(last(r)).toBe(`Found candidate server ${NZ}`); }); - test('a candidate without a usable copy is passed over', () => { + test('a candidate with the whole code system is preferred over one with a fragment', () => { const r = choose(['http://example.org/cs/frag']); expect(r.server).toBe(OTHER); - expect(r.log).toContain(`Candidate server ${AU} dropped for http://example.org/cs/frag: its copy of the code system is 'not-present'`); expect(last(r)).toBe(`Found candidate server ${OTHER}`); }); + test('a candidate with only a fragment is used if there is nothing better', () => { + const r = choose(['http://example.org/cs/fragonly']); + expect(r.server).toBe(AU); + expect(last(r)).toBe(`Found candidate server ${AU} (it has only a fragment of http://example.org/cs/fragonly)`); + }); + + // listing a code system in TerminologyCapabilities says the server supports it, whatever + // content it reports (e.g. Ontoserver, with stub CodeSystem resources for SNOMED CT) + test('a candidate that lists a code system supports it, whatever content it reports', () => { + const r = choose(['http://example.org/cs/stub']); + expect(r.server).toBe(AU); + expect(last(r)).toBe(`Found candidate server ${AU}`); + }); + test('no agreement: the most authoritative, the first on a tie', () => { const r = choose(['https://au.example/CodeSystem/a', 'https://nz.example/CodeSystem/x']); expect(r.server).toBe(AU); diff --git a/tests/tx/ecosystem-resolver.test.js b/tests/tx/ecosystem-resolver.test.js index 6ebd27015..c5de29297 100644 --- a/tests/tx/ecosystem-resolver.test.js +++ b/tests/tx/ecosystem-resolver.test.js @@ -117,21 +117,21 @@ describe('EcosystemResolver', () => { expect(await withKey.findServer(SCT, EE, 5)).toBe(KEYED); }); - test('a candidate without the content is passed over', async () => { + // a candidate lists the code system in its TerminologyCapabilities, and that says it supports + // it, whatever content it reports + test('a candidate is used whatever content it reports, but one with a fragment comes after the others', async () => { const r = resolver(); mockListing(); - mockResolve(SCT, { candidates: [{ url: KEYED, open: true, content: 'not-present' }, { url: OPEN, open: true, content: 'complete' }] }); - expect(await r.findServer(SCT, null, 5)).toBe(OPEN); + mockResolve(SCT, { candidates: [{ url: KEYED, open: true, content: 'fragment' }, { url: OPEN, open: true, content: 'not-present' }] }); + expect(await r.findServers(SCT, null, 5)).toEqual([{ url: OPEN, authoritative: false }, { url: KEYED, authoritative: false }]); }); - // a server that holds the concepts in its own tables, and says not-present, has to be - // registered as authoritative to be used - test('an authoritative server is used whatever the registry says about the content', async () => { + test('what the registry says about the content doesn\'t stop a server being used', async () => { const r = resolver(); mockListing(); mockResolve(`${SCT}|${EE}`, { authoritative: [{ url: KEYED, open: true, content: 'not-present' }], candidates: [{ url: OPEN, open: true, content: 'not-present' }, { url: OAUTH, open: true }] }); - expect(await r.findServers(SCT, EE, 5)).toEqual([{ url: KEYED, authoritative: true }, { url: OAUTH, authoritative: false }]); + expect(await r.findServers(SCT, EE, 5)).toEqual([{ url: KEYED, authoritative: true }, { url: OPEN, authoritative: false }, { url: OAUTH, authoritative: false }]); }); }); @@ -225,28 +225,24 @@ describe('EcosystemResolver', () => { expect(search.isDone()).toBe(false); }); - test('a code system the TerminologyCapabilities doesn\'t list, or says has no content, is searched for', async () => { + test('a code system the TerminologyCapabilities lists is supported, whatever content it says; one it doesn\'t list is searched for', async () => { const r = resolver(); mockListing(); + // a server that holds the codes in its own tables, with a stub CodeSystem: listing it says + // it supports it nock('https://open.example').get('/fhir/metadata').query({ mode: 'terminology' }).reply(200, { resourceType: 'TerminologyCapabilities', codeSystem: [ { uri: 'http://example.org/tables', version: [{ code: '1' }], content: 'not-present' } ] }); - // a server that holds the codes in its own tables, and says so in the CodeSystem too - nock('https://open.example').get('/fhir/CodeSystem').query(q => q.url === 'http://example.org/tables' && q._summary === 'true').reply(200, { resourceType: 'Bundle', entry: [ - { resource: { resourceType: 'CodeSystem', url: 'http://example.org/tables', version: '1', content: 'not-present' } } - ] }); nock('https://open.example').get('/fhir/CodeSystem').query(q => q.url === 'http://example.org/unlisted').reply(200, { resourceType: 'Bundle', entry: [ { resource: { resourceType: 'CodeSystem', url: 'http://example.org/unlisted', version: '2024', content: 'complete' } }, { resource: { resourceType: 'CodeSystem', url: 'http://example.org/unlisted', version: '2025', content: 'fragment' } }, { resource: { resourceType: 'CodeSystem', url: 'http://example.org/unlisted', version: '2023', content: 'example' } } ] }); - expect(await r.listVersions(OPEN, 'http://example.org/tables')).toBeNull(); + expect(await r.listVersions(OPEN, 'http://example.org/tables')).toEqual([{ code: '1', isDefault: false }]); expect(await r.listVersions(OPEN, 'http://example.org/unlisted')).toEqual([{ code: '2024', isDefault: false }, { code: '2025', isDefault: false }]); expect(nock.isDone()).toBe(true); // and what the search found is kept expect(await r.listVersions(OPEN, 'http://example.org/unlisted')).toEqual([{ code: '2024', isDefault: false }, { code: '2025', isDefault: false }]); - // for an authoritative server, what it says about the content doesn't matter - expect(await r.listVersions(OPEN, 'http://example.org/tables', null, true)).toEqual([{ code: '1', isDefault: false }]); }); }); diff --git a/tests/tx/metadata-codesystems.test.js b/tests/tx/metadata-codesystems.test.js new file mode 100644 index 000000000..a996200ed --- /dev/null +++ b/tests/tx/metadata-codesystems.test.js @@ -0,0 +1,71 @@ +// Which code systems TerminologyCapabilities lists. Listing a code system (version) says this +// server supports it - $validate-code works on it - and that's how the tx ecosystem reads it, +// whatever content is reported. So CodeSystem resources are listed only when their content is +// complete or fragment: not-present stubs, examples and supplements aren't. Code systems with a +// native provider (factory) are always listed + +const { MetadataHandler } = require('../../tx/workers/metadata'); + +function cs(url, version, content, extra = {}) { + return { url, version, content, jsonObj: { url, version, content, ...extra } }; +} + +function factory(url, version) { + return { system: () => url, version: () => version, content: () => 'complete' }; +} + +function provider(codeSystems, factories = []) { + return { + codeSystems: new Map(codeSystems.map(c => [c.url + '|' + c.version, c])), + codeSystemFactories: new Map(factories.map(f => [f.system() + '|' + f.version(), f])) + }; +} + +describe('TerminologyCapabilities code system list', () => { + const handler = new MetadataHandler({}); + const list = async (p) => (await handler.buildCodeSystemEntries(p)) || []; + + test('complete and fragment code systems are listed, with their content', async () => { + const entries = await list(provider([ + cs('http://example.org/complete', '1', 'complete'), + cs('http://example.org/fragment', '1', 'fragment') + ])); + expect(entries.map(e => [e.uri, e.content])).toEqual([ + ['http://example.org/complete', 'complete'], + ['http://example.org/fragment', 'fragment'] + ]); + }); + + test('not-present, example and supplement code systems are not listed', async () => { + const entries = await list(provider([ + cs('http://example.org/stub', '1', 'not-present'), + cs('http://example.org/example', '1', 'example'), + cs('http://example.org/supplement', '1', 'supplement', { supplements: 'http://example.org/complete' }), + cs('http://example.org/none', '1', undefined) + ])); + expect(entries).toEqual([]); + }); + + test('a stub for a code system with a native provider: the provider\'s version is listed, not the stub\'s', async () => { + const entries = await list(provider( + [cs('http://snomed.info/sct', 'http://snomed.info/sct/900000000000207008/version/20200131', 'not-present')], + [factory('http://snomed.info/sct', 'http://snomed.info/sct/900000000000207008/version/20260501')] + )); + expect(entries).toHaveLength(1); + expect(entries[0].uri).toBe('http://snomed.info/sct'); + expect(entries[0].content).toBe('complete'); + expect(entries[0].version.map(v => v.code)).toEqual(['http://snomed.info/sct/900000000000207008/version/20260501']); + }); + + test('versions are listed only if they are supported, and content is the best of them', async () => { + const entries = await list(provider([ + cs('http://example.org/multi', '1', 'fragment'), + cs('http://example.org/multi', '2', 'not-present'), + cs('http://example.org/multi', '3', 'complete'), + cs('http://example.org/multi', '4', 'fragment') + ])); + expect(entries).toHaveLength(1); + expect(entries[0].version.map(v => v.code)).toEqual(['1', '3', '4']); + expect(entries[0].content).toBe('complete'); + }); +}); diff --git a/tx/ecosystem-resolver.js b/tx/ecosystem-resolver.js index b143ad649..4433165cc 100644 --- a/tx/ecosystem-resolver.js +++ b/tx/ecosystem-resolver.js @@ -621,27 +621,24 @@ class EcosystemResolver { } /** - * The servers in a list from the registry that can be used, in the registry's order. A - * candidate the registry says doesn't have the content (from its TerminologyCapabilities) isn't - * used; an authoritative server is, whatever it says: a server that provides services for a code - * system it says it has no content for (because it holds the concepts in its own tables) has to - * be registered as authoritative for it + * The servers in a list from the registry that can be used, in the registry's order, except + * that candidates that say they have only a fragment of the code system come after the others. + * A server is a candidate because it lists the code system in its TerminologyCapabilities, and + * that says it supports it, whatever content it reports */ async chooseServers(list, authoritative, opContext = null) { const result = []; + const fragments = []; for (const s of list || []) { if (!s.url || this.isExcludedServer(s.url)) { continue; } - if (!authoritative && s.content && !EcosystemResolver.isUsableContent(s.content)) { - continue; - } const open = (s.open || s.security === 'open') && !s.token; if (open || this.credentials.hasCredentials(await this.serverCode(s.url, opContext))) { - result.push({ url: s.url, authoritative }); + (!authoritative && s.content === 'fragment' ? fragments : result).push({ url: s.url, authoritative }); } } - return result; + return result.concat(fragments); } /** @@ -669,13 +666,11 @@ class EcosystemResolver { * asked). * * What the server says in its TerminologyCapabilities comes first: if it lists the code system, - * and doesn't say that the content is anything other than complete or fragment, the versions it - * lists there are the answer. Otherwise - it doesn't list it, or says the content isn't there, or - * there's no TerminologyCapabilities - the server's CodeSystem resources for it are searched for, - * and the versions with complete or fragment content are the answer (searchVersions). - * - * For a server that's authoritative for the code system, what it says about the content isn't - * looked at (see chooseServers) + * the versions it lists there are the answer - listing a version says the server supports it, + * whatever content it reports. Otherwise - it doesn't list it, or there's no + * TerminologyCapabilities - the server's CodeSystem resources for it are searched for, and the + * versions with complete or fragment content (any content, for a server that's authoritative + * for it) are the answer (searchVersions) * * @param {string} server * @param {string} system @@ -686,7 +681,7 @@ class EcosystemResolver { async listVersions(server, system, opContext = null, authoritative = false) { const caps = await this.codeSystemsOf(server, opContext); const entry = caps ? caps.get(system) : null; - if (entry && (authoritative || entry.content === undefined || EcosystemResolver.isUsableContent(entry.content))) { + if (entry) { return entry.versions; } const failure = caps ? null : this.#failureOf(this.versions, server); diff --git a/tx/workers/metadata.js b/tx/workers/metadata.js index 0d5abc769..66859fd90 100644 --- a/tx/workers/metadata.js +++ b/tx/workers/metadata.js @@ -14,6 +14,13 @@ const {TerminologyCapabilities} = require("../library/terminologycapabilities"); * Used by TXModule to handle /metadata requests */ class MetadataHandler { + /** the CodeSystem.content values for which a CodeSystem resource is listed in TerminologyCapabilities */ + static LISTED_CONTENT = ['complete', 'fragment']; + + static contentRank(content) { + return content === 'complete' ? 2 : content === 'fragment' ? 1 : 0; + } + host; /** @@ -351,14 +358,19 @@ class MetadataHandler { async buildCodeSystemEntries(provider) { const seenSystems = new Map(); // url -> entry for deduplication - // Process provider.codeSystems (direct CodeSystem resources) + // Listing a code system (version) here says this server supports it: $validate-code works + // on it. That's how the tx ecosystem reads it (and what Ontoserver means), whatever the + // content element says. So only CodeSystem resources with content complete or fragment are + // listed; not-present stubs, examples and supplements aren't. A code system we hold a stub + // for but support natively is listed by its factory below. This applies to each version + // separately if (provider && provider.codeSystems) { for (const cs of provider.codeSystems.values()) { const url = cs.url || (cs.jsonObj && cs.jsonObj.url); const version = cs.version || (cs.jsonObj && cs.jsonObj.version); - const content = cs.content || cs.jsonObj.content; + const content = cs.content || (cs.jsonObj && cs.jsonObj.content); - if (url) { + if (url && MetadataHandler.LISTED_CONTENT.includes(content)) { this.addCodeSystemEntry(seenSystems, url, version, content); } } @@ -441,7 +453,9 @@ class MetadataHandler { if (!entry.version) { entry.version = []; } - if (content) { + // content is per code system, not per version: report the best of the versions listed + // (complete over fragment), so clients can prefer a server with the whole code system + if (content && MetadataHandler.contentRank(content) > MetadataHandler.contentRank(entry.content)) { entry.content = content; } // Check if version already exists diff --git a/tx/workers/validate.js b/tx/workers/validate.js index fe555fb9a..527076358 100644 --- a/tx/workers/validate.js +++ b/tx/workers/validate.js @@ -2409,8 +2409,8 @@ class ValidateWorker extends TerminologyWorker { throw new Issue('error', 'invalid', null, null, 'Unable to find code to validate (looked for coding | codeableConcept | code in parameters)', null, 400).handleAsOO(400); } - // Get the CodeSystem - from parameter or by url - const codeSystem = await this.resolveCodeSystem(params, txp, coded?.coding?.[0] ?? null, mode); + // Get the CodeSystem - from parameter or by url, else from the codings + const codeSystem = await this.resolveCodeSystemForCoded(params, txp, coded, mode); if (!codeSystem) { if (!coded?.coding?.[0].system) { let msg = this.i18n.translate('Coding_has_no_system__cannot_validate', txp.HTTPLanguages, []); @@ -2448,10 +2448,53 @@ class ValidateWorker extends TerminologyWorker { switch (mode.mode) { case 'code': return 'system'; case 'coding': return 'Coding.system'; - default: return 'CodeableConcept.coding[0].system'; + default: return `CodeableConcept.coding[${mode.codingIndex || 0}].system`; } } + /** + * The code system for CodeSystem/$validate-code. With a codeSystem or url parameter, that's it. + * Otherwise it comes from the code being validated - and for a CodeableConcept, that's the + * first coding whose system is known: the order of the codings doesn't matter, and the other + * codings are checked against it as for any value set (one in a system that isn't known is + * reported, and doesn't stop the CodeableConcept being valid). If none of the codings' systems + * is known, every one of them is reported, not just the first (each issue at its own coding, + * each system as x-caused-by-unknown-system: see handlePrepareError). + * + * mode.codingIndex is set to the coding the code system came from, for the paths of issues + * about it (systemPath) + */ + async resolveCodeSystemForCoded(params, txp, coded, mode) { + const codings = coded?.coding ?? []; + if (mode.mode !== 'codeableConcept' || codings.length < 2 || + this.getResourceParam(params, 'codeSystem') || this.getStringParam(params, 'url')) { + return this.resolveCodeSystem(params, txp, codings[0] ?? null, mode); + } + let failure = null; + for (let i = 0; i < codings.length; i++) { + if (!codings[i].system) { + continue; + } + mode.codingIndex = i; + try { + const cs = await this.resolveCodeSystem(params, txp, codings[i], mode); + if (cs) { + return cs; + } + } catch (error) { + if (!(error instanceof Issue) || error.isHandleAsOO()) { + throw error; + } + failure = failure ? failure.addIssue(error) : error; + } + } + mode.codingIndex = 0; + if (failure) { + throw failure; + } + return null; + } + /** * The path to the coding itself, for an issue about the coding rather than one of its properties. * A CodeableConcept is validated one coding at a time, so an issue raised before that loop starts @@ -2983,14 +3026,19 @@ class ValidateWorker extends TerminologyWorker { async handlePrepareError(error, coded, mode, txp) { let op = new OperationOutcome(); op.addIssue(error); - const extra = this.ecosystemIssues(error.unknownSystem ? [error.unknownSystem] : [], error.level === 'error' ? 'error' : 'warning'); + // a CodeableConcept none of whose codings' systems is known: one issue for each, chained to + // the first (see resolveCodeSystemForCoded) + const unknown = [error, ...error.issues].filter(i => i.unknownSystem); + const unknownSystems = [...new Set(unknown.map(i => i.unknownSystem))]; + const extra = this.ecosystemIssues(unknownSystems, error.level === 'error' ? 'error' : 'warning'); for (const iss of [...extra, ...this.sameUrlSupplementIssues()]) { op.addIssue(iss); } let p = new Parameters(); p.addParamResource('issues', op.jsonObj); p.addParamBool('result', false); - p.addParamStr('message', [error.message, ...extra.filter(i => i.level === 'error').map(i => i.message)].join('; ')); + p.addParamStr('message', [...new Set([error.message, ...unknown.map(i => i.message), + ...extra.filter(i => i.level === 'error').map(i => i.message)])].join('; ')); if (!mode || !coded) { // nothing to add } else if (mode == 'codeableConcept') { @@ -3015,8 +3063,8 @@ class ValidateWorker extends TerminologyWorker { p.addParamCode('code', coded.coding[0].code) } } - if (error.unknownSystem) { - p.addParamCanonical("x-caused-by-unknown-system", error.unknownSystem); + for (const us of unknownSystems) { + p.addParamCanonical("x-caused-by-unknown-system", us); } return p.jsonObj; } From b35799fce49f891eccbc05060d1ea130fa239e06 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:08:15 +1100 Subject: [PATCH 4/8] revise handling of special value sets (#488) --- tests/tx/expand-unclosed-total.test.js | 87 ++++++++++++++++++ tests/tx/validate-cc-unknown-systems.test.js | 96 ++++++++++++++++++++ tx/library/parameters.js | 10 +- tx/workers/expand.js | 2 + 4 files changed, 191 insertions(+), 4 deletions(-) create mode 100644 tests/tx/expand-unclosed-total.test.js create mode 100644 tests/tx/validate-cc-unknown-systems.test.js diff --git a/tests/tx/expand-unclosed-total.test.js b/tests/tx/expand-unclosed-total.test.js new file mode 100644 index 000000000..eebc93421 --- /dev/null +++ b/tests/tx/expand-unclosed-total.test.js @@ -0,0 +1,87 @@ +/** + * An expansion that includes a code system with a grammar (urn:ietf:bcp:47) has infinite + * members, so it reports no total, even when the value set has other includes (#488) + */ + +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { IETFLanguageCodeFactory } = require('../../tx/cs/cs-lang'); + +const UNCLOSED = 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed'; +const UNCLOSED_REASON = 'http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason'; + +function expandRequest(includes, count) { + const parameter = [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: includes } } }, + { name: 'tx-resource', resource: { + resourceType: 'CodeSystem', url: 'urn:frag1', version: '1', status: 'active', content: 'fragment', caseSensitive: true, + concept: [{ code: 'a', display: 'Apple' }, { code: 'd', display: 'Date' }] } }, + // the test library has no THO: a stand in for the value set that bcp:47 is enumerated from + { name: 'tx-resource', resource: { + resourceType: 'ValueSet', url: 'http://terminology.hl7.org/ValueSet/Languages', version: '1', status: 'active', + compose: { include: [{ system: 'urn:ietf:bcp:47', concept: [{ code: 'aa' }, { code: 'ab' }, { code: 'de' }, { code: 'en' }] }] } } } + ]; + if (count !== undefined) { + parameter.push({ name: 'count', valueInteger: count }); + } + return { resourceType: 'Parameters', parameter }; +} + +const FRAG = { system: 'urn:frag1', concept: [{ code: 'a' }] }; +const LANG = { system: 'urn:ietf:bcp:47' }; + +describe('$expand: unclosed expansions report no total (#488)', () => { + let app; + let factories; + let hadLang; + let previousLang; + + beforeAll(async () => { + app = await getTestApp(); + factories = getTxModule().endpoints[0].provider.codeSystemFactories; + hadLang = factories.has('urn:ietf:bcp:47'); + previousLang = factories.get('urn:ietf:bcp:47'); + factories.set('urn:ietf:bcp:47', new IETFLanguageCodeFactory(getTxModule().i18n)); + }, 60000); + + afterAll(async () => { + if (hadLang) { + factories.set('urn:ietf:bcp:47', previousLang); + } else { + factories.delete('urn:ietf:bcp:47'); + } + await shutdownTestApp(); + }); + + async function expand(includes, count) { + const res = await request(app) + .post('/tx/r5/ValueSet/$expand') + .set('Content-Type', 'application/json') + .send(expandRequest(includes, count)); + if (res.status !== 200) { + throw new Error('expand failed: ' + JSON.stringify(res.body)); + } + return res.body.expansion; + } + + function expectUnclosedNoTotal(exp) { + const ext = exp.extension || []; + expect(ext.find(e => e.url === UNCLOSED)?.valueBoolean).toBe(true); + expect(ext.find(e => e.url === UNCLOSED_REASON)?.valueString).toMatch(/urn:ietf:bcp:47.*infinite members/); + expect(exp.total).toBeUndefined(); + } + + test.each([ + ['bcp:47 alone', [LANG], undefined], + ['another include first', [FRAG, LANG], undefined], + ['another include first, count 3', [FRAG, LANG], 3], + ['another include first, count 0', [FRAG, LANG], 0], + ['another include second', [LANG, FRAG], undefined] + ])('%s', async (name, includes, count) => { + const exp = await expand(includes, count); + expectUnclosedNoTotal(exp); + if (count === 3) { + expect((exp.contains || []).length).toBe(3); + } + }); +}); diff --git a/tests/tx/validate-cc-unknown-systems.test.js b/tests/tx/validate-cc-unknown-systems.test.js new file mode 100644 index 000000000..bac61e7d9 --- /dev/null +++ b/tests/tx/validate-cc-unknown-systems.test.js @@ -0,0 +1,96 @@ +// $validate-code on a CodeableConcept whose codings come from code systems the server doesn't +// know (reported by the Ontoserver team, Dec 2026). Every unknown system is reported - an issue at +// each coding's system, and an x-caused-by-unknown-system for each system - not just the first. +// And on CodeSystem/$validate-code, with no url, the code system is the first coding's that is +// known, so the order of the codings doesn't change the answer + +const request = require('supertest'); +const { getTestApp, shutdownTestApp } = require('./setup'); + +const KNOWN = 'http://example.org/fhir/CodeSystem/cc-unknown-known'; +const CS = { + resourceType: 'CodeSystem', url: KNOWN, version: '1', status: 'active', content: 'complete', + concept: [{ code: 'k1', display: 'K1' }] +}; +const U1 = 'http://hl7.org/fhir/test/CodeSystem/imaginary'; +const U2 = 'http://hl7.org/fhir/test/CodeSystem/other'; +const VS = { + resourceType: 'ValueSet', url: 'http://example.org/fhir/ValueSet/cc-unknown', version: '1', status: 'active', + compose: { include: [{ system: U1 }, { system: U2 }] } +}; + +describe('$validate-code: a CodeableConcept with codings from unknown code systems', () => { + let app; + + beforeAll(async () => { + app = await getTestApp(); + }, 60000); + + afterAll(async () => { + await shutdownTestApp(); + }); + + const validateCS = (coding) => request(app) + .post('/tx/r5/CodeSystem/$validate-code') + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [ + { name: 'codeableConcept', valueCodeableConcept: { coding } }, + { name: 'tx-resource', resource: CS } + ] }); + + const param = (body, name) => (body.parameter || []).find(p => p.name === name); + const result = (body) => param(body, 'result').valueBoolean; + const causedBy = (body) => (body.parameter || []).filter(p => p.name === 'x-caused-by-unknown-system').map(p => p.valueCanonical); + const issues = (body) => ((param(body, 'issues') || {}).resource || { issue: [] }).issue + .map(i => [i.severity, i.code, (i.expression || []).join(',')]); + + test('CodeSystem: two unknown systems - both are reported', async () => { + const res = await validateCS([{ system: U1, code: 'code-b' }, { system: U2, code: 'other' }]); + expect(res.status).toBe(200); + expect(result(res.body)).toBe(false); + expect(causedBy(res.body)).toEqual([U1, U2]); + expect(issues(res.body)).toEqual([ + ['error', 'not-found', 'CodeableConcept.coding[0].system'], + ['error', 'not-found', 'CodeableConcept.coding[1].system'] + ]); + expect(param(res.body, 'message').valueString).toContain(U1); + expect(param(res.body, 'message').valueString).toContain(U2); + }); + + test('CodeSystem: a system repeated, and a coding with no system - each coding with a system is reported, each system once', async () => { + const res = await validateCS([{ system: U1, code: 'a' }, { code: 'nosys' }, { system: U2, code: 'b' }, { system: U1, code: 'c' }]); + expect(result(res.body)).toBe(false); + expect(causedBy(res.body)).toEqual([U1, U2]); + expect(issues(res.body)).toEqual([ + ['error', 'not-found', 'CodeableConcept.coding[0].system'], + ['error', 'not-found', 'CodeableConcept.coding[2].system'], + ['error', 'not-found', 'CodeableConcept.coding[3].system'] + ]); + }); + + test('CodeSystem: the order of the codings doesn\'t matter - the known code system is used either way', async () => { + for (const coding of [ + [{ system: KNOWN, code: 'k1' }, { system: U2, code: 'other' }], + [{ system: U2, code: 'other' }, { system: KNOWN, code: 'k1' }] + ]) { + const res = await validateCS(coding); + expect(result(res.body)).toBe(true); + expect(causedBy(res.body)).toEqual([]); + const unknownAt = coding.findIndex(c => c.system === U2); + expect(issues(res.body)).toEqual([['warning', 'not-found', `CodeableConcept.coding[${unknownAt}].system`]]); + } + }); + + test('ValueSet: two unknown systems - both are named in x-caused-by-unknown-system', async () => { + const res = await request(app) + .post('/tx/r5/ValueSet/$validate-code') + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: VS }, + { name: 'codeableConcept', valueCodeableConcept: { coding: [{ system: U1, code: 'code-b' }, { system: U2, code: 'other' }] } } + ] }); + expect(res.status).toBe(200); + expect(result(res.body)).toBe(false); + expect(causedBy(res.body).sort()).toEqual([U1, U2].sort()); + }); +}); diff --git a/tx/library/parameters.js b/tx/library/parameters.js index 7298df975..80ea08063 100644 --- a/tx/library/parameters.js +++ b/tx/library/parameters.js @@ -46,14 +46,16 @@ class Parameters { } } + /** + * Adds a canonical parameter. These repeat (x-unknown-system, x-caused-by-unknown-system: one + * for each system), so an existing parameter of the same name isn't replaced - but the same + * value isn't added twice + */ addParamCanonical(name, value) { if (!this.jsonObj.parameter) { this.jsonObj.parameter = []; } - let p = this.jsonObj.parameter.find(x => x.name === name); - if (p) { - p.valueCanonical = value; - } else { + if (!this.jsonObj.parameter.some(x => x.name === name && x.valueCanonical === value)) { this.jsonObj.parameter.push({name: name, valueCanonical: value}); } } diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 5a7ad73cc..c3c5b7965 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1439,6 +1439,8 @@ class ValueSetExpander { Extensions.addBoolean(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed", true); Extensions.addString(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason", "The code System '" + cs.system() + "' has a grammar and so has infinite members. This extension is based on " + cs.specialEnumeration()); await this.importValueSet(base, expansion, valueSets, 0); + // infinite members: there's no total, whatever the other includes add (#488) + this.noTotal(); notClosed.value = true; } else if (!cs.canBeExpanded()) { throw new Issue("error", "not-supported", null, 'CODESYSTEM_NOT_ENUMERABLE', this.worker.i18n.translate('CODESYSTEM_NOT_ENUMERABLE', this.params.httpLanguages, [cs.system()]), null, 422).withDiagnostics(this.worker.opContext.diagnostics()); From 2559712f2013a3788dc65d7d0f6101a24138bdb1 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:08:24 +1100 Subject: [PATCH 5/8] post-release --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ package-lock.json | 4 ++-- package.json | 10 ++++++++-- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b79aba706..49226e764 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,34 @@ All notable changes to Health Intersections FHIRsmith will be documented in this The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.1.2] - 2026-mm-dd + +### Security + +- + +### Added + +- + +### Changed + +- TerminologyCapabilities lists only the code systems (and versions) that the server supports, i.e. can `$validate-code` against: CodeSystem resources with content `complete` or `fragment`, and code systems with a native provider. `not-present` stubs, examples and supplements are no longer listed. `codeSystem.content` is the best content of the versions listed +- Registry and ecosystem resolution: a server that lists a code system in its TerminologyCapabilities supports it, whatever content it reports (as Ontoserver means it). Candidates are no longer passed over for reporting `not-present`; a candidate with only a `fragment` comes after the others + +### Fixed + +- `$validate-code` on a CodeableConcept with codings from several code systems the server doesn't know reports all of them - an issue at each coding's system and an `x-caused-by-unknown-system` for each system - not just the first (CodeSystem and ValueSet `$validate-code`; reported by the Ontoserver team) +- CodeSystem `$validate-code` on a CodeableConcept, with no `url`: the code system is that of the first coding whose system is known, not always the first coding's. A CodeableConcept with a valid coding was invalid if an unknown-system coding came before it + +### Removed + +- + +### Tx Conformance Statement + +(paste) + ## [1.1.1] - 2026-12-06 ### Security diff --git a/package-lock.json b/package-lock.json index 4ed1d3884..7cbb80b2b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "fhirsmith", - "version": "1.1.1", + "version": "1.1.2-snapshot", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fhirsmith", - "version": "1.1.1", + "version": "1.1.2-snapshot", "license": "BSD-3-Clause", "dependencies": { "axios": "^1.13.4", diff --git a/package.json b/package.json index da89bff06..792124689 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fhirsmith", - "version": "1.1.1", + "version": "1.1.2-snapshot", "txVersion": "1.12.1-snapshot", "description": "A Node.js server that provides a collection of tools to serve the FHIR ecosystem", "main": "server.js", @@ -122,5 +122,11 @@ "bugs": { "url": "https://github.com/HealthIntersections/fhirsmith/issues" }, - "homepage": "https://github.com/HealthIntersections/fhirsmith#readme" + "homepage": "https://github.com/HealthIntersections/fhirsmith#readme", + "allowScripts": { + "@parcel/watcher": false, + "bcrypt": false, + "koffi": false, + "unrs-resolver": false + } } From 04cc3b39cd5d81adbc417095c165ab284c62494b Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:25:01 +1100 Subject: [PATCH 6/8] UNII and NDC fixes (#484, #485, #487) --- .../ndc-history-data/ndc-history-testing.db | 0 .../ndc-history-testing.db-journal | Bin 0 -> 512 bytes .../ndc-history-data2/ndc-history-testing.db | 0 .../ndc-history-testing.db-journal | Bin 0 -> 512 bytes .../ndc-history-data3/ndc-history-testing.db | 0 .../ndc-history-testing.db-journal | Bin 0 -> 512 bytes tests/cs/cs-ndc.test.js | 88 +++++++++++++ tests/cs/cs-unii.test.js | 50 ++++++-- tests/tx/expand-ndc.test.js | 120 ++++++++++++++++++ tests/tx/expand-unii.test.js | 98 ++++++++++++++ tx/cs/cs-ndc.js | 59 ++++++++- tx/cs/cs-unii.js | 83 +++++++++++- tx/workers/expand.js | 7 +- 13 files changed, 482 insertions(+), 23 deletions(-) create mode 100644 _to_delete/ndc-history-data/ndc-history-testing.db create mode 100644 _to_delete/ndc-history-data/ndc-history-testing.db-journal create mode 100644 _to_delete/ndc-history-data2/ndc-history-testing.db create mode 100644 _to_delete/ndc-history-data2/ndc-history-testing.db-journal create mode 100644 _to_delete/ndc-history-data3/ndc-history-testing.db create mode 100644 _to_delete/ndc-history-data3/ndc-history-testing.db-journal create mode 100644 tests/tx/expand-ndc.test.js create mode 100644 tests/tx/expand-unii.test.js diff --git a/_to_delete/ndc-history-data/ndc-history-testing.db b/_to_delete/ndc-history-data/ndc-history-testing.db new file mode 100644 index 000000000..e69de29bb diff --git a/_to_delete/ndc-history-data/ndc-history-testing.db-journal b/_to_delete/ndc-history-data/ndc-history-testing.db-journal new file mode 100644 index 0000000000000000000000000000000000000000..a7eca64df3e93ce5e0d5e6b8dc1d44e8aba145d8 GIT binary patch literal 512 kcmcb4mG!5>!sP1=Kw#UUe-T78FfakJ0GKsO4DS#C0MxMte*gdg literal 0 HcmV?d00001 diff --git a/_to_delete/ndc-history-data2/ndc-history-testing.db b/_to_delete/ndc-history-data2/ndc-history-testing.db new file mode 100644 index 000000000..e69de29bb diff --git a/_to_delete/ndc-history-data2/ndc-history-testing.db-journal b/_to_delete/ndc-history-data2/ndc-history-testing.db-journal new file mode 100644 index 0000000000000000000000000000000000000000..75cba280ca6c3a5570ed73d0ac0be86b5bc9534f GIT binary patch literal 512 kcmcb4mG!5>!sP1=K)|hJE(M|)7?^-q0L&UChIa@609axLH~;_u literal 0 HcmV?d00001 diff --git a/_to_delete/ndc-history-data3/ndc-history-testing.db b/_to_delete/ndc-history-data3/ndc-history-testing.db new file mode 100644 index 000000000..e69de29bb diff --git a/_to_delete/ndc-history-data3/ndc-history-testing.db-journal b/_to_delete/ndc-history-data3/ndc-history-testing.db-journal new file mode 100644 index 0000000000000000000000000000000000000000..98b4692337f78fe16aec28e8d329b8ae8ad45569 GIT binary patch literal 512 kcmcb4mG!5>!sP1=K=4cF##<20z`z8=0$|oCF}y { }); }); + describe('Combined filters (#484)', () => { + async function walk(set) { + const codes = []; + let c = await provider.filterConcept(null, set); + while (c) { + codes.push(c); + c = await provider.filterConcept(null, set); + } + return codes; + } + + async function bla11() { + const db = new SqliteDatabase(testDbPath, { readOnly: true }); + try { + return db.all(`SELECT pkg.Code11 FROM NDCPackages pkg JOIN NDCProducts p ON pkg.ProductKey = p.NDCKey + WHERE p.Category = 'BLA' ORDER BY pkg.NDCKey`).map(r => r.Code11); + } finally { + db.close(); + } + } + + test.each([ + ['category first', [['category', 'BLA'], ['code-type', '11-digit']]], + ['code-type first', [['code-type', '11-digit'], ['category', 'BLA']]] + ])('category and 11-digit, %s: the 11 digit codes of the category\'s packages', async (name, filters) => { + const ctxt = await provider.getPrepContext(true); + for (const [prop, value] of filters) { + await provider.filter(ctxt, true, prop, '=', value); + } + const sets = await provider.executeFilters(ctxt); + expect(sets.length).toBe(1); + const expected = await bla11(); + expect(expected.length).toBeGreaterThan(0); + const codes = await walk(sets[0]); + expect(codes.map(c => c.code)).toEqual(expected); + expect(await provider.filterSize(ctxt, sets[0])).toBe(expected.length); + // membership: the 11 digit form is in, the 10 digit form isn't + const pkg = codes[0]; + expect(await provider.filterLocate(ctxt, sets[0], pkg.code)).toBeInstanceOf(NdcConcept); + const db = new SqliteDatabase(testDbPath, { readOnly: true }); + let tenDigit; + try { + tenDigit = db.get('SELECT Code FROM NDCPackages WHERE Code11 = ?', [pkg.code]).Code; + } finally { + db.close(); + } + expect(tenDigit).toContain('-'); + expect(await provider.filterLocate(ctxt, sets[0], tenDigit)).toBeNull(); + }); + + test('10-digit and 11-digit together: nothing', async () => { + const ctxt = await provider.getPrepContext(true); + await provider.filter(ctxt, true, 'code-type', '=', '10-digit'); + await provider.filter(ctxt, true, 'code-type', '=', '11-digit'); + const sets = await provider.executeFilters(ctxt); + expect(await provider.filterSize(ctxt, sets[0])).toBe(0); + expect(await walk(sets[0])).toEqual([]); + }); + }); + + describe('Iterator (#485)', () => { + test('walks every product and package, as many as it counts', async () => { + const total = await provider.totalCount(); + const iter = await provider.iterator(null); + expect(iter.total).toBe(total); + const codes = new Set(); + let products = 0; + let c = await provider.nextContext(iter); + while (c) { + expect(c).toBeInstanceOf(NdcConcept); + if (!c.isPackage) { + products++; + } + codes.add(c.code); + c = await provider.nextContext(iter); + } + expect(codes.size).toBe(total); + expect(products).toBe(factory._productCount); + expect(await provider.countAllCodes(false)).toBe(total); + }); + + test('a concept has nothing under it', async () => { + const iter = await provider.iterator((await provider.locate('0002-0152')).context); + expect(iter.total).toBe(0); + expect(await provider.nextContext(iter)).toBeNull(); + }); + }); + describe('Error Handling', () => { test('should handle unsupported filters', async () => { diff --git a/tests/cs/cs-unii.test.js b/tests/cs/cs-unii.test.js index 147807228..3f6e12a45 100644 --- a/tests/cs/cs-unii.test.js +++ b/tests/cs/cs-unii.test.js @@ -65,8 +65,17 @@ describe('UniiServices', () => { expect(provider.description()).toBe('UNII Codes'); }); - test('should return -1 for total count (database-driven)', () => { - expect(provider.totalCount()).toBe(-1); + test('should count the codes in the database (#487)', async () => { + const db = new SqliteDatabase('./data/unii-testing.db', { readOnly: true }); + let expected; + try { + expected = db.get('SELECT COUNT(*) as count FROM Unii').count; + } finally { + db.close(); + } + expect(expected).toBeGreaterThan(0); + expect(await provider.totalCount()).toBe(expected); + expect(await provider.countAllCodes(false)).toBe(expected); }); test('should not have parents', () => { @@ -213,21 +222,38 @@ describe('UniiServices', () => { }); describe('Iterator Functionality', () => { - test('should return basic iterator info', async () => { + test('should walk all the codes (#487)', async () => { + const total = await provider.totalCount(); const iterator = await provider.iterator(null); - expect(iterator).toBeNull(); + expect(iterator.total).toBe(total); + const codes = new Set(); + let c = await provider.nextContext(iterator); + while (c) { + expect(c).toBeInstanceOf(UniiConcept); + codes.add(c.code); + c = await provider.nextContext(iterator); + } + expect(codes.size).toBe(total); + expect(await provider.nextContext(iterator)).toBeNull(); }); - test('should return null iterator for specific concept', async () => { - const result = await provider.locate('2T8Q726O95'); - const iterator = await provider.iterator(result.context); - expect(iterator).toBeNull(); + test('should give the walked concepts the same descriptions as locate', async () => { + const located = (await provider.locate('2T8Q726O95')).context; + const iterator = await provider.iterator(null); + let c = await provider.nextContext(iterator); + while (c && c.code !== '2T8Q726O95') { + c = await provider.nextContext(iterator); + } + expect(c).not.toBeNull(); + expect(c.display).toBe(located.display); + expect(c.others).toEqual(located.others); }); - test('should throw error on nextContext', async () => { - const iterator = await provider.iterator(null); - const next = await provider.nextContext(iterator); - expect(next).toBeNull(); + test('should return an empty iterator for a specific concept (no children)', async () => { + const result = await provider.locate('2T8Q726O95'); + const iterator = await provider.iterator(result.context); + expect(iterator.total).toBe(0); + expect(await provider.nextContext(iterator)).toBeNull(); }); }); diff --git a/tests/tx/expand-ndc.test.js b/tests/tx/expand-ndc.test.js new file mode 100644 index 000000000..d86c81d62 --- /dev/null +++ b/tests/tx/expand-ndc.test.js @@ -0,0 +1,120 @@ +/** + * $expand of NDC: the whole code system can be listed (#485), and an include with a category + * filter and code-type = 11-digit lists the category's packages in their 11 digit form, + * whichever filter comes first (#484) + */ + +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { NdcServicesFactory } = require('../../tx/cs/cs-ndc'); +const { NdcDataMigrator } = require('../../tx/importers/import-ndc.module'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); + +const NDC = 'http://hl7.org/fhir/sid/ndc'; + +describe('$expand of NDC (#484, #485)', () => { + let app; + let factory; + let factories; + let had; + let before; + let all; + let bla11; + + beforeAll(async () => { + app = await getTestApp(); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ndc-expand-')); + const dbFile = path.join(dir, 'ndc.db'); + await new NdcDataMigrator().migrate(path.join(__dirname, '..', '..', 'tx', 'data', 'ndc'), dbFile, 'NDC-TEST-2024', { verbose: false }); + const db = new SqliteDatabase(dbFile, { readOnly: true }); + try { + all = db.get('SELECT (SELECT COUNT(*) FROM NDCProducts) + (SELECT COUNT(*) FROM NDCPackages) AS n').n; + bla11 = db.all(`SELECT pkg.Code11 FROM NDCPackages pkg JOIN NDCProducts p ON pkg.ProductKey = p.NDCKey + WHERE p.Category = 'BLA' ORDER BY pkg.NDCKey`).map(r => r.Code11); + } finally { + db.close(); + } + factory = new NdcServicesFactory(getTxModule().i18n, dbFile); + await factory.load(); + factories = getTxModule().endpoints[0].provider.codeSystemFactories; + had = factories.has(NDC); + before = factories.get(NDC); + factories.set(NDC, factory); + }, 120000); + + afterAll(async () => { + if (factories) { + if (had) { + factories.set(NDC, before); + } else { + factories.delete(NDC); + } + } + if (factory) { + await factory.close(); + } + await shutdownTestApp(); + }); + + async function expand(include, count) { + const parameter = [{ name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', + compose: { include: [include] } } }]; + if (count !== undefined) { + parameter.push({ name: 'count', valueInteger: count }); + } + const res = await request(app) + .post('/tx/r5/ValueSet/$expand') + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter }); + if (res.status !== 200) { + throw new Error('expand failed: ' + JSON.stringify(res.body)); + } + return res.body.expansion; + } + + test('the test data has BLA packages', () => { + expect(bla11.length).toBeGreaterThan(5); + }); + + describe('the whole code system (#485)', () => { + const whole = { system: NDC }; + + test('count=0: the total', async () => { + const exp = await expand(whole, 0); + expect(exp.total).toBe(all); + }); + + test('count=5: five codes, and the same total', async () => { + const exp = await expand(whole, 5); + expect(exp.contains.length).toBe(5); + expect(exp.total).toBe(all); + }); + + test('no count: every code', async () => { + const exp = await expand(whole); + expect(exp.total).toBe(all); + expect(new Set(exp.contains.map(c => c.code)).size).toBe(all); + }); + }); + + describe('category and code-type = 11-digit (#484)', () => { + const category = { property: 'category', op: '=', value: 'BLA' }; + const elevenDigit = { property: 'code-type', op: '=', value: '11-digit' }; + + test.each([ + ['category first', [category, elevenDigit]], + ['code-type first', [elevenDigit, category]] + ])('%s: the 11 digit codes', async (name, filter) => { + const exp = await expand({ system: NDC, filter }); + expect(exp.contains.map(c => c.code)).toEqual(bla11); + expect(exp.total).toBe(bla11.length); + const counted = await expand({ system: NDC, filter }, 0); + expect(counted.total).toBe(bla11.length); + const page = await expand({ system: NDC, filter }, 3); + expect(page.contains.map(c => c.code)).toEqual(bla11.slice(0, 3)); + }); + }); +}); diff --git a/tests/tx/expand-unii.test.js b/tests/tx/expand-unii.test.js new file mode 100644 index 000000000..5835d6084 --- /dev/null +++ b/tests/tx/expand-unii.test.js @@ -0,0 +1,98 @@ +/** + * $expand of the whole of UNII: the total is the number of UNII codes, with or without count, + * and the codes can be listed (#487) + */ + +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { UniiServicesFactory } = require('../../tx/cs/cs-unii'); +const { UniiDataMigrator } = require('../../tx/importers/import-unii.module'); +const { SqliteDatabase } = require('../../library/sql/node-sqlite'); + +const UNII = 'http://fdasis.nlm.nih.gov'; + +describe('$expand of the whole of UNII (#487)', () => { + let app; + let factory; + let factories; + let had; + let before; + let dir; + let codeCount; + + beforeAll(async () => { + app = await getTestApp(); + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'unii-expand-')); + const dbFile = path.join(dir, 'unii.db'); + await new UniiDataMigrator().migrate(path.join(__dirname, '..', 'data', 'unii-source-testing.txt'), dbFile, '20250702', false); + const db = new SqliteDatabase(dbFile, { readOnly: true }); + try { + codeCount = db.get('SELECT COUNT(*) as count FROM Unii').count; + } finally { + db.close(); + } + factory = new UniiServicesFactory(getTxModule().i18n, dbFile); + await factory.load(); + factories = getTxModule().endpoints[0].provider.codeSystemFactories; + had = factories.has(UNII); + before = factories.get(UNII); + factories.set(UNII, factory); + }, 120000); + + afterAll(async () => { + if (factories) { + if (had) { + factories.set(UNII, before); + } else { + factories.delete(UNII); + } + } + if (factory) { + await factory.close(); + } + await shutdownTestApp(); + }); + + async function expand(count) { + const parameter = [{ name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', + compose: { include: [{ system: UNII }] } } }]; + if (count !== undefined) { + parameter.push({ name: 'count', valueInteger: count }); + } + const res = await request(app) + .post('/tx/r5/ValueSet/$expand') + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter }); + if (res.status !== 200) { + throw new Error('expand failed: ' + JSON.stringify(res.body)); + } + return res.body.expansion; + } + + test('the test data has codes', () => { + expect(codeCount).toBeGreaterThan(10); + }); + + test('count=0: the total is the number of codes', async () => { + const exp = await expand(0); + expect(exp.total).toBe(codeCount); + expect(exp.contains).toBeUndefined(); + }); + + test('no count: all the codes, and the total', async () => { + const exp = await expand(); + expect(exp.total).toBe(codeCount); + expect(exp.contains.length).toBe(codeCount); + expect(new Set(exp.contains.map(c => c.code)).size).toBe(codeCount); + expect(exp.contains.every(c => c.system === UNII && c.display)).toBe(true); + }); + + test('count=10: a page of 10, and the same total', async () => { + const exp = await expand(10); + expect(exp.total).toBe(codeCount); + expect(exp.contains.length).toBe(10); + }); +}); diff --git a/tx/cs/cs-ndc.js b/tx/cs/cs-ndc.js index 5241399a3..1d7c773b3 100644 --- a/tx/cs/cs-ndc.js +++ b/tx/cs/cs-ndc.js @@ -531,7 +531,7 @@ class NdcServices extends CodeSystemProvider { } const hyphen = v === '10-digit'; return { - products: false, packages: true, code11: !hyphen, + products: false, packages: true, code11: !hyphen, form: v, // an 11 digit code shared by two packages is listed once, as the package it resolves to packageWhere: hyphen ? null : `pkg.NDCKey = (SELECT o.NDCKey FROM NDCPackages o WHERE o.Code11 = pkg.Code11 ORDER BY ${NDC_CODE11_PREFERENCE.replace(/pkg\./g, 'o.')} LIMIT 1)`, check: (c) => c.isPackage && c.code.includes('-') === hyphen @@ -553,8 +553,42 @@ class NdcServices extends CodeSystemProvider { return set; } + /** + * The include's filters, as one set: every filter is SQL conditions on the same rows, so they + * are one query whatever order they come in. That matters because a package is written in the + * form the set asks for: walking 'category' and checking 'code-type = 11-digit' afterwards wrote + * the 10 digit form, which the check then refused (#484). It also makes the set's size the + * include's size (count=0, paging) + */ async executeFilters(filterContext) { - return filterContext.filters; + const filters = filterContext.filters; + if (filters.length <= 1) { + return filters; + } + return [{ + property: filters.map(f => f.property).join(','), + op: filters.map(f => f.op).join(','), + value: filters.map(f => f.value).join(','), + spec: this.#combineSpecs(filters.map(f => f.spec)), + _iterator: null + }]; + } + + #combineSpecs(specs) { + const forms = new Set(specs.map(sp => sp.form).filter(f => f)); + // code-type = 10-digit and code-type = 11-digit: a package is written in one form or the other + const none = forms.size > 1; + const join = (wheres) => wheres.filter(w => w).map(w => `(${w})`).join(' AND ') || null; + return { + products: !none && specs.every(sp => sp.products), + packages: !none && specs.every(sp => sp.packages), + code11: specs.some(sp => sp.code11), + productWhere: join(specs.map(sp => sp.productWhere)), + productArgs: specs.flatMap(sp => sp.productWhere ? (sp.productArgs || []) : []), + packageWhere: join(specs.map(sp => sp.packageWhere)), + packageArgs: specs.flatMap(sp => sp.packageWhere ? (sp.packageArgs || []) : []), + check: (c) => !none && specs.every(sp => sp.check(c)) + }; } #productSql(spec, select) { @@ -651,7 +685,26 @@ class NdcServices extends CodeSystemProvider { return set.spec.check(concept); } - // Iterator methods - not supported for NDC + /** + * All the codes: the products, then the packages (in their 10 digit form), in NDCKey order - + * the codes countAllCodes counts (#485). A product's packages aren't its children, so a + * concept has nothing to walk + */ + async iterator(context) { + const all = { products: true, packages: true, check: () => true }; + if (context) { + await this.#ensureContext(context); + return { total: 0, set: { spec: { products: false, packages: false, check: () => false }, _iterator: null } }; + } + return { total: await this.totalCount(), set: { spec: all, _iterator: null } }; + } + + async nextContext(iteratorContext) { + if (!iteratorContext || !iteratorContext.set) { + return null; + } + return await this.filterConcept(null, iteratorContext.set); + } versionAlgorithm() { return 'date'; diff --git a/tx/cs/cs-unii.js b/tx/cs/cs-unii.js index 79af012c3..56197ae03 100644 --- a/tx/cs/cs-unii.js +++ b/tx/cs/cs-unii.js @@ -11,12 +11,27 @@ class UniiConcept { } } +/** + * A walk over all the UNII codes, read from the database a batch at a time (in UniiKey order) + */ +class UniiIteratorContext { + constructor(total) { + this.total = total; + this.lastKey = -1; + this.buffer = []; + this.done = total === 0; + } +} + +const ITERATOR_BATCH = 1000; + class UniiServices extends CodeSystemProvider { - constructor(opContext, supplements, db, version, ownsDb = true) { + constructor(opContext, supplements, db, version, ownsDb = true, count = null) { super(opContext, supplements); this.db = db; this._version = version; this.ownsDb = ownsDb; + this._count = count; } // Clean up database connection when provider is destroyed @@ -43,8 +58,14 @@ class UniiServices extends CodeSystemProvider { return 'UNII Codes'; } - totalCount() { - return -1; // Database-driven, use count query if needed + /** + * The number of UNII codes: counted when the factory loads, or here if it wasn't (#487) + */ + async totalCount() { + if (this._count == null) { + this._count = await this.#getTotalCount(); + } + return this._count; } hasParents() { @@ -182,6 +203,55 @@ class UniiServices extends CodeSystemProvider { versionAlgorithm() { return 'date'; } + + // Iterator methods: UNII has no hierarchy, so only the whole code system can be walked (#487) + async iterator(context) { + if (context) { + await this.#ensureContext(context); + return new UniiIteratorContext(0); + } + return new UniiIteratorContext(await this.totalCount()); + } + + async nextContext(iteratorContext) { + if (!iteratorContext) { + return null; + } + if (iteratorContext.buffer.length === 0 && !iteratorContext.done) { + await this.#readBatch(iteratorContext); + } + return iteratorContext.buffer.length > 0 ? iteratorContext.buffer.shift() : null; + } + + async #readBatch(iteratorContext) { + const rows = await this.db.all('SELECT UniiKey, Code, Display FROM Unii WHERE UniiKey > ? ORDER BY UniiKey LIMIT ?', + [iteratorContext.lastKey, ITERATOR_BATCH]); + if (rows.length < ITERATOR_BATCH) { + iteratorContext.done = true; + } + if (rows.length === 0) { + return; + } + const first = rows[0].UniiKey; + const last = rows[rows.length - 1].UniiKey; + iteratorContext.lastKey = last; + const byKey = new Map(); + for (const row of rows) { + const concept = new UniiConcept(row.Code, row.Display); + byKey.set(row.UniiKey, concept); + iteratorContext.buffer.push(concept); + } + // the other descriptions, as locate() gives them + const descs = await this.db.all('SELECT UniiKey, Display FROM UniiDesc WHERE UniiKey BETWEEN ? AND ? ORDER BY UniiDescKey', + [first, last]); + for (const row of descs) { + const concept = byKey.get(row.UniiKey); + const desc = row.Display ? row.Display.trim() : ''; + if (concept && desc && !concept.others.includes(desc)) { + concept.others.push(desc); + } + } + } } class UniiServicesFactory extends CodeSystemFactoryProvider { @@ -196,6 +266,7 @@ class UniiServicesFactory extends CodeSystemFactoryProvider { this._pool = null; this.uses = 0; this._version = null; + this._count = null; } async load() { @@ -203,6 +274,7 @@ class UniiServicesFactory extends CodeSystemFactoryProvider { try { const row = db.get('SELECT Version FROM UniiVersion'); this._version = row ? row.Version : 'unknown'; + this._count = db.get('SELECT COUNT(*) as count FROM Unii').count; } finally { db.close(); } @@ -230,7 +302,7 @@ class UniiServicesFactory extends CodeSystemFactoryProvider { build(opContext, supplements) { this.uses++; - return new UniiServices(opContext, supplements, this.#pool(), this._version, false); + return new UniiServices(opContext, supplements, this.#pool(), this._version, false, this._count); } async close() { @@ -266,5 +338,6 @@ class UniiServicesFactory extends CodeSystemFactoryProvider { module.exports = { UniiServices, UniiServicesFactory, - UniiConcept + UniiConcept, + UniiIteratorContext }; \ No newline at end of file diff --git a/tx/workers/expand.js b/tx/workers/expand.js index c3c5b7965..9cff0b2e2 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1477,10 +1477,11 @@ class ValueSetExpander { // 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) + // (null: the provider can't count without the inactive codes, so walk them; negative: + // it doesn't know how many codes it has (#487), so walk them too) counted = await cs.countAllCodes(excludeInactive || this.params.activeOnly); } - if (counted != null) { + if (counted != null && counted >= 0) { this.addToTotal(counted); } else { const iter = await cs.iterator(null); @@ -1516,7 +1517,7 @@ class ValueSetExpander { // 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) const all = await cs.countAllCodes(excludeInactive); - this.addToTotal(all != null ? all : tcount); + this.addToTotal(all != null && all >= 0 ? all : tcount); } else { this.addToTotal(tcount); } From cf552800dd28406b47b292047f07a0323ac29fb6 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:36:02 +1100 Subject: [PATCH 7/8] #486 fix CPT filter interpretation --- tests/cs/cs-cpt.test.js | 33 ++++++++++++ tests/tx/validate-cpt-modified.test.js | 74 ++++++++++++++++++++++++++ tx/cs/cs-cpt.js | 10 ++++ 3 files changed, 117 insertions(+) create mode 100644 tests/tx/validate-cpt-modified.test.js diff --git a/tests/cs/cs-cpt.test.js b/tests/cs/cs-cpt.test.js index 880f21312..2c555457b 100644 --- a/tests/cs/cs-cpt.test.js +++ b/tests/cs/cs-cpt.test.js @@ -481,6 +481,39 @@ describe('CPT Provider', () => { }); }); + describe('Locating expressions in filters (#486)', () => { + async function filterSet(prop, value) { + const filterContext = await provider.getPrepContext(false); + await provider.filter(filterContext, false, prop, '=', value); + return { filterContext, set: (await provider.executeFilters(filterContext))[0] }; + } + + test('modified = true: a valid expression is in', async () => { + const { filterContext, set } = await filterSet('modified', 'true'); + for (const expression of testData.validExpressions) { + const located = await provider.filterLocate(filterContext, set, expression); + expect(located).toBeInstanceOf(CPTExpression); + expect(await provider.code(located)).toBe(expression); + } + }); + + test('modified = true: a plain code is not in', async () => { + const { filterContext, set } = await filterSet('modified', 'true'); + expect(await provider.filterLocate(filterContext, set, testData.baseCodes[0])).toBeNull(); + }); + + test('modified = true: an expression that does not parse gets the reason', async () => { + const { filterContext, set } = await filterSet('modified', 'true'); + expect(await provider.filterLocate(filterContext, set, '99999:25')).toBe("Base CPT Code '99999' not found"); + expect(await provider.filterLocate(filterContext, set, '99202:99')).toBe("Modifier CPT code '99' not found"); + }); + + test.each([['modified', 'false'], ['modifier', 'true'], ['modifier', 'false']])('%s = %s: an expression is not in', async (prop, value) => { + const { filterContext, set } = await filterSet(prop, value); + expect(await provider.filterLocate(filterContext, set, testData.validExpressions[0])).toBeNull(); + }); + }); + describe('Iterator Support', () => { test('should iterate all codes', async () => { const iterator = await provider.iterator(null); diff --git a/tests/tx/validate-cpt-modified.test.js b/tests/tx/validate-cpt-modified.test.js new file mode 100644 index 000000000..f922d6a98 --- /dev/null +++ b/tests/tx/validate-cpt-modified.test.js @@ -0,0 +1,74 @@ +/** + * $validate-code of a CPT expression (a code with modifiers) against a value set with the + * filter modified = true (#486) + */ + +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { CPTServicesFactory } = require('../../tx/cs/cs-cpt'); + +const CPT = 'http://www.ama-assn.org/go/cpt'; + +describe('$validate-code of CPT expressions against modified = true (#486)', () => { + let app; + let factories; + let had; + let before; + + beforeAll(async () => { + app = await getTestApp(); + const factory = new CPTServicesFactory(getTxModule().i18n, path.join(__dirname, '..', '..', 'tx', 'data', 'cpt-fragment.db'), { readOnly: true }); + await factory.load(); + factories = getTxModule().endpoints[0].provider.codeSystemFactories; + had = factories.has(CPT); + before = factories.get(CPT); + factories.set(CPT, factory); + }, 60000); + + afterAll(async () => { + if (factories) { + if (had) { + factories.set(CPT, before); + } else { + factories.delete(CPT); + } + } + await shutdownTestApp(); + }); + + async function validate(code, modified = 'true') { + const res = await request(app) + .post('/tx/r5/ValueSet/$validate-code') + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [ + { system: CPT, filter: [{ property: 'modified', op: '=', value: modified }] }] } } }, + { name: 'system', valueUri: CPT }, + { name: 'code', valueCode: code } + ] }); + if (res.status !== 200) { + throw new Error('validate failed: ' + JSON.stringify(res.body)); + } + const p = (name) => (res.body.parameter || []).find(x => x.name === name); + return { result: p('result').valueBoolean, message: p('message') ? p('message').valueString : null }; + } + + test('an expression is in modified = true', async () => { + expect((await validate('99202:25')).result).toBe(true); + }); + + test('a plain code is not in modified = true', async () => { + expect((await validate('99202')).result).toBe(false); + }); + + test('an expression is not in modified = false', async () => { + expect((await validate('99202:25', 'false')).result).toBe(false); + }); + + test('an expression with an unknown modifier is not in, and says why', async () => { + const r = await validate('99202:99'); + expect(r.result).toBe(false); + expect(r.message).toContain("'99'"); + }); +}); diff --git a/tx/cs/cs-cpt.js b/tx/cs/cs-cpt.js index d7112afa1..db50179a6 100644 --- a/tx/cs/cs-cpt.js +++ b/tx/cs/cs-cpt.js @@ -557,6 +557,16 @@ class CPTServices extends BaseCSServices { if (concept) { return concept; } + if (!set.closed && code && code.includes(':')) { + // an open filter (modified = true) has expressions in it, which aren't listed: parse the + // code as one, and it's in if the filter takes it (#486). An expression that doesn't + // parse gets the reason + const located = this.#parse(code); + if (!located.context) { + return located.message; + } + return (await this.filterCheck(filterContext, set, located.context)) ? located.context : null; + } return null; } From cddc348346dbb0b8a5d7be32466f5d330fec82cc Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Mon, 7 Dec 2026 03:42:01 +1100 Subject: [PATCH 8/8] omop status fixes --- tests/cs/cs-omop.test.js | 18 +++-- tests/tx/omop-invalid-reason.test.js | 111 +++++++++++++++++++++++++++ tx/cs/cs-omop.js | 30 ++++++-- 3 files changed, 145 insertions(+), 14 deletions(-) create mode 100644 tests/tx/omop-invalid-reason.test.js diff --git a/tests/cs/cs-omop.test.js b/tests/cs/cs-omop.test.js index c2b582e17..0cf2a8a59 100644 --- a/tests/cs/cs-omop.test.js +++ b/tests/cs/cs-omop.test.js @@ -184,12 +184,18 @@ describe('OMOP Provider', () => { } }); - test('should return false for inactive/deprecated concepts', async () => { - if (testData.sampleConcepts.length > 0) { - const result = await provider.locate(testData.sampleConcepts[0]); - expect(await provider.isInactive(result.context)).toBe(false); - expect(await provider.isDeprecated(result.context)).toBe(false); - } + // in the fixture: 3000483 is valid, 40485492 has invalid_reason D, 44790758 has U + test.each([ + ['3000483', false], + ['40485492', true], + ['44790758', true] + ])('%s: inactive is %s (invalid_reason D or U, #475)', async (code, inactive) => { + const result = await provider.locate(code); + expect(result.context).not.toBeNull(); + expect(await provider.isInactive(result.context)).toBe(inactive); + expect(await provider.isInactive(code)).toBe(inactive); + expect(await provider.getStatus(result.context)).toBe(inactive ? 'inactive' : 'active'); + expect(await provider.isDeprecated(result.context)).toBe(false); }); test('should return empty definition', async () => { diff --git a/tests/tx/omop-invalid-reason.test.js b/tests/tx/omop-invalid-reason.test.js new file mode 100644 index 000000000..95861dbd2 --- /dev/null +++ b/tests/tx/omop-invalid-reason.test.js @@ -0,0 +1,111 @@ +/** + * OMOP concepts with invalid_reason D (deleted) or U (replaced by an update) are inactive (#475). + * In the fixture: 3000483 is valid, 40485492 has D, 44790758 has U + */ + +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { OMOPServicesFactory } = require('../../tx/cs/cs-omop'); + +const OMOP = 'https://fhir-terminology.ohdsi.org'; +const VALID = '3000483'; +const DELETED = '40485492'; +const UPDATED = '44790758'; + +describe('OMOP invalid_reason (#475)', () => { + let app; + let factory; + let factories; + let keys; + let previous; + + beforeAll(async () => { + app = await getTestApp(); + factory = new OMOPServicesFactory(getTxModule().i18n, path.join(__dirname, '..', '..', 'tx', 'data', 'omop-fragment.db'), { readOnly: true }); + await factory.load(); + factories = getTxModule().endpoints[0].provider.codeSystemFactories; + // the system and system|version, as the library registers a provider + keys = [OMOP, OMOP + '|' + factory.version()]; + previous = keys.map(k => [k, factories.has(k), factories.get(k)]); + for (const k of keys) { + factories.set(k, factory); + } + }, 60000); + + afterAll(async () => { + for (const [k, had, before] of previous || []) { + if (had) { + factories.set(k, before); + } else { + factories.delete(k); + } + } + if (factory && factory.close) { + await factory.close(); + } + await shutdownTestApp(); + }); + + async function post(op, parameter) { + const res = await request(app) + .post('/tx/r5/' + op) + .set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter }); + if (res.status !== 200) { + throw new Error(op + ' failed: ' + JSON.stringify(res.body)); + } + return res.body; + } + + const param = (body, name) => (body.parameter || []).find(p => p.name === name); + const property = (body, code) => (body.parameter || []).filter(p => p.name === 'property') + .map(p => Object.fromEntries(p.part.map(x => [x.name, x]))) + .find(p => p.code.valueCode === code); + + const valueSet = (inactive) => ({ resourceType: 'ValueSet', url: 'http://example.org/vs/p2', status: 'active', + compose: Object.assign(inactive === undefined ? {} : { inactive }, + { include: [{ system: OMOP, concept: [{ code: DELETED }, { code: UPDATED }, { code: VALID }] }] }) }); + + test.each([ + ['activeOnly', [{ name: 'activeOnly', valueBoolean: true }], undefined], + ['compose.inactive = false', [], false] + ])('$expand with %s: only the valid concept', async (name, extra, inactive) => { + const body = await post('ValueSet/$expand', [{ name: 'valueSet', resource: valueSet(inactive) }, ...extra]); + expect(body.expansion.total).toBe(1); + expect(body.expansion.contains.map(c => c.code)).toEqual([VALID]); + }); + + test('$expand without them: the invalid concepts are listed as inactive', async () => { + const body = await post('ValueSet/$expand', [{ name: 'valueSet', resource: valueSet() }]); + const byCode = Object.fromEntries(body.expansion.contains.map(c => [c.code, c])); + expect(byCode[DELETED].inactive).toBe(true); + expect(byCode[UPDATED].inactive).toBe(true); + expect(byCode[VALID].inactive).toBeUndefined(); + }); + + test.each([[DELETED, true], [UPDATED, true], [VALID, false]])('$lookup %s: inactive = %s', async (code, inactive) => { + const body = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: OMOP }, { name: 'code', valueCode: code }]); + expect(property(body, 'inactive').value.valueBoolean).toBe(inactive); + }); + + test.each([DELETED, UPDATED])('CodeSystem/$validate-code %s: valid, and says it is inactive', async (code) => { + const body = await post('CodeSystem/$validate-code', [{ name: 'url', valueUri: OMOP }, { name: 'code', valueCode: code }]); + expect(param(body, 'result').valueBoolean).toBe(true); + expect(param(body, 'inactive').valueBoolean).toBe(true); + }); + + test.each([ + ['activeOnly', [{ name: 'activeOnly', valueBoolean: true }], undefined], + ['compose.inactive = false', [], false] + ])('ValueSet/$validate-code with %s: the invalid concepts are not in', async (name, extra, inactive) => { + for (const code of [DELETED, UPDATED]) { + const body = await post('ValueSet/$validate-code', [{ name: 'valueSet', resource: valueSet(inactive) }, + { name: 'system', valueUri: OMOP }, { name: 'code', valueCode: code }, ...extra]); + expect(param(body, 'result').valueBoolean).toBe(false); + } + const body = await post('ValueSet/$validate-code', [{ name: 'valueSet', resource: valueSet(inactive) }, + { name: 'system', valueUri: OMOP }, { name: 'code', valueCode: VALID }, ...extra]); + expect(param(body, 'result').valueBoolean).toBe(true); + }); +}); diff --git a/tx/cs/cs-omop.js b/tx/cs/cs-omop.js index 8949ccbb5..33cf0e40b 100644 --- a/tx/cs/cs-omop.js +++ b/tx/cs/cs-omop.js @@ -8,13 +8,15 @@ const { SqliteDatabase, SqliteWorkerPool } = require('../../library/sql/node-sql const { Issue } = require('../library/operation-outcome'); class OMOPConcept { - constructor(code, display, domain, conceptClass, standard, vocabulary) { + constructor(code, display, domain, conceptClass, standard, vocabulary, invalidReason = null) { this.code = code; this.display = display; this.domain = domain; this.conceptClass = conceptClass; this.standard = standard || 'NS'; this.vocabulary = vocabulary; + // D (deleted) or U (replaced by an update): OMOP says the concept is invalid (#475) + this.invalidReason = invalidReason || null; } } @@ -184,9 +186,18 @@ class OMOPServices extends BaseCSServices { return false; // OMOP concepts are not abstract } + /** + * A concept is valid only while invalid_reason is empty: D (deleted) and U (replaced by an + * update) are inactive (#475) + */ async isInactive(context) { - await this.#ensureContext(context); - return false; // Handle via standard_concept if needed + const ctxt = await this.#ensureContext(context); + return !!(ctxt && ctxt.invalidReason); + } + + async getStatus(context) { + const ctxt = await this.#ensureContext(context); + return ctxt && ctxt.invalidReason ? 'inactive' : 'active'; } async isDeprecated(context) { @@ -460,7 +471,7 @@ class OMOPServices extends BaseCSServices { if (!code) return { context: null, message: 'Empty code' }; const sql = ` - SELECT concept_id, concept_name, standard_concept, + SELECT concept_id, concept_name, standard_concept, invalid_reason, Domains.domain_id, ConceptClasses.concept_class_id, Vocabularies.vocabulary_id FROM Concepts, Domains, ConceptClasses, Vocabularies @@ -478,7 +489,8 @@ class OMOPServices extends BaseCSServices { row.domain_id, row.concept_class_id, row.standard_concept || 'NS', - row.vocabulary_id + row.vocabulary_id, + row.invalid_reason ); return { context: concept, message: null }; } @@ -513,7 +525,7 @@ class OMOPServices extends BaseCSServices { if (prop === 'domain' && op === '=') { let sql = ` - SELECT concept_id, concept_name, domain_id + SELECT concept_id, concept_name, domain_id, invalid_reason FROM Concepts WHERE standard_concept = 'S' AND domain_id IN ( @@ -564,7 +576,8 @@ class OMOPServices extends BaseCSServices { row.domain_id, '', // concept_class not in basic filter query 'S', // standard_concept is 'S' by filter - '' // vocabulary not in basic filter query + '', // vocabulary not in basic filter query + row.invalid_reason ); } @@ -581,7 +594,8 @@ class OMOPServices extends BaseCSServices { row.domain_id, '', 'S', - '' + '', + row.invalid_reason ); } else { return `Code '${code}' is not in the value set`;