@aehrc/ecl-core 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -12
- package/dist/derive/compress-expression.d.ts +2 -0
- package/dist/derive/compress-expression.d.ts.map +1 -1
- package/dist/derive/critique.d.ts +17 -0
- package/dist/derive/critique.d.ts.map +1 -1
- package/dist/derive/derive-ecl.d.ts +78 -3
- package/dist/derive/derive-ecl.d.ts.map +1 -1
- package/dist/derive/refinements.d.ts +1 -1
- package/dist/derive/refinements.d.ts.map +1 -1
- package/dist/derive/set-queries.d.ts +77 -1
- package/dist/derive/set-queries.d.ts.map +1 -1
- package/dist/derive/taxonomy-graph.d.ts +58 -0
- package/dist/derive/taxonomy-graph.d.ts.map +1 -1
- package/dist/index.cjs +1379 -150
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +1378 -151
- package/dist/minify/minify.d.ts +34 -0
- package/dist/minify/minify.d.ts.map +1 -0
- package/dist/parser/index.d.ts +14 -0
- package/dist/parser/index.d.ts.map +1 -1
- package/dist/terminology/fhir-service.d.ts +49 -0
- package/dist/terminology/fhir-service.d.ts.map +1 -1
- package/dist/terminology/types.d.ts +26 -0
- package/dist/terminology/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -42419,8 +42419,9 @@ function runParseAttempt(input, predictionMode) {
|
|
|
42419
42419
|
parser.removeErrorListeners();
|
|
42420
42420
|
parser.addErrorListener(errorListener);
|
|
42421
42421
|
let ast = null;
|
|
42422
|
+
let tree = null;
|
|
42422
42423
|
try {
|
|
42423
|
-
|
|
42424
|
+
tree = parser.expressionconstraint();
|
|
42424
42425
|
ast = new ECLASTVisitor().visit(tree);
|
|
42425
42426
|
const currentToken = parser.currentToken;
|
|
42426
42427
|
if (currentToken.type !== import_antlr4ts.Token.EOF) {
|
|
@@ -42437,7 +42438,8 @@ function runParseAttempt(input, predictionMode) {
|
|
|
42437
42438
|
} catch {}
|
|
42438
42439
|
return {
|
|
42439
42440
|
ast,
|
|
42440
|
-
errors: errorListener.getErrors()
|
|
42441
|
+
errors: errorListener.getErrors(),
|
|
42442
|
+
tree
|
|
42441
42443
|
};
|
|
42442
42444
|
}
|
|
42443
42445
|
/**
|
|
@@ -42461,6 +42463,22 @@ function parseWithFallback(input) {
|
|
|
42461
42463
|
if (sll.ast !== null && sll.errors.length === 0) return sll;
|
|
42462
42464
|
return runParseAttempt(input, import_PredictionMode.PredictionMode.LL);
|
|
42463
42465
|
}
|
|
42466
|
+
/**
|
|
42467
|
+
* Parses `input` and returns the ANTLR parse tree, which keeps every character
|
|
42468
|
+
* of the source: whitespace, comments and display terms included. The AST from
|
|
42469
|
+
* `parseECL` drops these, so code that rewrites the source text exactly (such as
|
|
42470
|
+
* the minifier) walks this tree instead.
|
|
42471
|
+
*
|
|
42472
|
+
* Uses the same SLL-then-LL strategy as `parseECL`. `errors` are ANTLR's raw
|
|
42473
|
+
* messages; call `parseECL` for the clearer ones shown to users.
|
|
42474
|
+
*/
|
|
42475
|
+
function parseConcreteTree(input) {
|
|
42476
|
+
const { tree, errors } = parseWithFallback(input);
|
|
42477
|
+
return {
|
|
42478
|
+
tree,
|
|
42479
|
+
errors
|
|
42480
|
+
};
|
|
42481
|
+
}
|
|
42464
42482
|
function parseECL(input) {
|
|
42465
42483
|
if (input === lastInput && lastResult !== null) return lastResult;
|
|
42466
42484
|
const tokenLexer = new ECLLexer(new import_antlr4ts.ANTLRInputStream(input));
|
|
@@ -43238,6 +43256,8 @@ function toHttpError(options) {
|
|
|
43238
43256
|
return new TerminologyHttpError(`Terminology server returned HTTP ${options.status} for ${options.operation}${suffix}`, options);
|
|
43239
43257
|
}
|
|
43240
43258
|
// src/terminology/fhir-service.ts
|
|
43259
|
+
/** SNOMED CT's description type for a fully specified name. */
|
|
43260
|
+
var FSN_TYPE = "900000000000003001";
|
|
43241
43261
|
/** URL of the R5 `ValueSet.expansion.contains.property` element as an R4 extension. */
|
|
43242
43262
|
var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/extension-ValueSet.expansion.contains.property";
|
|
43243
43263
|
/**
|
|
@@ -43245,23 +43265,53 @@ var CONTAINS_PROPERTY_EXTENSION = "http://hl7.org/fhir/5.0/StructureDefinition/e
|
|
|
43245
43265
|
* extension form; undefined when the server sent no parent property at all.
|
|
43246
43266
|
*/
|
|
43247
43267
|
function parentCodes(item) {
|
|
43268
|
+
return propertyCodes(item, "parent");
|
|
43269
|
+
}
|
|
43270
|
+
/** One boolean property of an expansion entry, from R5 `property` or its R4 extension form; undefined when absent. */
|
|
43271
|
+
function propertyBoolean(item, code) {
|
|
43272
|
+
const direct = item.property?.find((p) => p.code === code && typeof p.valueBoolean === "boolean");
|
|
43273
|
+
if (direct) return direct.valueBoolean;
|
|
43274
|
+
for (const ext of item.extension ?? []) {
|
|
43275
|
+
if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
|
|
43276
|
+
const parts = ext.extension ?? [];
|
|
43277
|
+
if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
|
|
43278
|
+
const value = parts.find((x) => x.url === "value")?.valueBoolean;
|
|
43279
|
+
if (typeof value === "boolean") return value;
|
|
43280
|
+
}
|
|
43281
|
+
}
|
|
43282
|
+
/** The codes of one coded property of an expansion entry, or undefined when the entry has none. */
|
|
43283
|
+
function propertyCodes(item, code) {
|
|
43248
43284
|
const codes = [];
|
|
43249
43285
|
let seen = false;
|
|
43250
43286
|
for (const p of item.property ?? []) {
|
|
43251
|
-
if (p.code !==
|
|
43287
|
+
if (p.code !== code) continue;
|
|
43252
43288
|
seen = true;
|
|
43253
43289
|
if (p.valueCode) codes.push(p.valueCode);
|
|
43254
43290
|
}
|
|
43255
43291
|
for (const ext of item.extension ?? []) {
|
|
43256
43292
|
if (ext.url !== CONTAINS_PROPERTY_EXTENSION) continue;
|
|
43257
43293
|
const parts = ext.extension ?? [];
|
|
43258
|
-
if (parts.find((x) => x.url === "code")?.valueCode !==
|
|
43294
|
+
if (parts.find((x) => x.url === "code")?.valueCode !== code) continue;
|
|
43259
43295
|
seen = true;
|
|
43260
43296
|
const value = parts.find((x) => x.url === "value")?.valueCode;
|
|
43261
43297
|
if (value) codes.push(value);
|
|
43262
43298
|
}
|
|
43263
43299
|
return seen ? codes : void 0;
|
|
43264
43300
|
}
|
|
43301
|
+
var conceptListCache = /* @__PURE__ */ new WeakMap();
|
|
43302
|
+
/**
|
|
43303
|
+
* `[{"code": ...}, ...]` for a compose's `concept`. Cached for the life of the
|
|
43304
|
+
* list only when the array is frozen, so the text cannot go stale: derive
|
|
43305
|
+
* freezes its member list, which it sends with every comparison, and any other
|
|
43306
|
+
* caller's array is built afresh each time.
|
|
43307
|
+
*/
|
|
43308
|
+
function conceptListJson(codes) {
|
|
43309
|
+
const cached = conceptListCache.get(codes);
|
|
43310
|
+
if (cached !== void 0) return cached;
|
|
43311
|
+
const json = "[" + codes.map((code) => "{\"code\":" + JSON.stringify(code) + "}").join(",") + "]";
|
|
43312
|
+
if (Object.isFrozen(codes)) conceptListCache.set(codes, json);
|
|
43313
|
+
return json;
|
|
43314
|
+
}
|
|
43265
43315
|
var DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
|
|
43266
43316
|
/** True when running in a browser environment. */
|
|
43267
43317
|
var IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
|
|
@@ -43293,8 +43343,33 @@ var ConcurrencyQueue = class {
|
|
|
43293
43343
|
};
|
|
43294
43344
|
var RETRY_BASE_DELAY_MS = 500;
|
|
43295
43345
|
var RETRY_MAX_DELAY_MS = 1e4;
|
|
43296
|
-
var RETRY_MAX_ATTEMPTS = 3;
|
|
43297
43346
|
var RETRY_JITTER_MS = 200;
|
|
43347
|
+
/** Default for {@link FhirTerminologyServiceOptions.rateLimitWaitMs}. */
|
|
43348
|
+
var DEFAULT_RATE_LIMIT_WAIT_MS = 6e4;
|
|
43349
|
+
/**
|
|
43350
|
+
* Milliseconds until the server says requests may resume, from `Retry-After`
|
|
43351
|
+
* (seconds or an HTTP date) or `x-ratelimit-reset` (seconds from now, or an
|
|
43352
|
+
* epoch time in seconds), whichever is later; 0 when it says neither.
|
|
43353
|
+
*/
|
|
43354
|
+
/** `x-ratelimit-remaining`, when the server sends it. */
|
|
43355
|
+
function remainingRequests(headers) {
|
|
43356
|
+
const value = headers.get("x-ratelimit-remaining")?.trim();
|
|
43357
|
+
if (!value) return void 0;
|
|
43358
|
+
const n = Number(value);
|
|
43359
|
+
return Number.isFinite(n) && n >= 0 ? n : void 0;
|
|
43360
|
+
}
|
|
43361
|
+
function serverResetMs(headers, now) {
|
|
43362
|
+
let ms = 0;
|
|
43363
|
+
const retryAfter = headers.get("Retry-After")?.trim();
|
|
43364
|
+
if (retryAfter) {
|
|
43365
|
+
const seconds = Number(retryAfter);
|
|
43366
|
+
const at = Number.isFinite(seconds) ? now + seconds * 1e3 : Date.parse(retryAfter);
|
|
43367
|
+
if (Number.isFinite(at)) ms = Math.max(ms, at - now);
|
|
43368
|
+
}
|
|
43369
|
+
const reset = Number(headers.get("x-ratelimit-reset"));
|
|
43370
|
+
if (Number.isFinite(reset) && reset > 0) ms = Math.max(ms, reset > 1e9 ? reset * 1e3 - now : reset * 1e3);
|
|
43371
|
+
return Math.max(0, ms);
|
|
43372
|
+
}
|
|
43298
43373
|
/**
|
|
43299
43374
|
* Characters that carry structural meaning inside the *canonical* implicit ValueSet URL
|
|
43300
43375
|
* (`http://snomed.info/sct?fhir_vs=ecl/<expression>`) and must therefore be percent-encoded
|
|
@@ -43371,10 +43446,26 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43371
43446
|
*/
|
|
43372
43447
|
bulkExpandUnsupported = false;
|
|
43373
43448
|
queue;
|
|
43449
|
+
rateLimitWaitMs;
|
|
43450
|
+
/** No request is sent before this time: the server said its rate limit is spent until then. */
|
|
43451
|
+
pausedUntil = 0;
|
|
43452
|
+
/**
|
|
43453
|
+
* Requests held by the rate limit, oldest first (a retry goes back to the
|
|
43454
|
+
* front). When a pause ends they do not all go at once, which would meet
|
|
43455
|
+
* one success and a storm of 429s: one goes first (the probe), and its
|
|
43456
|
+
* response says how many more the server has room for.
|
|
43457
|
+
*/
|
|
43458
|
+
held = [];
|
|
43459
|
+
/** A probe is in flight: the others wait for its answer. */
|
|
43460
|
+
probing = false;
|
|
43461
|
+
/** Requests sent and not yet answered, so `x-ratelimit-remaining` is not spent twice. */
|
|
43462
|
+
unanswered = 0;
|
|
43463
|
+
wakeTimer;
|
|
43374
43464
|
constructor(options = {}) {
|
|
43375
43465
|
const maxConcurrency = options.maxConcurrency ?? 25;
|
|
43376
43466
|
if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
|
|
43377
43467
|
this.queue = new ConcurrencyQueue(maxConcurrency);
|
|
43468
|
+
this.rateLimitWaitMs = options.rateLimitWaitMs ?? DEFAULT_RATE_LIMIT_WAIT_MS;
|
|
43378
43469
|
this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
|
|
43379
43470
|
this.timeout = options.timeout ?? 2e3;
|
|
43380
43471
|
this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
|
|
@@ -43552,18 +43643,74 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43552
43643
|
* status that is not an "unknown code" response.
|
|
43553
43644
|
*/
|
|
43554
43645
|
async fetchWithRetry(url, timeoutMs, init) {
|
|
43555
|
-
|
|
43556
|
-
|
|
43557
|
-
|
|
43558
|
-
|
|
43559
|
-
|
|
43560
|
-
|
|
43561
|
-
|
|
43646
|
+
const started = Date.now();
|
|
43647
|
+
for (let attempt = 1;; attempt++) {
|
|
43648
|
+
const probe = await this.waitForRateLimit(attempt > 1);
|
|
43649
|
+
this.unanswered++;
|
|
43650
|
+
let response;
|
|
43651
|
+
try {
|
|
43652
|
+
response = await this.fetchWithTimeout(url, timeoutMs, init);
|
|
43653
|
+
} catch (error) {
|
|
43654
|
+
this.release(probe, 0);
|
|
43655
|
+
throw error;
|
|
43656
|
+
}
|
|
43657
|
+
const now = Date.now();
|
|
43658
|
+
const resetMs = serverResetMs(response.headers, now);
|
|
43659
|
+
const remaining = remainingRequests(response.headers);
|
|
43660
|
+
if (response.status !== 429) {
|
|
43661
|
+
if (remaining === 0 && resetMs > 0) this.pauseUntil(now + resetMs);
|
|
43662
|
+
this.release(probe, remaining ?? Infinity);
|
|
43663
|
+
return response;
|
|
43664
|
+
}
|
|
43665
|
+
const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1), RETRY_MAX_DELAY_MS);
|
|
43562
43666
|
const jitter = Math.random() * RETRY_JITTER_MS;
|
|
43563
|
-
const waitMs =
|
|
43564
|
-
|
|
43667
|
+
const waitMs = (resetMs > 0 ? resetMs : backoff) + jitter;
|
|
43668
|
+
this.pauseUntil(now + waitMs);
|
|
43669
|
+
this.release(probe, 0);
|
|
43670
|
+
if (now + waitMs - started > this.rateLimitWaitMs) throw new Error(`FHIR request rate-limited after ${attempt} attempts over ${Math.round((now - started) / 1e3)} s`);
|
|
43565
43671
|
}
|
|
43566
|
-
|
|
43672
|
+
}
|
|
43673
|
+
pauseUntil(time) {
|
|
43674
|
+
this.pausedUntil = Math.max(this.pausedUntil, time);
|
|
43675
|
+
this.schedule();
|
|
43676
|
+
}
|
|
43677
|
+
/**
|
|
43678
|
+
* Go now, or wait in line while the rate limit is spent or other requests
|
|
43679
|
+
* are held; true when this request is the probe. A retry waits at the front.
|
|
43680
|
+
*/
|
|
43681
|
+
waitForRateLimit(retry) {
|
|
43682
|
+
if (!retry && !this.probing && this.held.length === 0 && Date.now() >= this.pausedUntil) return Promise.resolve(false);
|
|
43683
|
+
return new Promise((resolve) => {
|
|
43684
|
+
if (retry) this.held.unshift(resolve);
|
|
43685
|
+
else this.held.push(resolve);
|
|
43686
|
+
this.schedule();
|
|
43687
|
+
});
|
|
43688
|
+
}
|
|
43689
|
+
/** When the pause ends, send the oldest held request alone, as the probe. */
|
|
43690
|
+
schedule() {
|
|
43691
|
+
if (this.wakeTimer !== void 0 || this.probing || this.held.length === 0) return;
|
|
43692
|
+
this.wakeTimer = setTimeout(() => {
|
|
43693
|
+
this.wakeTimer = void 0;
|
|
43694
|
+
if (Date.now() < this.pausedUntil) {
|
|
43695
|
+
this.schedule();
|
|
43696
|
+
return;
|
|
43697
|
+
}
|
|
43698
|
+
const next = this.held.shift();
|
|
43699
|
+
if (!next) return;
|
|
43700
|
+
this.probing = true;
|
|
43701
|
+
next(true);
|
|
43702
|
+
}, Math.max(0, this.pausedUntil - Date.now()));
|
|
43703
|
+
}
|
|
43704
|
+
/**
|
|
43705
|
+
* A request's answer: if it was the probe, the next may go; while no pause
|
|
43706
|
+
* is set, let as many held requests go as the server has room for
|
|
43707
|
+
* (`remaining`), oldest first, and probe again for the rest.
|
|
43708
|
+
*/
|
|
43709
|
+
release(probe, room) {
|
|
43710
|
+
this.unanswered--;
|
|
43711
|
+
if (probe) this.probing = false;
|
|
43712
|
+
if (Date.now() >= this.pausedUntil) for (let n = room - this.unanswered; n > 0 && this.held.length > 0; n--) this.held.shift()?.(false);
|
|
43713
|
+
this.schedule();
|
|
43567
43714
|
}
|
|
43568
43715
|
fetchQueued(url, timeoutMs, init) {
|
|
43569
43716
|
return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
|
|
@@ -43607,7 +43754,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43607
43754
|
}
|
|
43608
43755
|
const conceptInfo = {
|
|
43609
43756
|
id: conceptId,
|
|
43610
|
-
fsn: display,
|
|
43757
|
+
fsn: params.filter((p) => p.name === "designation").find((p) => p.part?.some((q) => q.name === "use" && q.valueCoding?.code === FSN_TYPE))?.part?.find((q) => q.name === "value")?.valueString ?? display,
|
|
43611
43758
|
pt: display,
|
|
43612
43759
|
active
|
|
43613
43760
|
};
|
|
@@ -43728,7 +43875,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43728
43875
|
}));
|
|
43729
43876
|
}
|
|
43730
43877
|
async bulkExpand(conceptIds) {
|
|
43731
|
-
const url = `${this.baseUrl}/ValueSet/$expand?property=inactive&activeOnly=false`;
|
|
43878
|
+
const url = `${this.baseUrl}/ValueSet/$expand?property=inactive&activeOnly=false&includeDesignations=true`;
|
|
43732
43879
|
const include = {
|
|
43733
43880
|
system: "http://snomed.info/sct",
|
|
43734
43881
|
concept: conceptIds.map((code) => ({ code }))
|
|
@@ -43767,7 +43914,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43767
43914
|
else if ((entry.property ?? []).find((p) => p.code === "inactive")?.valueBoolean === true) active = false;
|
|
43768
43915
|
results.set(code, {
|
|
43769
43916
|
id: code,
|
|
43770
|
-
fsn: display,
|
|
43917
|
+
fsn: entry.designation?.find((d) => d.use?.code === FSN_TYPE)?.value ?? display,
|
|
43771
43918
|
pt: display,
|
|
43772
43919
|
active
|
|
43773
43920
|
});
|
|
@@ -43923,6 +44070,53 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43923
44070
|
const data = await response.json();
|
|
43924
44071
|
return FhirTerminologyService.relationshipsOf(data.parameter ?? []);
|
|
43925
44072
|
}
|
|
44073
|
+
/**
|
|
44074
|
+
* Many `$lookup`s in one FHIR batch Bundle, so a sample of relationships
|
|
44075
|
+
* costs one request against the rate limit rather than one per concept.
|
|
44076
|
+
*/
|
|
44077
|
+
async getDefiningRelationshipsMany(conceptIds) {
|
|
44078
|
+
const version = this.snomedVersion ? `&version=${encodeURIComponent(this.snomedVersion)}` : "";
|
|
44079
|
+
const body = {
|
|
44080
|
+
resourceType: "Bundle",
|
|
44081
|
+
type: "batch",
|
|
44082
|
+
entry: conceptIds.map((id) => ({ request: {
|
|
44083
|
+
method: "GET",
|
|
44084
|
+
url: `CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(id)}&property=*${version}`
|
|
44085
|
+
} }))
|
|
44086
|
+
};
|
|
44087
|
+
const operation = `batch $lookup of the relationships of ${conceptIds.length} concepts`;
|
|
44088
|
+
const url = this.baseUrl;
|
|
44089
|
+
const response = await this.request(url, this.timeout * Math.max(1, conceptIds.length), operation, {
|
|
44090
|
+
method: "POST",
|
|
44091
|
+
headers: {
|
|
44092
|
+
"Content-Type": "application/fhir+json",
|
|
44093
|
+
Accept: "application/fhir+json"
|
|
44094
|
+
},
|
|
44095
|
+
body: JSON.stringify(body)
|
|
44096
|
+
});
|
|
44097
|
+
if (!response.ok) {
|
|
44098
|
+
const { detail } = await FhirTerminologyService.readErrorBody(response);
|
|
44099
|
+
throw toHttpError({
|
|
44100
|
+
status: response.status,
|
|
44101
|
+
statusText: response.statusText,
|
|
44102
|
+
url,
|
|
44103
|
+
operation,
|
|
44104
|
+
detail
|
|
44105
|
+
});
|
|
44106
|
+
}
|
|
44107
|
+
const data = await response.json();
|
|
44108
|
+
return conceptIds.map((id, i) => FhirTerminologyService.batchRelationships(id, data.entry?.[i]));
|
|
44109
|
+
}
|
|
44110
|
+
/** One batch entry's relationships: null for an unknown code, an Error for any other failure. */
|
|
44111
|
+
static batchRelationships(id, entry) {
|
|
44112
|
+
const status = Number.parseInt(entry?.response?.status ?? "", 10);
|
|
44113
|
+
const resource = entry?.resource;
|
|
44114
|
+
let answer;
|
|
44115
|
+
if (status >= 200 && status < 300 && resource?.resourceType === "Parameters") answer = FhirTerminologyService.relationshipsOf(resource.parameter ?? []);
|
|
44116
|
+
else if (FhirTerminologyService.isUnknownCodeResponse(status, resource?.resourceType === "OperationOutcome" ? resource : null)) answer = null;
|
|
44117
|
+
else answer = /* @__PURE__ */ new Error(`$lookup of ${id} in a batch answered ${entry?.response?.status ?? "nothing"}`);
|
|
44118
|
+
return answer;
|
|
44119
|
+
}
|
|
43926
44120
|
/** The relationships in a `$lookup` response's `property` parameters; role groups are numbered from 1. */
|
|
43927
44121
|
static relationshipsOf(parameters) {
|
|
43928
44122
|
const partValue = (parts, name) => FhirTerminologyService.eclValue(parts?.find((p) => p.name === name));
|
|
@@ -43970,24 +44164,22 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43970
44164
|
* @throws {TerminologyHttpError} when the server answered with an error status.
|
|
43971
44165
|
*/
|
|
43972
44166
|
async expandCompose(compose, options = {}) {
|
|
43973
|
-
const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false } = options;
|
|
43974
|
-
const
|
|
44167
|
+
const { count = 0, offset = 0, activeOnly = true, timeoutMs = 6e4, parents = false, children = false, activity = false } = options;
|
|
44168
|
+
const system = {
|
|
43975
44169
|
system: "http://snomed.info/sct",
|
|
43976
|
-
...this.snomedVersion ? { version: this.snomedVersion } : {}
|
|
43977
|
-
|
|
44170
|
+
...this.snomedVersion ? { version: this.snomedVersion } : {}
|
|
44171
|
+
};
|
|
44172
|
+
const toInclude = (clause) => "ecl" in clause ? JSON.stringify({
|
|
44173
|
+
...system,
|
|
44174
|
+
filter: [{
|
|
43978
44175
|
property: "constraint",
|
|
43979
44176
|
op: "=",
|
|
43980
44177
|
value: clause.ecl
|
|
43981
|
-
}]
|
|
43982
|
-
})
|
|
43983
|
-
const
|
|
43984
|
-
|
|
43985
|
-
|
|
43986
|
-
include: compose.include.map(toInclude),
|
|
43987
|
-
...compose.exclude?.length ? { exclude: compose.exclude.map(toInclude) } : {}
|
|
43988
|
-
}
|
|
43989
|
-
};
|
|
43990
|
-
const property = parents ? "&property=parent" : "";
|
|
44178
|
+
}]
|
|
44179
|
+
}) : `${JSON.stringify(system).slice(0, -1)},"concept":${conceptListJson(clause.concepts)}}`;
|
|
44180
|
+
const exclude = compose.exclude?.length ? `,"exclude":[${compose.exclude.map(toInclude).join(",")}]` : "";
|
|
44181
|
+
const body = `{"resourceType":"ValueSet","compose":{"include":[${compose.include.map(toInclude).join(",")}]${exclude}}}`;
|
|
44182
|
+
const property = (parents ? "&property=parent" : "") + (children ? "&property=child" : "") + (activity ? "&property=inactive" : "");
|
|
43991
44183
|
const url = `${this.baseUrl}/ValueSet/$expand?count=${count}&offset=${offset}&activeOnly=${activeOnly}${property}`;
|
|
43992
44184
|
const operation = "POST ValueSet/$expand of an inline compose";
|
|
43993
44185
|
const response = await this.request(url, timeoutMs, operation, {
|
|
@@ -43996,7 +44188,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
43996
44188
|
"Content-Type": "application/fhir+json",
|
|
43997
44189
|
Accept: "application/fhir+json"
|
|
43998
44190
|
},
|
|
43999
|
-
body
|
|
44191
|
+
body
|
|
44000
44192
|
});
|
|
44001
44193
|
if (!response.ok) {
|
|
44002
44194
|
const { detail } = await FhirTerminologyService.readErrorBody(response);
|
|
@@ -44014,6 +44206,13 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44014
44206
|
const found = parentCodes(item);
|
|
44015
44207
|
if (found) result.concepts[i].parents = found;
|
|
44016
44208
|
});
|
|
44209
|
+
if (activity) (data.expansion?.contains ?? []).forEach((item, i) => {
|
|
44210
|
+
const stated = item.inactive === true ? true : propertyBoolean(item, "inactive");
|
|
44211
|
+
if (stated !== void 0) result.concepts[i].inactive = stated;
|
|
44212
|
+
});
|
|
44213
|
+
if (children) (data.expansion?.contains ?? []).forEach((item, i) => {
|
|
44214
|
+
result.concepts[i].children = propertyCodes(item, "child") ?? [];
|
|
44215
|
+
});
|
|
44017
44216
|
return result;
|
|
44018
44217
|
}
|
|
44019
44218
|
/**
|
|
@@ -44049,7 +44248,8 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44049
44248
|
const total = typeof expansion.total === "number" ? expansion.total : 0;
|
|
44050
44249
|
const concepts = (expansion.contains ?? []).map((item) => ({
|
|
44051
44250
|
code: item.code ?? "",
|
|
44052
|
-
display: item.display ?? ""
|
|
44251
|
+
display: item.display ?? "",
|
|
44252
|
+
...item.inactive === true ? { inactive: true } : {}
|
|
44053
44253
|
}));
|
|
44054
44254
|
return {
|
|
44055
44255
|
total,
|
|
@@ -44086,7 +44286,7 @@ var FhirTerminologyService = class FhirTerminologyService {
|
|
|
44086
44286
|
return {
|
|
44087
44287
|
results: contains.slice(0, 20).map((item) => {
|
|
44088
44288
|
const display = item.display ?? "";
|
|
44089
|
-
const fsnDesignation = item.designation?.find((d) => d.use?.code ===
|
|
44289
|
+
const fsnDesignation = item.designation?.find((d) => d.use?.code === FSN_TYPE);
|
|
44090
44290
|
return {
|
|
44091
44291
|
id: item.code ?? "",
|
|
44092
44292
|
fsn: fsnDesignation?.value ?? display,
|
|
@@ -48436,6 +48636,12 @@ function compareExpressions(a, b) {
|
|
|
48436
48636
|
var SNOMED_ROOT = "138875005";
|
|
48437
48637
|
/** Ontoserver returns at most this many concepts per page, whatever `count` asks for. */
|
|
48438
48638
|
var PAGE_SIZE = 5e4;
|
|
48639
|
+
/**
|
|
48640
|
+
* Codes per request when looking concepts up by code. The server's cost grows
|
|
48641
|
+
* with the codes in a request, and is paid again for every page of it, so a
|
|
48642
|
+
* long list costs least as many small requests rather than one paged one.
|
|
48643
|
+
*/
|
|
48644
|
+
var LOOKUP_CHUNK = 1e4;
|
|
48439
48645
|
/** Numeric order for SCTIDs, so output does not depend on input or server order. */
|
|
48440
48646
|
function byId(a, b) {
|
|
48441
48647
|
return a.length - b.length || compareText(a, b);
|
|
@@ -48460,15 +48666,92 @@ function countClauses(ecl) {
|
|
|
48460
48666
|
return ecl.match(/\b\d{6,18}\b/g)?.length ?? 0;
|
|
48461
48667
|
}
|
|
48462
48668
|
/**
|
|
48669
|
+
* `terminology`, counting the requests that fail because of the server: it
|
|
48670
|
+
* could not be reached, timed out, was rate-limited or answered 5xx. A 4xx
|
|
48671
|
+
* other than 429 is about the request, not the server, and is not counted.
|
|
48672
|
+
* Derive drops what a failed request was for and goes on, so this count is
|
|
48673
|
+
* what tells a degraded result from a complete one.
|
|
48674
|
+
*/
|
|
48675
|
+
var UNCOUNTED = Symbol("uncounted");
|
|
48676
|
+
/**
|
|
48677
|
+
* The service behind a {@link countingFailures} wrapper (or `terminology`
|
|
48678
|
+
* itself), for a request whose failure the caller recovers from by other
|
|
48679
|
+
* requests, which are counted: a failure there loses nothing, so it must not
|
|
48680
|
+
* mark the result incomplete.
|
|
48681
|
+
*/
|
|
48682
|
+
function uncounted(terminology) {
|
|
48683
|
+
return terminology[UNCOUNTED] ?? terminology;
|
|
48684
|
+
}
|
|
48685
|
+
function countingFailures(terminology) {
|
|
48686
|
+
let count = 0;
|
|
48687
|
+
const counted = (error) => {
|
|
48688
|
+
if (!(isTerminologyHttpError(error) && error.status >= 400 && error.status < 500 && error.status !== 429)) count++;
|
|
48689
|
+
throw error;
|
|
48690
|
+
};
|
|
48691
|
+
return {
|
|
48692
|
+
service: new Proxy(terminology, { get(target, prop, receiver) {
|
|
48693
|
+
if (prop === UNCOUNTED) return uncounted(target);
|
|
48694
|
+
const value = Reflect.get(target, prop, receiver);
|
|
48695
|
+
if (typeof value !== "function") return value;
|
|
48696
|
+
return (...args) => {
|
|
48697
|
+
const out = value.apply(target, args);
|
|
48698
|
+
return out instanceof Promise ? out.catch(counted) : out;
|
|
48699
|
+
};
|
|
48700
|
+
} }),
|
|
48701
|
+
failures: () => count
|
|
48702
|
+
};
|
|
48703
|
+
}
|
|
48704
|
+
/**
|
|
48463
48705
|
* Set queries against the server. At most {@link MAX_IN_FLIGHT} run at once:
|
|
48464
48706
|
* many carry the whole member list, and the service may not queue them itself.
|
|
48465
48707
|
*/
|
|
48466
48708
|
var SetQueries = class {
|
|
48467
48709
|
expandCompose;
|
|
48710
|
+
parallelPages;
|
|
48468
48711
|
inFlight = 0;
|
|
48469
48712
|
waiting = [];
|
|
48470
|
-
constructor(expandCompose) {
|
|
48713
|
+
constructor(expandCompose, parallelPages = false) {
|
|
48471
48714
|
this.expandCompose = expandCompose;
|
|
48715
|
+
this.parallelPages = parallelPages;
|
|
48716
|
+
}
|
|
48717
|
+
/**
|
|
48718
|
+
* The rest of an expansion whose first `first.length` concepts have been
|
|
48719
|
+
* read, up to `until`, in order. Pages step by the first page's length, which
|
|
48720
|
+
* is the server's page cap when it returned fewer than asked (Ontoserver
|
|
48721
|
+
* caps at 50,000; other servers lower). With `parallelPages` those pages are
|
|
48722
|
+
* asked for at once. Whatever is still missing after that (a server whose
|
|
48723
|
+
* pages shrink) is read one page after another, advancing by what each page
|
|
48724
|
+
* actually held, so a smaller cap never silently drops concepts.
|
|
48725
|
+
*/
|
|
48726
|
+
async rest(compose, first, until, options) {
|
|
48727
|
+
const concepts = [...first];
|
|
48728
|
+
const step = first.length;
|
|
48729
|
+
if (step === 0) return concepts;
|
|
48730
|
+
const page = async (offset, count) => (await this.expand(compose, {
|
|
48731
|
+
...options,
|
|
48732
|
+
count,
|
|
48733
|
+
offset
|
|
48734
|
+
})).concepts;
|
|
48735
|
+
if (this.parallelPages) await this.pagesAtOnce(concepts, step, until, page);
|
|
48736
|
+
while (concepts.length < until) {
|
|
48737
|
+
const p = await page(concepts.length, Math.min(PAGE_SIZE, until - concepts.length));
|
|
48738
|
+
if (p.length === 0) break;
|
|
48739
|
+
for (const c of p) concepts.push(c);
|
|
48740
|
+
}
|
|
48741
|
+
return concepts;
|
|
48742
|
+
}
|
|
48743
|
+
/**
|
|
48744
|
+
* Append the pages from `step` to `until`, `step` apart, asked for at once.
|
|
48745
|
+
* Only the run of full pages is kept: after a short one the offsets no longer line up.
|
|
48746
|
+
*/
|
|
48747
|
+
async pagesAtOnce(concepts, step, until, page) {
|
|
48748
|
+
const offsets = [];
|
|
48749
|
+
for (let o = step; o < until; o += step) offsets.push(o);
|
|
48750
|
+
const pages = await Promise.all(offsets.map((o) => page(o, Math.min(step, until - o))));
|
|
48751
|
+
for (const p of pages) {
|
|
48752
|
+
for (const c of p) concepts.push(c);
|
|
48753
|
+
if (p.length < step) return;
|
|
48754
|
+
}
|
|
48472
48755
|
}
|
|
48473
48756
|
async expand(...args) {
|
|
48474
48757
|
if (this.inFlight >= 8) await new Promise((resolve) => this.waiting.push(resolve));
|
|
@@ -48495,23 +48778,75 @@ var SetQueries = class {
|
|
|
48495
48778
|
}
|
|
48496
48779
|
/** Up to `max` codes of the set, sorted, plus the set's exact total. */
|
|
48497
48780
|
async codes(compose, max, activeOnly = true) {
|
|
48498
|
-
const
|
|
48499
|
-
|
|
48500
|
-
|
|
48501
|
-
|
|
48502
|
-
|
|
48503
|
-
|
|
48504
|
-
|
|
48781
|
+
const { concepts, total } = await this.concepts(compose, max, activeOnly);
|
|
48782
|
+
return {
|
|
48783
|
+
codes: concepts.map((c) => c.code).sort(byId),
|
|
48784
|
+
total
|
|
48785
|
+
};
|
|
48786
|
+
}
|
|
48787
|
+
/** Up to `max` concepts of the set with their terms, in the server's order, plus the set's exact total. */
|
|
48788
|
+
async concepts(compose, max, activeOnly = true) {
|
|
48789
|
+
const first = await this.expand(compose, {
|
|
48790
|
+
count: Math.min(PAGE_SIZE, max),
|
|
48791
|
+
offset: 0,
|
|
48792
|
+
activeOnly
|
|
48793
|
+
});
|
|
48794
|
+
const total = first.total;
|
|
48795
|
+
return {
|
|
48796
|
+
concepts: await this.rest(compose, first.concepts, Math.min(max, total), { activeOnly }),
|
|
48797
|
+
total
|
|
48798
|
+
};
|
|
48799
|
+
}
|
|
48800
|
+
/**
|
|
48801
|
+
* The concepts of `codes` the server knows, in chunks of {@link LOOKUP_CHUNK}
|
|
48802
|
+
* run concurrently, with their terms and, as asked, parents and children.
|
|
48803
|
+
* With `activeOnly: false` inactive ones come back flagged `inactive`.
|
|
48804
|
+
*/
|
|
48805
|
+
async lookup(codes, options = {}) {
|
|
48806
|
+
return (await this.lookupEach(codes, options, (concepts) => concepts)).flat();
|
|
48807
|
+
}
|
|
48808
|
+
/**
|
|
48809
|
+
* {@link lookup}, with each chunk's answer passed through `each` as it
|
|
48810
|
+
* arrives, so a caller that keeps less than the server sends need not hold
|
|
48811
|
+
* every answer at once. The results are in chunk order.
|
|
48812
|
+
*/
|
|
48813
|
+
async lookupEach(codes, options, each) {
|
|
48814
|
+
const chunks = [];
|
|
48815
|
+
for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) chunks.push(codes.slice(i, i + LOOKUP_CHUNK));
|
|
48816
|
+
return Promise.all(chunks.map(async (chunk) => {
|
|
48817
|
+
const compose = { include: [{ concepts: chunk }] };
|
|
48818
|
+
const expandOptions = {
|
|
48819
|
+
activeOnly: options.activeOnly ?? true,
|
|
48820
|
+
...options
|
|
48821
|
+
};
|
|
48822
|
+
const page = await this.expand(compose, {
|
|
48823
|
+
...expandOptions,
|
|
48824
|
+
count: chunk.length,
|
|
48825
|
+
offset: 0
|
|
48505
48826
|
});
|
|
48506
|
-
total
|
|
48507
|
-
|
|
48508
|
-
|
|
48509
|
-
|
|
48510
|
-
|
|
48511
|
-
|
|
48512
|
-
|
|
48827
|
+
if (page.concepts.length >= page.total) return each(page.concepts);
|
|
48828
|
+
return each(await this.rest(compose, page.concepts, page.total, expandOptions));
|
|
48829
|
+
}));
|
|
48830
|
+
}
|
|
48831
|
+
/**
|
|
48832
|
+
* Up to `max` concepts of a set known to have at most `max`, such as a list
|
|
48833
|
+
* of codes: with `parallelPages` every page is asked for at once, since the
|
|
48834
|
+
* offsets do not depend on the first page's total.
|
|
48835
|
+
*/
|
|
48836
|
+
async conceptsUpTo(compose, max, activeOnly = true) {
|
|
48837
|
+
if (!this.parallelPages || max <= PAGE_SIZE) return this.concepts(compose, max, activeOnly);
|
|
48838
|
+
const offsets = [];
|
|
48839
|
+
for (let o = 0; o < max; o += PAGE_SIZE) offsets.push(o);
|
|
48840
|
+
const pages = await Promise.all(offsets.map((offset) => this.expand(compose, {
|
|
48841
|
+
count: Math.min(PAGE_SIZE, max - offset),
|
|
48842
|
+
offset,
|
|
48843
|
+
activeOnly
|
|
48844
|
+
})));
|
|
48845
|
+
const total = pages[0].total;
|
|
48846
|
+
const concepts = pages.flatMap((p) => p.concepts);
|
|
48847
|
+
if (concepts.length < Math.min(max, total)) return this.concepts(compose, max, activeOnly);
|
|
48513
48848
|
return {
|
|
48514
|
-
|
|
48849
|
+
concepts,
|
|
48515
48850
|
total
|
|
48516
48851
|
};
|
|
48517
48852
|
}
|
|
@@ -48521,20 +48856,17 @@ var SetQueries = class {
|
|
|
48521
48856
|
*/
|
|
48522
48857
|
async graph(compose, max) {
|
|
48523
48858
|
const graph = /* @__PURE__ */ new Map();
|
|
48524
|
-
|
|
48525
|
-
|
|
48526
|
-
|
|
48527
|
-
|
|
48528
|
-
|
|
48529
|
-
|
|
48530
|
-
|
|
48531
|
-
|
|
48532
|
-
|
|
48533
|
-
graph.set(c.code, c.parents ?? []);
|
|
48534
|
-
}
|
|
48535
|
-
offset += r.concepts.length;
|
|
48536
|
-
if (r.concepts.length === 0 || offset >= r.total) return graph;
|
|
48859
|
+
const first = await this.expand(compose, {
|
|
48860
|
+
count: PAGE_SIZE,
|
|
48861
|
+
offset: 0,
|
|
48862
|
+
parents: true
|
|
48863
|
+
});
|
|
48864
|
+
if (first.total > max) return "too-large";
|
|
48865
|
+
for (const c of await this.rest(compose, first.concepts, first.total, { parents: true })) {
|
|
48866
|
+
if (!c.parents && c.code !== "138875005") return "no-parents";
|
|
48867
|
+
graph.set(c.code, c.parents ?? []);
|
|
48537
48868
|
}
|
|
48869
|
+
return graph;
|
|
48538
48870
|
}
|
|
48539
48871
|
countEcl(ecl) {
|
|
48540
48872
|
return this.count({ include: [{ ecl }] });
|
|
@@ -48865,6 +49197,30 @@ function outermost(g, items, max) {
|
|
|
48865
49197
|
}
|
|
48866
49198
|
return kept;
|
|
48867
49199
|
}
|
|
49200
|
+
/**
|
|
49201
|
+
* Groups of two or more concepts whose terms match, ordered by term. Runs of
|
|
49202
|
+
* whitespace and the case of the first letter are ignored, as SNOMED CT
|
|
49203
|
+
* terms are mostly case-insensitive only there. Concepts without a term are
|
|
49204
|
+
* left out.
|
|
49205
|
+
*/
|
|
49206
|
+
function findDuplicateTerms(concepts) {
|
|
49207
|
+
const groups = /* @__PURE__ */ new Map();
|
|
49208
|
+
for (const { code, display } of concepts) {
|
|
49209
|
+
const term = display.trim().replaceAll(/\s+/g, " ");
|
|
49210
|
+
if (!term) continue;
|
|
49211
|
+
const key = term.charAt(0).toLowerCase() + term.slice(1);
|
|
49212
|
+
const group = groups.get(key) ?? /* @__PURE__ */ new Map();
|
|
49213
|
+
group.set(code, display.trim());
|
|
49214
|
+
groups.set(key, group);
|
|
49215
|
+
}
|
|
49216
|
+
return [...groups].filter(([, g]) => g.size > 1).sort(([a], [b]) => a.localeCompare(b)).map(([, g]) => {
|
|
49217
|
+
const conceptIds = [...g.keys()].sort(byId);
|
|
49218
|
+
return {
|
|
49219
|
+
term: g.get(conceptIds[0]) ?? "",
|
|
49220
|
+
conceptIds
|
|
49221
|
+
};
|
|
49222
|
+
});
|
|
49223
|
+
}
|
|
48868
49224
|
// src/derive/greedy-grouping.ts
|
|
48869
49225
|
var MINIMUM_CLUSTER_SIZE = 2;
|
|
48870
49226
|
var FIT_THRESHOLD = .9;
|
|
@@ -49008,122 +49364,439 @@ function chooseInclusions(candidates, inList, maxClauses) {
|
|
|
49008
49364
|
// src/derive/taxonomy-graph.ts
|
|
49009
49365
|
async function loadTaxonomyGraph(members, q, options) {
|
|
49010
49366
|
const max = options.maxConcepts;
|
|
49011
|
-
const memberList =
|
|
49367
|
+
const memberList = options.memberCodes ? {
|
|
49368
|
+
codes: options.memberCodes,
|
|
49369
|
+
total: options.memberCodes.length
|
|
49370
|
+
} : await q.codes({ include: [members.clause] }, max + 1);
|
|
49012
49371
|
if (memberList.total > max) return { unavailable: "the set" };
|
|
49372
|
+
if (options.walk) {
|
|
49373
|
+
const walked = await walkedGraph(memberList.codes, q, options);
|
|
49374
|
+
if (walked) return walked;
|
|
49375
|
+
}
|
|
49376
|
+
const around = await eclSubgraph(members, q, options);
|
|
49377
|
+
if ("unavailable" in around) return around;
|
|
49378
|
+
const ids = new Ids();
|
|
49379
|
+
return await withDescendants(new LoadedGraph(new Set(memberList.codes), numbered(ids, around.up), numbered(ids, around.childGraph), ids), options, async (load) => {
|
|
49380
|
+
if (load.length === 0) return /* @__PURE__ */ new Map();
|
|
49381
|
+
const below = await q.graph({ include: [{ ecl: `<< ${orGroup(load)}` }] }, max);
|
|
49382
|
+
return typeof below === "string" ? below : numbered(ids, below);
|
|
49383
|
+
}) ?? { unavailable: "the descendants of the candidate groupers" };
|
|
49384
|
+
}
|
|
49385
|
+
/** `>> set` with each concept's parents, and the children of those concepts, by ECL queries that carry the set. */
|
|
49386
|
+
async function eclSubgraph(members, q, options) {
|
|
49387
|
+
const max = options.maxConcepts;
|
|
49013
49388
|
const up = await q.graph({ include: [{ ecl: `>> ${members.ecl}` }] }, max);
|
|
49014
49389
|
if (typeof up === "string") return refused(up, "the set with its ancestors");
|
|
49015
49390
|
const childGraph = await q.graph({ include: [{ ecl: `<! (>> ${members.ecl})` }] }, max);
|
|
49016
49391
|
if (typeof childGraph === "string") return refused(childGraph, "the children of those ancestors");
|
|
49017
|
-
|
|
49392
|
+
return {
|
|
49393
|
+
up,
|
|
49394
|
+
childGraph
|
|
49395
|
+
};
|
|
49396
|
+
}
|
|
49397
|
+
function numbered(ids, graph) {
|
|
49398
|
+
const out = /* @__PURE__ */ new Map();
|
|
49399
|
+
for (const [id, parents] of graph) out.set(ids.at(id), parents.map((p) => ids.at(p)));
|
|
49400
|
+
return out;
|
|
49401
|
+
}
|
|
49402
|
+
/**
|
|
49403
|
+
* The graph with the descendants loaded of the concepts `descend` picks (and
|
|
49404
|
+
* the roots), or of those `fallbackDescend` picks when those are too many
|
|
49405
|
+
* (the graph is then partial); a refusal when even those are too many, and
|
|
49406
|
+
* null when `fetch` cannot say.
|
|
49407
|
+
*/
|
|
49408
|
+
async function withDescendants(graph, options, fetch) {
|
|
49018
49409
|
const roots = new Set(graph.roots());
|
|
49019
|
-
|
|
49410
|
+
const loadFor = (pick) => graph.ancestors().filter((id) => graph.children(id).length > 0 && pick(id));
|
|
49411
|
+
let down = await fetch(loadFor((id) => options.descend(id, graph) || roots.has(id)));
|
|
49020
49412
|
if (down === "too-large" && options.fallbackDescend) {
|
|
49021
49413
|
const fallback = options.fallbackDescend;
|
|
49022
|
-
down = await
|
|
49414
|
+
down = await fetch(loadFor((id) => fallback(id, graph)));
|
|
49023
49415
|
graph.partial = true;
|
|
49024
49416
|
}
|
|
49417
|
+
if (down === null) return null;
|
|
49025
49418
|
if (typeof down === "string") return refused(down, "the descendants of the candidate groupers");
|
|
49026
49419
|
graph.addBelow(down);
|
|
49027
49420
|
return graph;
|
|
49028
49421
|
}
|
|
49029
|
-
/**
|
|
49030
|
-
|
|
49031
|
-
|
|
49032
|
-
|
|
49033
|
-
|
|
49422
|
+
/** Concept ids, each numbered once, shared by a walk and the graph built from it. */
|
|
49423
|
+
var Ids = class {
|
|
49424
|
+
list = [];
|
|
49425
|
+
index = /* @__PURE__ */ new Map();
|
|
49426
|
+
get(id) {
|
|
49427
|
+
return this.index.get(id);
|
|
49428
|
+
}
|
|
49429
|
+
/** The number of `id`, given one if it has none. */
|
|
49430
|
+
at(id) {
|
|
49431
|
+
let i = this.index.get(id);
|
|
49432
|
+
if (i === void 0) {
|
|
49433
|
+
i = this.list.length;
|
|
49434
|
+
this.list.push(id);
|
|
49435
|
+
this.index.set(id, i);
|
|
49436
|
+
}
|
|
49437
|
+
return i;
|
|
49438
|
+
}
|
|
49439
|
+
};
|
|
49440
|
+
/**
|
|
49441
|
+
* Concepts looked up with their parents and children, by number. Resolving a
|
|
49442
|
+
* list can start one, converting each chunk as it arrives, so the server's
|
|
49443
|
+
* answers are not all held at once (see {@link TaxonomyGraphOptions.seed}).
|
|
49444
|
+
*/
|
|
49445
|
+
var Walk = class {
|
|
49446
|
+
ids = new Ids();
|
|
49447
|
+
nodes = /* @__PURE__ */ new Map();
|
|
49448
|
+
/** The nodes for `concepts`, not yet added; null when one came back without the parents or children asked for. */
|
|
49449
|
+
nodesFor(concepts) {
|
|
49450
|
+
const at = (id) => this.ids.at(id);
|
|
49451
|
+
const out = [];
|
|
49452
|
+
for (const c of concepts) {
|
|
49453
|
+
if (!c.children || !c.parents && c.code !== "138875005") return null;
|
|
49454
|
+
out.push([at(c.code), {
|
|
49455
|
+
parents: (c.parents ?? []).map(at),
|
|
49456
|
+
children: c.children.map(at),
|
|
49457
|
+
display: c.display
|
|
49458
|
+
}]);
|
|
49459
|
+
}
|
|
49460
|
+
return out;
|
|
49461
|
+
}
|
|
49462
|
+
add(nodes) {
|
|
49463
|
+
for (const [i, n] of nodes) this.nodes.set(i, n);
|
|
49464
|
+
}
|
|
49465
|
+
/** True when every one of `codes` has been looked up. */
|
|
49466
|
+
has(codes) {
|
|
49467
|
+
for (const c of codes) {
|
|
49468
|
+
const i = this.ids.get(c);
|
|
49469
|
+
if (i === void 0 || !this.nodes.has(i)) return false;
|
|
49470
|
+
}
|
|
49471
|
+
return true;
|
|
49472
|
+
}
|
|
49473
|
+
};
|
|
49474
|
+
/** Record looked-up concepts; false when one came back without the parents or children asked for. */
|
|
49475
|
+
function record(walk, concepts) {
|
|
49476
|
+
const nodes = walk.nodesFor(concepts);
|
|
49477
|
+
if (nodes) walk.add(nodes);
|
|
49478
|
+
return nodes !== null;
|
|
49479
|
+
}
|
|
49480
|
+
/**
|
|
49481
|
+
* The graph built by walking (see {@link TaxonomyGraphOptions.walk}), or null
|
|
49482
|
+
* when the server does not return children, or a refusal when it is too large.
|
|
49483
|
+
*/
|
|
49484
|
+
async function walkedGraph(memberCodes, q, options) {
|
|
49485
|
+
const max = options.maxConcepts;
|
|
49486
|
+
const members = new Set(memberCodes);
|
|
49487
|
+
const seeded = options.seed?.has(members) ? options.seed : void 0;
|
|
49488
|
+
const walk = seeded ?? new Walk();
|
|
49489
|
+
if (!seeded && !record(walk, await q.lookup(memberCodes, {
|
|
49490
|
+
parents: true,
|
|
49491
|
+
children: true
|
|
49492
|
+
}))) return null;
|
|
49493
|
+
const climbed = await walkUp(memberCodes, walk, q, max);
|
|
49494
|
+
if (climbed !== "done") return climbed;
|
|
49495
|
+
const { ids, nodes } = walk;
|
|
49496
|
+
const up = /* @__PURE__ */ new Map();
|
|
49497
|
+
const childGraph = /* @__PURE__ */ new Map();
|
|
49498
|
+
for (const [i, n] of nodes) {
|
|
49499
|
+
up.set(i, n.parents);
|
|
49500
|
+
for (const c of n.children) {
|
|
49501
|
+
if (nodes.has(c)) continue;
|
|
49502
|
+
const parents = childGraph.get(c);
|
|
49503
|
+
if (parents) parents.push(i);
|
|
49504
|
+
else childGraph.set(c, [i]);
|
|
49505
|
+
}
|
|
49506
|
+
}
|
|
49507
|
+
const graph = new LoadedGraph(members, up, childGraph, ids);
|
|
49508
|
+
const loaded = await withDescendants(graph, options, (load) => walkDown(load, walk, q, max));
|
|
49509
|
+
if (!loaded || "unavailable" in loaded) return loaded;
|
|
49510
|
+
graph.loadBelow = async (load) => {
|
|
49511
|
+
const more = await walkDown(load, walk, options.belowQueries ?? q, max);
|
|
49512
|
+
if (more === "too-large" || more === null) return false;
|
|
49513
|
+
graph.addBelow(more);
|
|
49514
|
+
return true;
|
|
49515
|
+
};
|
|
49516
|
+
graph.term = (id) => {
|
|
49517
|
+
const i = ids.get(id);
|
|
49518
|
+
return i === void 0 ? void 0 : nodes.get(i)?.display;
|
|
49519
|
+
};
|
|
49520
|
+
return graph;
|
|
49521
|
+
}
|
|
49522
|
+
/**
|
|
49523
|
+
* Add the ancestors of `start` to the walk, a level at a time: `'done'`, a
|
|
49524
|
+
* refusal when they are too many, or null when the server ignored
|
|
49525
|
+
* `property=child` (then no parent lists its child).
|
|
49526
|
+
*/
|
|
49527
|
+
async function walkUp(start, walk, q, max) {
|
|
49528
|
+
const { ids, nodes } = walk;
|
|
49529
|
+
let frontier = newParents(start.map((c) => ids.at(c)), nodes);
|
|
49530
|
+
while (frontier.length > 0) {
|
|
49531
|
+
if (nodes.size + frontier.length > max) return { unavailable: "the set with its ancestors" };
|
|
49532
|
+
const found = await q.lookup(frontier.map((i) => ids.list[i]), {
|
|
49533
|
+
parents: true,
|
|
49534
|
+
children: true
|
|
49535
|
+
});
|
|
49536
|
+
if (!record(walk, found)) return null;
|
|
49537
|
+
frontier = newParents(found.map((c) => ids.at(c.code)), nodes);
|
|
49538
|
+
}
|
|
49539
|
+
for (const [i, n] of nodes) if (n.parents.some((p) => !nodes.get(p)?.children.includes(i))) return null;
|
|
49540
|
+
return "done";
|
|
49541
|
+
}
|
|
49542
|
+
function newParents(codes, nodes) {
|
|
49543
|
+
const out = /* @__PURE__ */ new Set();
|
|
49544
|
+
for (const c of codes) for (const p of nodes.get(c)?.parents ?? []) if (!nodes.has(p)) out.add(p);
|
|
49545
|
+
return [...out];
|
|
49546
|
+
}
|
|
49547
|
+
/**
|
|
49548
|
+
* `<< load` with each concept's parents, walked down level by level. Concepts
|
|
49549
|
+
* already in the walk are not looked up, and those looked up are added to it,
|
|
49550
|
+
* so a later walk does not look them up again.
|
|
49551
|
+
*/
|
|
49552
|
+
async function walkDown(load, walk, q, max) {
|
|
49553
|
+
const { ids, nodes } = walk;
|
|
49554
|
+
const result = /* @__PURE__ */ new Map();
|
|
49555
|
+
let level = [...new Set(load.map((c) => ids.at(c)))];
|
|
49556
|
+
while (level.length > 0) {
|
|
49557
|
+
const missing = level.filter((c) => !nodes.has(c));
|
|
49558
|
+
if (missing.length > 0 && !record(walk, await q.lookup(missing.map((i) => ids.list[i]), {
|
|
49559
|
+
parents: true,
|
|
49560
|
+
children: true
|
|
49561
|
+
}))) return null;
|
|
49562
|
+
level = descendOneLevel(level, nodes, result);
|
|
49563
|
+
if (result.size + level.length > max) return "too-large";
|
|
49564
|
+
}
|
|
49565
|
+
return result;
|
|
49566
|
+
}
|
|
49567
|
+
/** Record `level` in `result` and return its children not yet there. */
|
|
49568
|
+
function descendOneLevel(level, nodes, result) {
|
|
49569
|
+
const next = /* @__PURE__ */ new Set();
|
|
49570
|
+
for (const c of level) {
|
|
49571
|
+
const n = nodes.get(c);
|
|
49572
|
+
if (!n) continue;
|
|
49573
|
+
result.set(c, n.parents);
|
|
49574
|
+
for (const child of n.children) if (!result.has(child)) next.add(child);
|
|
49575
|
+
}
|
|
49576
|
+
return [...next];
|
|
49034
49577
|
}
|
|
49035
49578
|
function refused(reason, what) {
|
|
49036
49579
|
return { unavailable: reason === "no-parents" ? "parents" : what };
|
|
49037
49580
|
}
|
|
49581
|
+
/**
|
|
49582
|
+
* The graph, with each concept numbered once and its parents and children held
|
|
49583
|
+
* as lists of numbers, so a graph of a few hundred thousand concepts keeps one
|
|
49584
|
+
* copy of each edge in each direction (it held four, with strings, before).
|
|
49585
|
+
*/
|
|
49038
49586
|
var LoadedGraph = class {
|
|
49039
49587
|
members;
|
|
49040
|
-
|
|
49588
|
+
ids;
|
|
49041
49589
|
partial = false;
|
|
49042
|
-
|
|
49043
|
-
|
|
49044
|
-
|
|
49590
|
+
loadBelow;
|
|
49591
|
+
term;
|
|
49592
|
+
/** Parents by number; a list may be the caller's (see SHARED) until the graph adds to it. */
|
|
49593
|
+
parentIdx = [];
|
|
49594
|
+
/** Children, in the order each child was first given parents (as `childrenOf` built them). */
|
|
49595
|
+
childIdx = [];
|
|
49596
|
+
/** When each concept was first given parents; -1 for a concept only seen as a parent. */
|
|
49597
|
+
rank = (/* @__PURE__ */ new Int32Array(1024)).fill(-1);
|
|
49598
|
+
nextRank = 0;
|
|
49599
|
+
/** How many of a concept's parents came from `up`, which come first. */
|
|
49600
|
+
upLength = /* @__PURE__ */ new Int32Array(1024);
|
|
49601
|
+
/** Bits: IN_UP, BELOW and SHARED (below the class). */
|
|
49602
|
+
flags = /* @__PURE__ */ new Uint8Array(1024);
|
|
49603
|
+
counts = /* @__PURE__ */ new Int32Array(1024);
|
|
49045
49604
|
cache = /* @__PURE__ */ new Map();
|
|
49046
|
-
counts = /* @__PURE__ */ new Map();
|
|
49047
49605
|
rootIds = [];
|
|
49048
|
-
constructor(members, up, childGraph) {
|
|
49606
|
+
constructor(members, up, childGraph, ids) {
|
|
49049
49607
|
this.members = members;
|
|
49050
|
-
this.
|
|
49608
|
+
this.ids = ids;
|
|
49051
49609
|
this.merge(up);
|
|
49610
|
+
for (const i of up.keys()) {
|
|
49611
|
+
this.flags[i] |= IN_UP;
|
|
49612
|
+
this.upLength[i] = this.parentIdx[i]?.length ?? 0;
|
|
49613
|
+
}
|
|
49052
49614
|
this.merge(childGraph);
|
|
49053
|
-
this.childMap = childrenOf(this.parentMap);
|
|
49054
49615
|
this.countMembers();
|
|
49055
49616
|
}
|
|
49056
49617
|
/** Add `<< candidates`, so their descendants are complete. */
|
|
49057
49618
|
addBelow(down) {
|
|
49058
49619
|
this.merge(down);
|
|
49059
|
-
for (const
|
|
49060
|
-
this.childMap = childrenOf(this.parentMap);
|
|
49620
|
+
for (const i of down.keys()) this.flags[i] |= BELOW;
|
|
49061
49621
|
this.cache.clear();
|
|
49062
49622
|
}
|
|
49623
|
+
/** The number of `id`, given one if it has none, with room for it here. */
|
|
49624
|
+
at(id) {
|
|
49625
|
+
const i = this.ids.at(id);
|
|
49626
|
+
this.room(i);
|
|
49627
|
+
return i;
|
|
49628
|
+
}
|
|
49629
|
+
/** Room for concept `i`, and for every concept numbered before it. */
|
|
49630
|
+
room(i) {
|
|
49631
|
+
while (this.parentIdx.length <= i) {
|
|
49632
|
+
this.parentIdx.push(void 0);
|
|
49633
|
+
this.childIdx.push(void 0);
|
|
49634
|
+
}
|
|
49635
|
+
while (i >= this.rank.length) this.grow();
|
|
49636
|
+
}
|
|
49637
|
+
/** The number of `id` when the graph has it. */
|
|
49638
|
+
known(id) {
|
|
49639
|
+
const i = this.ids.get(id);
|
|
49640
|
+
return i !== void 0 && i < this.parentIdx.length ? i : void 0;
|
|
49641
|
+
}
|
|
49642
|
+
grow() {
|
|
49643
|
+
const size = this.rank.length * 2;
|
|
49644
|
+
const rank = new Int32Array(size).fill(-1);
|
|
49645
|
+
rank.set(this.rank);
|
|
49646
|
+
this.rank = rank;
|
|
49647
|
+
this.upLength = withSize(this.upLength, size);
|
|
49648
|
+
this.counts = withSize(this.counts, size);
|
|
49649
|
+
const flags = new Uint8Array(size);
|
|
49650
|
+
flags.set(this.flags);
|
|
49651
|
+
this.flags = flags;
|
|
49652
|
+
}
|
|
49063
49653
|
merge(graph) {
|
|
49064
|
-
for (const [
|
|
49065
|
-
|
|
49066
|
-
for (const p of parents)
|
|
49067
|
-
this.
|
|
49654
|
+
for (const [i, parents] of graph) {
|
|
49655
|
+
this.room(i);
|
|
49656
|
+
for (const p of parents) this.room(p);
|
|
49657
|
+
if (this.rank[i] < 0) this.rank[i] = this.nextRank++;
|
|
49658
|
+
if (!this.parentIdx[i] && new Set(parents).size === parents.length) {
|
|
49659
|
+
this.parentIdx[i] = parents;
|
|
49660
|
+
this.flags[i] |= SHARED;
|
|
49661
|
+
for (const p of parents) this.addChild(p, i);
|
|
49662
|
+
} else for (const p of parents) this.addParent(i, p);
|
|
49663
|
+
}
|
|
49664
|
+
}
|
|
49665
|
+
addParent(i, p) {
|
|
49666
|
+
let known = this.parentIdx[i];
|
|
49667
|
+
if (known?.includes(p)) return;
|
|
49668
|
+
if (!known || (this.flags[i] & SHARED) !== 0) {
|
|
49669
|
+
known = known ? [...known] : [];
|
|
49670
|
+
this.parentIdx[i] = known;
|
|
49671
|
+
this.flags[i] &= ~SHARED;
|
|
49672
|
+
}
|
|
49673
|
+
known.push(p);
|
|
49674
|
+
this.addChild(p, i);
|
|
49675
|
+
}
|
|
49676
|
+
/** Put `child` among `parent`'s children, keeping them in rank order. */
|
|
49677
|
+
addChild(parent, child) {
|
|
49678
|
+
const list = this.childIdx[parent];
|
|
49679
|
+
if (!list) {
|
|
49680
|
+
this.childIdx[parent] = [child];
|
|
49681
|
+
return;
|
|
49068
49682
|
}
|
|
49683
|
+
const r = this.rank[child];
|
|
49684
|
+
let at = list.length;
|
|
49685
|
+
while (at > 0 && this.rank[list[at - 1]] > r) at--;
|
|
49686
|
+
if (at === list.length) list.push(child);
|
|
49687
|
+
else list.splice(at, 0, child);
|
|
49069
49688
|
}
|
|
49070
49689
|
countMembers() {
|
|
49071
49690
|
const nonRoots = /* @__PURE__ */ new Set();
|
|
49072
|
-
for (const m of this.members)
|
|
49073
|
-
|
|
49074
|
-
|
|
49691
|
+
for (const m of this.members) this.at(m);
|
|
49692
|
+
const seen = new Uint8Array(this.parentIdx.length);
|
|
49693
|
+
const touched = [];
|
|
49694
|
+
for (const m of this.members) {
|
|
49695
|
+
const start = this.at(m);
|
|
49696
|
+
this.upFrom(start, seen, touched);
|
|
49697
|
+
for (const a of touched) {
|
|
49698
|
+
this.counts[a]++;
|
|
49699
|
+
seen[a] = 0;
|
|
49700
|
+
if (a !== start && this.members.has(this.ids.list[a])) nonRoots.add(m);
|
|
49701
|
+
}
|
|
49702
|
+
touched.length = 0;
|
|
49075
49703
|
}
|
|
49076
49704
|
this.rootIds.push(...[...this.members].filter((m) => !nonRoots.has(m)).sort(byId));
|
|
49077
49705
|
}
|
|
49706
|
+
/** `start` and everything reachable from it along `up`'s parents, into `touched`, marked in `seen`. */
|
|
49707
|
+
upFrom(start, seen, touched) {
|
|
49708
|
+
seen[start] = 1;
|
|
49709
|
+
touched.push(start);
|
|
49710
|
+
for (const next of touched) {
|
|
49711
|
+
const parents = this.parentIdx[next] ?? [];
|
|
49712
|
+
const fromUp = this.upLength[next];
|
|
49713
|
+
for (const p of fromUp === parents.length ? parents : parents.slice(0, fromUp)) {
|
|
49714
|
+
if (seen[p]) continue;
|
|
49715
|
+
seen[p] = 1;
|
|
49716
|
+
touched.push(p);
|
|
49717
|
+
}
|
|
49718
|
+
}
|
|
49719
|
+
}
|
|
49720
|
+
names(list) {
|
|
49721
|
+
const out = [];
|
|
49722
|
+
if (list) for (const i of list) out.push(this.ids.list[i]);
|
|
49723
|
+
return out;
|
|
49724
|
+
}
|
|
49078
49725
|
aboveMember(id) {
|
|
49079
|
-
|
|
49726
|
+
const i = this.known(id);
|
|
49727
|
+
return i !== void 0 && (this.flags[i] & IN_UP) !== 0;
|
|
49080
49728
|
}
|
|
49081
49729
|
children(id) {
|
|
49082
|
-
|
|
49730
|
+
const i = this.known(id);
|
|
49731
|
+
return i === void 0 ? [] : this.names(this.childIdx[i]);
|
|
49083
49732
|
}
|
|
49084
49733
|
parents(id) {
|
|
49085
|
-
|
|
49734
|
+
const i = this.known(id);
|
|
49735
|
+
return i === void 0 ? [] : this.names(this.parentIdx[i]);
|
|
49086
49736
|
}
|
|
49087
49737
|
descendants(id) {
|
|
49088
|
-
|
|
49738
|
+
const i = this.known(id);
|
|
49739
|
+
if (i === void 0) return [id];
|
|
49740
|
+
let list = this.cache.get(i);
|
|
49089
49741
|
if (!list) {
|
|
49090
|
-
list =
|
|
49091
|
-
this.cache.set(
|
|
49742
|
+
list = this.reachableDown(i);
|
|
49743
|
+
if (list.length >= CACHED_DESCENDANTS) this.cache.set(i, list);
|
|
49092
49744
|
}
|
|
49093
|
-
return list;
|
|
49745
|
+
return this.names(list);
|
|
49746
|
+
}
|
|
49747
|
+
/** `start` and everything below it, in the order a depth-first walk first meets them. */
|
|
49748
|
+
reachableDown(start) {
|
|
49749
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
49750
|
+
const stack = [start];
|
|
49751
|
+
for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of this.childIdx[next] ?? []) {
|
|
49752
|
+
if (seen.has(x)) continue;
|
|
49753
|
+
seen.add(x);
|
|
49754
|
+
stack.push(x);
|
|
49755
|
+
}
|
|
49756
|
+
return Int32Array.from(seen);
|
|
49094
49757
|
}
|
|
49095
49758
|
hasDescendants(id) {
|
|
49096
|
-
|
|
49759
|
+
const i = this.known(id);
|
|
49760
|
+
if (i === void 0) return false;
|
|
49761
|
+
return (this.flags[i] & BELOW) !== 0 || (this.flags[i] & IN_UP) !== 0 && !this.childIdx[i]?.length;
|
|
49097
49762
|
}
|
|
49098
49763
|
truePos(id) {
|
|
49099
|
-
|
|
49764
|
+
const i = this.known(id);
|
|
49765
|
+
return i === void 0 ? 0 : this.counts[i];
|
|
49766
|
+
}
|
|
49767
|
+
membersBelow(id) {
|
|
49768
|
+
const start = this.known(id);
|
|
49769
|
+
if (start === void 0) return this.members.has(id) ? [id] : [];
|
|
49770
|
+
const found = [];
|
|
49771
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
49772
|
+
const stack = [start];
|
|
49773
|
+
for (let next = stack.pop(); next !== void 0; next = stack.pop()) {
|
|
49774
|
+
if (this.members.has(this.ids.list[next])) found.push(this.ids.list[next]);
|
|
49775
|
+
for (const c of this.childIdx[next] ?? []) {
|
|
49776
|
+
if (seen.has(c) || (this.flags[c] & IN_UP) === 0) continue;
|
|
49777
|
+
seen.add(c);
|
|
49778
|
+
stack.push(c);
|
|
49779
|
+
}
|
|
49780
|
+
}
|
|
49781
|
+
return found.sort(byId);
|
|
49100
49782
|
}
|
|
49101
49783
|
roots() {
|
|
49102
49784
|
return this.rootIds;
|
|
49103
49785
|
}
|
|
49104
49786
|
ancestors() {
|
|
49105
|
-
return
|
|
49787
|
+
return this.ids.list.filter((id, i) => i < this.parentIdx.length && (this.flags[i] & IN_UP) !== 0 && id !== "138875005").sort(byId);
|
|
49106
49788
|
}
|
|
49107
49789
|
};
|
|
49108
|
-
|
|
49109
|
-
|
|
49110
|
-
|
|
49111
|
-
|
|
49112
|
-
|
|
49113
|
-
|
|
49114
|
-
|
|
49115
|
-
|
|
49116
|
-
|
|
49117
|
-
|
|
49118
|
-
function reachable(start, edges) {
|
|
49119
|
-
const seen = /* @__PURE__ */ new Set([start]);
|
|
49120
|
-
const stack = [start];
|
|
49121
|
-
for (let next = stack.pop(); next !== void 0; next = stack.pop()) for (const x of edges.get(next) ?? []) {
|
|
49122
|
-
if (seen.has(x)) continue;
|
|
49123
|
-
seen.add(x);
|
|
49124
|
-
stack.push(x);
|
|
49125
|
-
}
|
|
49126
|
-
return seen;
|
|
49790
|
+
/** The fewest descendants worth caching. */
|
|
49791
|
+
var CACHED_DESCENDANTS = 64;
|
|
49792
|
+
var IN_UP = 1;
|
|
49793
|
+
var BELOW = 2;
|
|
49794
|
+
/** The concept's parent list is the caller's, so it is copied before the graph adds to it. */
|
|
49795
|
+
var SHARED = 4;
|
|
49796
|
+
function withSize(a, size) {
|
|
49797
|
+
const out = new Int32Array(size);
|
|
49798
|
+
out.set(a);
|
|
49799
|
+
return out;
|
|
49127
49800
|
}
|
|
49128
49801
|
// src/derive/refinements.ts
|
|
49129
49802
|
/** Members whose relationships are read to profile the attributes the set shares. */
|
|
@@ -49164,19 +49837,39 @@ async function readRelationships(sample, getRelationships, notes) {
|
|
|
49164
49837
|
return sampled;
|
|
49165
49838
|
}
|
|
49166
49839
|
/**
|
|
49840
|
+
* The sample's relationships in one batch request; null (read one by one)
|
|
49841
|
+
* when the batch fails. Entries the batch could not answer are read one by
|
|
49842
|
+
* one. `many` is not counted as a failure (see `uncounted`): only the one-by-one
|
|
49843
|
+
* reads, which lose what they cannot read, are.
|
|
49844
|
+
*/
|
|
49845
|
+
async function readMany(sample, many, getRelationships, notes) {
|
|
49846
|
+
let answers;
|
|
49847
|
+
try {
|
|
49848
|
+
answers = await many(sample);
|
|
49849
|
+
} catch {
|
|
49850
|
+
return null;
|
|
49851
|
+
}
|
|
49852
|
+
const answered = answers.filter((a) => !(a instanceof Error));
|
|
49853
|
+
const retry = sample.filter((_, i) => answers[i] instanceof Error);
|
|
49854
|
+
if (retry.length > 0) answered.push(...await readRelationships(retry, getRelationships, notes));
|
|
49855
|
+
return answered;
|
|
49856
|
+
}
|
|
49857
|
+
/**
|
|
49167
49858
|
* Refinement candidates for the set, likeliest first. `roots` are the set's
|
|
49168
49859
|
* roots (all of them when `roots.total` fits); `givenFoci` come from the input
|
|
49169
49860
|
* or the caller, and the most specific concept above every member is added
|
|
49170
49861
|
* unless `fixedFocus` says the caller chose the focus.
|
|
49171
49862
|
*/
|
|
49172
|
-
async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes) {
|
|
49863
|
+
async function refinementCandidates(members, roots, givenFoci, fixedFocus, q, terminology, notes, batch = false) {
|
|
49173
49864
|
const getRelationships = terminology.getDefiningRelationships?.bind(terminology);
|
|
49174
49865
|
if (!getRelationships) {
|
|
49175
49866
|
notes.push("Refinement candidates need a terminology service with getDefiningRelationships.");
|
|
49176
49867
|
return [];
|
|
49177
49868
|
}
|
|
49178
49869
|
const sample = (await q.codes({ include: [members.clause] }, REFINEMENT_SAMPLE)).codes;
|
|
49179
|
-
const
|
|
49870
|
+
const quiet = uncounted(terminology);
|
|
49871
|
+
const many = batch ? quiet.getDefiningRelationshipsMany?.bind(quiet) : void 0;
|
|
49872
|
+
const sampled = (many && await readMany(sample, many, getRelationships, notes)) ?? await readRelationships(sample, getRelationships, notes);
|
|
49180
49873
|
const profiles = profileAttributes(sampled);
|
|
49181
49874
|
if (profiles.length === 0) {
|
|
49182
49875
|
notes.push("No attribute is shared by most members, so no refinement candidates were built.");
|
|
@@ -49421,14 +50114,21 @@ var DEFAULTS = {
|
|
|
49421
50114
|
greedyGrouping: true,
|
|
49422
50115
|
useGraph: true,
|
|
49423
50116
|
maxGraphConcepts: 2e5,
|
|
49424
|
-
critique: false
|
|
50117
|
+
critique: false,
|
|
50118
|
+
restrictTo: "auto",
|
|
50119
|
+
parallelPages: true,
|
|
50120
|
+
localScoring: false,
|
|
50121
|
+
scopedExclusions: true,
|
|
50122
|
+
walkGraph: true,
|
|
50123
|
+
batchLookups: true
|
|
49425
50124
|
};
|
|
49426
50125
|
var CRITIQUE_DEFAULTS = {
|
|
49427
50126
|
maxClauses: 35,
|
|
49428
50127
|
nearMissShare: .9,
|
|
49429
50128
|
nearMissMinSize: 5,
|
|
49430
50129
|
maxNearMisses: 5,
|
|
49431
|
-
impliedInactive: false
|
|
50130
|
+
impliedInactive: false,
|
|
50131
|
+
maxDuplicateTerms: 20
|
|
49432
50132
|
};
|
|
49433
50133
|
/** Above this many concept references, candidates are not formatted or given terms. */
|
|
49434
50134
|
var MAX_DECORATED_CLAUSES = 200;
|
|
@@ -49455,6 +50155,13 @@ var MAX_SUBTRACTED = 2;
|
|
|
49455
50155
|
*/
|
|
49456
50156
|
async function deriveEcl(input, terminology, options = {}) {
|
|
49457
50157
|
if (!terminology.expandCompose) throw new Error("deriveEcl needs a terminology service that supports expandCompose (POST ValueSet/$expand)");
|
|
50158
|
+
const { service, failures } = countingFailures(terminology);
|
|
50159
|
+
const result = await derive(input, service, options);
|
|
50160
|
+
result.failures = failures();
|
|
50161
|
+
return result;
|
|
50162
|
+
}
|
|
50163
|
+
async function derive(input, terminology, options) {
|
|
50164
|
+
if (!terminology.expandCompose) throw new Error("unreachable: checked by deriveEcl");
|
|
49458
50165
|
const opts = {
|
|
49459
50166
|
...DEFAULTS,
|
|
49460
50167
|
...options
|
|
@@ -49463,21 +50170,28 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49463
50170
|
const q = new SetQueries((compose, o) => expandCompose(compose, {
|
|
49464
50171
|
timeoutMs: opts.queryTimeoutMs,
|
|
49465
50172
|
...o
|
|
49466
|
-
}));
|
|
50173
|
+
}), opts.parallelPages);
|
|
50174
|
+
const quiet = uncounted(terminology);
|
|
50175
|
+
const quietExpand = quiet.expandCompose?.bind(quiet) ?? expandCompose;
|
|
50176
|
+
const belowQueries = new SetQueries((compose, o) => quietExpand(compose, {
|
|
50177
|
+
timeoutMs: opts.queryTimeoutMs,
|
|
50178
|
+
...o
|
|
50179
|
+
}), opts.parallelPages);
|
|
49467
50180
|
const notes = [];
|
|
49468
|
-
const { report, members } = await resolveInput(input, q, terminology, notes);
|
|
50181
|
+
const { report, members } = await resolveInput(input, q, terminology, notes, opts.walkGraph);
|
|
49469
50182
|
const result = {
|
|
49470
50183
|
input: report,
|
|
49471
50184
|
hierarchies: [],
|
|
49472
50185
|
roots: 0,
|
|
49473
50186
|
candidates: [],
|
|
49474
|
-
notes
|
|
50187
|
+
notes,
|
|
50188
|
+
failures: 0
|
|
49475
50189
|
};
|
|
49476
50190
|
if (!members) {
|
|
49477
50191
|
if (notes.length === 0) notes.push("The input has no active concepts the server knows, so there is nothing to derive.");
|
|
49478
50192
|
return result;
|
|
49479
50193
|
}
|
|
49480
|
-
const graph = opts.useGraph ? await loadGraph(members, q, opts, notes) : null;
|
|
50194
|
+
const graph = opts.useGraph ? await loadGraph(members, q, opts, notes, belowQueries) : null;
|
|
49481
50195
|
const critique = critiqueOptions(opts.critique);
|
|
49482
50196
|
let hierarchies = [];
|
|
49483
50197
|
if (opts.hierarchySummary || critique) hierarchies = graph ? await graphHierarchies(graph, terminology) : await hierarchyDistribution(members, q);
|
|
@@ -49491,8 +50205,12 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49491
50205
|
}, opts.maxRoots + 1);
|
|
49492
50206
|
result.roots = rootQuery.total;
|
|
49493
50207
|
const scorer = new Scorer(members, q, opts, notes);
|
|
49494
|
-
|
|
49495
|
-
|
|
50208
|
+
const countedLocally = /* @__PURE__ */ new Set();
|
|
50209
|
+
if (graph) {
|
|
50210
|
+
const worth = worthCounting(graphCandidates(graph, opts, notes), inputCost(input, members), opts, notes);
|
|
50211
|
+
await scorer.score(countOnGraph(worth, graph, opts, countedLocally));
|
|
50212
|
+
await scorer.score(await restrictedCovers(graph, members, q, opts, notes));
|
|
50213
|
+
} else await scorer.score(await hierarchyCandidates(rootQuery.codes, result.roots, members, q, opts, notes));
|
|
49496
50214
|
if (wantRefinements(opts.refinements, result.roots, scorer.scored)) await scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes);
|
|
49497
50215
|
await scorer.score([inputItself(input, members)]);
|
|
49498
50216
|
if (critique) result.critique = await buildCritique(critique, {
|
|
@@ -49503,9 +50221,11 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49503
50221
|
hierarchies,
|
|
49504
50222
|
scored: scorer.scored
|
|
49505
50223
|
}, q, terminology, opts);
|
|
49506
|
-
scorer.scored.
|
|
49507
|
-
|
|
49508
|
-
const
|
|
50224
|
+
const useful = scorer.scored.filter((s) => s.covered > 0);
|
|
50225
|
+
useful.sort((a, b) => byRank(rankOf(a), rankOf(b)));
|
|
50226
|
+
const top = useful.slice(0, opts.maxCandidates);
|
|
50227
|
+
await checkLocalCounts(top, countedLocally, members, q, opts, notes);
|
|
50228
|
+
const terms = opts.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, notes);
|
|
49509
50229
|
result.candidates = top.map((s) => ({
|
|
49510
50230
|
expression: decorate(s.ecl, terms),
|
|
49511
50231
|
...s
|
|
@@ -49516,7 +50236,7 @@ async function deriveEcl(input, terminology, options = {}) {
|
|
|
49516
50236
|
async function scoreRefinements(input, members, rootQuery, scorer, q, terminology, opts, notes) {
|
|
49517
50237
|
let given = "ecl" in input ? refsetFoci(input.ecl) : [];
|
|
49518
50238
|
if (opts.refinementFocus) given = [asFocus(opts.refinementFocus)];
|
|
49519
|
-
const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes)).map(({ focus, clauses }) => ({
|
|
50239
|
+
const refinements = (await refinementCandidates(members, rootQuery, given, Boolean(opts.refinementFocus), q, terminology, notes, opts.batchLookups)).map(({ focus, clauses }) => ({
|
|
49520
50240
|
ecl: refinementText(focus, clauses),
|
|
49521
50241
|
construction: {
|
|
49522
50242
|
kind: "refinement",
|
|
@@ -49547,7 +50267,7 @@ async function subtractions(scored, members, terminology, opts) {
|
|
|
49547
50267
|
critique: false,
|
|
49548
50268
|
omitTerms: true,
|
|
49549
50269
|
maxCandidates: 3
|
|
49550
|
-
})).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0);
|
|
50270
|
+
})).candidates.find((x) => x.construction.kind !== "expression" && x.misses.count === 0 && x.additions.count < c.additions.count);
|
|
49551
50271
|
if (d) built.push({
|
|
49552
50272
|
ecl: `(${c.ecl}) MINUS (${d.ecl})`,
|
|
49553
50273
|
construction: {
|
|
@@ -49567,6 +50287,7 @@ async function subtractions(scored, members, terminology, opts) {
|
|
|
49567
50287
|
function wantRefinements(mode, roots, scored) {
|
|
49568
50288
|
if (mode === "always") return true;
|
|
49569
50289
|
if (mode === "never") return false;
|
|
50290
|
+
if (scored.some((c) => c.exact && c.construction.kind === "restricted-cover")) return false;
|
|
49570
50291
|
if (roots > REFINEMENT_ROOTS) return true;
|
|
49571
50292
|
return roots > 3 && !scored.some((c) => c.exact && c.clauses <= 3);
|
|
49572
50293
|
}
|
|
@@ -49582,7 +50303,11 @@ async function buildCritique(limits, found, q, terminology, opts) {
|
|
|
49582
50303
|
const { input, result, members, graph, hierarchies, scored } = found;
|
|
49583
50304
|
const induced = scored.filter((s) => s.exact && s.construction.kind !== "refset" && s.construction.kind !== "expression");
|
|
49584
50305
|
const best = Math.min(members.size, ...induced.map((s) => s.clauses));
|
|
49585
|
-
const [near, inactive] = await Promise.all([
|
|
50306
|
+
const [near, inactive, duplicateTerms] = await Promise.all([
|
|
50307
|
+
nearMisses(limits, members, graph, q, terminology, opts, result.notes),
|
|
50308
|
+
"refsetId" in input ? inactiveMembers(members, graph, q, result.notes) : [...result.input.inactive],
|
|
50309
|
+
sharedTerms(limits.maxDuplicateTerms, members, q, terminology, opts, result.notes)
|
|
50310
|
+
]);
|
|
49586
50311
|
const critique = {
|
|
49587
50312
|
clauses: {
|
|
49588
50313
|
best,
|
|
@@ -49592,7 +50317,8 @@ async function buildCritique(limits, found, q, terminology, opts) {
|
|
|
49592
50317
|
nearMisses: near,
|
|
49593
50318
|
hierarchies,
|
|
49594
50319
|
spansHierarchies: hierarchies.length > 1,
|
|
49595
|
-
inactive
|
|
50320
|
+
inactive,
|
|
50321
|
+
duplicateTerms
|
|
49596
50322
|
};
|
|
49597
50323
|
if (limits.impliedInactive) {
|
|
49598
50324
|
const profile = limits.impliedInactive === true ? "HISTORY-MOD" : limits.impliedInactive;
|
|
@@ -49614,9 +50340,9 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
|
|
|
49614
50340
|
return [];
|
|
49615
50341
|
}
|
|
49616
50342
|
const local = nearMissCandidates(graph, limits.nearMissShare, limits.nearMissMinSize).slice(0, limits.maxNearMisses * NEAR_MISS_CANDIDATES_PER_REPORTED);
|
|
49617
|
-
const counted = await Promise.allSettled(local.map((n) => q.sample({
|
|
50343
|
+
const counted = await nearMissesOnGraph(local, graph, opts.sampleSize) ?? await Promise.allSettled(local.map((n) => q.sample({
|
|
49618
50344
|
include: [{ ecl: `<< ${n.conceptId}` }],
|
|
49619
|
-
exclude: [members.clause]
|
|
50345
|
+
exclude: [opts.scopedExclusions ? { concepts: graph.membersBelow(n.conceptId) } : members.clause]
|
|
49620
50346
|
}, opts.sampleSize)));
|
|
49621
50347
|
const confirmed = [];
|
|
49622
50348
|
counted.forEach((r, i) => {
|
|
@@ -49643,6 +50369,71 @@ async function nearMisses(limits, members, graph, q, terminology, opts, notes) {
|
|
|
49643
50369
|
return found;
|
|
49644
50370
|
}
|
|
49645
50371
|
/**
|
|
50372
|
+
* What each near-miss candidate adds, counted on a walked graph
|
|
50373
|
+
* after walking down below the candidates whose descendants are not loaded;
|
|
50374
|
+
* null when the graph cannot (not walked, or too many), and the server counts.
|
|
50375
|
+
*/
|
|
50376
|
+
async function nearMissesOnGraph(local, graph, sampleSize) {
|
|
50377
|
+
if (!graph.loadBelow || local.length === 0) return null;
|
|
50378
|
+
const need = local.map((n) => n.conceptId).filter((id) => !graph.hasDescendants(id));
|
|
50379
|
+
try {
|
|
50380
|
+
if (need.length > 0 && !await graph.loadBelow(need)) return null;
|
|
50381
|
+
} catch {
|
|
50382
|
+
return null;
|
|
50383
|
+
}
|
|
50384
|
+
return local.map((n) => {
|
|
50385
|
+
const missing = graph.descendants(n.conceptId).filter((x) => !graph.members.has(x)).sort(byId);
|
|
50386
|
+
const sample = missing.slice(0, sampleSize).map((code) => ({
|
|
50387
|
+
code,
|
|
50388
|
+
display: graph.term?.(code) ?? ""
|
|
50389
|
+
}));
|
|
50390
|
+
return {
|
|
50391
|
+
status: "fulfilled",
|
|
50392
|
+
value: {
|
|
50393
|
+
count: missing.length,
|
|
50394
|
+
sample
|
|
50395
|
+
}
|
|
50396
|
+
};
|
|
50397
|
+
});
|
|
50398
|
+
}
|
|
50399
|
+
/**
|
|
50400
|
+
* Members that share a preferred term (CHK13): one listing of the members with
|
|
50401
|
+
* their terms, plus a lookup of the FSNs that tell each group apart.
|
|
50402
|
+
*/
|
|
50403
|
+
async function sharedTerms(max, members, q, terminology, opts, notes) {
|
|
50404
|
+
const limit = Math.max(0, Math.floor(max));
|
|
50405
|
+
if (limit === 0) return [];
|
|
50406
|
+
if (members.size > opts.maxGraphConcepts) {
|
|
50407
|
+
notes.push(`Shared terms were not checked: the list has ${members.size} members, more than ${opts.maxGraphConcepts} (maxGraphConcepts).`);
|
|
50408
|
+
return [];
|
|
50409
|
+
}
|
|
50410
|
+
let groups;
|
|
50411
|
+
try {
|
|
50412
|
+
groups = findDuplicateTerms(members.concepts ?? (await q.concepts({ include: [members.clause] }, members.size)).concepts);
|
|
50413
|
+
} catch (error) {
|
|
50414
|
+
notes.push(`Shared terms were not checked: ${errorMessage(error)}.`);
|
|
50415
|
+
return [];
|
|
50416
|
+
}
|
|
50417
|
+
if (groups.length > limit) notes.push(`${plural(groups.length, "term")} ${groups.length === 1 ? "is" : "are"} shared by more than one member; the first ${limit} ${limit === 1 ? "is" : "are"} listed (maxDuplicateTerms).`);
|
|
50418
|
+
const found = groups.slice(0, limit).map((g) => ({
|
|
50419
|
+
term: g.term,
|
|
50420
|
+
concepts: g.conceptIds.map((conceptId) => ({ conceptId }))
|
|
50421
|
+
}));
|
|
50422
|
+
if (!opts.omitTerms && found.length > 0) await addFsns(found, terminology);
|
|
50423
|
+
return found;
|
|
50424
|
+
}
|
|
50425
|
+
/** Each concept's FSN, where it says more than the shared term. */
|
|
50426
|
+
async function addFsns(found, terminology) {
|
|
50427
|
+
const concepts = found.flatMap((d) => d.concepts);
|
|
50428
|
+
try {
|
|
50429
|
+
const info = await terminology.validateConcepts(concepts.map((c) => c.conceptId));
|
|
50430
|
+
for (const c of concepts) {
|
|
50431
|
+
const concept = info.get(c.conceptId);
|
|
50432
|
+
if (concept?.fsn && concept.fsn !== concept.pt) c.fsn = concept.fsn;
|
|
50433
|
+
}
|
|
50434
|
+
} catch {}
|
|
50435
|
+
}
|
|
50436
|
+
/**
|
|
49646
50437
|
* A reference set's inactive members (CHK07). Its member set holds only the
|
|
49647
50438
|
* active ones, so one count says whether there are any, and a listing which
|
|
49648
50439
|
* (two off the graph, which already holds the active members).
|
|
@@ -49692,7 +50483,7 @@ function formKey(ecl) {
|
|
|
49692
50483
|
return ecl;
|
|
49693
50484
|
}
|
|
49694
50485
|
}
|
|
49695
|
-
async function resolveInput(input, q, terminology, notes) {
|
|
50486
|
+
async function resolveInput(input, q, terminology, notes, lookUp = false) {
|
|
49696
50487
|
if ("refsetId" in input) return resolveRefset(input.refsetId.trim(), q, terminology, notes);
|
|
49697
50488
|
if ("ecl" in input) {
|
|
49698
50489
|
const ecl = `(${stripTermsAndComments(input.ecl)})`;
|
|
@@ -49730,8 +50521,19 @@ async function resolveInput(input, q, terminology, notes) {
|
|
|
49730
50521
|
members: null
|
|
49731
50522
|
};
|
|
49732
50523
|
const listed = { include: [{ concepts: wellFormed }] };
|
|
49733
|
-
|
|
49734
|
-
|
|
50524
|
+
let activeConcepts;
|
|
50525
|
+
let knownConcepts;
|
|
50526
|
+
let walk;
|
|
50527
|
+
let walkable = true;
|
|
50528
|
+
const looked = lookUp ? await lookUpList(wellFormed, q) : null;
|
|
50529
|
+
if (looked) {
|
|
50530
|
+
knownConcepts = { concepts: looked.concepts };
|
|
50531
|
+
activeConcepts = { concepts: looked.concepts.filter((c) => !c.inactive) };
|
|
50532
|
+
walk = looked.walk;
|
|
50533
|
+
walkable = looked.walkable;
|
|
50534
|
+
} else [activeConcepts, knownConcepts] = await Promise.all([q.conceptsUpTo(listed, wellFormed.length, true), q.conceptsUpTo(listed, wellFormed.length, false)]);
|
|
50535
|
+
const active = activeConcepts.concepts.map((c) => c.code).sort(byId);
|
|
50536
|
+
const known = new Set(knownConcepts.concepts.map((c) => c.code));
|
|
49735
50537
|
const activeSet = new Set(active);
|
|
49736
50538
|
report.inactive = wellFormed.filter((id) => known.has(id) && !activeSet.has(id));
|
|
49737
50539
|
report.unknown = wellFormed.filter((id) => !known.has(id));
|
|
@@ -49740,15 +50542,73 @@ async function resolveInput(input, q, terminology, notes) {
|
|
|
49740
50542
|
report,
|
|
49741
50543
|
members: null
|
|
49742
50544
|
};
|
|
50545
|
+
Object.freeze(active);
|
|
49743
50546
|
return {
|
|
49744
50547
|
report,
|
|
49745
50548
|
members: {
|
|
49746
50549
|
clause: { concepts: active },
|
|
49747
50550
|
ecl: orGroup(active),
|
|
49748
|
-
size: active.length
|
|
50551
|
+
size: active.length,
|
|
50552
|
+
concepts: activeConcepts.concepts,
|
|
50553
|
+
...walk ? { walk } : {},
|
|
50554
|
+
...walkable ? {} : { walkUnsupported: true }
|
|
49749
50555
|
}
|
|
49750
50556
|
};
|
|
49751
50557
|
}
|
|
50558
|
+
/**
|
|
50559
|
+
* One chunked lookup of a list, for activity, terms, parents and children (for
|
|
50560
|
+
* walkGraph). Each chunk is cut down as it arrives: the terms kept, the active
|
|
50561
|
+
* concepts' parents and children numbered into a walk (none when the server
|
|
50562
|
+
* left them out).
|
|
50563
|
+
*/
|
|
50564
|
+
/**
|
|
50565
|
+
* The list looked up once, with each concept's activity, parents and children:
|
|
50566
|
+
* its concepts, and the walk they seed (absent, with `walkable` false, when
|
|
50567
|
+
* the server gave no parents or children). Activity is asked for explicitly
|
|
50568
|
+
* (`property=inactive`), so a server that states it (Ontoserver) answers with
|
|
50569
|
+
* nothing more. On one that does not, a list with no concept flagged inactive
|
|
50570
|
+
* is checked with one count per chunk; null when that count disagrees: the
|
|
50571
|
+
* server does not flag inactive concepts, so the caller must ask twice and
|
|
50572
|
+
* difference the answers.
|
|
50573
|
+
*/
|
|
50574
|
+
async function lookUpList(codes, q) {
|
|
50575
|
+
const seed = new Walk();
|
|
50576
|
+
const chunks = await q.lookupEach(codes, {
|
|
50577
|
+
activeOnly: false,
|
|
50578
|
+
parents: true,
|
|
50579
|
+
children: true,
|
|
50580
|
+
activity: true
|
|
50581
|
+
}, (concepts) => ({
|
|
50582
|
+
terms: concepts.map(({ code, display, inactive }) => inactive ? {
|
|
50583
|
+
code,
|
|
50584
|
+
display,
|
|
50585
|
+
inactive
|
|
50586
|
+
} : {
|
|
50587
|
+
code,
|
|
50588
|
+
display
|
|
50589
|
+
}),
|
|
50590
|
+
nodes: seed.nodesFor(concepts.filter((c) => !c.inactive)),
|
|
50591
|
+
stated: concepts.every((c) => c.inactive !== void 0)
|
|
50592
|
+
}));
|
|
50593
|
+
const concepts = chunks.flatMap((c) => c.terms);
|
|
50594
|
+
if (chunks.some((c) => !c.stated) && !concepts.some((c) => c.inactive) && await activeCount(codes, q) !== concepts.length) return null;
|
|
50595
|
+
if (chunks.some((c) => c.nodes === null)) return {
|
|
50596
|
+
concepts,
|
|
50597
|
+
walkable: false
|
|
50598
|
+
};
|
|
50599
|
+
for (const c of chunks) if (c.nodes) seed.add(c.nodes);
|
|
50600
|
+
return {
|
|
50601
|
+
concepts,
|
|
50602
|
+
walk: seed,
|
|
50603
|
+
walkable: true
|
|
50604
|
+
};
|
|
50605
|
+
}
|
|
50606
|
+
/** How many of `codes` are active, one count per lookup chunk. */
|
|
50607
|
+
async function activeCount(codes, q) {
|
|
50608
|
+
const counts = [];
|
|
50609
|
+
for (let i = 0; i < codes.length; i += LOOKUP_CHUNK) counts.push(q.count({ include: [{ concepts: codes.slice(i, i + LOOKUP_CHUNK) }] }));
|
|
50610
|
+
return (await Promise.all(counts)).reduce((a, b) => a + b, 0);
|
|
50611
|
+
}
|
|
49752
50612
|
async function resolveRefset(refsetId, q, terminology, notes) {
|
|
49753
50613
|
const report = {
|
|
49754
50614
|
given: 1,
|
|
@@ -49765,7 +50625,16 @@ async function resolveRefset(refsetId, q, terminology, notes) {
|
|
|
49765
50625
|
const ecl = `(^ ${refsetId})`;
|
|
49766
50626
|
report.members = await q.countEcl(ecl);
|
|
49767
50627
|
if (report.members === 0) {
|
|
49768
|
-
|
|
50628
|
+
let info;
|
|
50629
|
+
try {
|
|
50630
|
+
info = await terminology.getConceptInfo(refsetId);
|
|
50631
|
+
} catch (error) {
|
|
50632
|
+
notes.push(`${refsetId} has no active members; could not look it up to say why: ${errorMessage(error)}.`);
|
|
50633
|
+
return {
|
|
50634
|
+
report,
|
|
50635
|
+
members: null
|
|
50636
|
+
};
|
|
50637
|
+
}
|
|
49769
50638
|
if (info === null) report.unknown.push(refsetId);
|
|
49770
50639
|
else if (info.active) notes.push(`${refsetId} |${info.pt}| has no active members, or is not a reference set.`);
|
|
49771
50640
|
else report.inactive.push(refsetId);
|
|
@@ -49805,14 +50674,19 @@ async function graphHierarchies(g, terminology) {
|
|
|
49805
50674
|
})).sort((a, b) => b.count - a.count || byId(a.conceptId, b.conceptId));
|
|
49806
50675
|
}
|
|
49807
50676
|
/** The IS-A subgraph around the set, or null (with a note) when the per-query path must be used. */
|
|
49808
|
-
async function loadGraph(members, q, opts, notes) {
|
|
50677
|
+
async function loadGraph(members, q, opts, notes, belowQueries) {
|
|
49809
50678
|
let why;
|
|
49810
50679
|
try {
|
|
49811
50680
|
const graph = await loadTaxonomyGraph(members, q, {
|
|
49812
50681
|
maxConcepts: opts.maxGraphConcepts,
|
|
49813
50682
|
descend: (id, g) => coverDescend(id, g) || refactorDescend(id, g),
|
|
49814
|
-
fallbackDescend: refactorDescend
|
|
50683
|
+
fallbackDescend: refactorDescend,
|
|
50684
|
+
walk: opts.walkGraph && !members.walkUnsupported,
|
|
50685
|
+
...members.walk ? { seed: members.walk } : {},
|
|
50686
|
+
belowQueries,
|
|
50687
|
+
..."concepts" in members.clause ? { memberCodes: members.clause.concepts } : {}
|
|
49815
50688
|
});
|
|
50689
|
+
delete members.walk;
|
|
49816
50690
|
if (!("unavailable" in graph)) {
|
|
49817
50691
|
if (graph.partial) notes.push(`The IS-A subgraph is partial: below the set's roots and every candidate grouper it has more than ${opts.maxGraphConcepts} concepts (maxGraphConcepts), so descendants were loaded only for greedy grouping's candidates, and hierarchy forms that need others were left out.`);
|
|
49818
50692
|
return graph;
|
|
@@ -49877,7 +50751,8 @@ function graphCandidates(g, opts, notes) {
|
|
|
49877
50751
|
if (local) candidates.push({
|
|
49878
50752
|
ecl,
|
|
49879
50753
|
construction,
|
|
49880
|
-
local
|
|
50754
|
+
local,
|
|
50755
|
+
form
|
|
49881
50756
|
});
|
|
49882
50757
|
}
|
|
49883
50758
|
return candidates.sort((a, b) => byRank({
|
|
@@ -49890,6 +50765,70 @@ function graphCandidates(g, opts, notes) {
|
|
|
49890
50765
|
...b.local
|
|
49891
50766
|
}));
|
|
49892
50767
|
}
|
|
50768
|
+
/** AMT's level reference sets, likeliest first for a list of products: MPUU, MP, TPUU, TP, MPP, TPP, CTPP. */
|
|
50769
|
+
var AMT_LEVEL_REFSETS = [
|
|
50770
|
+
"929360071000036103",
|
|
50771
|
+
"929360061000036106",
|
|
50772
|
+
"929360031000036100",
|
|
50773
|
+
"929360021000036102",
|
|
50774
|
+
"929360081000036101",
|
|
50775
|
+
"929360041000036105",
|
|
50776
|
+
"929360051000036108"
|
|
50777
|
+
];
|
|
50778
|
+
var MEDICINAL_PRODUCT = "763158003";
|
|
50779
|
+
/**
|
|
50780
|
+
* The cover exact within `restrictTo` (see {@link DeriveOptions.restrictTo}).
|
|
50781
|
+
* A concept of `>> set` may stand as `<< x` when nothing of `restrictTo` below
|
|
50782
|
+
* it is a non-member: one query finds the concepts of `>> set` that are above
|
|
50783
|
+
* such a non-member. The highest of the rest, with each member that is itself
|
|
50784
|
+
* above a non-member, cover the set exactly once ANDed with `restrictTo`.
|
|
50785
|
+
*/
|
|
50786
|
+
async function restrictedCovers(g, members, q, opts, notes) {
|
|
50787
|
+
if (g.partial) return [];
|
|
50788
|
+
const restrictTo = opts.restrictTo === "auto" ? await amtLevel(g, members, q) : opts.restrictTo.trim();
|
|
50789
|
+
if (!restrictTo) return [];
|
|
50790
|
+
const within = /^\^ ?\d+$/.test(restrictTo) ? restrictTo : `(${restrictTo})`;
|
|
50791
|
+
let blocked;
|
|
50792
|
+
try {
|
|
50793
|
+
blocked = await q.codes({ include: [{ ecl: `(>> ${members.ecl}) AND (>> (${within} MINUS ${members.ecl}))` }] }, opts.maxGraphConcepts);
|
|
50794
|
+
} catch (error) {
|
|
50795
|
+
notes.push(`No cover within ${restrictTo}: ${errorMessage(error)}.`);
|
|
50796
|
+
return [];
|
|
50797
|
+
}
|
|
50798
|
+
const above = new Set(blocked.codes);
|
|
50799
|
+
const free = (id) => id !== "138875005" && !above.has(id);
|
|
50800
|
+
const includes = [];
|
|
50801
|
+
for (const x of /* @__PURE__ */ new Set([...g.ancestors(), ...g.members])) if (free(x)) {
|
|
50802
|
+
if (!g.parents(x).some(free)) includes.push({
|
|
50803
|
+
conceptId: x,
|
|
50804
|
+
operator: "<<"
|
|
50805
|
+
});
|
|
50806
|
+
} else if (g.members.has(x)) includes.push({
|
|
50807
|
+
conceptId: x,
|
|
50808
|
+
operator: "="
|
|
50809
|
+
});
|
|
50810
|
+
if (includes.length + 1 >= members.size) return [];
|
|
50811
|
+
includes.sort((a, b) => byId(a.conceptId, b.conceptId));
|
|
50812
|
+
return [{
|
|
50813
|
+
ecl: `${orGroup(includes.map((c) => c.operator === "=" ? c.conceptId : `<< ${c.conceptId}`))} AND ${within}`,
|
|
50814
|
+
construction: {
|
|
50815
|
+
kind: "restricted-cover",
|
|
50816
|
+
restrictTo,
|
|
50817
|
+
includes
|
|
50818
|
+
}
|
|
50819
|
+
}];
|
|
50820
|
+
}
|
|
50821
|
+
/** `^ R` for the AMT level reference set R holding every member, when all of them are medicinal products; else ''. */
|
|
50822
|
+
async function amtLevel(g, members, q) {
|
|
50823
|
+
if (g.truePos(MEDICINAL_PRODUCT) !== members.size) return "";
|
|
50824
|
+
for (const refset of AMT_LEVEL_REFSETS) try {
|
|
50825
|
+
if (await q.count({
|
|
50826
|
+
include: [members.clause],
|
|
50827
|
+
exclude: [{ ecl: `^ ${refset}` }]
|
|
50828
|
+
}) === 0) return `^ ${refset}`;
|
|
50829
|
+
} catch {}
|
|
50830
|
+
return "";
|
|
50831
|
+
}
|
|
49893
50832
|
/**
|
|
49894
50833
|
* The lowest non-member concepts with every member below them, at most 3. Their
|
|
49895
50834
|
* descendants may not be loaded: under `within` they are still worth counting
|
|
@@ -50300,6 +51239,82 @@ function exactScore(size) {
|
|
|
50300
51239
|
clauses: 0
|
|
50301
51240
|
};
|
|
50302
51241
|
}
|
|
51242
|
+
/**
|
|
51243
|
+
* localScoring: the candidates with their counts taken from the
|
|
51244
|
+
* graph, when it is complete and nothing restricts what additions count;
|
|
51245
|
+
* `countedLocally` collects those so counted.
|
|
51246
|
+
*/
|
|
51247
|
+
function countOnGraph(candidates, graph, opts, countedLocally) {
|
|
51248
|
+
if (!opts.localScoring || graph.partial || opts.within) return candidates;
|
|
51249
|
+
return candidates.map((b) => {
|
|
51250
|
+
const known = b.form ? graphScore(b.form, graph, opts.sampleSize) : null;
|
|
51251
|
+
if (!known) return b;
|
|
51252
|
+
countedLocally.add(b.ecl);
|
|
51253
|
+
return {
|
|
51254
|
+
...b,
|
|
51255
|
+
known: {
|
|
51256
|
+
...known,
|
|
51257
|
+
clauses: countClauses(b.ecl)
|
|
51258
|
+
}
|
|
51259
|
+
};
|
|
51260
|
+
});
|
|
51261
|
+
}
|
|
51262
|
+
/** Additions and misses of a form counted on the graph, with sample codes (no terms yet). */
|
|
51263
|
+
function graphScore(form, g, sampleSize) {
|
|
51264
|
+
const selected = evaluate(form, g);
|
|
51265
|
+
if (!selected) return null;
|
|
51266
|
+
const additions = [...selected].filter((x) => !g.members.has(x)).sort(byId);
|
|
51267
|
+
const misses = [...g.members].filter((m) => !selected.has(m)).sort(byId);
|
|
51268
|
+
const sample = (ids) => ids.slice(0, sampleSize).map((code) => ({
|
|
51269
|
+
code,
|
|
51270
|
+
display: ""
|
|
51271
|
+
}));
|
|
51272
|
+
return {
|
|
51273
|
+
covered: g.members.size - misses.length,
|
|
51274
|
+
additions: {
|
|
51275
|
+
count: additions.length,
|
|
51276
|
+
sample: sample(additions)
|
|
51277
|
+
},
|
|
51278
|
+
misses: {
|
|
51279
|
+
count: misses.length,
|
|
51280
|
+
sample: sample(misses)
|
|
51281
|
+
},
|
|
51282
|
+
exact: additions.length === 0 && misses.length === 0
|
|
51283
|
+
};
|
|
51284
|
+
}
|
|
51285
|
+
/**
|
|
51286
|
+
* The best candidate, when counted on the graph, is counted again
|
|
51287
|
+
* on the server (the server's counts replace the graph's), and the samples of
|
|
51288
|
+
* the others counted on the graph get their terms in one lookup.
|
|
51289
|
+
*/
|
|
51290
|
+
async function checkLocalCounts(top, countedLocally, members, q, opts, notes) {
|
|
51291
|
+
if (countedLocally.size === 0) return;
|
|
51292
|
+
const best = top.length > 0 ? top[0] : void 0;
|
|
51293
|
+
if (best && countedLocally.has(best.ecl)) try {
|
|
51294
|
+
if (await q.countEcl(best.ecl) === best.covered + best.additions.count) {
|
|
51295
|
+
await fillTerms(top, countedLocally, q);
|
|
51296
|
+
return;
|
|
51297
|
+
}
|
|
51298
|
+
const server = await compare(best.ecl, members, q, opts.sampleSize, opts.within);
|
|
51299
|
+
if (server.additions.count !== best.additions.count || server.misses.count !== best.misses.count) notes.push(`Graph counts for ${best.ecl.slice(0, 120)} differed from the server's (+${best.additions.count} -${best.misses.count} on the graph, +${server.additions.count} -${server.misses.count} on the server).`);
|
|
51300
|
+
Object.assign(best, server);
|
|
51301
|
+
} catch (error) {
|
|
51302
|
+
notes.push(`Could not check ${best.ecl.slice(0, 120)} on the server: ${errorMessage(error)}`);
|
|
51303
|
+
}
|
|
51304
|
+
await fillTerms(top, countedLocally, q);
|
|
51305
|
+
}
|
|
51306
|
+
/** Terms for the samples of the candidates counted on the graph, in one lookup. */
|
|
51307
|
+
async function fillTerms(top, countedLocally, q) {
|
|
51308
|
+
const codes = /* @__PURE__ */ new Set();
|
|
51309
|
+
for (const s of top) {
|
|
51310
|
+
if (!countedLocally.has(s.ecl)) continue;
|
|
51311
|
+
for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) codes.add(c.code);
|
|
51312
|
+
}
|
|
51313
|
+
if (codes.size === 0) return;
|
|
51314
|
+
const found = await q.concepts({ include: [{ concepts: [...codes] }] }, codes.size, false);
|
|
51315
|
+
const terms = new Map(found.concepts.map((c) => [c.code, c.display]));
|
|
51316
|
+
for (const s of top) for (const c of [...s.additions.sample, ...s.misses.sample]) if (!c.display) c.display = terms.get(c.code) ?? "";
|
|
51317
|
+
}
|
|
50303
51318
|
/** Additions and misses of `ecl` against the set, counted and sampled by the server. */
|
|
50304
51319
|
async function compare(ecl, members, q, sampleSize, within) {
|
|
50305
51320
|
const counted = within ? `(${ecl}) AND (${within})` : ecl;
|
|
@@ -50318,7 +51333,13 @@ async function compare(ecl, members, q, sampleSize, within) {
|
|
|
50318
51333
|
clauses: countClauses(ecl)
|
|
50319
51334
|
};
|
|
50320
51335
|
}
|
|
50321
|
-
|
|
51336
|
+
/**
|
|
51337
|
+
* Preferred terms for the ids in the candidates worth decorating. Terms are
|
|
51338
|
+
* decoration: when the lookup fails, the candidates go out with bare ids and,
|
|
51339
|
+
* given `notes`, a note says why (the failure itself is counted by the caller's
|
|
51340
|
+
* service), rather than losing a finished result.
|
|
51341
|
+
*/
|
|
51342
|
+
async function displayTerms(candidates, terminology, notes) {
|
|
50322
51343
|
const ids = /* @__PURE__ */ new Set();
|
|
50323
51344
|
for (const c of candidates) {
|
|
50324
51345
|
if (c.clauses > MAX_DECORATED_CLAUSES) continue;
|
|
@@ -50326,7 +51347,13 @@ async function displayTerms(candidates, terminology) {
|
|
|
50326
51347
|
}
|
|
50327
51348
|
const terms = /* @__PURE__ */ new Map();
|
|
50328
51349
|
if (ids.size === 0) return terms;
|
|
50329
|
-
|
|
51350
|
+
let infos;
|
|
51351
|
+
try {
|
|
51352
|
+
infos = await terminology.validateConcepts([...ids].sort(byId));
|
|
51353
|
+
} catch (error) {
|
|
51354
|
+
notes?.push(`Display terms could not be looked up: ${errorMessage(error)}.`);
|
|
51355
|
+
return terms;
|
|
51356
|
+
}
|
|
50330
51357
|
for (const [id, info] of infos) if (info?.pt) terms.set(id, info.pt);
|
|
50331
51358
|
return terms;
|
|
50332
51359
|
}
|
|
@@ -50406,6 +51433,7 @@ function bareSub(s) {
|
|
|
50406
51433
|
function formatDeriveReport(result) {
|
|
50407
51434
|
const lines = [];
|
|
50408
51435
|
const { input } = result;
|
|
51436
|
+
if (result.failures > 0) lines.push(incompleteLine(result.failures));
|
|
50409
51437
|
const duplicates = input.duplicates ? ` (${plural(input.duplicates, "duplicate")} ignored)` : "";
|
|
50410
51438
|
lines.push(`Members: ${input.members} of ${input.given} distinct ids${duplicates}`);
|
|
50411
51439
|
const leftOut = [
|
|
@@ -50458,8 +51486,16 @@ function reviewLines(c, inactiveListedAbove) {
|
|
|
50458
51486
|
lines.push(`Inactive members: ${c.inactive.length}: ${c.inactive.slice(0, 20).join(", ")}${more}.`);
|
|
50459
51487
|
}
|
|
50460
51488
|
if (c.impliedInactive?.count) lines.push(sampleLine("Implied inactive codes not listed", c.impliedInactive));
|
|
51489
|
+
for (const d of c.duplicateTerms) {
|
|
51490
|
+
const concepts = d.concepts.map((x) => x.fsn ? `${x.conceptId} |${x.fsn}|` : x.conceptId);
|
|
51491
|
+
lines.push(`Same term, different concepts: |${d.term}| is ${concepts.join(", ")}.`);
|
|
51492
|
+
}
|
|
50461
51493
|
return lines.length > 0 ? lines : ["Nothing flagged."];
|
|
50462
51494
|
}
|
|
51495
|
+
/** The first line of a report whose result lost candidates or checks to server failures. */
|
|
51496
|
+
function incompleteLine(failures) {
|
|
51497
|
+
return `Incomplete: ${failures} server ${failures === 1 ? "query" : "queries"} failed, so candidates or checks that needed them are missing and a better form may exist (see Notes). Run it again when the server recovers.`;
|
|
51498
|
+
}
|
|
50463
51499
|
function errorMessage(error) {
|
|
50464
51500
|
return error instanceof Error ? error.message : String(error);
|
|
50465
51501
|
}
|
|
@@ -50474,6 +51510,12 @@ function plural(n, noun) {
|
|
|
50474
51510
|
* Needs a terminology service with `expandCompose`.
|
|
50475
51511
|
*/
|
|
50476
51512
|
async function compressExpression(ecl, terminology, options = {}) {
|
|
51513
|
+
const { service, failures } = countingFailures(terminology);
|
|
51514
|
+
const result = await compress(ecl, service, options);
|
|
51515
|
+
result.failures = failures();
|
|
51516
|
+
return result;
|
|
51517
|
+
}
|
|
51518
|
+
async function compress(ecl, terminology, options) {
|
|
50477
51519
|
const original = stripTermsAndComments(ecl);
|
|
50478
51520
|
const parsed = parseECL(original);
|
|
50479
51521
|
const result = {
|
|
@@ -50481,7 +51523,8 @@ async function compressExpression(ecl, terminology, options = {}) {
|
|
|
50481
51523
|
group: null,
|
|
50482
51524
|
candidates: [],
|
|
50483
51525
|
notes: [],
|
|
50484
|
-
errors: []
|
|
51526
|
+
errors: [],
|
|
51527
|
+
failures: 0
|
|
50485
51528
|
};
|
|
50486
51529
|
if (!parsed.ast || parsed.errors.length > 0) {
|
|
50487
51530
|
result.errors = parsed.errors.map((e) => e.message);
|
|
@@ -50530,7 +51573,7 @@ async function compressExpression(ecl, terminology, options = {}) {
|
|
|
50530
51573
|
built.sort((a, b) => cost(a) - cost(b) || Number(b.exact) - Number(a.exact) || SOURCE_ORDER[a.source] - SOURCE_ORDER[b.source] || a.ecl.length - b.ecl.length);
|
|
50531
51574
|
const top = built.slice(0, options.maxCandidates ?? 8);
|
|
50532
51575
|
for (const c of built) if (c.source !== "derived" && !top.includes(c)) top.push(c);
|
|
50533
|
-
const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology);
|
|
51576
|
+
const terms = options.omitTerms ? /* @__PURE__ */ new Map() : await displayTerms(top, terminology, result.notes);
|
|
50534
51577
|
result.candidates = top.map((c) => ({
|
|
50535
51578
|
expression: decorate(c.ecl, terms),
|
|
50536
51579
|
...c,
|
|
@@ -50655,6 +51698,7 @@ function orInside(sub, text) {
|
|
|
50655
51698
|
function formatCompressReport(result) {
|
|
50656
51699
|
if (result.errors.length > 0) return `Not compressed: ${result.errors.join("; ")}`;
|
|
50657
51700
|
const lines = [`Original selects ${result.members} concepts.`];
|
|
51701
|
+
if (result.failures > 0) lines.unshift(incompleteLine(result.failures));
|
|
50658
51702
|
if (result.group && result.group.start > 0) lines.push(`Compressed group: ${result.group.text}`);
|
|
50659
51703
|
for (const note of result.notes) lines.push(`Note: ${note}`);
|
|
50660
51704
|
result.candidates.forEach((c, i) => {
|
|
@@ -50670,6 +51714,189 @@ function formatCompressReport(result) {
|
|
|
50670
51714
|
});
|
|
50671
51715
|
return lines.join("\n");
|
|
50672
51716
|
}
|
|
51717
|
+
// src/minify/minify.ts
|
|
51718
|
+
var import_TerminalNode = require_TerminalNode();
|
|
51719
|
+
var MinifyError = class extends Error {
|
|
51720
|
+
parseErrors;
|
|
51721
|
+
constructor(message, parseErrors) {
|
|
51722
|
+
super(message);
|
|
51723
|
+
this.parseErrors = parseErrors;
|
|
51724
|
+
this.name = "MinifyError";
|
|
51725
|
+
}
|
|
51726
|
+
};
|
|
51727
|
+
/**
|
|
51728
|
+
* Returns the shortest form of an ECL expression that parses to the same
|
|
51729
|
+
* expression.
|
|
51730
|
+
*
|
|
51731
|
+
* - Display terms (`404684003 |Clinical finding|`) are removed.
|
|
51732
|
+
* - Whitespace is removed wherever the grammar makes it optional, and becomes a
|
|
51733
|
+
* single space where it is mandatory (after `AND`, `OR` and `MINUS`, and
|
|
51734
|
+
* between the items of a set such as `(en-au (prefer) en-gb)`).
|
|
51735
|
+
* - A space is also kept where removing it would join two words or numbers
|
|
51736
|
+
* (`D term`, `R 363698007`) or two characters into a different operator
|
|
51737
|
+
* (`< !!>`, `{ {`).
|
|
51738
|
+
* - Quoted strings (term filters, alternate identifiers, dates) are kept as
|
|
51739
|
+
* written, except that a tab or line break in one becomes a space.
|
|
51740
|
+
* - Block comments are kept unless `removeComments` is set.
|
|
51741
|
+
*
|
|
51742
|
+
* The result contains no tab, carriage return or line feed, so it is safe for
|
|
51743
|
+
* an RF2 file. Operand order, brackets and refinement groups are unchanged.
|
|
51744
|
+
*
|
|
51745
|
+
* Throws `MinifyError` if the expression cannot be parsed.
|
|
51746
|
+
*/
|
|
51747
|
+
function minifyExpression(expression, options = {}) {
|
|
51748
|
+
const tree = parseOrThrow(expression);
|
|
51749
|
+
const minified = new Minifier(options.removeComments ?? false).print(tree);
|
|
51750
|
+
const check = parseConcreteTree(minified);
|
|
51751
|
+
if (!check.tree || check.errors.length > 0 || structureOf(check.tree) !== structureOf(tree)) throw new MinifyError(`Minifying changed the expression's structure; the result was: ${minified}`, check.errors);
|
|
51752
|
+
return minified;
|
|
51753
|
+
}
|
|
51754
|
+
function parseOrThrow(expression) {
|
|
51755
|
+
const { tree, errors } = parseConcreteTree(expression);
|
|
51756
|
+
if (tree && errors.length === 0) return tree;
|
|
51757
|
+
const friendly = parseECL(expression).errors;
|
|
51758
|
+
const reported = friendly.length > 0 ? friendly : errors;
|
|
51759
|
+
throw new MinifyError(`Cannot minify invalid ECL: ${reported[0]?.message ?? "unknown error"}`, reported);
|
|
51760
|
+
}
|
|
51761
|
+
var VERBATIM_RULES = /* @__PURE__ */ new Set([ECLParser.RULE_matchsearchtermset]);
|
|
51762
|
+
var TERM_BEARING_RULES = /* @__PURE__ */ new Set([ECLParser.RULE_eclconceptreference, ECLParser.RULE_altidentifier]);
|
|
51763
|
+
var LINE_BREAK_OR_TAB = /[\t\r\n]/g;
|
|
51764
|
+
var WHITESPACE_CHAR_RULES = /* @__PURE__ */ new Set([
|
|
51765
|
+
ECLParser.RULE_htab,
|
|
51766
|
+
ECLParser.RULE_cr,
|
|
51767
|
+
ECLParser.RULE_lf
|
|
51768
|
+
]);
|
|
51769
|
+
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
51770
|
+
var JOINING_PAIRS = /* @__PURE__ */ new Set([
|
|
51771
|
+
"<<",
|
|
51772
|
+
"<!",
|
|
51773
|
+
"<=",
|
|
51774
|
+
">>",
|
|
51775
|
+
">!",
|
|
51776
|
+
">=",
|
|
51777
|
+
"!!",
|
|
51778
|
+
"!=",
|
|
51779
|
+
"!<",
|
|
51780
|
+
"!>",
|
|
51781
|
+
"{{",
|
|
51782
|
+
"}}",
|
|
51783
|
+
"/*",
|
|
51784
|
+
"*/",
|
|
51785
|
+
"//",
|
|
51786
|
+
".."
|
|
51787
|
+
]);
|
|
51788
|
+
function needsSpace(before, after) {
|
|
51789
|
+
if (WORD_CHAR.test(before) && WORD_CHAR.test(after)) return true;
|
|
51790
|
+
return JOINING_PAIRS.has(before + after);
|
|
51791
|
+
}
|
|
51792
|
+
var Minifier = class {
|
|
51793
|
+
removeComments;
|
|
51794
|
+
out = "";
|
|
51795
|
+
brokenHere = false;
|
|
51796
|
+
afterUnquotedCode = false;
|
|
51797
|
+
constructor(removeComments) {
|
|
51798
|
+
this.removeComments = removeComments;
|
|
51799
|
+
}
|
|
51800
|
+
print(tree) {
|
|
51801
|
+
this.visit(tree);
|
|
51802
|
+
return this.out;
|
|
51803
|
+
}
|
|
51804
|
+
visit(node) {
|
|
51805
|
+
if (node instanceof import_TerminalNode.TerminalNode) {
|
|
51806
|
+
this.append(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
|
|
51807
|
+
return;
|
|
51808
|
+
}
|
|
51809
|
+
if (!(node instanceof import_antlr4ts.ParserRuleContext)) return;
|
|
51810
|
+
switch (node.ruleIndex) {
|
|
51811
|
+
case ECLParser.RULE_ws:
|
|
51812
|
+
this.separator(node, false);
|
|
51813
|
+
return;
|
|
51814
|
+
case ECLParser.RULE_mws:
|
|
51815
|
+
this.separator(node, true);
|
|
51816
|
+
return;
|
|
51817
|
+
}
|
|
51818
|
+
if (VERBATIM_RULES.has(node.ruleIndex)) {
|
|
51819
|
+
this.append(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
|
|
51820
|
+
return;
|
|
51821
|
+
}
|
|
51822
|
+
if (TERM_BEARING_RULES.has(node.ruleIndex)) {
|
|
51823
|
+
this.visitWithoutTerm(node);
|
|
51824
|
+
return;
|
|
51825
|
+
}
|
|
51826
|
+
for (const child of node.children ?? []) this.visit(child);
|
|
51827
|
+
}
|
|
51828
|
+
/** Prints a concept reference or alternate identifier without its `|term|`. */
|
|
51829
|
+
visitWithoutTerm(node) {
|
|
51830
|
+
const children = node.children ?? [];
|
|
51831
|
+
const firstPipe = children.findIndex((c) => c instanceof import_TerminalNode.TerminalNode && c.text === "|");
|
|
51832
|
+
if (firstPipe === -1) {
|
|
51833
|
+
for (const child of children) this.visit(child);
|
|
51834
|
+
this.noteUnquotedCode(node);
|
|
51835
|
+
return;
|
|
51836
|
+
}
|
|
51837
|
+
for (const child of children.slice(0, firstPipe - 1)) this.visit(child);
|
|
51838
|
+
this.noteUnquotedCode(node);
|
|
51839
|
+
for (const child of children.slice(firstPipe - 1)) if (child instanceof import_antlr4ts.ParserRuleContext && child.ruleIndex === ECLParser.RULE_ws) this.visit(child);
|
|
51840
|
+
this.brokenHere = true;
|
|
51841
|
+
}
|
|
51842
|
+
noteUnquotedCode(node) {
|
|
51843
|
+
const first = node.children?.[0];
|
|
51844
|
+
const quoted = first instanceof import_antlr4ts.ParserRuleContext && first.ruleIndex === ECLParser.RULE_qm;
|
|
51845
|
+
this.afterUnquotedCode = node.ruleIndex === ECLParser.RULE_altidentifier && !quoted;
|
|
51846
|
+
}
|
|
51847
|
+
/** Optional (`ws`) or mandatory (`mws`) whitespace, which may hold comments. */
|
|
51848
|
+
separator(node, mandatory) {
|
|
51849
|
+
if (node.text.length === 0) return;
|
|
51850
|
+
const comments = this.removeComments ? [] : (node.children ?? []).filter((c) => c instanceof import_antlr4ts.ParserRuleContext && c.ruleIndex === ECLParser.RULE_comment);
|
|
51851
|
+
this.brokenHere = true;
|
|
51852
|
+
for (const comment of comments) {
|
|
51853
|
+
this.append(comment.text.replaceAll(/\s+/g, " "));
|
|
51854
|
+
this.brokenHere = true;
|
|
51855
|
+
}
|
|
51856
|
+
if (mandatory && comments.length === 0) {
|
|
51857
|
+
this.out += " ";
|
|
51858
|
+
this.brokenHere = false;
|
|
51859
|
+
}
|
|
51860
|
+
}
|
|
51861
|
+
append(text) {
|
|
51862
|
+
if (text.length === 0) return;
|
|
51863
|
+
const last = this.out.at(-1);
|
|
51864
|
+
const keepApart = needsSpace(last ?? "", text[0]) || this.afterUnquotedCode && text.startsWith(".");
|
|
51865
|
+
if (this.brokenHere && last !== void 0 && keepApart) this.out += " ";
|
|
51866
|
+
this.out += text;
|
|
51867
|
+
this.brokenHere = false;
|
|
51868
|
+
this.afterUnquotedCode = false;
|
|
51869
|
+
}
|
|
51870
|
+
};
|
|
51871
|
+
/**
|
|
51872
|
+
* The parse tree reduced to what the expression means: rule names and
|
|
51873
|
+
* characters, without whitespace, comments, display terms, or the difference
|
|
51874
|
+
* between a tab and a space inside a string.
|
|
51875
|
+
*/
|
|
51876
|
+
function structureOf(tree) {
|
|
51877
|
+
const parts = [];
|
|
51878
|
+
const walk = (node) => {
|
|
51879
|
+
if (node instanceof import_TerminalNode.TerminalNode) {
|
|
51880
|
+
parts.push(node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
|
|
51881
|
+
return;
|
|
51882
|
+
}
|
|
51883
|
+
if (!(node instanceof import_antlr4ts.ParserRuleContext)) return;
|
|
51884
|
+
const rule = WHITESPACE_CHAR_RULES.has(node.ruleIndex) ? ECLParser.RULE_sp : node.ruleIndex;
|
|
51885
|
+
if (rule === ECLParser.RULE_ws || rule === ECLParser.RULE_mws) return;
|
|
51886
|
+
if (VERBATIM_RULES.has(rule)) {
|
|
51887
|
+
parts.push(`[${rule}]`, node.text.replaceAll(LINE_BREAK_OR_TAB, " "));
|
|
51888
|
+
return;
|
|
51889
|
+
}
|
|
51890
|
+
parts.push(`[${rule}]`);
|
|
51891
|
+
const children = node.children ?? [];
|
|
51892
|
+
const firstPipe = TERM_BEARING_RULES.has(rule) ? children.findIndex((c) => c instanceof import_TerminalNode.TerminalNode && c.text === "|") : -1;
|
|
51893
|
+
const kept = firstPipe === -1 ? children : children.slice(0, firstPipe - 1);
|
|
51894
|
+
for (const child of kept) walk(child);
|
|
51895
|
+
parts.push("]");
|
|
51896
|
+
};
|
|
51897
|
+
walk(tree);
|
|
51898
|
+
return parts.join("");
|
|
51899
|
+
}
|
|
50673
51900
|
// src/knowledge/operators.ts
|
|
50674
51901
|
/**
|
|
50675
51902
|
* All 15+ ECL operators with meanings, syntax, and examples.
|
|
@@ -51732,4 +52959,4 @@ var knowledgeGuides = [
|
|
|
51732
52959
|
function getGuide(uri) {
|
|
51733
52960
|
return knowledgeGuides.find((g) => g.uri === uri);
|
|
51734
52961
|
}
|
|
51735
|
-
export { CanonicaliseError, FhirTerminologyService, REFACTORING_RESOLVE_KIND, TerminologyError, TerminologyHttpError, TerminologyTransportError, allArticles, analyzeExpression, buildReplacementText, canonicalise, checkMixedRefinementOperators, clearFilterCache, compareExpressions, compressExpression, computeSemanticTokens, coreInsert, coreReplace, defaultFormattingOptions, deriveEcl, deriveInputFromText, detectCursorContext, detectFilterContext, eclSnippetCompletions, eclTokenModifiers, eclTokenTypes, expandToExpressionBoundaries, extractCompoundOperands, extractConceptIds, extractConceptSearchQuery, extractRefinementInfo, extractText, formatCompressReport, formatDeriveReport, formatDocument, formatRangeExpressions, getArticle, getArticlesByCategory, getCompletionItems, getCompletionItemsWithSearch, getConceptSearchPriority, getExpressionsInRange, getFhirFilterCompletions, getGuide, getOperatorHoverDoc, getRefactoringActions, getText, getValidOperatorsAtPosition, groupIntoExpressions, isConceptPositionValid, isEclEvaluationStrategy, isTerminologyError, isTerminologyHttpError, isTerminologyTransportError, isValidConceptId, isValidDescriptionId, isValidSnomedId, knowledgeGuides, offsetAt, operatorHoverDocs, parseConceptIdList, parseECL, positionAt, refineParseError, resolveAddDisplayTerms, resolveUnifiedSimplify, simplifyExpression, toHttpError, toTransportError, validateBoolean, validateIndentSize, validateIndentStyle, validateMaxLineLength, validateSemantics };
|
|
52962
|
+
export { CanonicaliseError, FhirTerminologyService, MinifyError, REFACTORING_RESOLVE_KIND, TerminologyError, TerminologyHttpError, TerminologyTransportError, allArticles, analyzeExpression, buildReplacementText, canonicalise, checkMixedRefinementOperators, clearFilterCache, compareExpressions, compressExpression, computeSemanticTokens, coreInsert, coreReplace, defaultFormattingOptions, deriveEcl, deriveInputFromText, detectCursorContext, detectFilterContext, eclSnippetCompletions, eclTokenModifiers, eclTokenTypes, expandToExpressionBoundaries, extractCompoundOperands, extractConceptIds, extractConceptSearchQuery, extractRefinementInfo, extractText, formatCompressReport, formatDeriveReport, formatDocument, formatRangeExpressions, getArticle, getArticlesByCategory, getCompletionItems, getCompletionItemsWithSearch, getConceptSearchPriority, getExpressionsInRange, getFhirFilterCompletions, getGuide, getOperatorHoverDoc, getRefactoringActions, getText, getValidOperatorsAtPosition, groupIntoExpressions, isConceptPositionValid, isEclEvaluationStrategy, isTerminologyError, isTerminologyHttpError, isTerminologyTransportError, isValidConceptId, isValidDescriptionId, isValidSnomedId, knowledgeGuides, minifyExpression, offsetAt, operatorHoverDocs, parseConceptIdList, parseECL, positionAt, refineParseError, resolveAddDisplayTerms, resolveUnifiedSimplify, simplifyExpression, toHttpError, toTransportError, validateBoolean, validateIndentSize, validateIndentStyle, validateMaxLineLength, validateSemantics };
|