@aehrc/ecl-core 1.1.2 → 1.2.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/dist/index.cjs CHANGED
@@ -25676,6 +25676,7 @@ function requireAntlr4ts() {
25676
25676
  return antlr4ts;
25677
25677
  }
25678
25678
  var antlr4tsExports = requireAntlr4ts();
25679
+ var PredictionModeExports = requirePredictionMode();
25679
25680
  var ATNDeserializerExports = requireATNDeserializer();
25680
25681
  var LexerExports = requireLexer();
25681
25682
  var LexerATNSimulatorExports = requireLexerATNSimulator();
@@ -50917,6 +50918,8 @@ var NodeType = /* @__PURE__ */ ((NodeType2) => {
50917
50918
  NodeType2["ConstraintOperator"] = "ConstraintOperator";
50918
50919
  NodeType2["LogicalOperator"] = "LogicalOperator";
50919
50920
  NodeType2["Refinement"] = "Refinement";
50921
+ NodeType2["AttributeSet"] = "AttributeSet";
50922
+ NodeType2["AttributeGroup"] = "AttributeGroup";
50920
50923
  NodeType2["Attribute"] = "Attribute";
50921
50924
  NodeType2["AttributeName"] = "AttributeName";
50922
50925
  NodeType2["AttributeValue"] = "AttributeValue";
@@ -51111,76 +51114,106 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51111
51114
  };
51112
51115
  }
51113
51116
  visitEclrefinement(ctx) {
51117
+ const content = this.buildRefinement(ctx);
51114
51118
  const attributes = [];
51115
- this.collectAttributesFromSubrefinement(ctx.subrefinement(), attributes);
51119
+ collectAttributes$1(content, attributes);
51120
+ return {
51121
+ type: NodeType.Refinement,
51122
+ range: this.getRange(ctx),
51123
+ attributes,
51124
+ content
51125
+ };
51126
+ }
51127
+ /**
51128
+ * eclrefinement : subrefinement ws (conjunctionrefinementset | disjunctionrefinementset)?
51129
+ *
51130
+ * The grammar forbids mixing conjunction and disjunction at the same level, so
51131
+ * at most one of the two sets is present and the resulting set is homogeneous.
51132
+ */
51133
+ buildRefinement(ctx) {
51134
+ const first = this.buildSubrefinement(ctx.subrefinement());
51116
51135
  const conjSet = ctx.conjunctionrefinementset();
51117
51136
  if (conjSet) {
51118
- const subs = conjSet.subrefinement();
51119
- for (const sub of subs) {
51120
- this.collectAttributesFromSubrefinement(sub, attributes);
51121
- }
51137
+ const rest = conjSet.subrefinement().map((sub) => this.buildSubrefinement(sub));
51138
+ return this.makeSet(ctx, "AND", conjunctionStyle(conjSet.conjunction()), [first, ...rest]);
51122
51139
  }
51123
51140
  const disjSet = ctx.disjunctionrefinementset();
51124
51141
  if (disjSet) {
51125
- const subs = disjSet.subrefinement();
51126
- for (const sub of subs) {
51127
- this.collectAttributesFromSubrefinement(sub, attributes);
51128
- }
51142
+ const rest = disjSet.subrefinement().map((sub) => this.buildSubrefinement(sub));
51143
+ return this.makeSet(ctx, "OR", ",", [first, ...rest]);
51129
51144
  }
51130
- return {
51131
- type: NodeType.Refinement,
51132
- range: this.getRange(ctx),
51133
- attributes
51134
- };
51145
+ return first;
51135
51146
  }
51136
- collectAttributesFromSubrefinement(ctx, attributes) {
51147
+ /** subrefinement : eclattributeset | eclattributegroup | ( eclrefinement ) */
51148
+ buildSubrefinement(ctx) {
51137
51149
  const attrSet = ctx.eclattributeset();
51138
51150
  if (attrSet) {
51139
- this.collectAttributesFromAttributeSet(attrSet, attributes);
51140
- return;
51151
+ return this.buildAttributeSet(attrSet);
51141
51152
  }
51142
51153
  const attrGroup = ctx.eclattributegroup();
51143
51154
  if (attrGroup) {
51144
- const groupAttrSet = attrGroup.eclattributeset();
51145
- this.collectAttributesFromAttributeSet(groupAttrSet, attributes);
51146
- return;
51155
+ const content = this.buildAttributeSet(attrGroup.eclattributeset());
51156
+ if (!content) {
51157
+ return null;
51158
+ }
51159
+ const cardinality = attrGroup.cardinality();
51160
+ const group = {
51161
+ type: NodeType.AttributeGroup,
51162
+ range: this.getRange(ctx),
51163
+ content
51164
+ };
51165
+ if (cardinality) {
51166
+ group.cardinality = "[" + cardinality.text + "]";
51167
+ }
51168
+ return group;
51147
51169
  }
51148
51170
  const nestedRef = ctx.eclrefinement();
51149
- if (nestedRef) {
51150
- const nested = this.visitEclrefinement(nestedRef);
51151
- attributes.push(...nested.attributes);
51152
- }
51171
+ return nestedRef ? markParenthesized(this.buildRefinement(nestedRef)) : null;
51153
51172
  }
51154
- collectAttributesFromAttributeSet(ctx, attributes) {
51155
- this.collectAttributeFromSubattributeset(ctx.subattributeset(), attributes);
51173
+ /** eclattributeset : subattributeset ws (conjunctionattributeset | disjunctionattributeset)? */
51174
+ buildAttributeSet(ctx) {
51175
+ const first = this.buildSubattributeSet(ctx.subattributeset());
51156
51176
  const conjSet = ctx.conjunctionattributeset();
51157
51177
  if (conjSet) {
51158
- const subs = conjSet.subattributeset();
51159
- for (const sub of subs) {
51160
- this.collectAttributeFromSubattributeset(sub, attributes);
51161
- }
51178
+ const rest = conjSet.subattributeset().map((sub) => this.buildSubattributeSet(sub));
51179
+ return this.makeSet(ctx, "AND", conjunctionStyle(conjSet.conjunction()), [first, ...rest]);
51162
51180
  }
51163
51181
  const disjSet = ctx.disjunctionattributeset();
51164
51182
  if (disjSet) {
51165
- const subs = disjSet.subattributeset();
51166
- for (const sub of subs) {
51167
- this.collectAttributeFromSubattributeset(sub, attributes);
51168
- }
51183
+ const rest = disjSet.subattributeset().map((sub) => this.buildSubattributeSet(sub));
51184
+ return this.makeSet(ctx, "OR", ",", [first, ...rest]);
51169
51185
  }
51186
+ return first;
51170
51187
  }
51171
- collectAttributeFromSubattributeset(ctx, attributes) {
51188
+ /** subattributeset : eclattribute | ( eclattributeset ) */
51189
+ buildSubattributeSet(ctx) {
51172
51190
  const attr = ctx.eclattribute();
51173
51191
  if (attr) {
51174
- const attrNode = this.visitEclattribute(attr);
51175
- if (attrNode) {
51176
- attributes.push(attrNode);
51177
- }
51178
- return;
51192
+ return this.visitEclattribute(attr);
51179
51193
  }
51180
51194
  const nestedSet = ctx.eclattributeset();
51181
- if (nestedSet) {
51182
- this.collectAttributesFromAttributeSet(nestedSet, attributes);
51195
+ return nestedSet ? markParenthesized(this.buildAttributeSet(nestedSet)) : null;
51196
+ }
51197
+ /**
51198
+ * Build a set node from its members, dropping members that failed to parse.
51199
+ * Collapses to the single member when only one survives, so a set node always
51200
+ * represents a real operator in the source.
51201
+ */
51202
+ makeSet(ctx, operator, style, members) {
51203
+ const present = members.filter((m) => m !== null);
51204
+ if (present.length === 0) {
51205
+ return null;
51183
51206
  }
51207
+ if (present.length === 1) {
51208
+ return present[0];
51209
+ }
51210
+ return {
51211
+ type: NodeType.AttributeSet,
51212
+ range: this.getRange(ctx),
51213
+ operator,
51214
+ conjunctionStyle: operator === "AND" ? style : ",",
51215
+ members: present
51216
+ };
51184
51217
  }
51185
51218
  // eslint-disable-next-line sonarjs/cognitive-complexity -- ANTLR visitor with multiple grammar rule branches
51186
51219
  visitEclattribute(ctx) {
@@ -51243,12 +51276,14 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51243
51276
  rawValue: ctx.text
51244
51277
  };
51245
51278
  }
51279
+ const cardinalityCtx = ctx.cardinality();
51246
51280
  return {
51247
51281
  type: NodeType.Attribute,
51248
51282
  range: this.getRange(ctx),
51249
51283
  name: attrName,
51250
51284
  value,
51251
- reversed
51285
+ reversed,
51286
+ cardinality: cardinalityCtx ? "[" + cardinalityCtx.text + "]" : void 0
51252
51287
  };
51253
51288
  }
51254
51289
  // Dotted expressions
@@ -51451,6 +51486,28 @@ class ECLASTVisitor extends AbstractParseTreeVisitorExports.AbstractParseTreeVis
51451
51486
  }
51452
51487
  }
51453
51488
  }
51489
+ function conjunctionStyle(conjunctions) {
51490
+ return conjunctions.some((c) => !c.text.trimStart().startsWith(",")) ? "AND" : ",";
51491
+ }
51492
+ function collectAttributes$1(node, out) {
51493
+ if (!node) return;
51494
+ switch (node.type) {
51495
+ case NodeType.Attribute:
51496
+ out.push(node);
51497
+ break;
51498
+ case NodeType.AttributeGroup:
51499
+ collectAttributes$1(node.content, out);
51500
+ break;
51501
+ case NodeType.AttributeSet:
51502
+ for (const member of node.members) {
51503
+ collectAttributes$1(member, out);
51504
+ }
51505
+ break;
51506
+ }
51507
+ }
51508
+ function markParenthesized(node) {
51509
+ return (node == null ? void 0 : node.type) === NodeType.AttributeSet ? { ...node, parenthesized: true } : node;
51510
+ }
51454
51511
  class ECLErrorListener {
51455
51512
  constructor() {
51456
51513
  __publicField(this, "errors", []);
@@ -51816,34 +51873,12 @@ function computeColumn(text, i, baseColumn) {
51816
51873
  }
51817
51874
  let lastInput = null;
51818
51875
  let lastResult = null;
51819
- function parseECL(input) {
51820
- if (input === lastInput && lastResult !== null) {
51821
- return lastResult;
51822
- }
51876
+ function runParseAttempt(input, predictionMode) {
51823
51877
  const inputStream = new antlr4tsExports.ANTLRInputStream(input);
51824
51878
  const lexer = new ECLLexer(inputStream);
51825
51879
  const tokenStream = new antlr4tsExports.CommonTokenStream(lexer);
51826
- tokenStream.fill();
51827
- const tokens = tokenStream.getTokens().map((token) => {
51828
- var _a;
51829
- return {
51830
- type: token.type,
51831
- text: token.text ?? "",
51832
- range: {
51833
- start: {
51834
- line: token.line,
51835
- column: token.charPositionInLine,
51836
- offset: token.startIndex
51837
- },
51838
- end: {
51839
- line: token.line,
51840
- column: token.charPositionInLine + (((_a = token.text) == null ? void 0 : _a.length) ?? 0),
51841
- offset: token.stopIndex + 1
51842
- }
51843
- }
51844
- };
51845
- });
51846
51880
  const parser = new ECLParser(tokenStream);
51881
+ parser.interpreter.setPredictionMode(predictionMode);
51847
51882
  const errorListener = new ECLErrorListener();
51848
51883
  parser.removeErrorListeners();
51849
51884
  parser.addErrorListener(errorListener);
@@ -51868,7 +51903,44 @@ function parseECL(input) {
51868
51903
  }
51869
51904
  } catch {
51870
51905
  }
51871
- const existingErrors = errorListener.getErrors();
51906
+ return { ast, errors: errorListener.getErrors() };
51907
+ }
51908
+ function parseWithFallback(input) {
51909
+ const sll = runParseAttempt(input, PredictionModeExports.PredictionMode.SLL);
51910
+ if (sll.ast !== null && sll.errors.length === 0) {
51911
+ return sll;
51912
+ }
51913
+ return runParseAttempt(input, PredictionModeExports.PredictionMode.LL);
51914
+ }
51915
+ function parseECL(input) {
51916
+ if (input === lastInput && lastResult !== null) {
51917
+ return lastResult;
51918
+ }
51919
+ const tokenInputStream = new antlr4tsExports.ANTLRInputStream(input);
51920
+ const tokenLexer = new ECLLexer(tokenInputStream);
51921
+ const tokenStream = new antlr4tsExports.CommonTokenStream(tokenLexer);
51922
+ tokenStream.fill();
51923
+ const tokens = tokenStream.getTokens().map((token) => {
51924
+ var _a;
51925
+ return {
51926
+ type: token.type,
51927
+ text: token.text ?? "",
51928
+ range: {
51929
+ start: {
51930
+ line: token.line,
51931
+ column: token.charPositionInLine,
51932
+ offset: token.startIndex
51933
+ },
51934
+ end: {
51935
+ line: token.line,
51936
+ column: token.charPositionInLine + (((_a = token.text) == null ? void 0 : _a.length) ?? 0),
51937
+ offset: token.stopIndex + 1
51938
+ }
51939
+ }
51940
+ };
51941
+ });
51942
+ const { ast, errors: parseErrors } = parseWithFallback(input);
51943
+ const existingErrors = parseErrors;
51872
51944
  if (existingErrors.length > 0) {
51873
51945
  const issues = analyzeExpression(input);
51874
51946
  if (issues.mixedOperator) {
@@ -51955,7 +52027,7 @@ function parseECL(input) {
51955
52027
  const warnings = ast ? checkMixedRefinementOperators(ast, input) : [];
51956
52028
  const result = {
51957
52029
  ast,
51958
- errors: errorListener.getErrors(),
52030
+ errors: parseErrors,
51959
52031
  warnings,
51960
52032
  tokens
51961
52033
  };
@@ -51968,6 +52040,7 @@ function extractConceptIds(ast, options) {
51968
52040
  const deduplicate = (options == null ? void 0 : options.deduplicate) ?? true;
51969
52041
  const seenIds = /* @__PURE__ */ new Set();
51970
52042
  function visitNode(node) {
52043
+ if (!node) return;
51971
52044
  switch (node.type) {
51972
52045
  case NodeType.ConceptReference:
51973
52046
  if (!deduplicate || !seenIds.has(node.conceptId)) {
@@ -51993,7 +52066,7 @@ function extractConceptIds(ast, options) {
51993
52066
  }
51994
52067
  break;
51995
52068
  case NodeType.ExpressionConstraint:
51996
- if (node.expression) visitNode(node.expression);
52069
+ visitNode(node.expression);
51997
52070
  break;
51998
52071
  case NodeType.SubExpressionConstraint:
51999
52072
  visitNode(node.focus);
@@ -52271,8 +52344,141 @@ function isValidDescriptionId(sctid) {
52271
52344
  const partitionId = sctid.substring(sctid.length - 3, sctid.length - 1);
52272
52345
  return partitionId === "01" || partitionId === "11";
52273
52346
  }
52347
+ class TerminologyError extends Error {
52348
+ constructor(message, options = {}) {
52349
+ super(message);
52350
+ /**
52351
+ * The underlying failure.
52352
+ *
52353
+ * Declared explicitly (rather than relying on `Error.cause`) so it is part of
52354
+ * the emitted type declarations and is present on every runtime.
52355
+ */
52356
+ __publicField(this, "cause");
52357
+ /** The request URL, when known. */
52358
+ __publicField(this, "url");
52359
+ /** The HTTP status, present only on {@link TerminologyHttpError}. */
52360
+ __publicField(this, "status");
52361
+ this.name = "TerminologyError";
52362
+ this.cause = options.cause;
52363
+ this.url = options.url;
52364
+ this.status = options.status;
52365
+ }
52366
+ }
52367
+ class TerminologyTransportError extends TerminologyError {
52368
+ constructor(message, options = {}) {
52369
+ super(message, options);
52370
+ __publicField(this, "kind", "transport");
52371
+ /** True when the failure was a client-side timeout rather than a hard failure. */
52372
+ __publicField(this, "timedOut");
52373
+ this.name = "TerminologyTransportError";
52374
+ this.timedOut = options.timedOut ?? false;
52375
+ }
52376
+ }
52377
+ class TerminologyHttpError extends TerminologyError {
52378
+ constructor(message, options) {
52379
+ super(message, options);
52380
+ __publicField(this, "kind", "http");
52381
+ /** The HTTP reason phrase, when the client exposes one. */
52382
+ __publicField(this, "statusText");
52383
+ this.name = "TerminologyHttpError";
52384
+ this.statusText = options.statusText;
52385
+ }
52386
+ }
52387
+ function isTerminologyError(value) {
52388
+ if (value instanceof TerminologyError) return true;
52389
+ if (!(value instanceof Error)) return false;
52390
+ const kind = value.kind;
52391
+ return value.name === "TerminologyTransportError" && kind === "transport" || value.name === "TerminologyHttpError" && kind === "http";
52392
+ }
52393
+ function isTerminologyTransportError(value) {
52394
+ return isTerminologyError(value) && value.kind === "transport";
52395
+ }
52396
+ function isTerminologyHttpError(value) {
52397
+ return isTerminologyError(value) && value.kind === "http";
52398
+ }
52399
+ function isAbortLike(error) {
52400
+ if (typeof error !== "object" || error === null) return false;
52401
+ const name = error.name;
52402
+ return name === "AbortError" || name === "TimeoutError";
52403
+ }
52404
+ function describe(error) {
52405
+ if (error instanceof Error) return error.message;
52406
+ return String(error);
52407
+ }
52408
+ function toTransportError(error, options) {
52409
+ if (isTerminologyTransportError(error)) return error;
52410
+ const timedOut = isAbortLike(error);
52411
+ const after = options.timeoutMs === void 0 ? "" : ` after ${options.timeoutMs}ms`;
52412
+ const reason = timedOut ? `timed out${after}` : `failed: ${describe(error)}`;
52413
+ return new TerminologyTransportError(`Could not reach the terminology server — ${options.operation} ${reason}`, {
52414
+ cause: error,
52415
+ url: options.url,
52416
+ timedOut
52417
+ });
52418
+ }
52419
+ function toHttpError(options) {
52420
+ const suffix = options.detail ? `: ${options.detail}` : "";
52421
+ return new TerminologyHttpError(
52422
+ `Terminology server returned HTTP ${options.status} for ${options.operation}${suffix}`,
52423
+ options
52424
+ );
52425
+ }
52274
52426
  const DEFAULT_USER_AGENT = "ecl-lsp/1.0.0";
52275
52427
  const IS_BROWSER = typeof globalThis !== "undefined" && "document" in globalThis;
52428
+ function isEclEvaluationStrategy(value) {
52429
+ return value === "auto" || value === "implicit-url" || value === "post";
52430
+ }
52431
+ class ConcurrencyQueue {
52432
+ constructor(max2) {
52433
+ __publicField(this, "running", 0);
52434
+ __publicField(this, "waiters", []);
52435
+ this.max = max2;
52436
+ }
52437
+ run(fn) {
52438
+ return new Promise((resolve, reject) => {
52439
+ const attempt = () => {
52440
+ this.running++;
52441
+ fn().then(resolve, reject).finally(() => {
52442
+ this.running--;
52443
+ const next = this.waiters.shift();
52444
+ if (next) next();
52445
+ });
52446
+ };
52447
+ if (this.running < this.max) attempt();
52448
+ else this.waiters.push(attempt);
52449
+ });
52450
+ }
52451
+ }
52452
+ const RETRY_BASE_DELAY_MS = 500;
52453
+ const RETRY_MAX_DELAY_MS = 1e4;
52454
+ const RETRY_MAX_ATTEMPTS = 3;
52455
+ const RETRY_JITTER_MS = 200;
52456
+ const CANONICAL_URL_RESERVED = [
52457
+ ["|", "%7C"],
52458
+ // FHIR canonical `system|version` delimiter — the issue #68 corruption
52459
+ ["#", "%23"],
52460
+ // URL fragment delimiter; also introduces ECL concrete values such as `#20`
52461
+ ["&", "%26"],
52462
+ // separates parameters within the canonical URL's own query string
52463
+ ["+", "%2B"],
52464
+ // read as a space by form-style query decoders
52465
+ ["?", "%3F"]
52466
+ // query string introducer
52467
+ ];
52468
+ function encodeEclForCanonicalUrl(expression) {
52469
+ let encoded = expression.replaceAll("%", "%25");
52470
+ for (const [character, escape] of CANONICAL_URL_RESERVED) {
52471
+ encoded = encoded.replaceAll(character, escape);
52472
+ }
52473
+ return encoded;
52474
+ }
52475
+ const VALUE_SET_NOT_FOUND = /value\s*sets?\s*not\s*found/i;
52476
+ const IMPLICIT_VALUE_SET_UNSUPPORTED = [
52477
+ /implicit[^.]*value\s*sets?[^.]*not\s*supported/i,
52478
+ /not\s*supported[^.]*implicit[^.]*value\s*sets?/i
52479
+ ];
52480
+ class EvaluationIssueError extends Error {
52481
+ }
52276
52482
  const _FhirTerminologyService = class _FhirTerminologyService {
52277
52483
  constructor(options = {}) {
52278
52484
  __publicField(this, "cache", /* @__PURE__ */ new Map());
@@ -52285,9 +52491,28 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52285
52491
  __publicField(this, "searchCacheTTL");
52286
52492
  // milliseconds
52287
52493
  __publicField(this, "snomedVersion");
52494
+ __publicField(this, "evaluationStrategy");
52288
52495
  __publicField(this, "onResolvedVersion");
52289
52496
  __publicField(this, "resolvedVersion", null);
52497
+ /**
52498
+ * Latched once a POST `ValueSet/$expand` fallback has succeeded in `'auto'` mode: the
52499
+ * server has demonstrated it cannot serve the implicit ValueSet URL form, so subsequent
52500
+ * evaluations skip the wasted round-trip for the lifetime of this instance.
52501
+ */
52502
+ __publicField(this, "usePostExpand", false);
52503
+ /**
52504
+ * Latched once a bulk `ValueSet/$expand` has been rejected with a 4xx: the server does
52505
+ * not accept a POSTed ValueSet enumerating concepts in `compose.include.concept`, and
52506
+ * the request shape never varies, so retrying it on every validation pass only costs a
52507
+ * wasted round-trip and a console warning (issue #55). 5xx responses are treated as
52508
+ * transient and do not latch.
52509
+ */
52510
+ __publicField(this, "bulkExpandUnsupported", false);
52511
+ __publicField(this, "queue");
52290
52512
  var _a;
52513
+ const maxConcurrency = options.maxConcurrency ?? 25;
52514
+ if (maxConcurrency <= 0) throw new Error(`maxConcurrency must be > 0, got ${maxConcurrency}`);
52515
+ this.queue = new ConcurrencyQueue(maxConcurrency);
52291
52516
  this.baseUrl = options.baseUrl ?? "https://tx.ontoserver.csiro.au/fhir";
52292
52517
  this.timeout = options.timeout ?? 2e3;
52293
52518
  this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
@@ -52295,6 +52520,7 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52295
52520
  this.searchTimeout = 5e3;
52296
52521
  this.searchCacheTTL = 5 * 60 * 1e3;
52297
52522
  this.snomedVersion = ((_a = options.snomedVersion) == null ? void 0 : _a.trim()) ? options.snomedVersion.trim() : void 0;
52523
+ this.evaluationStrategy = isEclEvaluationStrategy(options.evaluationStrategy) ? options.evaluationStrategy : "auto";
52298
52524
  this.onResolvedVersion = options.onResolvedVersion;
52299
52525
  }
52300
52526
  /** The SNOMED CT system URL base for implicit ValueSet URLs. */
@@ -52381,53 +52607,150 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52381
52607
  clearTimeout(timeoutId);
52382
52608
  }
52383
52609
  }
52610
+ /**
52611
+ * Perform a request, translating any network-level failure (connection
52612
+ * refused, DNS failure, timeout/abort) into a {@link TerminologyTransportError}
52613
+ * so callers can tell "server unreachable" from "server said no".
52614
+ */
52615
+ async request(url, timeoutMs, operation, init) {
52616
+ try {
52617
+ return await this.fetchQueued(url, timeoutMs, init);
52618
+ } catch (error) {
52619
+ throw toTransportError(error, { url, operation, timeoutMs });
52620
+ }
52621
+ }
52622
+ /** Read the body of an error response, extracting a FHIR OperationOutcome if present. */
52623
+ static async readErrorBody(response) {
52624
+ var _a, _b;
52625
+ let text;
52626
+ try {
52627
+ text = await response.text();
52628
+ } catch {
52629
+ return { outcome: null, detail: void 0 };
52630
+ }
52631
+ let parsed;
52632
+ try {
52633
+ parsed = JSON.parse(text);
52634
+ } catch {
52635
+ const trimmed = text.trim();
52636
+ return { outcome: null, detail: trimmed ? trimmed.slice(0, 200) : void 0 };
52637
+ }
52638
+ const outcome = typeof parsed === "object" && parsed !== null && parsed.resourceType === "OperationOutcome" ? parsed : null;
52639
+ const issue = (_a = outcome == null ? void 0 : outcome.issue) == null ? void 0 : _a[0];
52640
+ const detail = (issue == null ? void 0 : issue.diagnostics) ?? ((_b = issue == null ? void 0 : issue.details) == null ? void 0 : _b.text);
52641
+ return { outcome, detail };
52642
+ }
52643
+ /**
52644
+ * True when an error response is the server's well-formed way of saying
52645
+ * "I do not know this code" — the one case that maps to `null` rather than
52646
+ * an exception.
52647
+ *
52648
+ * A 404 is only accepted as such when the body is a real FHIR
52649
+ * OperationOutcome; a bare 404 (wrong base URL, proxy page) is a fault.
52650
+ */
52651
+ static isUnknownCodeResponse(status, outcome) {
52652
+ if (!outcome) return false;
52653
+ if (status === 404) return true;
52654
+ if (status !== 400 && status !== 422) return false;
52655
+ return (outcome.issue ?? []).some((issue) => {
52656
+ var _a;
52657
+ if (issue.code && _FhirTerminologyService.UNKNOWN_CODE_ISSUE_CODES.has(issue.code.toLowerCase())) {
52658
+ return true;
52659
+ }
52660
+ const prose = `${issue.diagnostics ?? ""} ${((_a = issue.details) == null ? void 0 : _a.text) ?? ""}`.toLowerCase();
52661
+ return _FhirTerminologyService.UNKNOWN_CODE_PHRASES.some((phrase) => prose.includes(phrase));
52662
+ });
52663
+ }
52664
+ /**
52665
+ * Look up a single concept.
52666
+ *
52667
+ * @returns the concept, or `null` when the terminology server gave a
52668
+ * well-formed answer saying the code is unknown to it.
52669
+ * @throws {TerminologyTransportError} when the server could not be reached,
52670
+ * the request timed out, or the response body was unusable.
52671
+ * @throws {TerminologyHttpError} when the server answered with an error
52672
+ * status that is not an "unknown code" response.
52673
+ */
52674
+ async fetchWithRetry(url, timeoutMs, init) {
52675
+ for (let attempt = 0; attempt < RETRY_MAX_ATTEMPTS; attempt++) {
52676
+ const response = await this.fetchWithTimeout(url, timeoutMs, init);
52677
+ if (response.status !== 429) return response;
52678
+ if (attempt === RETRY_MAX_ATTEMPTS - 1) {
52679
+ throw new Error(`FHIR request rate-limited after ${RETRY_MAX_ATTEMPTS} attempts`);
52680
+ }
52681
+ const retryAfterHeader = response.headers.get("Retry-After");
52682
+ const retryAfterMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : 0;
52683
+ const backoff = Math.min(RETRY_BASE_DELAY_MS * Math.pow(2, attempt), RETRY_MAX_DELAY_MS);
52684
+ const jitter = Math.random() * RETRY_JITTER_MS;
52685
+ const waitMs = Math.max(retryAfterMs, backoff + jitter);
52686
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
52687
+ }
52688
+ throw new Error("Unreachable");
52689
+ }
52690
+ fetchQueued(url, timeoutMs, init) {
52691
+ return this.queue.run(() => this.fetchWithRetry(url, timeoutMs, init));
52692
+ }
52384
52693
  async getConceptInfo(conceptId) {
52385
52694
  var _a;
52386
52695
  const cached = this.cache.get(conceptId);
52387
52696
  if (cached) {
52388
52697
  return cached;
52389
52698
  }
52390
- try {
52391
- let url = `${this.baseUrl}/CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(conceptId)}`;
52392
- if (this.snomedVersion) {
52393
- url += `&version=${encodeURIComponent(this.snomedVersion)}`;
52394
- }
52395
- const response = await this.fetchWithTimeout(url, this.timeout);
52396
- if (!response.ok) {
52699
+ let url = `${this.baseUrl}/CodeSystem/$lookup?system=http://snomed.info/sct&code=${encodeURIComponent(conceptId)}`;
52700
+ if (this.snomedVersion) {
52701
+ url += `&version=${encodeURIComponent(this.snomedVersion)}`;
52702
+ }
52703
+ const operation = `$lookup of concept ${conceptId}`;
52704
+ const response = await this.request(url, this.timeout, operation);
52705
+ if (!response.ok) {
52706
+ const { outcome, detail } = await _FhirTerminologyService.readErrorBody(response);
52707
+ if (_FhirTerminologyService.isUnknownCodeResponse(response.status, outcome)) {
52397
52708
  return null;
52398
52709
  }
52399
- const data = await response.json();
52400
- const params = data.parameter ?? [];
52401
- this.captureResolvedVersionFromLookup(params);
52402
- const display = ((_a = params.find((p) => p.name === "display")) == null ? void 0 : _a.valueString) ?? "";
52403
- const properties = params.filter((p) => p.name === "property");
52404
- const inactiveProperty = properties.find((prop) => {
52405
- const parts = prop.part ?? [];
52406
- const codePart = parts.find((p) => p.name === "code" && p.valueCode === "inactive");
52407
- return codePart !== void 0;
52710
+ throw toHttpError({
52711
+ status: response.status,
52712
+ statusText: response.statusText,
52713
+ url,
52714
+ operation,
52715
+ detail
52408
52716
  });
52409
- let active = true;
52410
- if (inactiveProperty) {
52411
- const valuePart = (inactiveProperty.part ?? []).find((p) => p.name === "value");
52412
- if ((valuePart == null ? void 0 : valuePart.valueBoolean) === true) {
52413
- active = false;
52414
- }
52415
- }
52416
- const conceptInfo = {
52417
- id: conceptId,
52418
- fsn: display,
52419
- pt: display,
52420
- // Simplified - would need to parse designations
52421
- active
52422
- };
52423
- if (this.cache.size < 1e4) {
52424
- this.cache.set(conceptId, conceptInfo);
52425
- }
52426
- return conceptInfo;
52717
+ }
52718
+ let data;
52719
+ try {
52720
+ data = await response.json();
52427
52721
  } catch (error) {
52428
- console.warn(`Failed to fetch concept ${conceptId}:`, error);
52429
- return null;
52722
+ throw new TerminologyTransportError(`Terminology server returned an unreadable response for ${operation}`, {
52723
+ cause: error,
52724
+ url
52725
+ });
52726
+ }
52727
+ const params = data.parameter ?? [];
52728
+ this.captureResolvedVersionFromLookup(params);
52729
+ const display = ((_a = params.find((p) => p.name === "display")) == null ? void 0 : _a.valueString) ?? "";
52730
+ const properties = params.filter((p) => p.name === "property");
52731
+ const inactiveProperty = properties.find((prop) => {
52732
+ const parts = prop.part ?? [];
52733
+ const codePart = parts.find((p) => p.name === "code" && p.valueCode === "inactive");
52734
+ return codePart !== void 0;
52735
+ });
52736
+ let active = true;
52737
+ if (inactiveProperty) {
52738
+ const valuePart = (inactiveProperty.part ?? []).find((p) => p.name === "value");
52739
+ if ((valuePart == null ? void 0 : valuePart.valueBoolean) === true) {
52740
+ active = false;
52741
+ }
52742
+ }
52743
+ const conceptInfo = {
52744
+ id: conceptId,
52745
+ fsn: display,
52746
+ pt: display,
52747
+ // Simplified - would need to parse designations
52748
+ active
52749
+ };
52750
+ if (this.cache.size < 1e4) {
52751
+ this.cache.set(conceptId, conceptInfo);
52430
52752
  }
52753
+ return conceptInfo;
52431
52754
  }
52432
52755
  async getHistoricalAssociations(conceptId) {
52433
52756
  const entries = Object.entries(_FhirTerminologyService.ASSOCIATION_REFSETS);
@@ -52446,7 +52769,7 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52446
52769
  const cmUrl = `${this.snomedSystemUrl}?fhir_cm=${refsetId}`;
52447
52770
  const targetUrl = "http://snomed.info/sct?fhir_vs";
52448
52771
  const url = `${this.baseUrl}/ConceptMap/$translate?code=${encodeURIComponent(conceptId)}&system=${encodeURIComponent("http://snomed.info/sct")}&target=${encodeURIComponent(targetUrl)}&url=${encodeURIComponent(cmUrl)}`;
52449
- const response = await this.fetchWithTimeout(url, this.timeout, {
52772
+ const response = await this.fetchQueued(url, this.timeout, {
52450
52773
  headers: { Accept: "application/fhir+json" }
52451
52774
  });
52452
52775
  if (!response.ok) return [];
@@ -52469,11 +52792,65 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52469
52792
  return [];
52470
52793
  }
52471
52794
  }
52795
+ /**
52796
+ * Validate a batch of concepts.
52797
+ *
52798
+ * A `null` map value means the terminology server positively reported the
52799
+ * code as unknown. Failures are never reported as `null` — they reject.
52800
+ *
52801
+ * @throws {TerminologyTransportError} when the server could not be reached.
52802
+ * @throws {TerminologyHttpError} when the server answered with an error status.
52803
+ */
52472
52804
  async validateConcepts(conceptIds) {
52473
52805
  const results = /* @__PURE__ */ new Map();
52474
52806
  if (conceptIds.length === 0) {
52475
52807
  return results;
52476
52808
  }
52809
+ const uncachedIds = this.partitionCached(conceptIds, results);
52810
+ if (uncachedIds.length === 0) {
52811
+ return results;
52812
+ }
52813
+ if (this.bulkExpandUnsupported) {
52814
+ await this.lookupEach(uncachedIds, results);
52815
+ return results;
52816
+ }
52817
+ try {
52818
+ const expandResults = await this.bulkExpand(uncachedIds);
52819
+ const missingIds = this.mergeExpandResults(uncachedIds, expandResults, results);
52820
+ await this.lookupEach(missingIds, results);
52821
+ return results;
52822
+ } catch (error) {
52823
+ if (isTerminologyTransportError(error)) throw error;
52824
+ if (isTerminologyHttpError(error) && error.status >= 400 && error.status < 500) {
52825
+ this.bulkExpandUnsupported = true;
52826
+ }
52827
+ await this.lookupEach(uncachedIds, results);
52828
+ return results;
52829
+ }
52830
+ }
52831
+ /**
52832
+ * Move concepts found in a bulk expansion into `results` (and the cache),
52833
+ * returning the IDs that were absent and still need an individual lookup.
52834
+ */
52835
+ mergeExpandResults(uncachedIds, expandResults, results) {
52836
+ const missingIds = [];
52837
+ for (const id of uncachedIds) {
52838
+ const info = expandResults.get(id);
52839
+ if (info) {
52840
+ results.set(id, info);
52841
+ if (this.cache.size < 1e4) {
52842
+ this.cache.set(id, info);
52843
+ }
52844
+ } else {
52845
+ missingIds.push(id);
52846
+ }
52847
+ }
52848
+ return missingIds;
52849
+ }
52850
+ /**
52851
+ * Move already-cached concepts into `results`, returning the IDs still to fetch.
52852
+ */
52853
+ partitionCached(conceptIds, results) {
52477
52854
  const uncachedIds = [];
52478
52855
  for (const id of conceptIds) {
52479
52856
  const cachedInfo = this.cache.get(id);
@@ -52483,40 +52860,17 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52483
52860
  uncachedIds.push(id);
52484
52861
  }
52485
52862
  }
52486
- if (uncachedIds.length === 0) {
52487
- return results;
52488
- }
52489
- try {
52490
- const expandResults = await this.bulkExpand(uncachedIds);
52491
- const missingIds = [];
52492
- for (const id of uncachedIds) {
52493
- const info = expandResults.get(id);
52494
- if (info) {
52495
- results.set(id, info);
52496
- if (this.cache.size < 1e4) {
52497
- this.cache.set(id, info);
52498
- }
52499
- } else {
52500
- missingIds.push(id);
52501
- }
52502
- }
52503
- if (missingIds.length > 0) {
52504
- const lookups = missingIds.map(async (id) => {
52505
- const info = await this.getConceptInfo(id);
52506
- results.set(id, info);
52507
- });
52508
- await Promise.all(lookups);
52509
- }
52510
- return results;
52511
- } catch (error) {
52512
- console.warn("Bulk concept validation failed, falling back to individual lookups:", error);
52513
- const lookups = uncachedIds.map(async (id) => {
52863
+ return uncachedIds;
52864
+ }
52865
+ /** Look each concept up individually, recording the result (or `null` if absent). */
52866
+ async lookupEach(conceptIds, results) {
52867
+ if (conceptIds.length === 0) return;
52868
+ await Promise.all(
52869
+ conceptIds.map(async (id) => {
52514
52870
  const info = await this.getConceptInfo(id);
52515
52871
  results.set(id, info);
52516
- });
52517
- await Promise.all(lookups);
52518
- return results;
52519
- }
52872
+ })
52873
+ );
52520
52874
  }
52521
52875
  async bulkExpand(conceptIds) {
52522
52876
  var _a, _b;
@@ -52533,13 +52887,21 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52533
52887
  resourceType: "ValueSet",
52534
52888
  compose: { include: [include] }
52535
52889
  };
52536
- const response = await this.fetchWithTimeout(url, this.timeout, {
52890
+ const operation = `bulk $expand of ${conceptIds.length} concept(s)`;
52891
+ const response = await this.request(url, this.timeout, operation, {
52537
52892
  method: "POST",
52538
52893
  headers: { "Content-Type": "application/fhir+json" },
52539
52894
  body: JSON.stringify(valueSet)
52540
52895
  });
52541
52896
  if (!response.ok) {
52542
- throw new Error(`Bulk expand failed: HTTP ${response.status}`);
52897
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
52898
+ throw toHttpError({
52899
+ status: response.status,
52900
+ statusText: response.statusText,
52901
+ url,
52902
+ operation,
52903
+ detail
52904
+ });
52543
52905
  }
52544
52906
  const data = await response.json();
52545
52907
  this.captureResolvedVersion((_a = data.expansion) == null ? void 0 : _a.parameter);
@@ -52568,6 +52930,14 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52568
52930
  }
52569
52931
  return results;
52570
52932
  }
52933
+ /**
52934
+ * Search for concepts by text or SCTID.
52935
+ *
52936
+ * An empty result set means the server found no matches.
52937
+ *
52938
+ * @throws {TerminologyTransportError} when the server could not be reached.
52939
+ * @throws {TerminologyHttpError} when the server answered with an error status.
52940
+ */
52571
52941
  // eslint-disable-next-line sonarjs/cognitive-complexity -- FHIR response parser with nested property traversal
52572
52942
  async searchConcepts(query) {
52573
52943
  if (!query || query.trim().length === 0) {
@@ -52594,22 +52964,17 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52594
52964
  }
52595
52965
  entriesToDelete.forEach((key) => this.searchCache.delete(key));
52596
52966
  }
52597
- try {
52598
- let response;
52599
- if (/^\d+$/.test(trimmedQuery) && isValidSnomedId(trimmedQuery)) {
52600
- response = await this.lookupById(trimmedQuery);
52601
- } else {
52602
- response = await this.searchByFilter(trimmedQuery);
52603
- }
52604
- this.searchCache.set(trimmedQuery, {
52605
- data: response,
52606
- timestamp: Date.now()
52607
- });
52608
- return response;
52609
- } catch (error) {
52610
- console.warn(`Search failed for query "${trimmedQuery}":`, error);
52611
- throw new Error("Terminology server unavailable");
52967
+ let response;
52968
+ if (/^\d+$/.test(trimmedQuery) && isValidSnomedId(trimmedQuery)) {
52969
+ response = await this.lookupById(trimmedQuery);
52970
+ } else {
52971
+ response = await this.searchByFilter(trimmedQuery);
52612
52972
  }
52973
+ this.searchCache.set(trimmedQuery, {
52974
+ data: response,
52975
+ timestamp: Date.now()
52976
+ });
52977
+ return response;
52613
52978
  }
52614
52979
  async lookupById(conceptId) {
52615
52980
  const info = await this.getConceptInfo(conceptId);
@@ -52628,50 +52993,160 @@ const _FhirTerminologyService = class _FhirTerminologyService {
52628
52993
  };
52629
52994
  }
52630
52995
  async evaluateEcl(expression, limit = 200) {
52631
- var _a, _b, _c, _d, _e;
52632
52996
  if (!expression || expression.trim().length === 0) {
52633
52997
  return { total: 0, concepts: [], truncated: false };
52634
52998
  }
52635
- const implicitVsUrl = `${this.snomedSystemUrl}?fhir_vs=ecl/${expression.trim()}`;
52636
- const url = `${this.baseUrl}/ValueSet/$expand?url=${encodeURIComponent(implicitVsUrl)}&count=${limit}`;
52637
- const response = await this.fetchWithTimeout(url, this.evaluationTimeout);
52638
- if (!response.ok) {
52639
- const data2 = await response.json().catch(() => null);
52640
- const issue = ((_b = (_a = data2 == null ? void 0 : data2.issue) == null ? void 0 : _a[0]) == null ? void 0 : _b.diagnostics) ?? ((_e = (_d = (_c = data2 == null ? void 0 : data2.issue) == null ? void 0 : _c[0]) == null ? void 0 : _d.details) == null ? void 0 : _e.text) ?? `HTTP ${response.status}`;
52641
- if (expression.includes("{{") && /no viable alternative/i.test(issue)) {
52642
- const cleaned = issue.replace(/^\[[0-9a-f-]+\]:\s*/i, "");
52643
- throw new Error(
52644
- `FHIR evaluation failed: ${cleaned}
52645
- Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by this terminology server.`
52646
- );
52647
- }
52648
- throw new Error(`FHIR evaluation failed: ${issue}`);
52999
+ const trimmed = expression.trim();
53000
+ const deadline = Date.now() + this.evaluationTimeout;
53001
+ try {
53002
+ return await this.runEvaluationStrategy(trimmed, limit, deadline);
53003
+ } catch (error) {
53004
+ if (!(error instanceof EvaluationIssueError)) throw error;
53005
+ throw this.createEvaluationError(trimmed, error);
52649
53006
  }
52650
- const data = await response.json();
52651
- const expansion = data.expansion ?? {};
52652
- this.captureResolvedVersion(expansion.parameter);
52653
- const total = typeof expansion.total === "number" ? expansion.total : 0;
52654
- const contains = expansion.contains ?? [];
52655
- const concepts = contains.map((item) => ({
52656
- code: item.code ?? "",
52657
- display: item.display ?? ""
52658
- }));
52659
- return {
52660
- total,
52661
- concepts,
52662
- truncated: total > concepts.length
52663
- };
52664
53007
  }
52665
- async searchByFilter(filter) {
52666
- const url = `${this.baseUrl}/ValueSet/$expand?url=${this.snomedSystemUrl}?fhir_vs&filter=${encodeURIComponent(filter)}&count=21&includeDesignations=true&activeOnly=true`;
52667
- const response = await this.fetchWithTimeout(url, this.searchTimeout);
52668
- if (!response.ok) {
52669
- throw new Error(`FHIR request failed: ${response.status}`);
53008
+ /**
53009
+ * Transport selection for {@link evaluateEcl}.
53010
+ *
53011
+ * A forced `'post'` strategy — or a latched successful POST fallback — goes straight to
53012
+ * `POST ValueSet/$expand`. Otherwise the implicit ValueSet URL GET runs first, and in
53013
+ * `'auto'` mode a failure whose *shape* says the server cannot serve implicit ValueSets
53014
+ * (issue #55) is retried over POST.
53015
+ */
53016
+ async runEvaluationStrategy(expression, limit, deadline) {
53017
+ if (this.evaluationStrategy === "post" || this.usePostExpand) {
53018
+ return await this.evaluateViaPostExpand(expression, limit, deadline);
52670
53019
  }
52671
- const data = await response.json();
52672
- const expansion = data.expansion ?? {};
52673
- this.captureResolvedVersion(expansion.parameter);
52674
- const contains = expansion.contains ?? [];
53020
+ const response = await this.fetchQueued(
53021
+ this.buildImplicitEvaluationUrl(expression, limit),
53022
+ this.remainingTimeout(deadline)
53023
+ );
53024
+ if (response.ok) {
53025
+ return this.parseEvaluationResponse(await response.json());
53026
+ }
53027
+ const outcome = await this.readOperationOutcome(response);
53028
+ if (this.evaluationStrategy === "implicit-url" || !this.shouldFallbackToPostExpand(response.status, outcome)) {
53029
+ throw new EvaluationIssueError(outcome.issue);
53030
+ }
53031
+ try {
53032
+ const result = await this.evaluateViaPostExpand(expression, limit, deadline);
53033
+ this.usePostExpand = true;
53034
+ return result;
53035
+ } catch (error) {
53036
+ if (!(error instanceof EvaluationIssueError)) throw error;
53037
+ throw new EvaluationIssueError(
53038
+ `${error.message} (POST ValueSet/$expand fallback; the implicit ValueSet URL also failed: ${outcome.issue})`,
53039
+ { cause: error }
53040
+ );
53041
+ }
53042
+ }
53043
+ /** `GET ValueSet/$expand?url=<canonical implicit ECL ValueSet>` — see {@link encodeEclForCanonicalUrl}. */
53044
+ buildImplicitEvaluationUrl(expression, limit) {
53045
+ const implicitVsUrl = `${this.snomedSystemUrl}?fhir_vs=ecl/${encodeEclForCanonicalUrl(expression)}`;
53046
+ return `${this.baseUrl}/ValueSet/$expand?url=${encodeURIComponent(implicitVsUrl)}&count=${limit}`;
53047
+ }
53048
+ /**
53049
+ * `POST ValueSet/$expand` carrying the ECL in `compose.include.filter` with
53050
+ * `property: "constraint"` — the form requested in issue #55. The expression travels in a
53051
+ * JSON body, so it needs no escaping at all.
53052
+ */
53053
+ async evaluateViaPostExpand(expression, limit, deadline) {
53054
+ const include = {
53055
+ system: "http://snomed.info/sct",
53056
+ // eslint-disable-line sonarjs/no-clear-text-protocols -- FHIR system URI, not a network URL
53057
+ ...this.snomedVersion ? { version: this.snomedVersion } : {},
53058
+ filter: [{ property: "constraint", op: "=", value: expression }]
53059
+ };
53060
+ const response = await this.fetchQueued(
53061
+ `${this.baseUrl}/ValueSet/$expand?count=${limit}`,
53062
+ this.remainingTimeout(deadline),
53063
+ {
53064
+ method: "POST",
53065
+ headers: { "Content-Type": "application/fhir+json", Accept: "application/fhir+json" },
53066
+ body: JSON.stringify({ resourceType: "ValueSet", compose: { include: [include] } })
53067
+ }
53068
+ );
53069
+ if (!response.ok) {
53070
+ throw new EvaluationIssueError((await this.readOperationOutcome(response)).issue);
53071
+ }
53072
+ return this.parseEvaluationResponse(await response.json());
53073
+ }
53074
+ /**
53075
+ * True when an implicit-URL failure indicates the implicit ValueSet *form* is unsupported
53076
+ * rather than the expression being invalid.
53077
+ *
53078
+ * Deliberately excludes a bare HTTP 422: that is also how a genuine ECL syntax error
53079
+ * presents, and retrying those over POST would only turn one clear error into two requests
53080
+ * and a muddled message. The `'not-found'` OperationOutcome code is still honoured on any
53081
+ * status, which covers servers that report a missing implicit ValueSet as 422.
53082
+ */
53083
+ shouldFallbackToPostExpand(status, outcome) {
53084
+ return status === 404 || status === 414 || outcome.code === "not-found" || VALUE_SET_NOT_FOUND.test(outcome.issue) || IMPLICIT_VALUE_SET_UNSUPPORTED.some((pattern) => pattern.test(outcome.issue));
53085
+ }
53086
+ /** Remaining milliseconds in the shared evaluation budget; throws once it is spent. */
53087
+ remainingTimeout(deadline) {
53088
+ const remaining = deadline - Date.now();
53089
+ if (remaining <= 0) {
53090
+ throw new EvaluationIssueError("evaluation timed out");
53091
+ }
53092
+ return remaining;
53093
+ }
53094
+ /** The machine-readable code and human-readable text of a FHIR error response. */
53095
+ async readOperationOutcome(response) {
53096
+ var _a, _b;
53097
+ const data = await response.json().catch(() => null);
53098
+ const first = (_a = data == null ? void 0 : data.issue) == null ? void 0 : _a[0];
53099
+ return {
53100
+ code: first == null ? void 0 : first.code,
53101
+ issue: (first == null ? void 0 : first.diagnostics) ?? ((_b = first == null ? void 0 : first.details) == null ? void 0 : _b.text) ?? `HTTP ${response.status}`
53102
+ };
53103
+ }
53104
+ /** Shared expansion mapping for both the implicit-URL and POST evaluation transports. */
53105
+ parseEvaluationResponse(data) {
53106
+ const expansion = data.expansion ?? {};
53107
+ this.captureResolvedVersion(expansion.parameter);
53108
+ const total = typeof expansion.total === "number" ? expansion.total : 0;
53109
+ const contains = expansion.contains ?? [];
53110
+ const concepts = contains.map((item) => ({
53111
+ code: item.code ?? "",
53112
+ display: item.display ?? ""
53113
+ }));
53114
+ return {
53115
+ total,
53116
+ concepts,
53117
+ truncated: total > concepts.length
53118
+ };
53119
+ }
53120
+ createEvaluationError(expression, error) {
53121
+ const issue = error.message;
53122
+ if (expression.includes("{{") && /no viable alternative/i.test(issue)) {
53123
+ const cleaned = issue.replace(/^\[[0-9a-f-]+\]:\s*/i, "");
53124
+ return new Error(
53125
+ `FHIR evaluation failed: ${cleaned}
53126
+ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by this terminology server.`,
53127
+ { cause: error }
53128
+ );
53129
+ }
53130
+ return new Error(`FHIR evaluation failed: ${issue}`, { cause: error });
53131
+ }
53132
+ async searchByFilter(filter) {
53133
+ const url = `${this.baseUrl}/ValueSet/$expand?url=${this.snomedSystemUrl}?fhir_vs&filter=${encodeURIComponent(filter)}&count=21&includeDesignations=true&activeOnly=true`;
53134
+ const operation = `concept search for "${filter}"`;
53135
+ const response = await this.request(url, this.searchTimeout, operation);
53136
+ if (!response.ok) {
53137
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
53138
+ throw toHttpError({
53139
+ status: response.status,
53140
+ statusText: response.statusText,
53141
+ url,
53142
+ operation,
53143
+ detail
53144
+ });
53145
+ }
53146
+ const data = await response.json();
53147
+ const expansion = data.expansion ?? {};
53148
+ this.captureResolvedVersion(expansion.parameter);
53149
+ const contains = expansion.contains ?? [];
52675
53150
  const hasMore = contains.length > 20;
52676
53151
  const results = contains.slice(0, 20).map((item) => {
52677
53152
  var _a;
@@ -52692,9 +53167,17 @@ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by
52692
53167
  async getSnomedEditions() {
52693
53168
  var _a;
52694
53169
  const url = `${this.baseUrl}/CodeSystem?url=http://snomed.info/sct`;
52695
- const response = await this.fetchWithTimeout(url, this.searchTimeout);
53170
+ const operation = "SNOMED CT edition discovery";
53171
+ const response = await this.request(url, this.searchTimeout, operation);
52696
53172
  if (!response.ok) {
52697
- throw new Error(`Failed to fetch SNOMED editions: HTTP ${response.status}`);
53173
+ const { detail } = await _FhirTerminologyService.readErrorBody(response);
53174
+ throw toHttpError({
53175
+ status: response.status,
53176
+ statusText: response.statusText,
53177
+ url,
53178
+ operation,
53179
+ detail
53180
+ });
52698
53181
  }
52699
53182
  const data = await response.json();
52700
53183
  const editionMap = /* @__PURE__ */ new Map();
@@ -52719,6 +53202,10 @@ Note: Some ECL 2.2 filter syntax (e.g. {{ D id = ... }}) may not be supported by
52719
53202
  return editions;
52720
53203
  }
52721
53204
  };
53205
+ /** Issue codes a FHIR server uses to say "this code is not in the code system". */
53206
+ __publicField(_FhirTerminologyService, "UNKNOWN_CODE_ISSUE_CODES", /* @__PURE__ */ new Set(["not-found", "code-invalid", "invalid-code"]));
53207
+ /** Phrases servers use in OperationOutcome prose when a code is unknown. */
53208
+ __publicField(_FhirTerminologyService, "UNKNOWN_CODE_PHRASES", ["unknown code", "not found", "invalid code", "unable to find"]);
52722
53209
  /** Map of SNOMED CT historical association reference set IDs to association types. */
52723
53210
  __publicField(_FhirTerminologyService, "ASSOCIATION_REFSETS", {
52724
53211
  "900000000000527005": "same-as",
@@ -53194,13 +53681,13 @@ function printAst(ast, sourceText, options) {
53194
53681
  if (!ast) {
53195
53682
  return "";
53196
53683
  }
53197
- return printExpression$1(ast, 0, 0, options, sourceText);
53684
+ return printExpression$1(ast, 0, 0, options, sourceText, true);
53198
53685
  }
53199
- function printExpression$1(node, depth, column, opts, src) {
53686
+ function printExpression$1(node, depth, column, opts, src, isRoot = false) {
53200
53687
  const inner = node.expression;
53201
53688
  switch (inner.type) {
53202
53689
  case NodeType.SubExpressionConstraint:
53203
- return printSubExpression$1(inner, depth, column, opts, src);
53690
+ return printSubExpression$1(inner, depth, column, opts, src, isRoot);
53204
53691
  case NodeType.CompoundExpression:
53205
53692
  return printCompoundExpression$1(inner, depth, column, opts, src);
53206
53693
  case NodeType.RefinedExpression:
@@ -53213,7 +53700,7 @@ function printExpression$1(node, depth, column, opts, src) {
53213
53700
  }
53214
53701
  }
53215
53702
  }
53216
- function printSubExpression$1(node, depth, column, opts, src) {
53703
+ function printSubExpression$1(node, depth, column, opts, src, isRoot = false) {
53217
53704
  let result = "";
53218
53705
  if (node.operator) {
53219
53706
  result += node.operator.operator + " ";
@@ -53230,10 +53717,11 @@ function printSubExpression$1(node, depth, column, opts, src) {
53230
53717
  break;
53231
53718
  case NodeType.ExpressionConstraint: {
53232
53719
  const innerExpr = node.focus;
53233
- if (opts.removeRedundantParentheses && !node.operator && !node.memberOf) {
53720
+ if (opts.removeRedundantParentheses && !node.operator && !node.memberOf && !node.filters && !node.historySupplement) {
53234
53721
  const inner = innerExpr.expression;
53235
- if (inner.type !== NodeType.CompoundExpression) {
53236
- result += printExpression$1(innerExpr, depth, column + result.length, opts, src);
53722
+ const needsParens = !isRoot && (inner.type === NodeType.RefinedExpression || inner.type === NodeType.DottedExpression);
53723
+ if (inner.type !== NodeType.CompoundExpression && !needsParens) {
53724
+ result += printExpression$1(innerExpr, depth, column + result.length, opts, src, isRoot);
53237
53725
  break;
53238
53726
  }
53239
53727
  }
@@ -53265,7 +53753,7 @@ function printSubExpression$1(node, depth, column, opts, src) {
53265
53753
  }
53266
53754
  function printCompoundExpression$1(node, depth, column, opts, src) {
53267
53755
  const op = node.operator.operator;
53268
- const opSep = opts.spaceAroundOperators ? ` ${op} ` : op;
53756
+ const opSep = ` ${op} `;
53269
53757
  let operands = node.operands;
53270
53758
  if (opts.removeRedundantParentheses && (op === "AND" || op === "OR")) {
53271
53759
  operands = flattenSameOperatorOperands(operands, op);
@@ -53328,42 +53816,84 @@ function printRefinedExpression$1(node, depth, column, opts, src) {
53328
53816
  }
53329
53817
  const focusIsMultilineParen = focus.includes("\n") && node.expression.focus.type === NodeType.ExpressionConstraint;
53330
53818
  const attrDepth = focusIsMultilineParen ? depth + 2 : depth + 1;
53331
- const ind = getIndentString(attrDepth, opts);
53332
- const refSrc = src.slice(node.refinement.range.start.offset, node.refinement.range.end.offset).trim();
53333
- const wholeBraces = refSrc.startsWith("{");
53334
- if (wholeBraces) {
53335
- const innerInd = getIndentString(attrDepth + 1, opts);
53336
- const attrs = node.refinement.attributes.map((a) => printAttribute$1(a, attrDepth + 1, innerInd.length, opts, src));
53337
- return focus + ":\n" + ind + "{\n" + attrs.map((a) => innerInd + a).join(",\n") + "\n" + ind + "}";
53338
- }
53339
- const attrParts = [];
53340
- let prevEnd = node.refinement.range.start.offset;
53341
- for (const attr of node.refinement.attributes) {
53342
- const printed = printAttribute$1(attr, attrDepth, ind.length, opts, src);
53343
- const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53344
- attrParts.push(ind + (inBraces ? "{ " + printed + " }" : printed));
53345
- prevEnd = attr.range.end.offset;
53346
- }
53347
- return focus + ":\n" + attrParts.join(",\n");
53348
- }
53349
- function isAttrInBraceGroup$1(attr, prevEnd, src) {
53350
- const gap = src.slice(prevEnd, attr.range.start.offset);
53351
- return gap.includes("{");
53819
+ const content = node.refinement.content;
53820
+ if (!content) {
53821
+ return focus + ":";
53822
+ }
53823
+ return focus + ":\n" + printMemberBlock(content, attrDepth, opts, src);
53352
53824
  }
53353
- function printRefinement$1(node, depth, opts, src) {
53354
- const parts = [];
53355
- let prevEnd = node.range.start.offset;
53356
- for (const attr of node.attributes) {
53357
- const printed = printAttribute$1(attr, depth, 0, opts, src);
53358
- const inBraces = isAttrInBraceGroup$1(attr, prevEnd, src);
53359
- parts.push(inBraces ? "{ " + printed + " }" : printed);
53360
- prevEnd = attr.range.end.offset;
53825
+ function setSeparator(node) {
53826
+ if (node.operator === "OR") return " OR ";
53827
+ return node.conjunctionStyle === "AND" ? " AND " : ", ";
53828
+ }
53829
+ function flattenSameOperatorMembers$1(node, opts) {
53830
+ const result = [];
53831
+ for (const member of node.members) {
53832
+ const redundant = member.type === NodeType.AttributeSet && member.operator === node.operator && (!member.parenthesized || opts.removeRedundantParentheses);
53833
+ if (redundant) {
53834
+ result.push(...flattenSameOperatorMembers$1(member, opts));
53835
+ } else {
53836
+ result.push(member);
53837
+ }
53838
+ }
53839
+ return result;
53840
+ }
53841
+ function printRefinementMember$1(node, depth, column, opts, src) {
53842
+ switch (node.type) {
53843
+ case NodeType.Attribute:
53844
+ return printAttribute$1(node, depth, column, opts, src);
53845
+ case NodeType.AttributeGroup: {
53846
+ const prefix = (node.cardinality ? node.cardinality + " " : "") + "{ ";
53847
+ return prefix + printRefinementMember$1(node.content, depth, column + prefix.length, opts, src) + " }";
53848
+ }
53849
+ case NodeType.AttributeSet: {
53850
+ const members = flattenSameOperatorMembers$1(node, opts);
53851
+ const sep = setSeparator(node);
53852
+ const parts = [];
53853
+ let col = column;
53854
+ for (const member of members) {
53855
+ const text = printNestedMember(member, depth, col, opts, src);
53856
+ parts.push(text);
53857
+ col += text.length + sep.length;
53858
+ }
53859
+ return parts.join(sep);
53860
+ }
53861
+ }
53862
+ }
53863
+ function printNestedMember(node, depth, column, opts, src) {
53864
+ if (node.type === NodeType.AttributeSet) {
53865
+ return "(" + printRefinementMember$1(node, depth, column + 1, opts, src) + ")";
53866
+ }
53867
+ return printRefinementMember$1(node, depth, column, opts, src);
53868
+ }
53869
+ function printMemberBlock(node, depth, opts, src) {
53870
+ const ind = getIndentString(depth, opts);
53871
+ if (node.type === NodeType.AttributeGroup) {
53872
+ const card = node.cardinality ? node.cardinality + " " : "";
53873
+ return ind + card + "{\n" + printMemberBlock(node.content, depth + 1, opts, src) + "\n" + ind + "}";
53874
+ }
53875
+ if (node.type === NodeType.AttributeSet) {
53876
+ const members = flattenSameOperatorMembers$1(node, opts);
53877
+ const rendered = members.map((member) => {
53878
+ const line = ind + printNestedMember(member, depth, ind.length, opts, src);
53879
+ if (member.type === NodeType.AttributeGroup && opts.maxLineLength > 0 && line.length > opts.maxLineLength) {
53880
+ return printMemberBlock(member, depth, opts, src);
53881
+ }
53882
+ return line;
53883
+ });
53884
+ if (node.operator === "AND" && node.conjunctionStyle === ",") {
53885
+ return rendered.join(",\n");
53886
+ }
53887
+ const keyword = node.operator;
53888
+ return rendered.map((text, i) => i === 0 ? text : ind + keyword + " " + text.slice(ind.length)).join("\n");
53361
53889
  }
53362
- return parts.join(", ");
53890
+ return ind + printAttribute$1(node, depth, ind.length, opts, src);
53891
+ }
53892
+ function printRefinement$1(node, depth, opts, src) {
53893
+ return node.content ? printRefinementMember$1(node.content, depth, 0, opts, src) : "";
53363
53894
  }
53364
53895
  function printAttribute$1(node, depth, column, opts, src) {
53365
- const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
53366
- const cardinalityPrefix = preNameSrc.length > 0 ? preNameSrc + " " : "";
53896
+ const cardinalityPrefix = node.cardinality ? node.cardinality + " " : "";
53367
53897
  let name;
53368
53898
  if (node.name.conceptId) {
53369
53899
  name = node.name.term ? node.name.conceptId + normalizeTerm(node.name.term) : node.name.conceptId;
@@ -53397,110 +53927,442 @@ function lastLineLength(text) {
53397
53927
  const lastNewline = text.lastIndexOf("\n");
53398
53928
  return lastNewline === -1 ? text.length : text.length - lastNewline - 1;
53399
53929
  }
53400
- function splitExpressions(text) {
53401
- const delimiter = "/* ECL-END */";
53402
- const delimiterPositions = [];
53403
- let i = 0;
53404
- while (i < text.length) {
53405
- if (text[i] === "/" && i + 1 < text.length && text[i + 1] === "/") {
53406
- while (i < text.length && text[i] !== "\n") i++;
53407
- continue;
53930
+ function printCanonical(ast, sourceText, outerOperator) {
53931
+ if (ast.type === NodeType.SubExpressionConstraint) {
53932
+ return printSubExpression(ast, sourceText, outerOperator);
53933
+ }
53934
+ return printExpression(ast, sourceText, outerOperator);
53935
+ }
53936
+ function printExpression(node, src, outerOperator) {
53937
+ const inner = node.expression;
53938
+ switch (inner.type) {
53939
+ case NodeType.SubExpressionConstraint:
53940
+ return printSubExpression(inner, src, outerOperator);
53941
+ case NodeType.CompoundExpression:
53942
+ return printCompoundExpression(inner, src);
53943
+ case NodeType.RefinedExpression:
53944
+ return printRefinedExpression(inner, src);
53945
+ case NodeType.DottedExpression:
53946
+ return printDottedExpression(inner, src);
53947
+ default: {
53948
+ const _exhaustive = inner;
53949
+ return String(_exhaustive);
53408
53950
  }
53409
- if (text.startsWith(delimiter, i)) {
53410
- delimiterPositions.push(i);
53411
- i += delimiter.length;
53412
- continue;
53951
+ }
53952
+ }
53953
+ function printSubExpression(node, src, outerOperator) {
53954
+ let result = "";
53955
+ if (node.operator) {
53956
+ result += node.operator.operator;
53957
+ }
53958
+ if (node.memberOf) {
53959
+ result += "^";
53960
+ }
53961
+ switch (node.focus.type) {
53962
+ case NodeType.ConceptReference:
53963
+ result += printConceptReference(node.focus);
53964
+ break;
53965
+ case NodeType.Wildcard:
53966
+ result += "*";
53967
+ break;
53968
+ case NodeType.ExpressionConstraint: {
53969
+ const innerExpr = node.focus.expression;
53970
+ if (innerExpr.type !== NodeType.CompoundExpression) {
53971
+ result += printExpression(node.focus, src, outerOperator);
53972
+ } else if (outerOperator && innerExpr.operator.operator === outerOperator) {
53973
+ result += printExpression(node.focus, src, outerOperator);
53974
+ } else {
53975
+ result += "(" + printExpression(node.focus, src) + ")";
53976
+ }
53977
+ break;
53413
53978
  }
53414
- i++;
53415
53979
  }
53416
- if (delimiterPositions.length === 0) {
53417
- return { expressions: [text], hasDelimiters: false };
53980
+ if (node.filters) {
53981
+ for (const filter of node.filters) {
53982
+ const filterText = src.slice(filter.range.start.offset, filter.range.end.offset);
53983
+ result += " " + filterText.replaceAll(/\s+/g, " ").trim();
53984
+ }
53418
53985
  }
53419
- const parts = [];
53420
- let lastEnd = 0;
53421
- for (const pos of delimiterPositions) {
53422
- parts.push(text.substring(lastEnd, pos));
53423
- lastEnd = pos + delimiter.length;
53986
+ if (node.historySupplement) {
53987
+ const histText = src.slice(node.historySupplement.range.start.offset, node.historySupplement.range.end.offset);
53988
+ result += " " + histText.replaceAll(/\s+/g, " ").trim();
53424
53989
  }
53425
- parts.push(text.substring(lastEnd));
53426
- const expressions = parts.map((p) => p.trim()).filter((p) => p.length > 0);
53427
- return { expressions, hasDelimiters: true };
53990
+ return result;
53428
53991
  }
53429
- function joinExpressions(expressions) {
53430
- return expressions.join("\n\n/* ECL-END */\n\n");
53992
+ function printCompoundExpression(node, src) {
53993
+ const op = node.operator.operator;
53994
+ return node.operands.map((operand) => printSubExpression(operand, src, op)).join(` ${op} `);
53431
53995
  }
53432
- function isCommentOrBlankLine(line) {
53433
- const trimmed = line.trim();
53434
- if (!trimmed) return true;
53435
- if (trimmed.startsWith("//")) return true;
53436
- const stripped = trimmed.replace(/\/\*[^]*?\*\//g, "").trim();
53437
- return stripped.length === 0;
53996
+ function printRefinedExpression(node, src) {
53997
+ const focus = printSubExpression(node.expression, src);
53998
+ const refinement = printRefinement(node.refinement, src);
53999
+ return focus + ":" + refinement;
53438
54000
  }
53439
- function maybeWrapCommentLine(line, options) {
53440
- if (!options.wrapComments || options.maxLineLength <= 0) return line;
53441
- if (line.length <= options.maxLineLength) return line;
53442
- const match = /^(\s*\/\/\s?)(.*)/.exec(line);
53443
- if (!match) return line;
53444
- const prefix = match[1];
53445
- const words = match[2].split(" ");
53446
- const lines = [];
53447
- let current = prefix;
53448
- for (const word of words) {
53449
- if (current.length + word.length + 1 > options.maxLineLength && current.trim() !== prefix.trim()) {
53450
- lines.push(current.trimEnd());
53451
- current = prefix + word;
53452
- } else {
53453
- current = current === prefix ? prefix + word : current + " " + word;
53454
- }
53455
- }
53456
- if (current.trim()) lines.push(current.trimEnd());
53457
- return lines.join("\n");
54001
+ function printDottedExpression(node, src) {
54002
+ const source = printSubExpression(node.source, src);
54003
+ const dots = node.attributes.map((a) => printSubExpression(a.attributeName, src));
54004
+ return source + dots.map((d) => "." + d).join("");
53458
54005
  }
53459
- function maybeWrapCommentBlock(text, options) {
53460
- if (!options.wrapComments) return text;
53461
- return text.split("\n").map((line) => maybeWrapCommentLine(line, options)).join("\n");
54006
+ function printRefinement(node, src) {
54007
+ return node.content ? printRefinementMember(node.content, src) : "";
53462
54008
  }
53463
- function formatExpression(text, options, ast) {
53464
- const lines = text.split("\n");
53465
- let firstCodeLine = -1;
53466
- let lastCodeLine = -1;
53467
- for (let i = 0; i < lines.length; i++) {
53468
- if (!isCommentOrBlankLine(lines[i])) {
53469
- if (firstCodeLine === -1) firstCodeLine = i;
53470
- lastCodeLine = i;
54009
+ function printRefinementMember(node, src) {
54010
+ switch (node.type) {
54011
+ case NodeType.Attribute:
54012
+ return printAttribute(node, src);
54013
+ case NodeType.AttributeGroup:
54014
+ return (node.cardinality ?? "") + "{" + printRefinementMember(node.content, src) + "}";
54015
+ case NodeType.AttributeSet: {
54016
+ const sep = node.operator === "OR" ? " OR " : ",";
54017
+ return node.members.map(
54018
+ (member) => member.type === NodeType.AttributeSet ? "(" + printRefinementMember(member, src) + ")" : printRefinementMember(member, src)
54019
+ ).join(sep);
53471
54020
  }
53472
54021
  }
53473
- if (firstCodeLine === -1) {
53474
- return text;
54022
+ }
54023
+ function printAttribute(node, src) {
54024
+ const cardinalityPrefix = node.cardinality ? node.cardinality + " " : "";
54025
+ let name;
54026
+ if (node.name.conceptId) {
54027
+ name = node.name.conceptId;
54028
+ } else if (node.name.expression) {
54029
+ name = printSubExpression(node.name.expression, src);
54030
+ } else {
54031
+ name = src.slice(node.name.range.start.offset, node.name.range.end.offset).trim();
53475
54032
  }
53476
- const leadingRaw = firstCodeLine > 0 ? lines.slice(0, firstCodeLine).join("\n") + "\n" : "";
53477
- const trailingRaw = lastCodeLine < lines.length - 1 ? "\n" + lines.slice(lastCodeLine + 1).join("\n") : "";
53478
- const bodyText = lines.slice(firstCodeLine, lastCodeLine + 1).join("\n");
53479
- const leadingText = maybeWrapCommentBlock(leadingRaw, options);
53480
- const trailingText = maybeWrapCommentBlock(trailingRaw, options);
53481
- const formattedBody = formatExpressionBody(bodyText, options, ast);
53482
- return leadingText + formattedBody + trailingText;
54033
+ const between = src.slice(node.name.range.end.offset, node.value.range.start.offset);
54034
+ const opMatch = /(!?=|[<>]=)/.exec(between);
54035
+ const compOp = opMatch ? opMatch[1] : "=";
54036
+ const hasHashPrefix = between.includes("#");
54037
+ let value;
54038
+ if (node.value.expression) {
54039
+ value = printSubExpression(node.value.expression, src);
54040
+ } else if (node.value.rawValue) {
54041
+ value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
54042
+ } else {
54043
+ value = src.slice(node.value.range.start.offset, node.value.range.end.offset).trim();
54044
+ }
54045
+ const reversed = node.reversed ? "R " : "";
54046
+ return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
53483
54047
  }
53484
- function applyRefinementCommaBreaks(text, options) {
53485
- var _a;
53486
- const lines = text.split("\n");
53487
- const result = [];
53488
- let depth = 0;
53489
- let refinementIndent = null;
53490
- for (const line of lines) {
53491
- const lineIndent = ((_a = /^(\s*)/.exec(line)) == null ? void 0 : _a[1]) ?? "";
53492
- if (refinementIndent === null && depth === 0 && lineIndent.length > 0) {
53493
- refinementIndent = lineIndent;
53494
- }
53495
- let commaIndent;
53496
- if (depth === 0 && refinementIndent) {
53497
- commaIndent = refinementIndent;
53498
- } else if (lineIndent.length > 0) {
53499
- commaIndent = lineIndent;
53500
- } else {
53501
- commaIndent = getIndentString(1, options);
53502
- }
53503
- let output = "";
54048
+ function printConceptReference(node) {
54049
+ return node.conceptId;
54050
+ }
54051
+ function normaliseAst(ast, sourceText) {
54052
+ return normaliseExpression(ast, sourceText);
54053
+ }
54054
+ function normaliseExpression(node, src) {
54055
+ const inner = node.expression;
54056
+ let normalised;
54057
+ switch (inner.type) {
54058
+ case NodeType.SubExpressionConstraint:
54059
+ normalised = normaliseSubExpression(inner, src);
54060
+ break;
54061
+ case NodeType.CompoundExpression:
54062
+ normalised = normaliseCompoundExpression(inner, src);
54063
+ break;
54064
+ case NodeType.RefinedExpression:
54065
+ normalised = normaliseRefinedExpression(inner, src);
54066
+ break;
54067
+ case NodeType.DottedExpression:
54068
+ normalised = normaliseDottedExpression(inner, src);
54069
+ break;
54070
+ default: {
54071
+ const _exhaustive = inner;
54072
+ normalised = _exhaustive;
54073
+ }
54074
+ }
54075
+ return { ...node, expression: normalised };
54076
+ }
54077
+ function normaliseSubExpression(node, src) {
54078
+ let focus;
54079
+ switch (node.focus.type) {
54080
+ case NodeType.ConceptReference:
54081
+ focus = stripTerm(node.focus);
54082
+ break;
54083
+ case NodeType.Wildcard:
54084
+ focus = { ...node.focus };
54085
+ break;
54086
+ case NodeType.ExpressionConstraint:
54087
+ focus = normaliseExpression(node.focus, src);
54088
+ break;
54089
+ }
54090
+ return {
54091
+ ...node,
54092
+ operator: node.operator ? { ...node.operator } : void 0,
54093
+ focus,
54094
+ filters: node.filters ? node.filters.map(copyFilter) : void 0,
54095
+ historySupplement: node.historySupplement ? { ...node.historySupplement } : void 0
54096
+ };
54097
+ }
54098
+ function normaliseCompoundExpression(node, src) {
54099
+ const op = node.operator.operator;
54100
+ let normOperands = node.operands.map((o) => normaliseSubExpression(o, src));
54101
+ if (op === "AND" || op === "OR") {
54102
+ normOperands = flattenSameOperator(normOperands, op, src);
54103
+ }
54104
+ if (op === "AND" || op === "OR") {
54105
+ normOperands.sort((a, b) => {
54106
+ const ka = printCanonical(a, src);
54107
+ const kb = printCanonical(b, src);
54108
+ return ka.localeCompare(kb);
54109
+ });
54110
+ }
54111
+ return {
54112
+ ...node,
54113
+ operator: { ...node.operator },
54114
+ operands: normOperands
54115
+ };
54116
+ }
54117
+ function flattenSameOperator(operands, operator, src) {
54118
+ const result = [];
54119
+ for (const operand of operands) {
54120
+ if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
54121
+ const inner = operand.focus.expression;
54122
+ if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
54123
+ const innerNorm = normaliseCompoundExpression(inner, src);
54124
+ result.push(...innerNorm.operands);
54125
+ continue;
54126
+ }
54127
+ }
54128
+ result.push(operand);
54129
+ }
54130
+ return result;
54131
+ }
54132
+ function normaliseRefinedExpression(node, src) {
54133
+ return {
54134
+ ...node,
54135
+ expression: normaliseSubExpression(node.expression, src),
54136
+ refinement: normaliseRefinement(node.refinement, src)
54137
+ };
54138
+ }
54139
+ function normaliseRefinement(node, src) {
54140
+ const content = node.content ? normaliseRefinementMember(node.content, src) : null;
54141
+ const attributes = [];
54142
+ collectAttributes(content, attributes);
54143
+ return { ...node, attributes, content };
54144
+ }
54145
+ function normaliseRefinementMember(node, src) {
54146
+ switch (node.type) {
54147
+ case NodeType.Attribute:
54148
+ return normaliseAttribute(node, src);
54149
+ case NodeType.AttributeGroup:
54150
+ return { ...node, content: normaliseRefinementMember(node.content, src) };
54151
+ case NodeType.AttributeSet: {
54152
+ const members = flattenSameOperatorMembers(node).map((m) => normaliseRefinementMember(m, src));
54153
+ members.sort((a, b) => compareRefinementMembers(a, b, src));
54154
+ return { ...node, conjunctionStyle: ",", members };
54155
+ }
54156
+ }
54157
+ }
54158
+ function flattenSameOperatorMembers(node) {
54159
+ const result = [];
54160
+ for (const member of node.members) {
54161
+ if (member.type === NodeType.AttributeSet && member.operator === node.operator) {
54162
+ result.push(...flattenSameOperatorMembers(member));
54163
+ } else {
54164
+ result.push(member);
54165
+ }
54166
+ }
54167
+ return result;
54168
+ }
54169
+ function collectAttributes(node, out) {
54170
+ if (!node) return;
54171
+ switch (node.type) {
54172
+ case NodeType.Attribute:
54173
+ out.push(node);
54174
+ break;
54175
+ case NodeType.AttributeGroup:
54176
+ collectAttributes(node.content, out);
54177
+ break;
54178
+ case NodeType.AttributeSet:
54179
+ for (const member of node.members) {
54180
+ collectAttributes(member, out);
54181
+ }
54182
+ break;
54183
+ }
54184
+ }
54185
+ function compareRefinementMembers(a, b, src) {
54186
+ if (a.type === NodeType.Attribute && b.type === NodeType.Attribute) {
54187
+ return compareAttributes(a, b, src);
54188
+ }
54189
+ if (a.type === NodeType.Attribute) return -1;
54190
+ if (b.type === NodeType.Attribute) return 1;
54191
+ return printRefinementMember(a, src).localeCompare(printRefinementMember(b, src));
54192
+ }
54193
+ function compareAttributes(a, b, src) {
54194
+ const aId = a.name.conceptId;
54195
+ const bId = b.name.conceptId;
54196
+ if (aId && bId) {
54197
+ const aBig = BigInt(aId);
54198
+ const bBig = BigInt(bId);
54199
+ if (aBig < bBig) return -1;
54200
+ if (aBig > bBig) return 1;
54201
+ return 0;
54202
+ }
54203
+ if (aId) return -1;
54204
+ if (bId) return 1;
54205
+ const aKey = a.name.expression ? printCanonical(a.name.expression, src) : "";
54206
+ const bKey = b.name.expression ? printCanonical(b.name.expression, src) : "";
54207
+ return aKey.localeCompare(bKey);
54208
+ }
54209
+ function normaliseAttribute(node, src) {
54210
+ return {
54211
+ ...node,
54212
+ name: normaliseAttributeName(node.name, src),
54213
+ value: normaliseAttributeValue(node.value, src)
54214
+ };
54215
+ }
54216
+ function normaliseAttributeName(node, src) {
54217
+ return {
54218
+ ...node,
54219
+ term: void 0,
54220
+ // §5.1: strip display terms
54221
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
54222
+ };
54223
+ }
54224
+ function normaliseAttributeValue(node, src) {
54225
+ return {
54226
+ ...node,
54227
+ expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
54228
+ };
54229
+ }
54230
+ function normaliseDottedExpression(node, src) {
54231
+ return {
54232
+ ...node,
54233
+ source: normaliseSubExpression(node.source, src),
54234
+ attributes: node.attributes.map(
54235
+ (a) => ({
54236
+ ...a,
54237
+ attributeName: normaliseSubExpression(a.attributeName, src)
54238
+ })
54239
+ )
54240
+ };
54241
+ }
54242
+ function stripTerm(node) {
54243
+ return { ...node, term: void 0 };
54244
+ }
54245
+ function copyFilter(node) {
54246
+ return { ...node };
54247
+ }
54248
+ function structuralSignature(ast, sourceText) {
54249
+ return printCanonical(normaliseAst(ast, sourceText), sourceText);
54250
+ }
54251
+ function signatureOf(text) {
54252
+ try {
54253
+ const { ast, errors: errors2 } = parseECL(text);
54254
+ if (!ast || errors2.length > 0) {
54255
+ return null;
54256
+ }
54257
+ return structuralSignature(ast, text);
54258
+ } catch {
54259
+ return null;
54260
+ }
54261
+ }
54262
+ function splitExpressions(text) {
54263
+ const delimiter = "/* ECL-END */";
54264
+ const delimiterPositions = [];
54265
+ let i = 0;
54266
+ while (i < text.length) {
54267
+ if (text[i] === "/" && i + 1 < text.length && text[i + 1] === "/") {
54268
+ while (i < text.length && text[i] !== "\n") i++;
54269
+ continue;
54270
+ }
54271
+ if (text.startsWith(delimiter, i)) {
54272
+ delimiterPositions.push(i);
54273
+ i += delimiter.length;
54274
+ continue;
54275
+ }
54276
+ i++;
54277
+ }
54278
+ if (delimiterPositions.length === 0) {
54279
+ return { expressions: [text], hasDelimiters: false };
54280
+ }
54281
+ const parts = [];
54282
+ let lastEnd = 0;
54283
+ for (const pos of delimiterPositions) {
54284
+ parts.push(text.substring(lastEnd, pos));
54285
+ lastEnd = pos + delimiter.length;
54286
+ }
54287
+ parts.push(text.substring(lastEnd));
54288
+ const expressions = parts.map((p) => p.trim()).filter((p) => p.length > 0);
54289
+ return { expressions, hasDelimiters: true };
54290
+ }
54291
+ function joinExpressions(expressions) {
54292
+ return expressions.join("\n\n/* ECL-END */\n\n");
54293
+ }
54294
+ function isCommentOrBlankLine(line) {
54295
+ const trimmed = line.trim();
54296
+ if (!trimmed) return true;
54297
+ if (trimmed.startsWith("//")) return true;
54298
+ const stripped = trimmed.replace(/\/\*[^]*?\*\//g, "").trim();
54299
+ return stripped.length === 0;
54300
+ }
54301
+ function maybeWrapCommentLine(line, options) {
54302
+ if (!options.wrapComments || options.maxLineLength <= 0) return line;
54303
+ if (line.length <= options.maxLineLength) return line;
54304
+ const match = /^(\s*\/\/\s?)(.*)/.exec(line);
54305
+ if (!match) return line;
54306
+ const prefix = match[1];
54307
+ const words = match[2].split(" ");
54308
+ const lines = [];
54309
+ let current = prefix;
54310
+ for (const word of words) {
54311
+ if (current.length + word.length + 1 > options.maxLineLength && current.trim() !== prefix.trim()) {
54312
+ lines.push(current.trimEnd());
54313
+ current = prefix + word;
54314
+ } else {
54315
+ current = current === prefix ? prefix + word : current + " " + word;
54316
+ }
54317
+ }
54318
+ if (current.trim()) lines.push(current.trimEnd());
54319
+ return lines.join("\n");
54320
+ }
54321
+ function maybeWrapCommentBlock(text, options) {
54322
+ if (!options.wrapComments) return text;
54323
+ return text.split("\n").map((line) => maybeWrapCommentLine(line, options)).join("\n");
54324
+ }
54325
+ function formatExpression(text, options, ast) {
54326
+ const lines = text.split("\n");
54327
+ let firstCodeLine = -1;
54328
+ let lastCodeLine = -1;
54329
+ for (let i = 0; i < lines.length; i++) {
54330
+ if (!isCommentOrBlankLine(lines[i])) {
54331
+ if (firstCodeLine === -1) firstCodeLine = i;
54332
+ lastCodeLine = i;
54333
+ }
54334
+ }
54335
+ if (firstCodeLine === -1) {
54336
+ return text;
54337
+ }
54338
+ const leadingRaw = firstCodeLine > 0 ? lines.slice(0, firstCodeLine).join("\n") + "\n" : "";
54339
+ const trailingRaw = lastCodeLine < lines.length - 1 ? "\n" + lines.slice(lastCodeLine + 1).join("\n") : "";
54340
+ const bodyText = lines.slice(firstCodeLine, lastCodeLine + 1).join("\n");
54341
+ const leadingText = maybeWrapCommentBlock(leadingRaw, options);
54342
+ const trailingText = maybeWrapCommentBlock(trailingRaw, options);
54343
+ const formattedBody = formatExpressionBody(bodyText, options, ast);
54344
+ return leadingText + formattedBody + trailingText;
54345
+ }
54346
+ function applyRefinementCommaBreaks(text, options) {
54347
+ var _a;
54348
+ const lines = text.split("\n");
54349
+ const result = [];
54350
+ let depth = 0;
54351
+ let refinementIndent = null;
54352
+ for (const line of lines) {
54353
+ const lineIndent = ((_a = /^(\s*)/.exec(line)) == null ? void 0 : _a[1]) ?? "";
54354
+ if (refinementIndent === null && depth === 0 && lineIndent.length > 0) {
54355
+ refinementIndent = lineIndent;
54356
+ }
54357
+ let commaIndent;
54358
+ if (depth === 0 && refinementIndent) {
54359
+ commaIndent = refinementIndent;
54360
+ } else if (lineIndent.length > 0) {
54361
+ commaIndent = lineIndent;
54362
+ } else {
54363
+ commaIndent = getIndentString(1, options);
54364
+ }
54365
+ let output = "";
53504
54366
  let inTerm = false;
53505
54367
  for (let i = 0; i < line.length; i++) {
53506
54368
  const ch = line[i];
@@ -53566,13 +54428,28 @@ function normalizeFilterBlocks(text) {
53566
54428
  return match.toLowerCase() === lower ? canonical : match;
53567
54429
  });
53568
54430
  }
53569
- normalized = normalized.replace(/\s*(!?=)\s*/g, " $1 ");
54431
+ normalized = normalized.replace(/\s*(!=|>=|<=)\s*/g, " $1 ");
54432
+ normalized = normalized.replace(new RegExp("\\s*(?<![!<>])=\\s*", "g"), " = ");
53570
54433
  normalized = normalized.replace(/,\s*/g, ", ");
53571
54434
  normalized = normalized.replace(/ {2,}/g, " ");
53572
54435
  normalized = normalized.replace(/^\s*/, " ").replace(/\s*$/, " ");
53573
54436
  return "{{" + normalized + "}}";
53574
54437
  });
53575
54438
  }
54439
+ function applyAstPrinter(normalizedText, options) {
54440
+ try {
54441
+ const reParsed = parseECL(normalizedText);
54442
+ const coversAll = reParsed.ast && reParsed.errors.length === 0 && reParsed.ast.range.end.offset >= normalizedText.trimEnd().length;
54443
+ if (!coversAll || !reParsed.ast) {
54444
+ return normalizedText;
54445
+ }
54446
+ const before = structuralSignature(reParsed.ast, normalizedText);
54447
+ const printed = printAst(reParsed.ast, normalizedText, options);
54448
+ return signatureOf(printed) === before ? printed : normalizedText;
54449
+ } catch {
54450
+ return normalizedText;
54451
+ }
54452
+ }
53576
54453
  function formatExpressionBody(text, options, ast) {
53577
54454
  const { comments, textWithoutComments } = extractComments(text);
53578
54455
  const nonDelimiterComments = comments.filter((c) => c.content.trim() !== "/* ECL-END */");
@@ -53580,9 +54457,9 @@ function formatExpressionBody(text, options, ast) {
53580
54457
  formatted = formatted.replace(
53581
54458
  // eslint-disable-next-line sonarjs/slow-regex -- bounded ECL expression text; no ReDoS risk
53582
54459
  new RegExp("(\\S?)(?<![A-Za-z])\\s*(AND|OR|MINUS)\\s*(?![A-Za-z])(\\S?)", "g"),
53583
- (match, before, op, after) => {
53584
- const formattedOp = options.spaceAroundOperators ? ` ${op} ` : op;
53585
- return (before ?? "") + formattedOp + (after ?? "");
54460
+ (_match, before, op, after) => {
54461
+ const formattedOp = ` ${op} `;
54462
+ return before + formattedOp + after;
53586
54463
  }
53587
54464
  );
53588
54465
  formatted = formatted.replace(/[ \t]*(:)[ \t]*/g, formatRefinementColon("$1"));
@@ -53590,23 +54467,21 @@ function formatExpressionBody(text, options, ast) {
53590
54467
  formatted = formatted.replace(new RegExp("[ \\t]*(?<![!<>])(=)[ \\t]*", "g"), formatRefinementEquals("$1"));
53591
54468
  formatted = formatted.replace(/(<<|<|>>|>)\s*(\d)/g, "$1 $2");
53592
54469
  formatted = formatted.replace(/(\d)\s+(\|)/g, "$1$2");
53593
- formatted = formatted.replace(/\|([^|]+)\|/g, (match, content) => {
54470
+ formatted = formatted.replace(/\|([^|]+)\|/g, (_match, content) => {
53594
54471
  return normalizeTerm(content);
53595
54472
  });
53596
54473
  if (ast) {
53597
- try {
53598
- const reParsed = parseECL(formatted);
53599
- const astCoversAll = reParsed.ast && reParsed.errors.length === 0 && reParsed.ast.range.end.offset >= formatted.trimEnd().length;
53600
- if (astCoversAll && reParsed.ast) {
53601
- formatted = printAst(reParsed.ast, formatted, options);
53602
- } else {
53603
- }
53604
- } catch {
53605
- }
54474
+ formatted = applyAstPrinter(formatted, options);
53606
54475
  }
53607
54476
  if (options.breakOnRefinementComma) {
53608
54477
  formatted = applyRefinementCommaBreaks(formatted, options);
53609
54478
  }
54479
+ {
54480
+ const baseline = signatureOf(normalizeFilterBlocks(textWithoutComments));
54481
+ if (baseline !== null && signatureOf(formatted) !== baseline) {
54482
+ formatted = textWithoutComments;
54483
+ }
54484
+ }
53610
54485
  const withComments = reinsertComments(formatted.trim(), text, nonDelimiterComments);
53611
54486
  return withComments;
53612
54487
  }
@@ -55828,62 +56703,45 @@ const eclTokenTypes = [
55828
56703
  // 8 — history supplement keywords
55829
56704
  ];
55830
56705
  const eclTokenModifiers = [];
55831
- const NT = {
55832
- ExpressionConstraint: "ExpressionConstraint",
55833
- SubExpressionConstraint: "SubExpressionConstraint",
55834
- CompoundExpression: "CompoundExpression",
55835
- RefinedExpression: "RefinedExpression",
55836
- DottedExpression: "DottedExpression",
55837
- DottedAttribute: "DottedAttribute",
55838
- Refinement: "Refinement",
55839
- Attribute: "Attribute",
55840
- FilterConstraint: "FilterConstraint",
55841
- HistorySupplement: "HistorySupplement"
55842
- };
55843
56706
  function collectAttributeNamePositions(ast, lineOffsets) {
55844
56707
  const positions = /* @__PURE__ */ new Set();
55845
56708
  function visit(node) {
55846
- var _a;
55847
- if (!(node == null ? void 0 : node.type)) return;
56709
+ if (!node) return;
55848
56710
  switch (node.type) {
55849
- case NT.ExpressionConstraint:
55850
- if (node.expression) visit(node.expression);
56711
+ case NodeType.ExpressionConstraint:
56712
+ visit(node.expression);
55851
56713
  break;
55852
- case NT.SubExpressionConstraint:
55853
- if (node.focus) visit(node.focus);
55854
- if (node.filters) {
55855
- for (const f of node.filters) visit(f);
55856
- }
55857
- if (node.historySupplement) visit(node.historySupplement);
56714
+ case NodeType.SubExpressionConstraint:
56715
+ visit(node.focus);
56716
+ for (const f of node.filters ?? []) visit(f);
56717
+ visit(node.historySupplement);
55858
56718
  break;
55859
- case NT.CompoundExpression:
56719
+ case NodeType.CompoundExpression:
55860
56720
  for (const op of node.operands) visit(op);
55861
56721
  break;
55862
- case NT.RefinedExpression:
56722
+ case NodeType.RefinedExpression:
55863
56723
  visit(node.expression);
55864
56724
  visit(node.refinement);
55865
56725
  break;
55866
- case NT.DottedExpression:
56726
+ case NodeType.DottedExpression:
55867
56727
  visit(node.source);
55868
56728
  for (const attr of node.attributes) visit(attr);
55869
56729
  break;
55870
- case NT.DottedAttribute:
55871
- if (node.attributeName) {
55872
- markSubExpressionAsAttrName(node.attributeName, lineOffsets, positions);
55873
- }
56730
+ case NodeType.DottedAttribute:
56731
+ markSubExpressionAsAttrName(node.attributeName, lineOffsets, positions);
55874
56732
  break;
55875
- case NT.Refinement:
56733
+ case NodeType.Refinement:
55876
56734
  for (const attr of node.attributes) visit(attr);
55877
56735
  break;
55878
- case NT.Attribute:
56736
+ case NodeType.Attribute:
55879
56737
  markAttributeName(node.name, lineOffsets, positions);
55880
- if ((_a = node.value) == null ? void 0 : _a.expression) visit(node.value.expression);
56738
+ visit(node.value.expression);
55881
56739
  break;
55882
- case NT.FilterConstraint:
56740
+ case NodeType.FilterConstraint:
55883
56741
  for (const ce of node.conceptExpressions) visit(ce);
55884
56742
  break;
55885
- case NT.HistorySupplement:
55886
- if (node.subsetExpression) visit(node.subsetExpression);
56743
+ case NodeType.HistorySupplement:
56744
+ visit(node.subsetExpression);
55887
56745
  break;
55888
56746
  }
55889
56747
  }
@@ -56117,275 +56975,6 @@ function isInsideFilterBlock(ranges, matchStart, matchEnd) {
56117
56975
  }
56118
56976
  return false;
56119
56977
  }
56120
- function printCanonical(ast, sourceText, outerOperator) {
56121
- if (ast.type === NodeType.SubExpressionConstraint) {
56122
- return printSubExpression(ast, sourceText, outerOperator);
56123
- }
56124
- return printExpression(ast, sourceText, outerOperator);
56125
- }
56126
- function printExpression(node, src, outerOperator) {
56127
- const inner = node.expression;
56128
- switch (inner.type) {
56129
- case NodeType.SubExpressionConstraint:
56130
- return printSubExpression(inner, src, outerOperator);
56131
- case NodeType.CompoundExpression:
56132
- return printCompoundExpression(inner, src);
56133
- case NodeType.RefinedExpression:
56134
- return printRefinedExpression(inner, src);
56135
- case NodeType.DottedExpression:
56136
- return printDottedExpression(inner, src);
56137
- default: {
56138
- const _exhaustive = inner;
56139
- return String(_exhaustive);
56140
- }
56141
- }
56142
- }
56143
- function printSubExpression(node, src, outerOperator) {
56144
- let result = "";
56145
- if (node.operator) {
56146
- result += node.operator.operator;
56147
- }
56148
- if (node.memberOf) {
56149
- result += "^";
56150
- }
56151
- switch (node.focus.type) {
56152
- case NodeType.ConceptReference:
56153
- result += printConceptReference(node.focus);
56154
- break;
56155
- case NodeType.Wildcard:
56156
- result += "*";
56157
- break;
56158
- case NodeType.ExpressionConstraint: {
56159
- const innerExpr = node.focus.expression;
56160
- if (innerExpr.type !== NodeType.CompoundExpression) {
56161
- result += printExpression(node.focus, src, outerOperator);
56162
- } else if (outerOperator && innerExpr.operator.operator === outerOperator) {
56163
- result += printExpression(node.focus, src, outerOperator);
56164
- } else {
56165
- result += "(" + printExpression(node.focus, src) + ")";
56166
- }
56167
- break;
56168
- }
56169
- }
56170
- if (node.filters) {
56171
- for (const filter of node.filters) {
56172
- const filterText = src.slice(filter.range.start.offset, filter.range.end.offset);
56173
- result += " " + filterText.replaceAll(/\s+/g, " ").trim();
56174
- }
56175
- }
56176
- if (node.historySupplement) {
56177
- const histText = src.slice(node.historySupplement.range.start.offset, node.historySupplement.range.end.offset);
56178
- result += " " + histText.replaceAll(/\s+/g, " ").trim();
56179
- }
56180
- return result;
56181
- }
56182
- function printCompoundExpression(node, src) {
56183
- const op = node.operator.operator;
56184
- return node.operands.map((operand) => printSubExpression(operand, src, op)).join(` ${op} `);
56185
- }
56186
- function printRefinedExpression(node, src) {
56187
- const focus = printSubExpression(node.expression, src);
56188
- const refinement = printRefinement(node.refinement, src);
56189
- return focus + ":" + refinement;
56190
- }
56191
- function printDottedExpression(node, src) {
56192
- const source = printSubExpression(node.source, src);
56193
- const dots = node.attributes.map((a) => printSubExpression(a.attributeName, src));
56194
- return source + dots.map((d) => "." + d).join("");
56195
- }
56196
- function printRefinement(node, src) {
56197
- const parts = [];
56198
- let prevEnd = node.range.start.offset;
56199
- for (const attr of node.attributes) {
56200
- const printed = printAttribute(attr, src);
56201
- const inBraces = isAttrInBraceGroup(attr, prevEnd, src);
56202
- parts.push(inBraces ? "{" + printed + "}" : printed);
56203
- prevEnd = attr.range.end.offset;
56204
- }
56205
- return parts.join(",");
56206
- }
56207
- function isAttrInBraceGroup(attr, prevEnd, src) {
56208
- const gap = src.slice(prevEnd, attr.range.start.offset);
56209
- return gap.includes("{");
56210
- }
56211
- function printAttribute(node, src) {
56212
- const preNameSrc = src.slice(node.range.start.offset, node.name.range.start.offset).trim();
56213
- const cardinalityRaw = preNameSrc.replace(/^\{?\s*/, "").trim();
56214
- const cardinalityPrefix = cardinalityRaw.length > 0 ? cardinalityRaw + " " : "";
56215
- let name;
56216
- if (node.name.conceptId) {
56217
- name = node.name.conceptId;
56218
- } else if (node.name.expression) {
56219
- name = printSubExpression(node.name.expression, src);
56220
- } else {
56221
- name = src.slice(node.name.range.start.offset, node.name.range.end.offset).trim();
56222
- }
56223
- const between = src.slice(node.name.range.end.offset, node.value.range.start.offset);
56224
- const opMatch = /(!?=|[<>]=)/.exec(between);
56225
- const compOp = opMatch ? opMatch[1] : "=";
56226
- const hasHashPrefix = between.includes("#");
56227
- let value;
56228
- if (node.value.expression) {
56229
- value = printSubExpression(node.value.expression, src);
56230
- } else if (node.value.rawValue) {
56231
- value = hasHashPrefix ? "#" + node.value.rawValue : node.value.rawValue;
56232
- } else {
56233
- value = src.slice(node.value.range.start.offset, node.value.range.end.offset).trim();
56234
- }
56235
- const reversed = node.reversed ? "R " : "";
56236
- return cardinalityPrefix + reversed + name + " " + compOp + " " + value;
56237
- }
56238
- function printConceptReference(node) {
56239
- return node.conceptId;
56240
- }
56241
- function normaliseAst(ast, sourceText) {
56242
- return normaliseExpression(ast, sourceText);
56243
- }
56244
- function normaliseExpression(node, src) {
56245
- const inner = node.expression;
56246
- let normalised;
56247
- switch (inner.type) {
56248
- case NodeType.SubExpressionConstraint:
56249
- normalised = normaliseSubExpression(inner, src);
56250
- break;
56251
- case NodeType.CompoundExpression:
56252
- normalised = normaliseCompoundExpression(inner, src);
56253
- break;
56254
- case NodeType.RefinedExpression:
56255
- normalised = normaliseRefinedExpression(inner, src);
56256
- break;
56257
- case NodeType.DottedExpression:
56258
- normalised = normaliseDottedExpression(inner, src);
56259
- break;
56260
- default: {
56261
- const _exhaustive = inner;
56262
- normalised = _exhaustive;
56263
- }
56264
- }
56265
- return { ...node, expression: normalised };
56266
- }
56267
- function normaliseSubExpression(node, src) {
56268
- let focus;
56269
- switch (node.focus.type) {
56270
- case NodeType.ConceptReference:
56271
- focus = stripTerm(node.focus);
56272
- break;
56273
- case NodeType.Wildcard:
56274
- focus = { ...node.focus };
56275
- break;
56276
- case NodeType.ExpressionConstraint:
56277
- focus = normaliseExpression(node.focus, src);
56278
- break;
56279
- }
56280
- return {
56281
- ...node,
56282
- operator: node.operator ? { ...node.operator } : void 0,
56283
- focus,
56284
- filters: node.filters ? node.filters.map(copyFilter) : void 0,
56285
- historySupplement: node.historySupplement ? { ...node.historySupplement } : void 0
56286
- };
56287
- }
56288
- function normaliseCompoundExpression(node, src) {
56289
- const op = node.operator.operator;
56290
- let normOperands = node.operands.map((o) => normaliseSubExpression(o, src));
56291
- if (op === "AND" || op === "OR") {
56292
- normOperands = flattenSameOperator(normOperands, op, src);
56293
- }
56294
- if (op === "AND" || op === "OR") {
56295
- normOperands.sort((a, b) => {
56296
- const ka = printCanonical(a, src);
56297
- const kb = printCanonical(b, src);
56298
- return ka.localeCompare(kb);
56299
- });
56300
- }
56301
- return {
56302
- ...node,
56303
- operator: { ...node.operator },
56304
- operands: normOperands
56305
- };
56306
- }
56307
- function flattenSameOperator(operands, operator, src) {
56308
- const result = [];
56309
- for (const operand of operands) {
56310
- if (operand.focus.type === NodeType.ExpressionConstraint && !operand.operator && !operand.memberOf && !operand.filters && !operand.historySupplement) {
56311
- const inner = operand.focus.expression;
56312
- if (inner.type === NodeType.CompoundExpression && inner.operator.operator === operator) {
56313
- const innerNorm = normaliseCompoundExpression(inner, src);
56314
- result.push(...innerNorm.operands);
56315
- continue;
56316
- }
56317
- }
56318
- result.push(operand);
56319
- }
56320
- return result;
56321
- }
56322
- function normaliseRefinedExpression(node, src) {
56323
- return {
56324
- ...node,
56325
- expression: normaliseSubExpression(node.expression, src),
56326
- refinement: normaliseRefinement(node.refinement, src)
56327
- };
56328
- }
56329
- function normaliseRefinement(node, src) {
56330
- const normAttrs = node.attributes.map((a) => normaliseAttribute(a, src));
56331
- normAttrs.sort((a, b) => compareAttributes(a, b, src));
56332
- return { ...node, attributes: normAttrs };
56333
- }
56334
- function compareAttributes(a, b, src) {
56335
- const aId = a.name.conceptId;
56336
- const bId = b.name.conceptId;
56337
- if (aId && bId) {
56338
- const aBig = BigInt(aId);
56339
- const bBig = BigInt(bId);
56340
- if (aBig < bBig) return -1;
56341
- if (aBig > bBig) return 1;
56342
- return 0;
56343
- }
56344
- if (aId) return -1;
56345
- if (bId) return 1;
56346
- const aKey = a.name.expression ? printCanonical(a.name.expression, src) : "";
56347
- const bKey = b.name.expression ? printCanonical(b.name.expression, src) : "";
56348
- return aKey.localeCompare(bKey);
56349
- }
56350
- function normaliseAttribute(node, src) {
56351
- return {
56352
- ...node,
56353
- name: normaliseAttributeName(node.name, src),
56354
- value: normaliseAttributeValue(node.value, src)
56355
- };
56356
- }
56357
- function normaliseAttributeName(node, src) {
56358
- return {
56359
- ...node,
56360
- term: void 0,
56361
- // §5.1: strip display terms
56362
- expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56363
- };
56364
- }
56365
- function normaliseAttributeValue(node, src) {
56366
- return {
56367
- ...node,
56368
- expression: node.expression ? normaliseSubExpression(node.expression, src) : void 0
56369
- };
56370
- }
56371
- function normaliseDottedExpression(node, src) {
56372
- return {
56373
- ...node,
56374
- source: normaliseSubExpression(node.source, src),
56375
- attributes: node.attributes.map(
56376
- (a) => ({
56377
- ...a,
56378
- attributeName: normaliseSubExpression(a.attributeName, src)
56379
- })
56380
- )
56381
- };
56382
- }
56383
- function stripTerm(node) {
56384
- return { ...node, term: void 0 };
56385
- }
56386
- function copyFilter(node) {
56387
- return { ...node };
56388
- }
56389
56978
  class CanonicaliseError extends Error {
56390
56979
  constructor(message, parseErrors) {
56391
56980
  super(message);
@@ -57430,6 +58019,9 @@ function getGuide(uri2) {
57430
58019
  exports.CanonicaliseError = CanonicaliseError;
57431
58020
  exports.FhirTerminologyService = FhirTerminologyService;
57432
58021
  exports.REFACTORING_RESOLVE_KIND = REFACTORING_RESOLVE_KIND;
58022
+ exports.TerminologyError = TerminologyError;
58023
+ exports.TerminologyHttpError = TerminologyHttpError;
58024
+ exports.TerminologyTransportError = TerminologyTransportError;
57433
58025
  exports.allArticles = allArticles;
57434
58026
  exports.analyzeExpression = analyzeExpression;
57435
58027
  exports.buildReplacementText = buildReplacementText;
@@ -57467,6 +58059,10 @@ exports.getText = getText;
57467
58059
  exports.getValidOperatorsAtPosition = getValidOperatorsAtPosition;
57468
58060
  exports.groupIntoExpressions = groupIntoExpressions;
57469
58061
  exports.isConceptPositionValid = isConceptPositionValid;
58062
+ exports.isEclEvaluationStrategy = isEclEvaluationStrategy;
58063
+ exports.isTerminologyError = isTerminologyError;
58064
+ exports.isTerminologyHttpError = isTerminologyHttpError;
58065
+ exports.isTerminologyTransportError = isTerminologyTransportError;
57470
58066
  exports.isValidConceptId = isValidConceptId;
57471
58067
  exports.isValidDescriptionId = isValidDescriptionId;
57472
58068
  exports.isValidSnomedId = isValidSnomedId;
@@ -57478,6 +58074,8 @@ exports.positionAt = positionAt;
57478
58074
  exports.refineParseError = refineParseError;
57479
58075
  exports.resolveAddDisplayTerms = resolveAddDisplayTerms;
57480
58076
  exports.resolveUnifiedSimplify = resolveUnifiedSimplify;
58077
+ exports.toHttpError = toHttpError;
58078
+ exports.toTransportError = toTransportError;
57481
58079
  exports.validateBoolean = validateBoolean;
57482
58080
  exports.validateIndentSize = validateIndentSize;
57483
58081
  exports.validateIndentStyle = validateIndentStyle;