From 5ed26efafc1be02a70159491b4314d274694713f Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Thu, 3 Dec 2026 06:40:10 +1100 Subject: [PATCH 01/11] bring importers into line, and improve documentation --- CHANGELOG.md | 2 +- tests/tx/sqlite-v2-cli-options.test.js | 106 ++++++++++++++++++ .../import-loinc-v2-classic.module.js | 17 +-- tx/importers/import-loinc-v2.module.js | 15 +-- tx/importers/import-rxnorm-v2.module.js | 17 +-- tx/importers/import-sct-v2-cache.module.js | 13 ++- tx/importers/import-sct-v2.module.js | 17 +-- tx/importers/readme.md | 64 ++++++++++- tx/importers/sqlite-v2/cli-options.js | 86 ++++++++++++++ tx/sqlite-v2/README.md | 6 +- 10 files changed, 303 insertions(+), 40 deletions(-) create mode 100644 tests/tx/sqlite-v2-cli-options.test.js create mode 100644 tx/importers/sqlite-v2/cli-options.js diff --git a/CHANGELOG.md b/CHANGELOG.md index f3507a1b0..72f7bb60b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- +- 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 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..230623d41 --- /dev/null +++ b/tests/tx/sqlite-v2-cli-options.test.js @@ -0,0 +1,106 @@ +/** + * 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('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/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..c9cee46f9 --- /dev/null +++ b/tx/importers/sqlite-v2/cli-options.js @@ -0,0 +1,86 @@ +/** + * 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) => { + try { + await fn(o); + } catch (error) { + module.logError(`${module.getName()} import failed: ${error.message}`); + if (o.verbose) { + console.error(error.stack); + } + process.exitCode = 1; + } + }; +} + +/** + * 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/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. From a57bd37bd2b934c6d0e51a8e930dd3323be1f93f Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Thu, 3 Dec 2026 11:12:10 +1100 Subject: [PATCH 02/11] fix bug handling --verbose on import --- CHANGELOG.md | 1 + library/server/daily-report.js | 1 + rest/endpoint/endpoint.js | 8 +++- rest/rest.js | 56 +++++++++++++++++++++++ shl/shl.js | 2 +- tests/server/module-daily-reports.test.js | 20 ++++++++ tests/tx/sqlite-v2-cli-options.test.js | 18 ++++++++ tx/importers/sqlite-v2/cli-options.js | 19 +++++++- tx/vs/vs-database.js | 2 +- 9 files changed, 122 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f7bb60b..660ac9737 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,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/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/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/sqlite-v2-cli-options.test.js b/tests/tx/sqlite-v2-cli-options.test.js index 230623d41..40a73a578 100644 --- a/tests/tx/sqlite-v2-cli-options.test.js +++ b/tests/tx/sqlite-v2-cli-options.test.js @@ -93,6 +93,24 @@ describe('sqlite-v2 importer options', () => { } }); + 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); diff --git a/tx/importers/sqlite-v2/cli-options.js b/tx/importers/sqlite-v2/cli-options.js index c9cee46f9..8c6d3062a 100644 --- a/tx/importers/sqlite-v2/cli-options.js +++ b/tx/importers/sqlite-v2/cli-options.js @@ -40,12 +40,12 @@ function addCommonOptions(cmd, version) { * @returns {function(Object): Promise} */ function importAction(module, fn) { - return async (o) => { + return async (o, cmd) => { try { await fn(o); } catch (error) { module.logError(`${module.getName()} import failed: ${error.message}`); - if (o.verbose) { + if (verboseOf(o, cmd)) { console.error(error.stack); } process.exitCode = 1; @@ -53,6 +53,21 @@ function importAction(module, fn) { }; } +/** + * 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 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'); From 06fc06f708e640982e3a1a9adc311aa860e61658 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Fri, 4 Dec 2026 05:55:57 +1100 Subject: [PATCH 03/11] rework VCL parser for correctness and add many test cases --- tests/vcl/vcl-parser.test.js | 31 +- tests/vcl/vcl-test-cases.test.js | 43 + tests/vcl/vcl.test.js | 95 +- vcl/vcl-parser.js | 1472 ++++++++++++++---------------- vcl/vcl.js | 85 +- 5 files changed, 827 insertions(+), 899 deletions(-) create mode 100644 tests/vcl/vcl-test-cases.test.js diff --git a/tests/vcl/vcl-parser.test.js b/tests/vcl/vcl-parser.test.js index 87999808e..097c1f448 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', () => { @@ -489,15 +482,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..32675ba22 100644 --- a/tests/vcl/vcl.test.js +++ b/tests/vcl/vcl.test.js @@ -1,16 +1,93 @@ +/** + * 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('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/vcl/vcl-parser.js b/vcl/vcl-parser.js index e0017d952..81f34cb2c 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); + return first; } - 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 - } - - 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); + throw new VCLParseException(`The expression nests more than ${MAX_VCL_DEPTH} levels deep`, open.position); } - - if (this.isSimpleCodeList()) { - this.parseSimpleCodeList(systemUri, isExclusion); - } else { - this.parseExprWithinParentheses(isExclusion); - } - - // 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); + } + + // ---- the compose ------------------------------------------------------------------------- - conceptSet.valueSet.push(uri); + 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() === '') { 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 +914,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 +956,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..d77099650 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 = [ - /