{"version":3,"sources":["../src/index.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/typePredicates.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/operationOutcome.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/getQuestionnaireResponse.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/fetchQuestionnaire.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/templateExtractRef.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/misc.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/templateMap.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/walkTemplate.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/fhirpathEvaluate.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/expressionManipulation.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/templateExtractPath.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/parseFhirPath.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/staticTemplateData.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/buildValueToInsert.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/templateInsert.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/entryPathPosition.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/evaluateTemplateExtractPath.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/mapToRecord.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/removeTemplateArtifacts.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/populateIntoTemplates.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/extractAllocateId.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/buildBundle.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/filterResources.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/createOutputParameters.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/createFhirPathContext.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/getComparisonSourceResponse.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/extract.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/createInputParameters.ts","../src/SDCExtractQuestionnaireResponseOperation/utils/logging.ts","../src/inAppExtraction/utils/typePredicates.ts","../src/inAppExtraction/utils/inAppExtract.ts"],"sourcesContent":["/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Export inAppExtraction interfaces\nexport type {\n  QuestionnaireOrCallback,\n  FetchQuestionnaireResolver,\n  ExtractResult,\n  InAppExtractOutput\n} from './inAppExtraction';\n\n// Export inAppExtraction utils\nexport {\n  inAppExtract,\n  extractResultIsOperationOutcome,\n  objIsTemplateExtractDebugInfo\n} from './inAppExtraction';\n\n// Export SDCExtractQuestionnaireResponseOperation interfaces\nexport type {\n  OutputParameters,\n  ReturnParameter,\n  IssuesParameter,\n  CustomDebugInfoParameter,\n  TemplateExtractDebugInfo,\n  TemplateExtractPathJsObject,\n  TemplateExtractValueEvaluation,\n  TemplateExtractPathJsObjectTuple,\n  InputParameters,\n  FetchQuestionnaireRequestConfig,\n  FetchQuestionnaireCallback,\n  FhirPatchParameters,\n  FhirPatchParameterEntry\n} from './SDCExtractQuestionnaireResponseOperation';\n\n// Export SDCExtractQuestionnaireResponseOperation utils\nexport {\n  extract,\n  createInputParameters,\n  canBeTemplateExtracted,\n  logTemplateExtractPathMapFull,\n  logTemplateExtractPathMapJsObjectFull,\n  logTemplateExtractPathMapResults,\n  logTemplateExtractPathMapJsObjectResults,\n  parametersIsFhirPatch\n} from './SDCExtractQuestionnaireResponseOperation';\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Coding, Extension, Parameters, ParametersParameter } from 'fhir/r4';\nimport type {\n  CustomComparisonSourceResponseParameter,\n  CustomQuestionnaireParameter,\n  QuestionnaireResponseParameter\n} from '../interfaces/inputParameters.interface';\nimport type { CanonicalParameter } from '@aehrc/sdc-populate/src/SDCPopulateQuestionnaireOperation/interfaces/inputParameters.interface';\nimport type {\n  FullUrlExtensionSlice,\n  IfMatchExtensionSlice,\n  IfModifiedSinceExtensionSlice,\n  IfNoneExistExtensionSlice,\n  IfNoneMatchExtensionSlice,\n  PatchRequestUrlExtensionSlice,\n  ResourceIdExtensionSlice,\n  TemplateExtensionSlice\n} from '../interfaces/templateExtractReference.interface';\nimport type {\n  FhirPatchParameters,\n  FhirPatchPart,\n  FhirPatchPathPart,\n  FhirPatchTypePart\n} from '../interfaces/fhirpatch.interface';\n\nexport function isQuestionnaireResponseParameter(\n  parameter: ParametersParameter\n): parameter is QuestionnaireResponseParameter {\n  return (\n    parameter.name === 'questionnaire-response' &&\n    parameter.resource?.resourceType === 'QuestionnaireResponse'\n  );\n}\n\nexport function isCustomQuestionnaireParameter(\n  parameter: ParametersParameter\n): parameter is CustomQuestionnaireParameter {\n  return parameter.name === 'questionnaire' && parameter.resource?.resourceType === 'Questionnaire';\n}\n\nexport function isCustomComparisonSourceResponseParameter(\n  parameter: ParametersParameter\n): parameter is CustomComparisonSourceResponseParameter {\n  return (\n    parameter.name === 'comparison-source-response' &&\n    parameter.resource?.resourceType === 'QuestionnaireResponse'\n  );\n}\n\nexport function isCanonicalParameter(\n  parameter: ParametersParameter\n): parameter is CanonicalParameter {\n  return parameter.name === 'canonical' && !!parameter.valueCanonical;\n}\n\n/* Type predicates for http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-templateExtract */\nexport function isTemplateExtensionSlice(\n  extension: Extension\n): extension is TemplateExtensionSlice {\n  return (\n    extension.url === 'template' &&\n    'valueReference' in extension &&\n    !!extension.valueReference?.reference &&\n    extension.valueReference.reference.startsWith('#')\n  );\n}\n\nexport function isFullUrlExtensionSlice(extension: Extension): extension is FullUrlExtensionSlice {\n  return extension.url === 'fullUrl' && !!extension.valueString;\n}\n\nexport function isResourceIdExtensionSlice(\n  extension: Extension\n): extension is ResourceIdExtensionSlice {\n  return extension.url === 'resourceId' && !!extension.valueString;\n}\n\nexport function isIfNoneMatchExtensionSlice(\n  extension: Extension\n): extension is IfNoneMatchExtensionSlice {\n  return extension.url === 'ifNoneMatch' && !!extension.valueString;\n}\n\nexport function isIfModifiedSinceExtensionSlice(\n  extension: Extension\n): extension is IfModifiedSinceExtensionSlice {\n  return extension.url === 'ifModifiedSince' && !!extension.valueString;\n}\n\nexport function isIfMatchExtensionSlice(extension: Extension): extension is IfMatchExtensionSlice {\n  return extension.url === 'ifMatch' && !!extension.valueString;\n}\n\nexport function isIfNoneExistExtensionSlice(\n  extension: Extension\n): extension is IfNoneExistExtensionSlice {\n  return extension.url === 'ifNoneExist' && !!extension.valueString;\n}\n\nexport function isPatchRequestUrlExtensionSlice(\n  extension: Extension\n): extension is PatchRequestUrlExtensionSlice {\n  return (\n    extension.url ===\n      'https://smartforms.csiro.au/ig/StructureDefinition/TemplateExtractExtensionPatchRequestUrl' &&\n    !!extension.valueString\n  );\n}\n\nexport function valueIsCoding(value: any): value is Coding {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    ('system' in value || 'code' in value || 'display' in value)\n  );\n}\n\nexport const validFhirPatchTypes = new Set(['add', 'insert', 'delete', 'replace', 'move']);\n\nexport function parametersIsFhirPatch(parameters: Parameters): parameters is FhirPatchParameters {\n  if (parameters.resourceType !== 'Parameters' || !Array.isArray(parameters.parameter)) {\n    return false;\n  }\n\n  return parameters.parameter.every((param) => {\n    if (param.name !== 'operation') return false;\n\n    // If part exists, it must be an array\n    if (!Array.isArray(param.part)) return false;\n\n    // Based on https://build.fhir.org/fhirpath-patch.html, there is no mandatory elements, but we enforce ourselves that a  FHIRPatch needs to have a \"type\" part with a valid operation type.\n    const typePart = param.part.find((p) => p.name === 'type' && typeof p.valueCode === 'string');\n    if (!typePart || typeof typePart.valueCode !== 'string') {\n      return false;\n    }\n\n    return validFhirPatchTypes.has(typePart.valueCode);\n  });\n}\n\nexport function isFhirPatchTypePart(part: FhirPatchPart): part is FhirPatchTypePart {\n  return part.name === 'type' && 'valueCode' in part;\n}\n\nexport function isFhirPatchPathPart(part: FhirPatchPart): part is FhirPatchPathPart {\n  return part.name === 'path' && 'valueString' in part;\n}\n\nexport function isFhirPatchNamePart(part: FhirPatchPart): part is FhirPatchPathPart {\n  return part.name === 'name' && 'valueString' in part;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OperationOutcome, OperationOutcomeIssue } from 'fhir/r4';\n\n/**\n * Create an OperationOutcome error with a supplied error message\n *\n * @author Sean Fong\n */\nexport function createErrorOutcome(errorMessage: string): OperationOutcome {\n  return {\n    resourceType: 'OperationOutcome',\n    issue: [\n      {\n        severity: 'error',\n        code: 'invalid',\n        details: { text: errorMessage }\n      }\n    ]\n  };\n}\n\n/**\n * Create an OperationOutcome error with a supplied error message\n *\n * @author Sean Fong\n */\nexport function createWarningOutcomeWithInvalid(errorMessage: string): OperationOutcome {\n  return {\n    resourceType: 'OperationOutcome',\n    issue: [createInvalidWarningIssue(errorMessage)]\n  };\n}\n\n/**\n * Create an OperationOutcome issue of severity \"warning\" and code \"invalid\" with a supplied warning message\n *\n * @author Sean Fong\n */\nexport function createInvalidWarningIssue(warningMessage: string): OperationOutcomeIssue {\n  return {\n    severity: 'warning',\n    code: 'invalid',\n    details: { text: warningMessage }\n  };\n}\n","import type { OperationOutcome, QuestionnaireResponse } from 'fhir/r4';\nimport type { InputParameters } from '../interfaces/inputParameters.interface';\nimport { isQuestionnaireResponseParameter } from './typePredicates';\nimport { createErrorOutcome } from './operationOutcome';\n\nexport function getQuestionnaireResponse(\n  inputParameters: InputParameters | QuestionnaireResponse\n): QuestionnaireResponse | OperationOutcome {\n  // Check if the input is a QuestionnaireResponse directly\n  if (inputParameters.resourceType === 'QuestionnaireResponse') {\n    return inputParameters;\n  }\n\n  // Check if the input is Parameters and find the QuestionnaireResponse parameter\n  if (inputParameters.resourceType === 'Parameters') {\n    const questionnaireResponseParam = inputParameters.parameter.find((param) =>\n      isQuestionnaireResponseParameter(param)\n    );\n\n    if (\n      questionnaireResponseParam &&\n      questionnaireResponseParam.resource &&\n      questionnaireResponseParam.resource.resourceType === 'QuestionnaireResponse'\n    ) {\n      return questionnaireResponseParam.resource;\n    }\n  }\n\n  // If no QuestionnaireResponse is found, return null\n  return createErrorOutcome(`No QuestionnaireResponse found in input parameters`);\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCustomQuestionnaireParameter } from './typePredicates';\nimport type { Bundle, OperationOutcome, Questionnaire, QuestionnaireResponse } from 'fhir/r4';\nimport { createErrorOutcome } from './operationOutcome';\nimport type { InputParameters } from '../interfaces/inputParameters.interface';\nimport type {\n  FetchQuestionnaireCallback,\n  FetchQuestionnaireRequestConfig\n} from '../interfaces/callback.interface';\n\nexport async function fetchQuestionnaire(\n  inputParameters: InputParameters | QuestionnaireResponse,\n  questionnaireResponse: QuestionnaireResponse,\n  fetchQuestionnaireCallback: FetchQuestionnaireCallback,\n  fetchQuestionnaireRequestConfig: FetchQuestionnaireRequestConfig\n): Promise<Questionnaire | OperationOutcome> {\n  // Check if we have a questionnaire parameter that provides us the Questionnaire resource upfront\n  if (inputParameters.resourceType === 'Parameters') {\n    const customQuestionnaireParam = inputParameters.parameter.find((param) =>\n      isCustomQuestionnaireParameter(param)\n    );\n    if (\n      customQuestionnaireParam &&\n      customQuestionnaireParam.name === 'questionnaire' &&\n      customQuestionnaireParam.resource.resourceType === 'Questionnaire'\n    ) {\n      return customQuestionnaireParam.resource;\n    }\n  }\n\n  // Questionnaire not provided, so we need to resolve it from QuestionnaireResponse.questionnaire\n  const questionnaireCanonical = questionnaireResponse.questionnaire;\n  if (!questionnaireCanonical || questionnaireCanonical === '') {\n    return createErrorOutcome(\n      `QuestionnaireResponse.questionnaire is empty, unable to fetch questionnaire`\n    );\n  }\n\n  const query = `Questionnaire?url=${questionnaireCanonical}`;\n  const response: Questionnaire | Bundle | OperationOutcome = await fetchQuestionnaireCallback(\n    query,\n    fetchQuestionnaireRequestConfig\n  );\n\n  if (response.resourceType === 'Questionnaire') {\n    // Return response as Questionnaire\n    return response;\n  }\n\n  if (response.resourceType === 'Bundle') {\n    // Return first Questionnaire in Bundle\n    const firstQuestionnaire = response.entry?.find(\n      (entry) => entry.resource?.resourceType === 'Questionnaire'\n    )?.resource as Questionnaire | undefined;\n    return (\n      firstQuestionnaire ?? createErrorOutcome(`Unable to fetch questionnaire with query ${query}`)\n    );\n  }\n\n  if (response.resourceType === 'OperationOutcome') {\n    // Return response as FHIR OperationOutcome\n    return response;\n  }\n\n  // Most likely an error, return error as OperationOutcome\n  return createErrorOutcome(JSON.stringify(response));\n}\n","import type { Extension, OperationOutcomeIssue, Questionnaire, QuestionnaireItem } from 'fhir/r4';\nimport type { TemplateExtractReference } from '../interfaces/templateExtractReference.interface';\nimport {\n  isFullUrlExtensionSlice,\n  isIfMatchExtensionSlice,\n  isIfModifiedSinceExtensionSlice,\n  isIfNoneExistExtensionSlice,\n  isIfNoneMatchExtensionSlice,\n  isPatchRequestUrlExtensionSlice,\n  isResourceIdExtensionSlice,\n  isTemplateExtensionSlice\n} from './typePredicates';\nimport { createInvalidWarningIssue } from './operationOutcome';\n\n/**\n * Parses and validates `sdc-questionnaire-templateExtract` extensions on a Questionnaire or QuestionnaireItem.\n *\n * This function extracts a structured `TemplateExtractReference` object from any extensions if present,\n * and verifies cardinality rules and format constraints for each known slice (e.g. `template`, `fullUrl`, etc.).\n * It also collects any violations into returned `OperationOutcomeIssue` warnings.\n *\n * Known validation rules:\n * - `template` slice must appear exactly once and must reference a contained resource (`#id` format).\n * - All slice URLs (except `template`) must occur at most once (0..1 cardinality).\n * - No nested extensions are allowed within any slice.\n *\n * @param {QuestionnaireItem | Questionnaire} item - The FHIR item to check for the extension.\n *\n * @returns {{\n *   templateExtractRefs: TemplateExtractReference[],\n *   warnings?: OperationOutcomeIssue[]\n * }}\n */\nexport function hasTemplateExtractRefExtension(item: QuestionnaireItem | Questionnaire): {\n  templateExtractRefs: TemplateExtractReference[];\n  warnings?: OperationOutcomeIssue[];\n} {\n  if (!item.extension || item.extension.length === 0) {\n    return {\n      templateExtractRefs: []\n    };\n  }\n\n  const templateExtractRefExtension = item.extension.filter(\n    (extension) =>\n      extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-templateExtract'\n  );\n\n  const itemId = 'linkId' in item ? item.linkId : 'QuestionnaireLevel';\n\n  return templateExtractRefExtension\n    .map((ext) => validateAndExtractTemplateExtractReference(ext, itemId))\n    .reduce(\n      (acc, { templateExtractRef, warning }) => {\n        const warnings = warning ? [warning] : [];\n\n        if (templateExtractRef) {\n          if (\n            acc.templateExtractRefs.some((ref) => ref.templateId === templateExtractRef.templateId)\n          ) {\n            // Repeated templateId, add a warning\n            warnings.push(\n              createInvalidWarningIssue(\n                `More than one sdc-questionnaire-templateExtract extension with templateId \"${templateExtractRef.templateId}\" found in ${itemId}. Only one occurrence will be used.`\n              )\n            );\n          }\n          acc.templateExtractRefs.push(templateExtractRef);\n        }\n\n        if (warnings.length) {\n          if (!acc.warnings) {\n            acc.warnings = [];\n          }\n          acc.warnings.push(...warnings);\n        }\n        return acc;\n      },\n      {\n        templateExtractRefs: []\n      } as {\n        templateExtractRefs: TemplateExtractReference[];\n        warnings?: OperationOutcomeIssue[];\n      }\n    );\n}\n\n/**\n * Checks whether a Questionnaire or any of its items contains a valid `sdc-questionnaire-templateExtract` extension with a required `template` slice.\n * Array.prototype.some() is short-circuiting, so it will return true as soon as it finds a valid extension.\n *\n * @param questionnaire - The FHIR Questionnaire to check.\n * @returns `true` if at least one valid template extract reference exists.\n */\nexport function canBeTemplateExtracted(questionnaire: Questionnaire): boolean {\n  // Check Questionnaire-level extension\n  const { templateExtractRefs } = hasTemplateExtractRefExtension(questionnaire);\n  if (templateExtractRefs?.length) {\n    return true;\n  }\n\n  // Check item-level extensions recursively\n  if (questionnaire.item) {\n    return questionnaire.item.some((item) => hasTemplateExtractRefExtensionRecursive(item));\n  }\n\n  return false;\n}\n/**\n * Recursively checks whether a `QuestionnaireItem` or any of its child items contains a `sdc-questionnaire-templateExtract` extension with a required `template` slice.\n * Array.prototype.some() is short-circuiting, so it will return true as soon as it finds a valid extension.\n */\nfunction hasTemplateExtractRefExtensionRecursive(item: QuestionnaireItem): boolean {\n  const { templateExtractRefs } = hasTemplateExtractRefExtension(item);\n  if (templateExtractRefs?.length) {\n    return true;\n  }\n\n  return item.item?.some((child) => hasTemplateExtractRefExtensionRecursive(child)) ?? false;\n}\n\n/**\n * Traverses a FHIR Questionnaire and collects all `sdc-questionnaire-templateExtract` extensions\n * that contain a required `template` slice. Also includes the Questionnaire-level extension if present.\n *\n * @param questionnaire - The FHIR Questionnaire resource to process.\n * @returns A Map where each key is a `QuestionnaireItem.linkId`, or 'QuestionnaireLevel', and the value is the extract template slice set.\n */\nexport function collectTemplateExtractRefs(questionnaire: Questionnaire): {\n  templateExtractRefMap: Map<string, TemplateExtractReference[]>;\n  templateExtractRefWarnings: OperationOutcomeIssue[];\n} {\n  const templateExtractRefMap = new Map<string, TemplateExtractReference[]>();\n  const templateExtractRefWarnings: OperationOutcomeIssue[] = [];\n\n  // Handle Questionnaire-level extension\n  const { templateExtractRefs, warnings } = hasTemplateExtractRefExtension(questionnaire);\n  if (templateExtractRefs?.length) {\n    templateExtractRefMap.set('QuestionnaireLevel', templateExtractRefs);\n  }\n\n  if (warnings) {\n    templateExtractRefWarnings.push(...warnings);\n  }\n\n  // Handle item-level extensions\n  if (questionnaire.item) {\n    for (const item of questionnaire.item) {\n      collectTemplateExtractRefRecursive(item, templateExtractRefMap, templateExtractRefWarnings);\n    }\n  }\n\n  return { templateExtractRefMap, templateExtractRefWarnings };\n}\n\n/**\n * Recursively walks through a QuestionnaireItem tree, extracting `templateExtract` extensions\n * and populating a map with entries where the required `template` slice exists.\n *\n * @param qItem - The QuestionnaireItem to evaluate.\n * @param templateExtractRefMap - A Map to populate with extracted template slices, keyed by `linkId`.\n * @param templateExtractRefWarnings - An array to collect any cardinality-related warnings encountered during collection. Each warning is an OperationOutcomeIssue describing missing or extra extensions within a `templateExtract` slice.\n */\nfunction collectTemplateExtractRefRecursive(\n  qItem: QuestionnaireItem,\n  templateExtractRefMap: Map<string, TemplateExtractReference[]>,\n  templateExtractRefWarnings: OperationOutcomeIssue[]\n): void {\n  const { templateExtractRefs, warnings } = hasTemplateExtractRefExtension(qItem);\n  if (templateExtractRefs?.length) {\n    templateExtractRefMap.set(qItem.linkId, templateExtractRefs); // Cast is safe because `template` is required\n  }\n\n  if (warnings) templateExtractRefWarnings.push(...warnings);\n\n  if (qItem.item) {\n    for (const childQItem of qItem.item) {\n      collectTemplateExtractRefRecursive(\n        childQItem,\n        templateExtractRefMap,\n        templateExtractRefWarnings\n      );\n    }\n  }\n}\n\n/**\n * Extracts a structured `TemplateExtractReference` object from the given templateExtract extension,\n * and verifies cardinality rules and format constraints for each known slice (e.g. `template`, `fullUrl`, etc.).\n * It also collects any violations into a returned `OperationOutcomeIssue` warning.\n *\n * Known validation rules:\n * - `template` slice must appear exactly once and must reference a contained resource (`#id` format).\n * - All slice URLs (except `template`) must occur at most once (0..1 cardinality).\n * - No nested extensions are allowed within any slice.\n *\n * @param {Extension} templateExtractRefExtension - The templateExtract extension.\n * @param {string} itemId - The linkId of the QuestionnaireItem or 'QuestionnaireLevel' for Questionnaire-level extensions.\n *\n * @returns {{\n *   templateExtractRef: TemplateExtractReference | null,\n *   warning?: OperationOutcomeIssue\n * }}\n */\nfunction validateAndExtractTemplateExtractReference(\n  templateExtractRefExtension: Extension,\n  itemId: string\n): {\n  templateExtractRef: TemplateExtractReference | null;\n  warning?: OperationOutcomeIssue;\n} {\n  const templateExtractRefSlices = templateExtractRefExtension.extension ?? [];\n  const cardinalityWarningStrings: string[] = [];\n  let templateCount = 0;\n  const seenSliceNames = new Set<string>();\n\n  const templateExtractRef: Partial<TemplateExtractReference> = {};\n\n  for (const slice of templateExtractRefSlices) {\n    // Check if the slice has nested extensions\n    if (slice.extension && slice.extension.length > 0) {\n      cardinalityWarningStrings.push(\n        `Extension slice with url \"${slice.url}\" must not have nested extensions (0..0).`\n      );\n    }\n\n    if (isTemplateExtensionSlice(slice)) {\n      const ref = slice.valueReference?.reference;\n      if (ref && ref.startsWith('#')) {\n        if (templateCount === 0) {\n          templateExtractRef.templateId = ref.substring(1); // remove leading '#'\n        }\n        templateCount++;\n      } else {\n        cardinalityWarningStrings.push(\n          `Invalid \"template\" reference format in ${itemId}: must start with '#'`\n        );\n      }\n      continue;\n    }\n\n    // Track slice URLs to catch duplicates (for 0..1 constraints)\n    if (seenSliceNames.has(slice.url)) {\n      cardinalityWarningStrings.push(\n        `Extension slice \"${slice.url}\" must not appear more than once (0..1).`\n      );\n      continue;\n    }\n    seenSliceNames.add(slice.url);\n\n    if (isFullUrlExtensionSlice(slice)) {\n      templateExtractRef.fullUrl = slice.valueString;\n      continue;\n    }\n\n    if (isResourceIdExtensionSlice(slice)) {\n      templateExtractRef.resourceId = slice.valueString;\n      continue;\n    }\n\n    if (isPatchRequestUrlExtensionSlice(slice)) {\n      templateExtractRef.patchRequestUrl = slice.valueString;\n\n      // resourceId and patchRequestUrl cannot both be present at the same time\n      if (templateExtractRef.resourceId) {\n        cardinalityWarningStrings.push(\n          `Extension slices \"resourceId\" and \"patchRequestUrl\" cannot both be present at the same time.`\n        );\n      }\n      continue;\n    }\n\n    if (isIfNoneMatchExtensionSlice(slice)) {\n      templateExtractRef.ifNoneMatch = slice.valueString;\n      continue;\n    }\n\n    if (isIfModifiedSinceExtensionSlice(slice)) {\n      templateExtractRef.ifModifiedSince = slice.valueString;\n      continue;\n    }\n\n    if (isIfMatchExtensionSlice(slice)) {\n      templateExtractRef.ifMatch = slice.valueString;\n      continue;\n    }\n\n    if (isIfNoneExistExtensionSlice(slice)) {\n      templateExtractRef.ifNoneExist = slice.valueString;\n    }\n  }\n\n  // Extension.template slice is required, and it should only appear once\n  if (!templateExtractRef.templateId) {\n    return {\n      templateExtractRef: null,\n      warning: createInvalidWarningIssue(\n        `sdc-questionnaire-templateExtract found in ${itemId}, but missing required \"template\" slice or it may be invalid.`\n      )\n    };\n  }\n\n  if (templateCount > 1) {\n    cardinalityWarningStrings.push(\n      `Extension slice \"template\" must appear exactly once (1..1), but found ${templateCount}.`\n    );\n  }\n\n  let warning: OperationOutcomeIssue | undefined;\n  if (cardinalityWarningStrings.length > 0) {\n    warning = createInvalidWarningIssue(\n      `Cardinality issues in ${itemId} sdc-questionnaire-templateExtract:\\n- ${cardinalityWarningStrings.join('\\n- ')}`\n    );\n  }\n\n  // We have validated that extension.template slice is present, so we can safely cast to ExtractedTemplate\n  return {\n    templateExtractRef: templateExtractRef as TemplateExtractReference,\n    ...(warning && { warning: warning })\n  };\n}\n","import type {\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireResponse,\n  QuestionnaireResponseItem\n} from 'fhir/r4';\n\n/**\n * Returns the Questionnaire.item matching the given linkId, searched recursively.\n *\n * @param questionnaire - The Questionnaire to search.\n * @param targetLinkId - The linkId of the item to find.\n * @returns The matching QuestionnaireItem, or null if not found.\n */\nexport function getQuestionnaireItem(\n  questionnaire: Questionnaire,\n  targetLinkId: string\n): QuestionnaireItem | null {\n  // Search through the top level items recursively\n  const topLevelQItems = questionnaire.item;\n  if (topLevelQItems) {\n    for (const topLevelQItem of topLevelQItems) {\n      const foundQItem = getQuestionnaireItemRecursive(topLevelQItem, targetLinkId);\n      if (foundQItem) {\n        return foundQItem;\n      }\n    }\n  }\n\n  // No matching item found in the questionnaire, return null\n  return null;\n}\n\n/**\n * Recursively searches a QuestionnaireItem and its children for the given linkId.\n *\n * @param qItem - The current QuestionnaireItem to search.\n * @param targetLinkId - The linkId to find.\n * @returns The matching QuestionnaireItem, or null if not found.\n */\nfunction getQuestionnaireItemRecursive(\n  qItem: QuestionnaireItem,\n  targetLinkId: string\n): QuestionnaireItem | null {\n  // Target linkId found in current item\n  if (qItem.linkId === targetLinkId) {\n    return qItem;\n  }\n\n  // Search through its child items recursively\n  const childQItems = qItem.item;\n  if (childQItems) {\n    for (const childQItem of childQItems) {\n      const foundQItem = getQuestionnaireItemRecursive(childQItem, targetLinkId);\n      if (foundQItem) {\n        return foundQItem;\n      }\n    }\n  }\n\n  // No matching item found in the current item or its child items, return null\n  return null;\n}\n\n/**\n * Returns the FHIRPath to a QuestionnaireResponse.item that matches the given linkId.\n *\n * @param questionnaireResponse - The QuestionnaireResponse to search through.\n * @param targetLinkId - The linkId of the item to find.\n * @returns A FHIRPath string using .item.where(linkId='...') syntax, or null if not found.\n */\nexport function getQuestionnaireResponseItemFhirPath(\n  questionnaireResponse: QuestionnaireResponse,\n  targetLinkId: string\n): string | null {\n  const topLevelQRItems = questionnaireResponse.item;\n  if (!topLevelQRItems) {\n    return null;\n  }\n\n  for (const item of topLevelQRItems) {\n    const path = getQuestionnaireResponseItemFhirPathRecursive(\n      item,\n      targetLinkId,\n      `item.where(linkId='${item.linkId}')`\n    );\n    if (path) {\n      return path;\n    }\n  }\n\n  return null;\n}\n\n/**\n * Recursively searches a QuestionnaireResponseItem tree and builds a FHIRPath to the item with the given linkId.\n *\n * @param qrItem - The current QuestionnaireResponseItem being traversed.\n * @param targetLinkId - The target linkId to match.\n * @param currentPath - The current FHIRPath traversal string using .where(linkId='...')\n * @returns A full FHIRPath string to the target item if found, or null if not found.\n */\nfunction getQuestionnaireResponseItemFhirPathRecursive(\n  qrItem: QuestionnaireResponseItem,\n  targetLinkId: string,\n  currentPath: string\n): string | null {\n  if (qrItem.linkId === targetLinkId) {\n    return currentPath;\n  }\n\n  const childQRItems = qrItem.item;\n  if (childQRItems) {\n    for (const childQRItem of childQRItems) {\n      const nextPath = `${currentPath}.item.where(linkId='${childQRItem.linkId}')`;\n      const childPath = getQuestionnaireResponseItemFhirPathRecursive(\n        childQRItem,\n        targetLinkId,\n        nextPath\n      );\n      if (childPath) {\n        return childPath;\n      }\n    }\n  }\n\n  return null;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Questionnaire, QuestionnaireResponse } from 'fhir/r4';\nimport type { TemplateDetails } from '../interfaces/templateExtractPath.interface';\nimport { getQuestionnaireItem, getQuestionnaireResponseItemFhirPath } from './misc';\nimport type { TemplateExtractReference } from '../interfaces/templateExtractReference.interface';\n\n/**\n * Builds a map of contained template resources (by `id`) to their contextual metadata\n * within the parent `Questionnaire` and `QuestionnaireResponse`.\n *\n * This is used to associate FHIR templates (typically contained `Questionnaire` resources)\n * with the specific `linkId` they are referenced from in the main questionnaire, based on\n * the `linkIdToTemplateExtractRefMap`.\n *\n * Each resulting `TemplateDetails` entry includes:\n * - the contained template resource,\n * - the `linkId` in the parent questionnaire that references it,\n * - the corresponding `Questionnaire.item`,\n * - and optionally the corresponding `QuestionnaireResponse.item` and its FHIRPath.\n *\n * @param {Questionnaire} questionnaire - The main questionnaire containing the template references and contained templates.\n * @param {QuestionnaireResponse} questionnaireResponse - The response associated with the questionnaire; may provide `item` context.\n * @param {Map<string, TemplateExtractReference>} linkIdToTemplateExtractRefMap - A map of linkId → template reference metadata.\n *\n * @returns {Map<string, TemplateDetails>} A map of template `id` → metadata for resolving contained templates and their context.\n */\nexport function createContainedTemplateMap(\n  questionnaire: Questionnaire,\n  questionnaireResponse: QuestionnaireResponse,\n  linkIdToTemplateExtractRefMap: Map<string, TemplateExtractReference[]>\n): Map<string, TemplateDetails> {\n  const templateMap = new Map<string, TemplateDetails>();\n  if (questionnaire.contained) {\n    // Create a templateId to linkId map\n    const templateIdToLinkIdMap = createTemplateIdToLinkIdMap(linkIdToTemplateExtractRefMap);\n\n    // Iterate over contained resources and map them to their templateId\n    for (const containedResource of questionnaire.contained) {\n      if (containedResource.id && templateIdToLinkIdMap.has(containedResource.id)) {\n        // fallback to \"\" really shouldn't happen, since we have type safety on the line above, https://github.com/microsoft/TypeScript/issues/13086\n        const targetLinkId = templateIdToLinkIdMap.get(containedResource.id) ?? '';\n\n        const targetQItem = getQuestionnaireItem(questionnaire, targetLinkId);\n        const targetQRItemFhirPath = getQuestionnaireResponseItemFhirPath(\n          questionnaireResponse,\n          targetLinkId\n        );\n\n        const templateExtractReferences = linkIdToTemplateExtractRefMap.get(targetLinkId);\n        const templateExtractReference = templateExtractReferences?.find(\n          (t) => t.templateId === containedResource.id\n        );\n        if (targetQItem && templateExtractReference) {\n          templateMap.set(containedResource.id, {\n            templateResource: containedResource,\n            templateExtractReference,\n            targetLinkId: targetLinkId,\n            targetQItem: targetQItem,\n            ...(targetQRItemFhirPath && { targetQRItemFhirPath })\n          });\n        }\n      }\n    }\n  }\n\n  return templateMap;\n}\n\n/**\n * Creates a reverse mapping from `templateId` to the `linkId` that references it.\n *\n * This is used to locate the `Questionnaire.item.linkId` that points to a particular\n * contained template resource, based on `linkIdToTemplateExtractRefMap` which maps linkIds\n * to their associated `TemplateExtractReference` metadata.\n *\n * @param {Map<string, TemplateExtractReference>} linkIdToTemplateExtractRefMap - A map of `linkId` to template reference info.\n *\n * @returns {Map<string, string>} A map of `templateId` → `linkId` that references the template.\n */\nfunction createTemplateIdToLinkIdMap(\n  linkIdToTemplateExtractRefMap: Map<string, TemplateExtractReference[]>\n): Map<string, string> {\n  const templateIdToLinkIdMap = new Map<string, string>();\n\n  for (const [linkId, templateExtractRefs] of linkIdToTemplateExtractRefMap.entries()) {\n    templateExtractRefs.forEach((templateExtractRef) => {\n      if (templateExtractRef.templateId) {\n        templateIdToLinkIdMap.set(templateExtractRef.templateId, linkId);\n      }\n    });\n  }\n\n  return templateIdToLinkIdMap;\n}\n","import type { OperationOutcomeIssue } from 'fhir/r4';\nimport { createInvalidWarningIssue } from './operationOutcome';\nimport type {\n  TemplateExtractPath,\n  TemplateExtractValueEvaluation\n} from '../interfaces/templateExtractPath.interface';\n\n/**\n * Recursively traverses a FHIR resource or JSON structure to identify and record\n * all `templateExtractContext` extensions within `extension` arrays. Builds a map of\n * `contextPathTuple` entries for later extraction of values.\n *\n * @param {any} obj - The FHIR resource or nested object to walk. Can be an array, object, primitive, or null.\n * @param {string} currentPath - The FHIRPath-style path leading to the current node in the object tree.\n * @param {string} templateId - Identifier of the template currently being processed (used in warnings).\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - A map to collect context paths and associated value paths.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - A list to which warning issues will be pushed if invalid data is found.\n */\nexport function walkTemplateForContexts(\n  obj: any, // This is any because it can refer to anything, a FHIR resource, an extension (array), string, identifier, dateTime, JSON object, etc.\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[]\n): void {\n  // obj is an array\n  if (Array.isArray(obj)) {\n    obj.forEach((item, index) =>\n      walkTemplateForContexts(\n        item,\n        `${currentPath}[${index}]`,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings\n      )\n    );\n    return;\n  }\n\n  // obj is a object\n  if (typeof obj === 'object' && obj !== null) {\n    for (const [key, value] of Object.entries(obj)) {\n      const childPath = `${currentPath}.${key}`;\n\n      // Look for extension array containing templateExtractContext extensions\n      if (key === 'extension' && Array.isArray(value)) {\n        addTemplateExtractContexts(\n          value,\n          childPath,\n          currentPath,\n          templateId,\n          templateExtractPathMap,\n          walkTemplateWarnings\n        );\n      }\n\n      walkTemplateForContexts(\n        value,\n        childPath,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings\n      );\n    }\n  }\n\n  return;\n}\n\n/**\n * Searches an `extension` array for the `templateExtractContext` extension defined by\n * the SDC specification, and adds it to the extract path map if valid.\n *\n * @param {any[]} value - The array of extensions on a FHIR element (e.g., `identifier.extension`).\n * @param {string} childPath - Full path to the extension array in the parent object.\n * @param {string} currentPath - The FHIRPath-style path of the parent element containing the extension.\n * @param {string} templateId - The ID of the current template being processed.\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - The map used to collect context and value mappings.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - A list where validation warnings are pushed.\n */\nfunction addTemplateExtractContexts(\n  value: any[],\n  childPath: string,\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[]\n): void {\n  // Find if templateExtractContext extension exists\n  const templateExtractContextIndex = value.findIndex(\n    (ext) =>\n      ext.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-templateExtractContext'\n  );\n  if (templateExtractContextIndex !== -1) {\n    const templateExtractContext = value[templateExtractContextIndex];\n    const logicalPath = `${childPath}[${templateExtractContextIndex}]`;\n    if (templateExtractContext?.valueString) {\n      // e.g. Patient.identifier[0].extension[0]\n      templateExtractPathMap.set(currentPath, {\n        contextPathTuple: [logicalPath, templateExtractContext.valueString],\n        valuePathMap: new Map<string, TemplateExtractValueEvaluation>()\n      });\n    } else {\n      walkTemplateWarnings.push(\n        createInvalidWarningIssue(\n          `Template ${templateId}: TemplateExtractContext extension found on ${logicalPath} but no valueString found.`\n        )\n      );\n    }\n  }\n\n  return;\n}\n\n/* TemplateExtractValue with templateExtractEntryPath */\n\n/**\n * Recursively walks through a FHIR resource or arbitrary JSON structure to locate and collect\n * `templateExtractValue` extensions. These are used to define FHIRPath expressions for extracting\n * values from within the context previously defined via `templateExtractContext`.\n *\n * @param {any} obj - The FHIR resource or nested JSON object/array to walk through.\n * @param {string} currentPath - Current FHIRPath-like string representing the path to the object.\n * @param {string} templateId - Identifier for the template being processed.\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - Map collecting context and value paths.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - List to accumulate any warnings generated while walking.\n * @param {string} templateExtractEntryPath - The entry path key corresponding to the context this value belongs to.\n */\nexport function walkTemplateForContextValues(\n  obj: any, // This is any because it can refer to anything, a FHIR resource, an extension (array), string, identifier, dateTime, JSON object, etc.\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[],\n  templateExtractEntryPath: string\n): void {\n  // obj is an array\n  if (Array.isArray(obj)) {\n    obj.forEach((item, index) =>\n      walkTemplateForContextValues(\n        item,\n        `${currentPath}[${index}]`,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings,\n        templateExtractEntryPath\n      )\n    );\n    return;\n  }\n\n  // obj is a object\n  if (typeof obj === 'object' && obj !== null) {\n    for (const [key, value] of Object.entries(obj)) {\n      const childPath = `${currentPath}.${key}`;\n\n      // Look for extension array containing templateExtractContext extensions\n      if (key === 'extension' && Array.isArray(value)) {\n        addTemplateExtractContextValues(\n          value,\n          childPath,\n          currentPath,\n          templateId,\n          templateExtractPathMap,\n          walkTemplateWarnings,\n          templateExtractEntryPath\n        );\n      }\n\n      walkTemplateForContextValues(\n        value,\n        childPath,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings,\n        templateExtractEntryPath\n      );\n    }\n  }\n\n  return;\n}\n\n/**\n * Adds a `templateExtractValue` extension (if found) to the `valuePathMap` within the appropriate\n * `TemplateExtractPath` in `templateExtractPathMap`. These specify how to extract values within the\n * previously defined context.\n *\n * @param {any[]} value - The array of extensions on a FHIR element.\n * @param {string} childPath - Path to the extension array (e.g., `Patient.identifier[0].extension`).\n * @param {string} currentPath - Path to the parent element.\n * @param {string} templateId - Identifier for the template (used for logging warnings).\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - Map collecting context and value extraction paths.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - List of warnings for malformed entries.\n * @param {string} templateExtractEntryPath - Path to the entry where this value extraction belongs (i.e., maps to a context).\n */\nfunction addTemplateExtractContextValues(\n  value: any[],\n  childPath: string,\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[],\n  templateExtractEntryPath: string\n): void {\n  // Find if templateExtractValue extension exists\n  const templateExtractValueIndex = value.findIndex(\n    (ext) =>\n      ext.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-templateExtractValue'\n  );\n  if (templateExtractValueIndex !== -1) {\n    const templateExtractValue = value[templateExtractValueIndex];\n    const logicalPath = `${childPath}[${templateExtractValueIndex}]`;\n    if (templateExtractValue?.valueString) {\n      // e.g. Patient.identifier[0].extension[0]\n      const valueEvaluation: TemplateExtractValueEvaluation = {\n        valueExpression: templateExtractValue.valueString,\n        valueResult: []\n      };\n      if (templateExtractPathMap.has(templateExtractEntryPath)) {\n        const templateExtractPath = templateExtractPathMap.get(templateExtractEntryPath);\n        if (templateExtractPath) {\n          templateExtractPath.valuePathMap.set(logicalPath, valueEvaluation);\n        }\n      } else {\n        templateExtractPathMap.set(currentPath, {\n          contextPathTuple: null,\n          valuePathMap: new Map<string, TemplateExtractValueEvaluation>([\n            [logicalPath, valueEvaluation]\n          ])\n        });\n      }\n    } else {\n      walkTemplateWarnings.push(\n        createInvalidWarningIssue(\n          `Template ${templateId}: TemplateExtractContext extension found on ${logicalPath} but no valueString found.`\n        )\n      );\n    }\n  }\n\n  return;\n}\n\n/* TemplateExtractValue standalone */\n\n/**\n * Recursively scans a FHIR resource (or any JSON structure) to find\n * `templateExtractValue` extensions that are **not** associated with a\n * `templateExtractContext`.\n *\n * Each standalone value discovered is added to `templateExtractPathMap`\n * under its own `currentPath` key, unless that logical path already exists\n * in `valuePathToValueExpressionMap` (indicating it was captured earlier while walking\n * context-based values).\n *\n * @param {any} obj - The current node being traversed (array, object, primitive, etc.).\n * @param {string} currentPath - FHIRPath-like string representing the path to `obj`.\n * @param {string} templateId - Identifier of the template being processed (used in warnings).\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - Collector for context/value mappings.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - Accumulates warnings for malformed extensions.\n * @param {Map<string, string>} valuePathToValueExpressionMap - Flat map of logical paths → value expressions gathered so far; used to avoid duplicates.\n */\nexport function walkTemplateForStandaloneValues(\n  obj: any, // This is any because it can refer to anything, a FHIR resource, an extension (array), string, identifier, dateTime, JSON object, etc.\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[],\n  valuePathToValueExpressionMap: Map<string, string>\n): void {\n  // obj is an array\n  if (Array.isArray(obj)) {\n    obj.forEach((item, index) =>\n      walkTemplateForStandaloneValues(\n        item,\n        `${currentPath}[${index}]`,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings,\n        valuePathToValueExpressionMap\n      )\n    );\n    return;\n  }\n\n  // obj is a object\n  if (typeof obj === 'object' && obj !== null) {\n    for (const [key, value] of Object.entries(obj)) {\n      const childPath = `${currentPath}.${key}`;\n\n      // Look for extension array containing templateExtractContext extensions\n      if (key === 'extension' && Array.isArray(value)) {\n        addTemplateExtractStandaloneValues(\n          value,\n          childPath,\n          currentPath,\n          templateId,\n          templateExtractPathMap,\n          walkTemplateWarnings,\n          valuePathToValueExpressionMap\n        );\n      }\n\n      walkTemplateForStandaloneValues(\n        value,\n        childPath,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings,\n        valuePathToValueExpressionMap\n      );\n    }\n  }\n\n  return;\n}\n\n/**\n * Adds a standalone `templateExtractValue` extension (i.e. one without an associated context)\n * to `templateExtractPathMap`, provided that logical path has not already been recorded in\n * `valuePathMap`.\n *\n * @param {any[]} value - The array of extensions on the current FHIR element.\n * @param {string} childPath - Path to the extension array (e.g. `Patient.name[0].extension`).\n * @param {string} currentPath - Path to the parent element that owns the extension array.\n * @param {string} templateId - Identifier for the template (used in warning messages).\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - Map collecting extract paths.\n * @param {OperationOutcomeIssue[]} walkTemplateWarnings - List of warning issues for invalid entries.\n * @param {Map<string, string>} valuePathMap - Flat map of logical paths already registered, used to skip duplicates.\n */\nfunction addTemplateExtractStandaloneValues(\n  value: any[],\n  childPath: string,\n  currentPath: string,\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>,\n  walkTemplateWarnings: OperationOutcomeIssue[],\n  valuePathMap: Map<string, string>\n): void {\n  // Find if templateExtractValue extension exists\n  const templateExtractValueIndex = value.findIndex(\n    (ext) =>\n      ext.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-templateExtractValue'\n  );\n  if (templateExtractValueIndex !== -1) {\n    const templateExtractValue = value[templateExtractValueIndex];\n    const logicalPath = `${childPath}[${templateExtractValueIndex}]`;\n\n    // TemplateExtractValue already exists in a valuePathMap, skip adding\n    if (valuePathMap.has(logicalPath)) {\n      return;\n    }\n\n    if (templateExtractValue?.valueString) {\n      // e.g. Patient.identifier[0].extension[0]\n      templateExtractPathMap.set(currentPath, {\n        contextPathTuple: null,\n        valuePathMap: new Map<string, TemplateExtractValueEvaluation>([\n          [logicalPath, { valueExpression: templateExtractValue.valueString, valueResult: [] }]\n        ])\n      });\n    } else {\n      walkTemplateWarnings.push(\n        createInvalidWarningIssue(\n          `Template ${templateId}: TemplateExtractContext extension found on ${logicalPath} but no valueString found.`\n        )\n      );\n    }\n  }\n\n  return;\n}\n","import fhirpath, { type Model } from 'fhirpath';\nimport fhirpath_r4_model from 'fhirpath/fhir-context/r4';\nimport type { OperationOutcomeIssue } from 'fhir/r4';\nimport { createInvalidWarningIssue } from './operationOutcome';\nimport { normaliseExpression } from './expressionManipulation';\nimport type { FhirPathEvalResult } from '../interfaces/templateExtractPath.interface';\n\n/**\n * Input parameters for evaluating a FHIRPath expression.\n *\n * These map directly to the arguments used by `fhirpath.evaluate(fhirData, path)`.\n */\nexport interface FhirPathEvaluateParams {\n  fhirData: any;\n  path: string;\n  envVars: Record<string, any>;\n  warnings: OperationOutcomeIssue[];\n}\n\n/**\n * Evaluates a FHIRPath expression against a given FHIR resource using the R4 model.\n *\n * @param params - Object containing the FHIR resource (`fhirData`) and the FHIRPath expression (`path`).\n * @returns The result of the FHIRPath evaluation as an array of matched values.\n */\nexport function fhirPathEvaluate(params: FhirPathEvaluateParams): FhirPathEvalResult {\n  const { fhirData, path, envVars, warnings } = params;\n  try {\n    return fhirpath.evaluate(\n      fhirData,\n      normaliseExpression(path),\n      envVars,\n      fhirpath_r4_model as Model,\n      {\n        async: false\n      }\n    );\n  } catch (e) {\n    // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n    console.warn(\n      `SDC-template-extract error:\\nFHIRPath evaluation failed for ${path}.\\n\\nDetails below: ` + e\n    );\n    warnings.push(createInvalidWarningIssue(String(e)));\n  }\n\n  // Return an empty array if evaluation fails\n  return [];\n}\n","import type { OperationOutcomeIssue, QuestionnaireResponse } from 'fhir/r4';\nimport { fhirPathEvaluate } from './fhirpathEvaluate';\n\n/**\n * Combines a base FHIRPath with an appended expression.\n * Returns the appended expression directly if it's a variable reference.\n */\nexport function getCombinedExpression(baseFhirPath: string, expressionToAppend: string): string {\n  // Use variable reference as-is\n  if (expressionToAppend.includes('%')) {\n    return normaliseExpression(expressionToAppend);\n  }\n\n  // baseFhirPath empty, return expression directly\n  if (baseFhirPath === '') {\n    return normaliseExpression(expressionToAppend);\n  }\n\n  // Default append behavior\n  return baseFhirPath + '.' + normaliseExpression(expressionToAppend); // Append to base path\n}\n\n/**\n * Normalizes a FHIRPath expression by handling special cases like `$this` and `ofType()`.\n * If the expression starts with `$this`, it wraps it in `select(...)` and appends to the base path. Otherwise, it appends the expression directly to the base path.\n * ofType() expressions are converted from FHIR primitive types to System types to ease questionnaire-authoring. See https://github.com/HL7/fhirpath.js/issues/168#issuecomment-2964663757.\n */\nexport function normaliseExpression(expression: string) {\n  let normalisedExpression = expression;\n\n  // expression starts with $this, wrap with select()\n  if (expression.includes('$this')) {\n    normalisedExpression = `select(${expression})`;\n  }\n\n  // expression has \"ofType\", handle it by converting FHIR primitive types to System types\n  if (expression.includes('ofType(')) {\n    normalisedExpression = normalisedExpression.replace(\n      /ofType\\(([^)]+)\\)/g,\n      (_, fhirType) => `ofType(${convertFhirTypeToSystemType(fhirType)})`\n    );\n  }\n\n  // Otherwise, return the expression as is\n  return normalisedExpression;\n}\n\nexport function getNumberOfTemplateInstances(\n  questionnaireResponse: QuestionnaireResponse,\n  targetQRItemFhirPath: string,\n  warnings: OperationOutcomeIssue[]\n): number {\n  if (targetQRItemFhirPath) {\n    const targetPathWithCount = getCombinedExpression(targetQRItemFhirPath, 'count()');\n    // Otherwise, evaluate it as a FHIRPath expression\n    const result = fhirPathEvaluate({\n      fhirData: questionnaireResponse,\n      path: targetPathWithCount,\n      envVars: {},\n      warnings: warnings\n    });\n\n    if (Array.isArray(result) && result.length === 1) {\n      return result[0];\n    }\n  }\n\n  return 0;\n}\n\nexport function addIndexToTargetPath(baseFhirPath: string, index: number): string {\n  // baseFhirPath empty, return expression directly\n  if (baseFhirPath === '') {\n    return baseFhirPath;\n  }\n\n  return baseFhirPath + `[${index}]`; // Append to base path\n}\n\n/**\n * Derives the relative value path segments for a value from the full writable path and the entry path.\n *\n * @param entryPathSegments - Segments pointing to the entry location (e.g. [\"MedicationStatement\", \"reasonCode\", 0])\n * @param writablePathSegments - Segments pointing to the writable value location (e.g. [\"MedicationStatement\", \"reasonCode\", 0, \"coding\", 0])\n * @returns The relative value path segments (e.g. [\"coding\", 0])\n */\nexport function getRelativeValuePathSegments(\n  entryPathSegments: (string | number)[],\n  writablePathSegments: (string | number)[]\n): (string | number)[] {\n  // Safety check: entrySegments must be a prefix of writableSegments\n  for (let i = 0; i < entryPathSegments.length; i++) {\n    if (entryPathSegments[i] !== entryPathSegments[i]) {\n      throw new Error(\n        `entryPathSegments must be a prefix of writablePathSegments. Mismatch at index ${i}.`\n      );\n    }\n  }\n\n  // Return the relative path after the entry point\n  return writablePathSegments.slice(entryPathSegments.length);\n}\n\n/**\n * Removes leading underscore from a string segment (e.g. '_field' → 'field').\n * Returns non-string segments unchanged.\n */\nexport function stripUnderscorePrefix(segment: string | number): string | number {\n  if (typeof segment === 'string' && segment.startsWith('_')) {\n    return segment.slice(1);\n  }\n  return segment;\n}\n\n/**\n * Returns updated entry and writable segments:\n * - Replaces the last entry segment with index if it's a number\n * - Strips underscore prefix from the last segment if it's a string starting with '_'\n */\nexport function cleanEntryPathSegments(\n  entryPathSegments: (string | number)[],\n  index: number\n): (string | number)[] {\n  const newSegments = [...entryPathSegments];\n\n  // Last segment is a number (an array index), replace it with the provided index\n  const lastIndex = newSegments.length - 1;\n  const lastSegment = newSegments[lastIndex];\n  if (typeof lastSegment === 'number') {\n    newSegments[lastIndex] = index;\n  }\n\n  // Last segment is a _field, strip underscore prefix (e.g. '_field' → 'field').\n  if (typeof lastSegment === 'string' && lastSegment.startsWith('_')) {\n    newSegments[lastIndex] = stripUnderscorePrefix(lastSegment);\n  }\n\n  return newSegments;\n}\n\n/**\n * Removes a trailing array index from a FHIRPath string (e.g. `foo.bar[2]` → `foo.bar`)\n * @param path - FHIRPath string\n * @returns Path without trailing index\n */\nexport function stripTrailingIndexFromPath(path: string): string {\n  return path.replace(/\\[\\d+\\]$/, '');\n}\n\ntype FhirType =\n  | 'boolean'\n  | 'string'\n  | 'uri'\n  | 'code'\n  | 'oid'\n  | 'id'\n  | 'uuid'\n  | 'markdown'\n  | 'base64Binary'\n  | 'integer'\n  | 'unsignedInt'\n  | 'positiveInt'\n  | 'integer64'\n  | 'decimal'\n  | 'date'\n  | 'dateTime'\n  | 'instant'\n  | 'time'\n  | 'Quantity';\n\ntype FhirSystemType =\n  | 'Boolean'\n  | 'String'\n  | 'Integer'\n  | 'Long'\n  | 'Decimal'\n  | 'DateTime'\n  | 'Time'\n  | 'Quantity';\n\nconst fhirTypeToSystemTypeMap: Record<FhirType, FhirSystemType> = {\n  boolean: 'Boolean',\n  string: 'String',\n  uri: 'String',\n  code: 'String',\n  oid: 'String',\n  id: 'String',\n  uuid: 'String',\n  markdown: 'String',\n  base64Binary: 'String',\n  integer: 'Integer',\n  unsignedInt: 'Integer',\n  positiveInt: 'Integer',\n  integer64: 'Long',\n  decimal: 'Decimal',\n  date: 'DateTime',\n  dateTime: 'DateTime',\n  instant: 'DateTime',\n  time: 'Time',\n  Quantity: 'Quantity'\n};\n\n/**\n * Defines automatic conversion of FHIR types to FHIRPath(System) types. Map lifted from https://github.com/HL7/fhirpath.js/blob/master/src/types.js.\n * See https://hl7.org/fhir/fhirpath.html#types.\n */\nfunction convertFhirTypeToSystemType(type: string): string {\n  return fhirTypeToSystemTypeMap[type as FhirType] ?? type;\n}\n","import type { FhirResource, OperationOutcomeIssue } from 'fhir/r4';\nimport type { TemplateExtractPath } from '../interfaces/templateExtractPath.interface';\nimport {\n  walkTemplateForContexts,\n  walkTemplateForContextValues,\n  walkTemplateForStandaloneValues\n} from './walkTemplate';\nimport { fhirPathEvaluate } from './fhirpathEvaluate';\n\n/**\n * Builds a map of FHIRPath expressions representing extractable data from a template,\n * and collects any warnings encountered during traversal.\n *\n * This function performs three main steps:\n * 1. Walks the resource to find all `templateExtractContext` extensions and builds a path map.\n * 2. Walks the subtree of each context to find associated `templateExtractValue` extensions.\n * 3. Walks the resource again to collect standalone `templateExtractValue` extensions not tied to a context.\n *\n * @param {string} templateId - The ID of the template being processed. Used for namespacing extract paths.\n * @param {FhirResource} resource - The FHIR resource containing the template definition, typically a contained StructureDefinition or similar.\n *\n * @returns {{\n *   templateExtractPathMap: Map<string, TemplateExtractPath>,\n *   walkTemplateWarnings: OperationOutcomeIssue[]\n * }} An object containing:\n * - `templateExtractPathMap`: A map from FHIRPath strings to `TemplateExtractPath` objects describing context/value pairs.\n * - `walkTemplateWarnings`: A list of issues (`OperationOutcomeIssue`) generated during traversal, such as missing expected fields or invalid structures.\n */\nexport function createTemplateExtractPathMap(\n  templateId: string,\n  resource: FhirResource\n): {\n  templateExtractPathMap: Map<string, TemplateExtractPath>;\n  walkTemplateWarnings: OperationOutcomeIssue[];\n} {\n  const basePath = resource.resourceType || 'Resource';\n\n  // First step: walk template to get all templateExtractContexts\n  const templateExtractPathMap = new Map<string, TemplateExtractPath>();\n  const walkTemplateWarnings: OperationOutcomeIssue[] = [];\n\n  walkTemplateForContexts(\n    resource,\n    basePath,\n    templateId,\n    templateExtractPathMap,\n    walkTemplateWarnings\n  );\n\n  // Second step: walk template to assign templateExtractValues to their contexts\n  for (const templateExtractEntryPath of templateExtractPathMap.keys()) {\n    const evaluateResult = fhirPathEvaluate({\n      fhirData: resource,\n      path: templateExtractEntryPath,\n      envVars: {},\n      warnings: walkTemplateWarnings\n    });\n    const subtree = evaluateResult[0];\n    if (typeof subtree === 'object' && subtree !== null) {\n      walkTemplateForContextValues(\n        subtree,\n        templateExtractEntryPath,\n        templateId,\n        templateExtractPathMap,\n        walkTemplateWarnings,\n        templateExtractEntryPath\n      );\n    }\n  }\n\n  // Third step: walk template to get standalone templateExtractValues (without a parent context)\n  // flatten the values path in templateExtractPaths\n  const valuePathMap = flattenValuePathMaps(templateExtractPathMap);\n  walkTemplateForStandaloneValues(\n    resource,\n    basePath,\n    templateId,\n    templateExtractPathMap,\n    walkTemplateWarnings,\n    valuePathMap\n  );\n\n  return {\n    templateExtractPathMap: templateExtractPathMap,\n    walkTemplateWarnings\n  };\n}\n\n/**\n * Flattens all `valuePathMap` entries from a map of `TemplateExtractPath` objects\n * into a single map of logical path to value expression.\n *\n * This is useful for quickly looking up all extractable value paths across all contexts\n * in a template extract definition.\n *\n * @param {Map<string, TemplateExtractPath>} templateExtractPaths -\n *   A map of FHIRPath entry strings to their corresponding `TemplateExtractPath` objects.\n *\n * @returns {Map<string, string>} A flattened map where keys are logical value paths and values are FHIRPath expressions.\n */\nfunction flattenValuePathMaps(\n  templateExtractPaths: Map<string, TemplateExtractPath>\n): Map<string, string> {\n  const valuePathToValueExpressionMap = new Map<string, string>();\n\n  for (const templateExtractPath of templateExtractPaths.values()) {\n    for (const [logicalPath, valueEvaluation] of templateExtractPath.valuePathMap.entries()) {\n      valuePathToValueExpressionMap.set(logicalPath, valueEvaluation.valueExpression);\n    }\n  }\n\n  return valuePathToValueExpressionMap;\n}\n","import { fhirPathEvaluate } from './fhirpathEvaluate';\nimport type { OperationOutcomeIssue } from 'fhir/r4';\nimport { stripUnderscorePrefix } from './expressionManipulation';\n\n/**\n * Parses a FHIRPath-style path into a \"writable\" path array of property names and indices.\n * Only the field directly before `.extension[...]` or the final `_field` will be rewritten.\n * We stop at the real insertion point, ignoring `_`-prefixed paths used only in templating.\n *\n * @param {string} fhirPath - A FHIRPath-style path like \"Patient.name[0]._text.extension[0]\".\n * @returns {(string | number)[]} - An array of \"writable \"path segments: strings for property names, numbers for array indices. e.g. [\"Patient\", \"name\", 0, \"text\"]\n */\nexport function parseFhirPathToWritableSegments(fhirPath: string): (string | number)[] {\n  // Matches property names and array indices in FHIRPath-style strings\n  // Example: \"Patient.name[0]._family.extension[0]\"\n  // Produces matches like: \"Patient\", \"name\", 0, \"_family\", \"extension\", 0\n  const segments = parseFhirPath(fhirPath);\n\n  // Produce writable segments\n  // 1. If the path ends in '.extension[x]', strip the last two segments\n  // 2. If the third last segment starts with '_', strip the underscore to get the base field\n  const writableSegments: (string | number)[] = [...segments];\n\n  // Check if the last three segments are: '_field', 'extension', number\n  const len = writableSegments.length;\n  if (\n    len >= 3 &&\n    writableSegments[len - 2] === 'extension' &&\n    typeof writableSegments[len - 1] === 'number'\n  ) {\n    // Remove trailing `.extension[x]`\n    writableSegments.splice(len - 2, 2);\n  }\n\n  // If the third last segment (currently the last segment) is a primitive wrapper (e.g. '_valueBoolean'), strip the underscore\n  const last = writableSegments[writableSegments.length - 1];\n  if (typeof last === 'string' && last.startsWith('_')) {\n    writableSegments[writableSegments.length - 1] = stripUnderscorePrefix(last); // '_field' → 'field'\n  }\n\n  // If the last segment is a number and the second last is a primitive wrapper for an array (e.g. '_given'), strip the underscore\n  const secondLast = writableSegments[writableSegments.length - 2];\n  if (typeof last === 'number' && typeof secondLast === 'string' && secondLast.startsWith('_')) {\n    writableSegments[writableSegments.length - 2] = stripUnderscorePrefix(secondLast); // '_field' → 'field'\n  }\n\n  return writableSegments;\n}\n\n/**\n * Parses a FHIRPath-style path into an array of property names and indices.\n *\n * @param {string} fhirPath - A FHIRPath-style path like \"Patient.name[0]._family.extension[0]\".\n * @returns {(string | number)[]} - An array of path segments: strings for property names, numbers for array indices.  e.g. [\"Patient\", \"name\", 0, \"_family\", \"extension\", 0]\n */\nexport function parseFhirPath(fhirPath: string): (string | number)[] {\n  const regex = /([^.[]+)|\\[(\\d+)]/g;\n  const segments: (string | number)[] = [];\n\n  let match;\n  while ((match = regex.exec(fhirPath)) !== null) {\n    if (match[1] !== undefined) {\n      segments.push(match[1]);\n    } else if (match[2] !== undefined) {\n      segments.push(Number(match[2]));\n    }\n  }\n\n  return segments;\n}\n\n/**\n * Determines the correct delete path based on how many extensions exist.\n * If only one extension is found, returns the path to a parent node to delete the entire element.\n * If multiple extensions exist, returns the full path to delete just the specific indexed extension.\n *\n * @param {any} resource - The root FHIR resource object to evaluate.\n * @param {(string | number)[]} segments - The FHIRPath-style path as an array of segments, e.g. [\"Patient\", \"_gender\", \"extension\", 0].\n * @param {'context' | 'value'} variant - The variant type, either 'context' or 'value'.\n * @param {OperationOutcomeIssue[]} populateIntoTemplateWarnings - An array to collect any warnings encountered during evaluation.\n * @returns {(string | number)[]} - The adjusted path to use for deletion. Either the original full path or a truncated one if only one extension exists.\n */\nexport function getAdjustedDeletePathSegments(\n  resource: any,\n  segments: (string | number)[],\n  variant: 'context' | 'value',\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n): (string | number)[] {\n  // Get path to the extension array\n  const lastNodeExtensionsPath = segments\n    .slice(0, -1) // drop the final index (e.g., extension[0])\n    .map((segment) => (typeof segment === 'number' ? `[${segment}]` : `.${segment}`))\n    .join('')\n    .replace(/^\\./, ''); // remove leading dot if it exists\n\n  const extensions = fhirPathEvaluate({\n    fhirData: resource,\n    path: lastNodeExtensionsPath,\n    envVars: {},\n    warnings: populateIntoTemplateWarnings\n  });\n\n  // Target extension is the only extension in the array, return the path to a parent node\n  // Depending on the variant, these are the outcomes:\n  // e.g. variant=\"context\": [\"Patient\", \"identifier\", \"extension\"] - to delete \"extension\".\n  // e.g. variant=\"value\": [\"Patient\", \"_gender\"] - to delete \"_gender\"\n  if (Array.isArray(extensions) && extensions.length === 1) {\n    return variant === 'context' ? segments.slice(0, -1) : segments.slice(0, -2);\n  }\n\n  // Keep full path if more than one extension\n  return segments;\n}\n","import type { FhirResource, OperationOutcomeIssue } from 'fhir/r4';\nimport { fhirPathEvaluate } from './fhirpathEvaluate';\n\n/**\n * Retrieves static template data from a clean template at the specified FHIR path.\n *\n * @param entryPath - Entry path to evaluate (e.g., \"MedicationStatement.reasonCode[0]\").\n * @param cleanTemplate - A clean version of the template with static template data.\n * @param populateIntoTemplateWarnings - Collects warnings or issues encountered during static template data evaluation.\n * @returns The object at the path if found and valid, otherwise an empty object.\n */\nexport function getStaticTemplateDataAtPath(\n  entryPath: string,\n  cleanTemplate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n): object {\n  const staticTemplateDataResult = fhirPathEvaluate({\n    fhirData: cleanTemplate,\n    path: entryPath,\n    envVars: {},\n    warnings: populateIntoTemplateWarnings\n  });\n  if (\n    Array.isArray(staticTemplateDataResult) &&\n    staticTemplateDataResult.length === 1 &&\n    typeof staticTemplateDataResult[0] === 'object' &&\n    staticTemplateDataResult[0] !== null\n  ) {\n    return staticTemplateDataResult[0];\n  }\n\n  return {};\n}\n\n/**\n * Merges static template data with the value to insert, if applicable.\n *\n * @param staticTemplateData - The static template data from the template.\n * @param valueToInsert - The value to insert.\n * @returns The combined object if both are valid, otherwise the original value to insert.\n */\nexport function combineStaticTemplateData(staticTemplateData: object, valueToInsert: any) {\n  // Combine static template data with the value to insert if applicable\n  if (\n    Object.keys(staticTemplateData).length > 0 &&\n    typeof valueToInsert === 'object' &&\n    valueToInsert !== null\n  ) {\n    return { ...staticTemplateData, ...valueToInsert };\n  }\n\n  // Otherwise, return the value to insert as is\n  return valueToInsert;\n}\n","import { parseFhirPathToWritableSegments } from './parseFhirPath';\nimport { valueIsCoding } from './typePredicates';\nimport { getRelativeValuePathSegments } from './expressionManipulation';\nimport { combineStaticTemplateData } from './staticTemplateData';\n\n/**\n * Builds an array of insertable values by applying value results to their relative path segments.\n * This function also combines values with static template data.\n *\n * @param entryPathSegments - Segments pointing to the entry location (e.g. [\"Observation\", \"code\"])\n * @param valuePath - Full FHIRPath string to the target value\n * @param valueResultsToInsert - Raw value results to insert\n * @param staticTemplateData - Static template data at valuePath to combine with each value\n * @returns Array of values shaped for insertion\n */\nexport function buildValuesToInsert(\n  entryPathSegments: (string | number)[],\n  valuePath: string,\n  valueResultsToInsert: any,\n  staticTemplateData: object\n): any[] {\n  // Get value path segments relative to the entry path\n  const writableSegments = parseFhirPathToWritableSegments(valuePath);\n  const relativeValuePathSegments = getRelativeValuePathSegments(\n    entryPathSegments,\n    writableSegments\n  );\n\n  // Not sure if this will ever happen\n  if (!Array.isArray(relativeValuePathSegments)) {\n    return valueResultsToInsert as any[];\n  }\n\n  // A trailing array index in the value path (e.g. `given[0]`) is just the template's placeholder\n  // position, not a count of values. Bump it per value so a multi-value result lands at consecutive\n  // indices instead of every value colliding on the same one.\n  const trailingIndex = relativeValuePathSegments[relativeValuePathSegments.length - 1];\n  const bumpTrailingIndex = typeof trailingIndex === 'number';\n\n  const valuesToInsert = [];\n  if (Array.isArray(valueResultsToInsert)) {\n    for (let i = 0; i < valueResultsToInsert.length; i++) {\n      const value = getValueFromResult([valueResultsToInsert[i]]);\n      const segmentsForThisValue = bumpTrailingIndex\n        ? [...relativeValuePathSegments.slice(0, -1), (trailingIndex as number) + i]\n        : relativeValuePathSegments;\n      const valueToInsert = buildSingleValueToInsertRecursive(segmentsForThisValue, value);\n      const fullValueToInsert = combineStaticTemplateData(staticTemplateData, valueToInsert);\n      valuesToInsert.push(fullValueToInsert);\n    }\n  }\n\n  return valuesToInsert;\n}\n\n/**\n * Recursively builds a nested object or array based on path segments and a value.\n *\n * @param valueSegments - Path segments to the target field\n * @param value - The value to insert at the target location\n * @returns A nested structure ready for insertion\n */\nfunction buildSingleValueToInsertRecursive(\n  valueSegments: (string | number)[],\n  value: string | number | object | undefined\n): any {\n  if (valueSegments.length === 0) {\n    return value;\n  }\n\n  const [head, ...rest] = valueSegments;\n\n  // If the next level is a number, wrap in array\n  if (typeof head === 'number') {\n    const arr = [];\n    arr[head] = buildSingleValueToInsertRecursive(rest, value);\n    return arr;\n  }\n\n  // Validate segment\n  if (head === undefined) {\n    throw new Error(\n      `Unexpected segment type: ${typeof head} (value: ${head}) in buildValueToInsertRecursive()`\n    );\n  }\n\n  return {\n    [head]: buildSingleValueToInsertRecursive(rest, value)\n  };\n}\n\n/**\n * Extracts a usable value from a valueResult returned by a FHIRPath evaluation.\n *\n * - If the result is a single-item array:\n *   - If the item is a FHIR `Coding`, returns an object with only defined fields (`code`, `display`, `system`).\n *   - Otherwise, returns the single item directly.\n * - If the result is an array with multiple values or unexpected structure, returns a JSON stringified version. FIXME\n *\n * @param {any} valueResult - The result of a FHIRPath evaluation. Usually an array.\n * @returns {string | number | object} A simplified value ready for assignment to the extracted template location.\n */\nfunction getValueFromResult(valueResult: any[]): string | number | object | undefined {\n  if (Array.isArray(valueResult) && valueResult.length === 1) {\n    const value = valueResult[0];\n    if (valueIsCoding(value)) {\n      return {\n        ...(value.system && { system: value.system }),\n        ...(value.code && { code: value.code }),\n        ...(value.display && { display: value.display })\n      };\n    }\n\n    return value;\n  }\n\n  // Return badly formed valueResult as undefined\n  return undefined;\n}\n","import { getAdjustedDeletePathSegments, parseFhirPath } from './parseFhirPath';\nimport type { FhirResource, OperationOutcomeIssue } from 'fhir/r4';\nimport { cleanEntryPathSegments } from './expressionManipulation';\nimport { buildValuesToInsert } from './buildValueToInsert';\nimport { getStaticTemplateDataAtPath } from './staticTemplateData';\nimport deepmerge from 'deepmerge';\n\n/**\n * Merges two arrays by index rather than by concatenation (deepmerge's default).\n *\n * Value paths address array elements positionally (e.g. `protocolApplied[0].doseNumberPositiveInt`),\n * so an incoming array must be merged into the element at the same index. Elements beyond the\n * target's length are appended, preserving the previous behaviour for genuinely new entries.\n */\nfunction mergeArrayByIndex(target: any[], source: any[], options: any): any[] {\n  const destination = target.slice();\n  source.forEach((item, index) => {\n    if (typeof destination[index] === 'undefined') {\n      destination[index] = options.cloneUnlessOtherwiseSpecified(item, options);\n    } else if (options.isMergeableObject(item)) {\n      destination[index] = deepmerge(target[index], item, options);\n    } else {\n      destination.push(item);\n    }\n  });\n  return destination;\n}\n\nexport function removeTemplateExtractValueExtension(\n  entryPath: string,\n  valuePath: string,\n  templateToMutate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n) {\n  const valuePathSegments = parseFhirPath(valuePath);\n  const adjustedDeletePathSegments = getAdjustedDeletePathSegments(\n    templateToMutate,\n    valuePathSegments,\n    'value',\n    populateIntoTemplateWarnings\n  );\n  deleteObjectAtPath(templateToMutate, entryPath, adjustedDeletePathSegments);\n}\n\nexport function removeTemplateExtractContextExtension(\n  entryPath: string,\n  contextPath: string,\n  templateToMutate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n) {\n  const contextPathSegments = parseFhirPath(contextPath);\n  const adjustedDeletePathSegments = getAdjustedDeletePathSegments(\n    templateToMutate,\n    contextPathSegments,\n    'context',\n    populateIntoTemplateWarnings\n  );\n  deleteObjectAtPath(templateToMutate, entryPath, adjustedDeletePathSegments);\n}\n\n/**\n * Inserts one or more evaluated values into the template at specified entry path.\n *\n * @param entryPath - Entry path where values should be inserted (e.g., \"MedicationStatement.reasonCode[0]\").\n * @param insertIndex - The actual index at which to insert the value - may differ from the index given by entryPath.\n * @param isNewInsert - Flag indicating if this is a new insert into an array (true) or a merge into an existing object at that path (false).\n * @param valuePath - The original valuePath used to derive the evaluated result.\n * @param valueResult - The evaluated result(s) from the FHIRPath expression.\n * @param templateToMutate - The target FHIR resource to be populated with evaluated values.\n * @param cleanTemplate - A clean version of the template with static template data.\n * @param populateIntoTemplateWarnings - Collects warnings or issues encountered during evaluation or insertion.\n */\nexport function insertValuesToPath(\n  entryPath: string,\n  insertIndex: number,\n  isNewInsert: boolean,\n  valuePath: string,\n  valueResult: any,\n  templateToMutate: FhirResource,\n  cleanTemplate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n) {\n  const entryPathSegments = parseFhirPath(entryPath);\n\n  // Static template data only needs to be spread in once, when this entry is first seeded\n  // (isNewInsert). Later merges into the same already-seeded element don't need it re-attached -\n  // deepmerge already preserves keys it isn't touching - and re-attaching it on every subsequent\n  // sibling value would make any static primitive array (e.g. a hardcoded `given`) duplicate\n  // itself once per sibling value merged in after the first.\n  const staticTemplateData = isNewInsert\n    ? getStaticTemplateDataAtPath(entryPath, cleanTemplate, populateIntoTemplateWarnings)\n    : {};\n  const valuesToInsert = buildValuesToInsert(\n    entryPathSegments,\n    valuePath,\n    valueResult,\n    staticTemplateData\n  );\n\n  // Insert each valueToInsert instance into template at the correct location, taking into account context index\n  // We can have multiple values to insert eg. given names ['First', 'Middle'] which will result in two objects like [{given: ['First']}, {given: ['Middle']}] which are merged\n  // Only the first item of this split can be a genuinely new array insert - the rest always merge into the\n  // element that first item just created (or already existed), regardless of the outer isNewInsert flag.\n  let isFirstInsert = isNewInsert;\n  for (let i = 0; i < valuesToInsert.length; i++) {\n    const valueToInsert = valuesToInsert[i];\n    const cleanedEntryPathSegments = cleanEntryPathSegments(entryPathSegments, insertIndex);\n\n    walkTemplateAndInsertValue(\n      templateToMutate,\n      entryPath,\n      cleanedEntryPathSegments,\n      isFirstInsert,\n      valueToInsert\n    );\n    isFirstInsert = false;\n  }\n}\n\n/**\n * Walks the object along the path and assigns the stringified value at the final location.\n *\n * @param {any} obj - The FHIR resource or nested object to walk. Can be an array, object, primitive, or null.\n * @param {string} entryPath - The full FHIRPath-style entryPath for error reporting.\n * @param {(string | number)[]} entryPathSegments - The FHIRPath-style entryPath as segments.\n * @param {boolean} isNewInsert - Flag indicating if this is a new insert into an array (true) or a merge into an existing object at that path (false).\n * @param {any} valueToInsert - The built value to assign at the last segment of the path.\n */\nexport function walkTemplateAndInsertValue(\n  obj: any,\n  entryPath: string,\n  entryPathSegments: (string | number)[],\n  isNewInsert: boolean,\n  valueToInsert: any\n): void {\n  // Check if the object is valid\n  if (!obj || typeof obj !== 'object') {\n    return;\n  }\n\n  // valueToInsert is undefined, skip whole traversal\n  if (valueToInsert === undefined) {\n    return;\n  }\n\n  let current = obj;\n\n  // Start from index \"1\" because we skip the first segment - usually the resourceType (e.g. \"Patient\")\n  for (let i = 1; i < entryPathSegments.length - 1; i++) {\n    const segment = entryPathSegments[i];\n\n    // Check for malformed paths e.g. caused by invalid FHIRPath input or array index out of bounds\n    if (segment === undefined) {\n      throw new Error(\n        `Invalid path segment from ${entryPath}, value is undefined: ${segment}, index: ${i} from insertValueAtPath().`\n      );\n    }\n\n    // If the path segment doesn't exist, create the structure:\n    // If the next segment is a number, assume it's an array. Otherwise, assume it's an object\n    if (typeof current === 'object' && current !== null && !(segment in current)) {\n      const nextSegment = entryPathSegments[i + 1];\n      current[segment] = typeof nextSegment === 'number' ? [] : {};\n    }\n\n    // Move to the next level in the object subtree\n    current = current[segment];\n  }\n\n  // Final segment: this should be an actual element name (`gender`) to write to\n  const finalSegment = entryPathSegments[entryPathSegments.length - 1];\n\n  // Validate final segment\n  if (finalSegment === undefined) {\n    throw new Error(\n      `Invalid final segment from ${entryPath}, value is undefined: ${finalSegment} from insertValueAtPath().`\n    );\n  }\n\n  const existingNode = current[finalSegment];\n\n  // New insert into an array, insert at the required index instead of merging with any existing object at that index\n  if (Array.isArray(current) && typeof finalSegment === 'number' && isNewInsert) {\n    current.splice(finalSegment, 0, valueToInsert);\n    return;\n  }\n\n  // Existing node is null or undefined, insert the value directly\n  if (existingNode === null || existingNode === undefined) {\n    current[finalSegment] = valueToInsert;\n    return;\n  }\n\n  // Existing node is an array, and we are inserting an array, concatenate them\n  if (Array.isArray(existingNode) && Array.isArray(valueToInsert)) {\n    current[finalSegment] = [...existingNode, ...valueToInsert];\n    return;\n  }\n\n  // Existing node is an array, and we are inserting a single value, push it to the array\n  if (Array.isArray(existingNode)) {\n    existingNode.push(valueToInsert);\n    return;\n  }\n\n  // Existing node is an object, and we are inserting an object, merge them\n  if (typeof existingNode === 'object' && typeof valueToInsert === 'object') {\n    // Deep merge required to handle arrays within objects.\n    // Arrays nested inside those objects are merged BY INDEX, not concatenated: a value path such\n    // as `Immunization.protocolApplied[0].doseNumberPositiveInt` targets a specific element of an\n    // existing template array, so concatenating would append a second, half-populated element\n    // instead of populating the one the path names.\n    current[finalSegment] = deepmerge(existingNode, valueToInsert, {\n      arrayMerge: mergeArrayByIndex\n    });\n    return;\n  }\n\n  // Fallback: overwrite primitive or incompatible types\n  current[finalSegment] = valueToInsert;\n}\n\n/**\n * Walks the object along the path and deletes the extension at the final segment.\n * Used to clean up post-insertion template artifacts, but works generically on any path.\n *\n * @param {any} obj - The FHIR resource or nested object to walk. Can be an array, object, primitive, or null.\n * @param {string} fullPath - The full FHIRPath-style path for error reporting.\n * @param {(string | number)[]} pathSegments - The FHIRPath-style path as segments.\n */\nexport function deleteObjectAtPath(\n  obj: any,\n  fullPath: string,\n  pathSegments: (string | number)[]\n): void {\n  if (!obj || typeof obj !== 'object') {\n    return;\n  }\n  const walkedNodes: any[] = [obj]; // DEBUG\n  let current = obj;\n\n  // Start from index \"1\" because we skip the first segment - usually the resourceType (e.g. \"Patient\")\n  for (let i = 1; i < pathSegments.length - 1; i++) {\n    const segment = pathSegments[i];\n\n    // Check for malformed paths e.g. caused by invalid FHIRPath input or array index out of bounds\n    if (segment === undefined || current == null) {\n      throw new Error(\n        `Invalid path segment from ${fullPath}, value is undefined: ${segment}, index: ${i} from deleteExtensionAtPath().`\n      );\n    }\n\n    // Move to the next level in the object subtree\n    current = current[segment];\n\n    // Exit early if the structure doesn't exist\n    if (current === undefined || current === null) {\n      return;\n    }\n\n    // Save the current state of the object into walked nodes - DEBUG\n    walkedNodes.push(current);\n  }\n\n  // Final segment: this should be the key or array index to delete from the resolved object\n  const finalSegment = pathSegments[pathSegments.length - 1];\n\n  // Validate final segment\n  if (finalSegment === undefined) {\n    throw new Error(\n      `Invalid final segment from ${fullPath}, value is undefined: ${finalSegment} from deleteExtensionAtPath().`\n    );\n  }\n\n  // Delete the array element (e.g., extension[0]) or object property (e.g., ._gender)\n  if (typeof finalSegment === 'number' && Array.isArray(current)) {\n    current.splice(finalSegment, 1);\n  }\n  // Check if it's an object property deletion (e.g., ._gender)\n  else if (typeof finalSegment === 'string' && current && typeof current === 'object') {\n    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n    delete current[finalSegment];\n  }\n}\n","import type { EntryPathPosition } from '../interfaces/entryPathPosition.interface';\nimport { parseFhirPath } from './parseFhirPath';\n\n/**\n * Calculates the starting index for a given `entryPath` based on its position within\n * a list of `EntryPathPosition` entries mapped to a `baseEntryPath`, accounting for the\n * position of the entry path in the templated array and the number of entries already\n * inserted into the base entry path.\n *\n * @param {string} baseEntryPath - The base key used to look up the list of positions.\n * @param {string} entryPath - The specific path whose starting index is being calculated.\n * @param {Map<string, EntryPathPosition[]>} entryPathPositionMap - A map from base paths to arrays of entry positions.\n * @returns {number} The computed starting index for the `entryPath`. Defaults to 0 if `entryPath` is not a path to an array element.\n */\nexport function getStartingIndex(\n  baseEntryPath: string,\n  entryPath: string,\n  entryPathPositionMap: Map<string, EntryPathPosition[]>\n): number {\n  // Parse entryPath to get the position of the element in the template array\n  const entryPathSegments = parseFhirPath(entryPath);\n  const finalSegment = entryPathSegments[entryPathSegments.length - 1];\n\n  if (typeof finalSegment === 'number') {\n    // We begin at the index given by the entry path\n    let startIndex = finalSegment;\n\n    const entryPathPositions = entryPathPositionMap.get(baseEntryPath);\n    if (entryPathPositions) {\n      for (const entryPathPosition of entryPathPositions) {\n        // Increment startIndex by the count of previous entries added to the base entry path\n        // We substract 1 to account for the templated object itself which is removed from the template before inserting values\n        startIndex += entryPathPosition.count - 1;\n      }\n    }\n\n    return startIndex;\n  }\n\n  // Final segment is not a number, return 0 (entryPath is not a path to an array element)\n  return 0;\n}\n\n/**\n * Adds a new `EntryPathPosition` entry to the list associated with the given `baseEntryPath`\n * in the `entryPathPositionMap`.\n *\n * If the `baseEntryPath` does not exist in the map yet, it initializes a new array for it.\n * The new position includes the `entryPath`, its `startIndex`, and the count of values being inserted.\n *\n * @param {string} baseEntryPath - The base entry path used to group related entry positions.\n * @param {string} entryPath - The specific entry path to be recorded within the group.\n * @param {number} startIndex - The index at which this entry's values begin.\n * @param {number} numberOfValuesToInsert - The number of values associated with this entry path.\n * @param {Map<string, EntryPathPosition[]>} entryPathPositionMap - A map tracking all positions grouped by base entry paths.\n */\nexport function addCurrentEntryPathPosition(\n  baseEntryPath: string,\n  entryPath: string,\n  startIndex: number,\n  numberOfValuesToInsert: number,\n  entryPathPositionMap: Map<string, EntryPathPosition[]>\n) {\n  // Initialise baseEntryPath entry if it does not exist\n  if (!entryPathPositionMap.has(baseEntryPath)) {\n    entryPathPositionMap.set(baseEntryPath, []);\n  }\n\n  const entryPathPosition: EntryPathPosition = {\n    entryPath: entryPath,\n    startIndex: startIndex,\n    count: numberOfValuesToInsert\n  };\n\n  // Push entryPathPosition into the baseEntryPath positions array\n  const baseEntryPathPositions = entryPathPositionMap.get(baseEntryPath);\n  if (baseEntryPathPositions) {\n    baseEntryPathPositions.push(entryPathPosition);\n  }\n}\n","import type { FhirResource, OperationOutcomeIssue, QuestionnaireResponse } from 'fhir/r4';\nimport { fhirPathEvaluate } from './fhirpathEvaluate';\nimport type { TemplateExtractPath } from '../interfaces/templateExtractPath.interface';\nimport { getCombinedExpression, stripTrailingIndexFromPath } from './expressionManipulation';\nimport { insertValuesToPath } from './templateInsert';\nimport type { EntryPathPosition } from '../interfaces/entryPathPosition.interface';\nimport { addCurrentEntryPathPosition, getStartingIndex } from './entryPathPosition';\n/**\n * Evaluates FHIRPath expressions from a value map and inserts the resulting values into the target template.\n *\n * @param questionnaireResponse - The source QuestionnaireResponse used as input for evaluation.\n * @param entryPath - Entry path where values should be inserted (e.g., \"MedicationStatement.reasonCode[0]\").\n * @param templateExtractPath - The template extract path entry containing context and value expressions to evaluate.\n * @param targetQRItemFhirPathWithIndex - The FHIRPath-style path for the target QuestionnaireResponse item, potentially with an index.\n * @param entryPathPositionMap - Tracks how many values were inserted at each entry path.\n * @param fhirPathContext - Additional FHIRPath variables or context used during evaluation.\n * @param templateToMutate - The target FHIR resource to be populated with evaluated values.\n * @param cleanTemplate - A clean version of the template with static template data.\n * @param populateIntoTemplateWarnings - Collects warnings or issues encountered during evaluation and insertion.\n */\nexport function evaluateAndInsertIntoPath(\n  questionnaireResponse: QuestionnaireResponse,\n  entryPath: string,\n  templateExtractPath: TemplateExtractPath,\n  targetQRItemFhirPathWithIndex: string,\n  entryPathPositionMap: Map<string, EntryPathPosition[]>,\n  fhirPathContext: Record<string, any>,\n  templateToMutate: FhirResource,\n  cleanTemplate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n) {\n  const { contextPathTuple, valuePathMap } = templateExtractPath;\n  const contextExpression = contextPathTuple?.[1] ?? null;\n\n  // Context path exists, use contextExpression to frame evaluation scope\n  // Otherwise, use targetQRItemFhirPathWithIndex as the context path\n  const contextPath = contextExpression\n    ? getCombinedExpression(targetQRItemFhirPathWithIndex, contextExpression)\n    : targetQRItemFhirPathWithIndex;\n\n  // Evaluate context path to get the context result\n  const contextResults = fhirPathEvaluate({\n    fhirData: questionnaireResponse,\n    path: contextPath,\n    envVars: fhirPathContext,\n    warnings: populateIntoTemplateWarnings\n  });\n\n  // Get the index that we should start inserting values at for this entry path\n  const baseEntryPath = stripTrailingIndexFromPath(entryPath);\n  const startingIndex = getStartingIndex(baseEntryPath, entryPath, entryPathPositionMap);\n\n  // Iterate over context results to evaluate values and insert into template\n  for (let i = 0; i < contextResults.length; i++) {\n    const contextResult = contextResults[i];\n    const insertIndex = startingIndex + i;\n\n    // Flag to track if this is a new insert - used to determine the correct behaviour when inserting into an array element\n    // The first time we see a context result, we add a new entry at the specified index\n    // Subsequent inserts for the same context result will merge into the same index\n    let isNewInsert = true;\n\n    for (const [valuePath, valueEvaluation] of valuePathMap.entries()) {\n      // Use context result to evaluate the value expression\n      const valueResult = fhirPathEvaluate({\n        fhirData: contextResult,\n        path: valueEvaluation.valueExpression,\n        envVars: fhirPathContext,\n        warnings: populateIntoTemplateWarnings\n      });\n\n      // Insert values to the specified entry path\n      insertValuesToPath(\n        entryPath,\n        insertIndex,\n        isNewInsert,\n        valuePath,\n        valueResult,\n        templateToMutate,\n        cleanTemplate,\n        populateIntoTemplateWarnings\n      );\n\n      if (Array.isArray(valueResult) && valueResult.length) {\n        // Values found, set flag to false so that subsequent inserts for the same context are now merged at the same index\n        isNewInsert = false;\n      }\n\n      // Collect value evaluation results for debugging\n      valueEvaluation.valueResult.push(valueResult);\n    }\n  }\n\n  // Track the number of inserted entries for the base entry path using entryPathPositionMap\n  addCurrentEntryPathPosition(\n    baseEntryPath,\n    entryPath,\n    startingIndex,\n    contextResults.length,\n    entryPathPositionMap\n  );\n}\n","import type {\n  TemplateExtractPath,\n  TemplateExtractPathJsObject\n} from '../interfaces/templateExtractPath.interface';\n\n/**\n * Converts a Map<string, TemplateExtractPath> to a Record<string, templateExtractPathMapToRecord>,\n * Converting any nested valuePathMap from Map to plain object.\n */\nexport function templateExtractPathMapToRecord(\n  templateExtractPathMap: Map<string, TemplateExtractPath>\n): Record<string, TemplateExtractPathJsObject> {\n  const templateExtractPaths: Record<string, TemplateExtractPathJsObject> = {};\n\n  for (const [entryPath, templateExtractPath] of templateExtractPathMap.entries()) {\n    templateExtractPaths[entryPath] = {\n      contextPathTuple: templateExtractPath.contextPathTuple,\n      valuePathMap: Object.fromEntries(templateExtractPath.valuePathMap) // convert inner Map to plain object\n    };\n  }\n\n  return templateExtractPaths;\n}\n","import {\n  removeTemplateExtractContextExtension,\n  removeTemplateExtractValueExtension\n} from './templateInsert';\nimport type { TemplateExtractValueEvaluation } from '../interfaces';\nimport type { FhirResource, OperationOutcomeIssue } from 'fhir/r4';\n\n/**\n * Removes template extraction artifacts from a FHIR resource instance.\n * - `templateExtractValue` extensions associated with evaluated value paths\n * - also removes `templateExtractContext` extension if a context path was used\n */\nexport function removeTemplateArtifacts(\n  entryPath: string,\n  contextPath: string | null,\n  valuePathMap: Map<string, TemplateExtractValueEvaluation>,\n  templateToMutate: FhirResource,\n  populateIntoTemplateWarnings: OperationOutcomeIssue[]\n) {\n  for (const [valuePath] of valuePathMap.entries()) {\n    removeTemplateExtractValueExtension(\n      entryPath,\n      valuePath,\n      templateToMutate,\n      populateIntoTemplateWarnings\n    );\n  }\n\n  if (contextPath) {\n    removeTemplateExtractContextExtension(\n      entryPath,\n      contextPath,\n      templateToMutate,\n      populateIntoTemplateWarnings\n    );\n  }\n}\n","import type {\n  TemplateDetails,\n  TemplateExtractPathJsObject\n} from '../interfaces/templateExtractPath.interface';\nimport type { FhirResource, OperationOutcomeIssue, QuestionnaireResponse } from 'fhir/r4';\nimport { createTemplateExtractPathMap } from './templateExtractPath';\nimport { evaluateAndInsertIntoPath } from './evaluateTemplateExtractPath';\nimport { templateExtractPathMapToRecord } from './mapToRecord';\nimport {\n  addIndexToTargetPath,\n  getNumberOfTemplateInstances,\n  stripTrailingIndexFromPath\n} from './expressionManipulation';\nimport { removeTemplateArtifacts } from './removeTemplateArtifacts';\nimport type { EntryPathPosition } from '../interfaces/entryPathPosition.interface';\nimport { createInvalidWarningIssue } from './operationOutcome';\nimport { parseFhirPath } from './parseFhirPath';\nimport { deleteObjectAtPath } from './templateInsert';\n\nexport function populateIntoTemplates(\n  questionnaireResponse: QuestionnaireResponse,\n  templateMap: Map<string, TemplateDetails>,\n  fhirPathContext: Record<string, any>\n): {\n  extractedResourceMap: Map<string, FhirResource[]>;\n  populateIntoTemplateWarnings: OperationOutcomeIssue[];\n  templateIdToExtractPaths: Record<string, Record<string, TemplateExtractPathJsObject>[]>;\n} {\n  const extractedResourceMap: Map<string, FhirResource[]> = new Map<string, FhirResource[]>();\n  const combinedWalkTemplateWarnings: OperationOutcomeIssue[] = [];\n  const populateIntoTemplateWarnings: OperationOutcomeIssue[] = [];\n  const templateIdToExtractPaths: Record<string, Record<string, TemplateExtractPathJsObject>[]> =\n    {};\n\n  // Iterate over each template e.g. patTemplate, AllergyIntoleranceTemplate\n  for (const [templateId, templateDetails] of templateMap.entries()) {\n    const { templateResource, targetQRItemFhirPath } = templateDetails;\n    if (!targetQRItemFhirPath) {\n      populateIntoTemplateWarnings.push(\n        createInvalidWarningIssue(`Template ${templateId} does not have a target QR item FHIRPath.`)\n      );\n      continue;\n    }\n\n    // Step 1: Build a map of FHIRPath expressions for templateExtractContexts and templateExtractValues\n    const { templateExtractPathMap, walkTemplateWarnings } = createTemplateExtractPathMap(\n      templateId,\n      templateResource\n    );\n    combinedWalkTemplateWarnings.push(...walkTemplateWarnings);\n    templateIdToExtractPaths[templateId] = [];\n\n    // Step 2: Get number of template instances for the target path\n    const numberOfTemplateInstances = getNumberOfTemplateInstances(\n      questionnaireResponse,\n      targetQRItemFhirPath,\n      populateIntoTemplateWarnings\n    );\n\n    // Iterate each matching QRItem instance (e.g., multiple allergy items)\n    const extractedResourcesByTemplateId: FhirResource[] = [];\n    const extractPathsByTemplateId: Record<string, TemplateExtractPathJsObject>[] = [];\n    for (let i = 0; i < numberOfTemplateInstances; i++) {\n      const templateExtractPathMapInstance = structuredClone(templateExtractPathMap);\n      const targetQRItemFhirPathWithIndex = addIndexToTargetPath(targetQRItemFhirPath, i);\n\n      // Step 3: Each new template instance should be deep copied to prevent mutating original template\n      const templateToMutate = structuredClone(templateResource);\n\n      // Step 4: Remove templateExtract artifacts from template instance e.g. templateExtractContext and templateExtractValue extensions\n      const entryPathPositionMap: Map<string, EntryPathPosition[]> = new Map<\n        string,\n        EntryPathPosition[]\n      >();\n\n      // Tracks indices of templated elements for each base entry path which is an array\n      // Used to delete these entries to create a clean template\n      const templatedElementsIndicesMap: Map<string, number[]> = new Map<string, number[]>();\n\n      for (const [entryPath, templateExtractPath] of templateExtractPathMapInstance.entries()) {\n        const { contextPathTuple, valuePathMap } = templateExtractPath;\n        const contextPath = contextPathTuple?.[0] ?? null;\n        removeTemplateArtifacts(\n          entryPath,\n          contextPath,\n          valuePathMap,\n          templateToMutate,\n          populateIntoTemplateWarnings\n        );\n\n        const entryPathSegments = parseFhirPath(entryPath);\n        const finalSegment = entryPathSegments[entryPathSegments.length - 1];\n        if (typeof finalSegment === 'number') {\n          // Path belongs to an array, add index to map for deletion to clean template later\n          // (Paths not belonging to an array are already removed from the template in removeTemplateArtifacts)\n          const baseEntryPath = stripTrailingIndexFromPath(entryPath);\n\n          const baseEntryPathPositions = templatedElementsIndicesMap.get(baseEntryPath);\n          if (baseEntryPathPositions) {\n            baseEntryPathPositions.push(finalSegment);\n          } else {\n            templatedElementsIndicesMap.set(baseEntryPath, [finalSegment]);\n          }\n        }\n      }\n\n      // Step 5: Prepare a clean template for reading static template data\n      const staticTemplate = structuredClone(templateToMutate);\n\n      // Step 5a: Remove templated elements from arrays in templateToMutate based on entryPathIndexMap\n      // (We keep these entries in staticTemplate to allow the static template to be read later, but delete them from templateToMutate to allow correct insertion of evaluated values)\n      for (const [baseEntryPath, indices] of templatedElementsIndicesMap.entries()) {\n        // Sort indices in descending order to prevent index shifting during deletion\n        indices.sort((a, b) => b - a);\n        for (const index of indices) {\n          const entryPathWithIndex = `${baseEntryPath}[${index}]`;\n          deleteObjectAtPath(\n            templateToMutate,\n            entryPathWithIndex,\n            parseFhirPath(entryPathWithIndex)\n          );\n        }\n      }\n\n      // Step 6: Evaluate and populate each templateExtractPath e.g. AllergyIntolerance.code, AllergyIntolerance.note\n      for (const [entryPath, templateExtractPath] of templateExtractPathMapInstance.entries()) {\n        evaluateAndInsertIntoPath(\n          questionnaireResponse,\n          entryPath,\n          templateExtractPath,\n          targetQRItemFhirPathWithIndex,\n          entryPathPositionMap,\n          fhirPathContext,\n          templateToMutate,\n          staticTemplate,\n          populateIntoTemplateWarnings\n        );\n      }\n\n      // Remove resource.id from templateToMutate\n      // Refer https://build.fhir.org/ig/HL7/sdc/extraction.html#template-based-extraction step 4\n      if (templateToMutate.id) {\n        delete templateToMutate.id;\n      }\n\n      // Add extracted resource and templateExtractPathMap instances to their respective arrays\n      extractedResourcesByTemplateId.push(templateToMutate);\n      extractPathsByTemplateId.push(templateExtractPathMapToRecord(templateExtractPathMapInstance));\n    }\n\n    // Step 7: Collate extracted resources and templateExtractPathMap instances\n    extractedResourceMap.set(templateId, extractedResourcesByTemplateId);\n    templateIdToExtractPaths[templateId] = extractPathsByTemplateId;\n  }\n\n  return {\n    extractedResourceMap,\n    populateIntoTemplateWarnings: [\n      ...combinedWalkTemplateWarnings,\n      ...populateIntoTemplateWarnings\n    ],\n    templateIdToExtractPaths\n  };\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport type { Questionnaire } from 'fhir/r4';\n\nexport function allocateIdsForExtract(questionnaire: Questionnaire): Record<string, string> {\n  const extractAllocateIds = getExtractAllocateIds(questionnaire);\n  const extractAllocateIdMap = new Map<string, string>();\n\n  for (const extractAllocateId of extractAllocateIds) {\n    extractAllocateIdMap.set(extractAllocateId, uuidv4());\n  }\n\n  // Convert extractAllocateIdMap into a Record<string, string>\n  return Object.fromEntries(extractAllocateIdMap);\n}\n\n/**\n * Returns all extractAllocateId values from the questionnaire.\n */\nexport function getExtractAllocateIds(questionnaire: Questionnaire): string[] {\n  return (\n    questionnaire.extension\n      ?.filter(\n        (ext) =>\n          ext.url ===\n          'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-extractAllocateId'\n      )\n      .map((ext) => ext.valueString)\n      .filter((v): v is string => typeof v === 'string') ?? []\n  );\n}\n","import type { Bundle, FhirResource, OperationOutcomeIssue, QuestionnaireResponse } from 'fhir/r4';\nimport type {\n  FhirPathEvalResult,\n  TemplateDetails,\n  TemplateExtractPathJsObject,\n  TemplateExtractPathJsObjectTuple\n} from '../interfaces/templateExtractPath.interface';\nimport { fhirPathEvaluate } from './fhirpathEvaluate';\nimport { v4 as uuidv4 } from 'uuid';\nimport cleanDeep from 'clean-deep';\nimport { parametersIsFhirPatch } from './typePredicates';\nimport type { BundleRequestType } from '../interfaces/bundle.interface';\nimport { addIndexToTargetPath } from './expressionManipulation';\nimport { applyFilters } from './filterResources';\n\n/**\n * Builds a FHIR transaction Bundle from extracted resources using the templateExtract extension.\n * If a resource has an ID, it's treated as an update (PUT); otherwise, it's treated as a create (POST).\n * The resulting Bundle includes properly populated fullUrl, request.method, request.url, and optional request metadata.\n *\n * @param extractedResourceMap - Map of template IDs to extracted FHIR resources.\n * @param comparisonResourceMap - Map of template IDs to comparison FHIR resources, if available. Used for filtering out unchanged resources.\n * @param containedTemplateMap - Map of template IDs to TemplateDetails including templateExtract metadata.\n * @param templateIdToExtractPaths - Map of template IDs to their respective TemplateExtractPathJsObject. We inject fullUrl in this function to help debugging.\n * @param fhirPathContext - FHIRPath context object that acts as envVars for fhirpath.evaluate\n * @param questionnaireResponse - The QuestionnaireResponse resource that contains the answers to be extracted.\n * @returns {Bundle} - A FHIR transaction Bundle containing all extracted resources with appropriate request entries.\n */\nexport function buildTransactionBundle(\n  extractedResourceMap: Map<string, FhirResource[]>,\n  comparisonResourceMap: Map<string, FhirResource[]> | null,\n  containedTemplateMap: Map<string, TemplateDetails>,\n  templateIdToExtractPaths: Record<string, Record<string, TemplateExtractPathJsObject>[]>,\n  fhirPathContext: Record<string, string>,\n  questionnaireResponse: QuestionnaireResponse\n): {\n  outputBundle: Bundle;\n  templateIdToExtractPathTuples: Record<string, TemplateExtractPathJsObjectTuple[]>;\n} {\n  const templateIdToExtractPathTuples: Record<string, TemplateExtractPathJsObjectTuple[]> = {};\n  const buildBundleWarnings: OperationOutcomeIssue[] = [];\n\n  const bundle: Bundle = {\n    resourceType: 'Bundle',\n    id: `sdc-template-extract-${generateShortId()}`,\n    meta: {\n      tag: [\n        {\n          code: '@aehrc/sdc-template-extract:generated',\n          system: 'urn:aehrc:sdc-template-extract'\n        }\n      ]\n    },\n    type: 'transaction',\n    timestamp: new Date().toISOString(),\n    entry: []\n  };\n\n  // Type guard for Bundle.entry\n  if (bundle.entry === undefined) {\n    return { outputBundle: bundle, templateIdToExtractPathTuples: templateIdToExtractPathTuples };\n  }\n\n  // Add entries to the bundle from the extracted resources\n  for (const [templateId, templateDetails] of containedTemplateMap.entries()) {\n    const { templateExtractReference, targetQRItemFhirPath } = templateDetails;\n\n    const extractPathsByTemplateId = templateIdToExtractPaths[templateId];\n\n    const extractedResources = extractedResourceMap.get(templateId);\n    const comparisonResources = comparisonResourceMap?.get(templateId);\n    if (!extractedResources || extractedResources.length === 0 || !extractPathsByTemplateId) {\n      continue;\n    }\n\n    // Iterate over each extracted resource for the current template\n    const templateExtractPathTuples: TemplateExtractPathJsObjectTuple[] = [];\n    for (let i = 0; i < extractedResources.length; i++) {\n      const extractedResource = extractedResources[i];\n      const comparisonResource = comparisonResources?.[i];\n      if (!extractedResource) {\n        continue;\n      }\n\n      // Filter resources (or parameter entries if the resource is a Parameters) based on two criteria:\n      // 1. Ensure FHIRPatch \"value\" part has value[x] field.\n      // 2. If a comparison-source-response (i.e. a pre-populated questionnaireResponse) is provided, only include changes compared to that response.\n      const retainedResource = applyFilters(extractedResource, comparisonResource ?? null);\n      if (!retainedResource) {\n        continue;\n      }\n\n      // Clean extracted resource\n      const cleanedRetainedResource = cleanDeep(retainedResource, {\n        emptyObjects: true,\n        emptyArrays: true,\n        nullValues: true,\n        undefinedValues: true\n      }) as FhirResource;\n\n      // Create context scope from QR where the \"templateExtract\" extension is defined for downstream FHIRPath evaluation\n      const contextScopeResult = createTemplateExtractContextScope(\n        questionnaireResponse,\n        targetQRItemFhirPath,\n        i,\n        fhirPathContext,\n        buildBundleWarnings\n      );\n\n      // resourceId\n      const resourceId = getResourceId(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.resourceId\n      );\n      const resourceType = cleanedRetainedResource.resourceType;\n      const hasResourceId = typeof resourceId === 'string' && resourceId !== '';\n\n      // PatchRequestUrl\n      const patchRequestUrl = getPatchRequestUrl(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.patchRequestUrl\n      );\n      const hasPatchRequestUrl = typeof patchRequestUrl === 'string' && patchRequestUrl !== '';\n\n      // fullUrl\n      // Otherwise, evaluate it as a FHIRPath expression\n      const fullUrl = getFullUrl(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.fullUrl\n      );\n\n      // ifNoneMatch, ifModifiedSince, ifMatch, ifNoneExist\n      const ifNoneMatch = getOptionalBundleEntryRequestProperty(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.ifNoneMatch\n      );\n      const ifModifiedSince = getOptionalBundleEntryRequestProperty(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.ifModifiedSince\n      );\n      const ifMatch = getOptionalBundleEntryRequestProperty(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.ifMatch\n      );\n      const ifNoneExist = getOptionalBundleEntryRequestProperty(\n        contextScopeResult,\n        fhirPathContext,\n        buildBundleWarnings,\n        templateExtractReference.ifNoneExist\n      );\n\n      // Request method\n      const requestMethod = getRequestMethod(cleanedRetainedResource, hasResourceId);\n\n      // Request url\n      const requestUrl =\n        requestMethod === 'PATCH' && hasPatchRequestUrl\n          ? patchRequestUrl\n          : hasResourceId\n            ? `${resourceType}/${resourceId}`\n            : resourceType;\n\n      // Add resourceId to resource\n      const resourceToAdd = addResourceIdToResource(\n        cleanedRetainedResource,\n        resourceId,\n        requestMethod\n      );\n\n      // Add entry to the bundle\n      bundle.entry.push({\n        fullUrl: fullUrl,\n        resource: resourceToAdd,\n        request: {\n          method: requestMethod,\n          url: requestUrl,\n\n          // ifNoneMatch, ifModifiedSince, ifMatch, ifNoneExist optional properties\n          ...(ifNoneMatch && { ifNoneMatch: ifNoneMatch }),\n          ...(ifModifiedSince && {\n            ifModifiedSince: ifModifiedSince\n          }),\n          ...(ifMatch && { ifMatch: ifMatch }),\n          ...(ifNoneExist && { ifNoneExist: ifNoneExist })\n        }\n      });\n\n      // Inject fullUrl into templateIdToExtractPaths for debugging\n      const extractPathsByTemplateIdInstance = extractPathsByTemplateId[i];\n      if (extractPathsByTemplateIdInstance) {\n        templateExtractPathTuples.push([fullUrl, extractPathsByTemplateIdInstance]);\n      }\n    }\n\n    // Add templateExtractPathTuples to the templateIdToExtractPathTuples record\n    templateIdToExtractPathTuples[templateId] = templateExtractPathTuples;\n  }\n\n  return { outputBundle: bundle, templateIdToExtractPathTuples: templateIdToExtractPathTuples };\n}\n\nfunction createTemplateExtractContextScope(\n  questionnaireResponse: QuestionnaireResponse,\n  targetQRItemFhirPath: string | undefined,\n  indexInstance: number,\n  fhirPathContext: Record<string, any>,\n  buildBundleWarnings: OperationOutcomeIssue[]\n): FhirPathEvalResult {\n  if (targetQRItemFhirPath) {\n    const targetQRItemFhirPathWithIndex = addIndexToTargetPath(targetQRItemFhirPath, indexInstance);\n    return fhirPathEvaluate({\n      fhirData: questionnaireResponse,\n      path: targetQRItemFhirPathWithIndex,\n      envVars: fhirPathContext,\n      warnings: buildBundleWarnings\n    });\n  }\n\n  // TargetQRItemFhirPath not defined, return an empty array\n  return [];\n}\n\nfunction getResourceId(\n  contextScopeResult: FhirPathEvalResult,\n  fhirPathContext: Record<string, any>,\n  buildBundleWarnings: OperationOutcomeIssue[],\n  resourceIdFromTemplateDetails?: string\n): string | undefined {\n  // templateExtract extension:resourceId FHIRPath expression available\n  if (resourceIdFromTemplateDetails) {\n    const result = fhirPathEvaluate({\n      fhirData: contextScopeResult,\n      path: resourceIdFromTemplateDetails,\n      envVars: fhirPathContext,\n      warnings: buildBundleWarnings\n    });\n\n    if (result.length > 0 && result[0] && typeof result[0] === 'string' && result[0] !== '') {\n      return result[0];\n    }\n  }\n\n  // templateExtract extension:resourceId unavailable or cannot be evaluated\n  return undefined;\n}\n\nfunction getPatchRequestUrl(\n  contextScopeResult: FhirPathEvalResult,\n  fhirPathContext: Record<string, any>,\n  buildBundleWarnings: OperationOutcomeIssue[],\n  patchRequestUrlFromTemplateDetails?: string\n): string | undefined {\n  // templateExtract extension:patchRequestUrl FHIRPath expression available\n  if (patchRequestUrlFromTemplateDetails) {\n    const result = fhirPathEvaluate({\n      fhirData: contextScopeResult,\n      path: patchRequestUrlFromTemplateDetails,\n      envVars: fhirPathContext,\n      warnings: buildBundleWarnings\n    });\n\n    if (result.length > 0 && result[0] && typeof result[0] === 'string' && result[0] !== '') {\n      return result[0];\n    }\n  }\n\n  // templateExtract extension:patchRequestUrl unavailable or cannot be evaluated\n  return undefined;\n}\n\n/**\n * Resolves a fullUrl using a FHIRPath expression from template details, falling back to a generated UUID if not available.\n */\nfunction getFullUrl(\n  contextScopeResult: FhirPathEvalResult,\n  fhirPathContext: Record<string, any>,\n  buildBundleWarnings: OperationOutcomeIssue[],\n  fullUrlFromTemplateDetails?: string\n): string {\n  // templateExtract extension:fullUrl FHIRPath expressions available\n  if (fullUrlFromTemplateDetails) {\n    const result = fhirPathEvaluate({\n      fhirData: contextScopeResult,\n      path: fullUrlFromTemplateDetails,\n      envVars: fhirPathContext,\n      warnings: buildBundleWarnings\n    });\n\n    if (result.length > 0 && result[0] && typeof result[0] === 'string') {\n      return `${result[0]}`;\n    }\n  }\n\n  // templateExtract extension:fullUrl unavailable or cannot be evaluated\n  return generateUUIDForFullUrl();\n}\n\n/**\n * Generates a full UUID-based `urn:uuid:` string for use in Bundle.fullUrl.\n */\nfunction generateUUIDForFullUrl(): string {\n  return `urn:uuid:${uuidv4()}`;\n}\n\nfunction getOptionalBundleEntryRequestProperty(\n  contextScopeResult: FhirPathEvalResult,\n  fhirPathContext: Record<string, any>,\n  buildBundleWarnings: OperationOutcomeIssue[],\n  optionalProperty?: string\n) {\n  if (optionalProperty) {\n    const result = fhirPathEvaluate({\n      fhirData: contextScopeResult,\n      path: optionalProperty,\n      envVars: fhirPathContext,\n      warnings: buildBundleWarnings\n    });\n\n    if (result.length > 0 && result[0] && typeof result[0].id === 'string') {\n      return result[0];\n    }\n  }\n\n  return null;\n}\n\n/**\n * Generates a short UUID segment to avoid HAPI FHIR fullUrl length restrictions.\n */\nfunction generateShortId(): string {\n  return uuidv4().split('-').pop() ?? '';\n}\n\n/**\n * Returns a new FHIR resource with the given resourceId, preserving order of resourceType, id, and other properties.\n * If no resourceId is provided, returns the original resource.\n */\nfunction addResourceIdToResource(\n  existingResource: FhirResource,\n  resourceId: string | undefined,\n  requestMethod: BundleRequestType\n): FhirResource {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  const { resourceType, id, ...rest } = existingResource;\n\n  if (!resourceId || requestMethod === 'PATCH') {\n    return existingResource;\n  }\n\n  return {\n    resourceType,\n    id: resourceId,\n    ...rest\n  } as FhirResource;\n}\n\nfunction getRequestMethod(resource: FhirResource, hasResourceId: boolean): BundleRequestType {\n  // If order for request.method to be PATCH:\n  // 1. ResourceType must be 'Parameters'\n  // 2. Resource must conform to the FHIRPathPatchProfile https://build.fhir.org/fhirpath-patch.html\n  if (resource.resourceType === 'Parameters') {\n    if (parametersIsFhirPatch(resource)) {\n      return 'PATCH';\n    }\n  }\n\n  // if the resource created has no ID property, then the method will be POST, otherwise it will be PUT\n  return hasResourceId ? 'PUT' : 'POST';\n}\n","import type { FhirResource, Parameters } from 'fhir/r4';\nimport {\n  isFhirPatchNamePart,\n  isFhirPatchPathPart,\n  isFhirPatchTypePart,\n  parametersIsFhirPatch\n} from './typePredicates';\nimport type {\n  FhirPatchParameterEntry,\n  FhirPatchPart,\n  FhirPatchPathPart,\n  FhirPatchTypePart\n} from '../interfaces/fhirpatch.interface';\nimport cleanDeep from 'clean-deep';\n\n/**\n * Determines whether a single extracted FHIR resource should be included in the bundle.\n *\n * Applies two filtering rules:\n * 1. **FHIRPatch validity filtering**: If the resource is a PATCH-type `Parameters`, include it only if the `value[x]` field inside the `operation.value` part is present and non-empty.\n * 2. **Change detection**: If a `comparisonResource` is provided, include this resource only if it differs from the original (e.g., the pre-populated resource). For Parameters resources, check each parameter entry.\n *\n * @param extractedResource - The newly extracted FHIR resource to evaluate.\n * @param comparisonResource - The source (pre-populated) resource to compare against, if available.\n * @returns `true` if the resource should be included in the extracted bundle; `false` otherwise.\n */\nexport function applyFilters(\n  extractedResource: FhirResource,\n  comparisonResource: FhirResource | null\n): FhirResource | null {\n  // Resource is a FHIRPatch Parameters resource\n  if (extractedResource.resourceType === 'Parameters') {\n    // Pre-filter step: Clean extracted and comparison resource\n    // This ensures that we don't have empty operation entries that would pass the comparison check below and should be filtered out\n    extractedResource = cleanDeep(extractedResource, {\n      emptyObjects: true,\n      emptyArrays: true,\n      nullValues: true,\n      undefinedValues: true\n    }) as Parameters;\n\n    comparisonResource = cleanDeep(comparisonResource, {\n      emptyObjects: true,\n      emptyArrays: true,\n      nullValues: true,\n      undefinedValues: true\n    }) as FhirResource | null;\n\n    if (!parametersIsFhirPatch(extractedResource)) {\n      // If the extracted resource is not a valid FHIRPatch Parameters resource after cleaning, skip it\n      return null;\n    }\n\n    // First filter criteria: Filter out operation entries where the value[x] is empty\n    extractedResource.parameter = filterFhirPatchEmptyValues(extractedResource.parameter);\n\n    // Second filter criteria: check if answers have changed between the pre-populated QR and the final QR. For Parameters resources, check each operation entry.\n    if (\n      comparisonResource &&\n      comparisonResource.resourceType === 'Parameters' &&\n      parametersIsFhirPatch(comparisonResource)\n    ) {\n      // Comparison resource need to go through the same filtering\n      comparisonResource.parameter = filterFhirPatchEmptyValues(comparisonResource.parameter);\n\n      // Filter out entries from extractedResource where the answers have not changed in comparison to comparisonResource\n      extractedResource.parameter = filterFhirPatchChangedOperations(\n        extractedResource.parameter,\n        comparisonResource.parameter\n      );\n    }\n\n    // If all operations were removed and none remain, skip this resource\n    const hasAnyValidOperation = extractedResource.parameter.some(\n      (param) => param.name === 'operation'\n    );\n    if (!hasAnyValidOperation) {\n      return null;\n    }\n\n    return extractedResource;\n  }\n\n  // Resource is a non-FHIRPatch Parameters resource\n  if (comparisonResource) {\n    // Second filter criteria: IF comparisonResource is provided, check if answers have changed between the pre-populated QR and the final QR\n    // Compare the extracted resource with the comparison resource\n    // If they are equal, nothing has changed, so we skip it\n    const resourcesAreEqual =\n      JSON.stringify(extractedResource) === JSON.stringify(comparisonResource);\n    if (resourcesAreEqual) {\n      return null;\n    }\n  }\n\n  return extractedResource;\n}\n\n// Type predicate to check if a FHIRPatch part is a value part\nfunction isValuePart(\n  part: FhirPatchPart | undefined\n): part is { [key: string]: unknown; name: 'value' } {\n  return part?.name === 'value';\n}\n\n// Filter out entries where the value[x] is empty\nfunction filterFhirPatchEmptyValues(\n  fhirPatchParameterEntries: FhirPatchParameterEntry[]\n): FhirPatchParameterEntry[] {\n  return fhirPatchParameterEntries.filter((param) => {\n    const valuePart = param.part?.find((part) => part.name === 'value');\n    return isValuePart(valuePart) && !fhirPatchValueIsEmpty(valuePart); // keep only if value is NOT empty\n  });\n}\n\nfunction fhirPatchValueIsEmpty(\n  patchValueParam: { name: 'value'; [key: string]: unknown } | undefined\n): boolean {\n  // FHIRPatch \"value\" part not present\n  if (!patchValueParam) {\n    return true;\n  }\n\n  // FHIRPatch \"value\" part only has one key - meaning value[x] not present, which means the QR item doesn't have an answer\n  return Object.keys(patchValueParam).length === 1;\n}\n\n/**\n * Extracts the type, path, and optional name parts from a FHIRPatch parameter entry.\n */\nfunction extractFhirPatchParameterEntryParts(entry: FhirPatchParameterEntry) {\n  const typePart = entry.part.find((p) => isFhirPatchTypePart(p)) as FhirPatchTypePart | undefined;\n  const pathPart = entry.part.find((p) => isFhirPatchPathPart(p)) as FhirPatchPathPart | undefined;\n  const namePart = entry.part.find((p) => isFhirPatchNamePart(p)) as FhirPatchPathPart | undefined;\n\n  return { typePart, pathPart, namePart };\n}\n\n/**\n * Builds a unique key for a FHIR Patch operation using its type, path,\n * and optional name parts.\n */\nfunction createFhirPatchKey(\n  typePart: FhirPatchTypePart,\n  pathPart: FhirPatchPathPart,\n  namePart?: FhirPatchPathPart\n): string {\n  let key = `${typePart.valueCode}-${pathPart.valueString}`;\n  if (namePart) {\n    key += `-${namePart.valueString}`;\n  }\n\n  return key;\n}\n\nfunction filterFhirPatchChangedOperations(\n  extractedEntries: FhirPatchParameterEntry[],\n  comparisonEntries: FhirPatchParameterEntry[]\n): FhirPatchParameterEntry[] {\n  // Build a map of comparison operations keyed by {type}-{path}\n  // Use a map instead of using indexes because some empty operations might be filtered out in filterFhirPatchEmptyValues previously, resulting in un-aligned indexes\n  const comparisonMap = new Map<string, FhirPatchParameterEntry>(\n    comparisonEntries\n      .map((entry) => {\n        const { typePart, pathPart, namePart } = extractFhirPatchParameterEntryParts(entry);\n        if (!typePart || !pathPart) {\n          return null;\n        }\n\n        const key = createFhirPatchKey(typePart, pathPart, namePart);\n        return [key, entry] as const;\n      })\n      .filter((x): x is [string, FhirPatchParameterEntry] => x !== null)\n  );\n\n  const operationsToRetain: FhirPatchParameterEntry[] = [];\n  for (const extractedOperation of extractedEntries) {\n    if (!extractedOperation) {\n      continue; // Skip if extractedOperation is missing\n    }\n\n    const { typePart, pathPart, namePart } =\n      extractFhirPatchParameterEntryParts(extractedOperation);\n    if (!typePart || !pathPart) {\n      // If we can't build the key, just keep it - as a conservative decision\n      operationsToRetain.push(extractedOperation);\n      continue;\n    }\n\n    const key = createFhirPatchKey(typePart, pathPart, namePart);\n    const comparisonOperation = comparisonMap.get(key);\n\n    const operationsAreEqual =\n      JSON.stringify(extractedOperation) === JSON.stringify(comparisonOperation);\n    if (operationsAreEqual) {\n      continue;\n    }\n\n    // If the operation has changed, keep it in the extracted resource\n    operationsToRetain.push(extractedOperation);\n  }\n\n  return operationsToRetain;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Bundle, OperationOutcomeIssue } from 'fhir/r4';\nimport type {\n  CustomDebugInfoParameter,\n  OutputParameters,\n  ReturnParameter,\n  TemplateExtractDebugInfo\n} from '../interfaces';\nimport { Base64 } from 'js-base64';\n\n/**\n * Create output parameters as a response to be returned to the renderer. If they are issues, return with an issues parameter.\n * Refer to https://build.fhir.org/ig/HL7/sdc/OperationDefinition-QuestionnaireResponse-extract.html.\n */\nexport function createOutputParameters(\n  bundle: Bundle,\n  issues: OperationOutcomeIssue[],\n  debugInfo: TemplateExtractDebugInfo\n): OutputParameters {\n  const returnParameter: ReturnParameter = {\n    name: 'return',\n    resource: bundle\n  };\n\n  const customDebugInfoParameter: CustomDebugInfoParameter = {\n    name: 'debugInfo-custom',\n    valueAttachment: {\n      contentType: 'application/json',\n      data: Base64.encode(JSON.stringify(debugInfo))\n    }\n  };\n\n  // No issues to report\n  if (issues.length === 0) {\n    return {\n      resourceType: 'Parameters',\n      parameter: [returnParameter, customDebugInfoParameter]\n    };\n  }\n\n  // There are issues, so include issues parameter\n  return {\n    resourceType: 'Parameters',\n    parameter: [\n      returnParameter,\n      {\n        name: 'issues',\n        resource: {\n          resourceType: 'OperationOutcome',\n          issue: issues\n        }\n      },\n      customDebugInfoParameter\n    ]\n  };\n}\n","import type { QuestionnaireResponse } from 'fhir/r4';\n\n/**\n * Builds a FHIRPath context with the response and allocated IDs.\n *\n * @param questionnaireResponse - The QuestionnaireResponse resource.\n * @param extractAllocateIds - Map of variable names to allocated IDs.\n * @returns FHIRPath context object.\n */\nexport function createFhirPathContext(\n  questionnaireResponse: QuestionnaireResponse,\n  extractAllocateIds: Record<string, string>\n): Record<string, any> {\n  return {\n    resource: questionnaireResponse,\n    rootResource: questionnaireResponse,\n    ...extractAllocateIds\n  };\n}\n","import type { QuestionnaireResponse } from 'fhir/r4';\nimport type { InputParameters } from '../interfaces/inputParameters.interface';\nimport { isCustomComparisonSourceResponseParameter } from './typePredicates';\n\nexport function getComparisonSourceResponse(\n  inputParameters: InputParameters | QuestionnaireResponse\n): QuestionnaireResponse | null {\n  // Input parameters is a QR, that means comparison-source-response does not exist\n  if (inputParameters.resourceType === 'QuestionnaireResponse') {\n    return null;\n  }\n\n  // Check if the input is Parameters and find the ComparisonSourceResponse parameter\n  if (inputParameters.resourceType === 'Parameters') {\n    const comparisonSourceResponseParam = inputParameters.parameter.find((param) =>\n      isCustomComparisonSourceResponseParameter(param)\n    );\n\n    if (\n      comparisonSourceResponseParam &&\n      comparisonSourceResponseParam.resource &&\n      comparisonSourceResponseParam.resource.resourceType === 'QuestionnaireResponse'\n    ) {\n      return comparisonSourceResponseParam.resource;\n    }\n  }\n\n  // If no ComparisonSourceResponse found, return null\n  return null;\n}\n","import type { InputParameters } from '../interfaces/inputParameters.interface';\nimport type { OutputParameters, TemplateExtractDebugInfo } from '../interfaces';\nimport type {\n  FetchQuestionnaireCallback,\n  FetchQuestionnaireRequestConfig\n} from '../interfaces/callback.interface';\nimport type {\n  FhirResource,\n  OperationOutcome,\n  OperationOutcomeIssue,\n  QuestionnaireResponse\n} from 'fhir/r4';\nimport { getQuestionnaireResponse } from './getQuestionnaireResponse';\nimport { fetchQuestionnaire } from './fetchQuestionnaire';\nimport { createErrorOutcome, createWarningOutcomeWithInvalid } from './operationOutcome';\nimport { canBeTemplateExtracted, collectTemplateExtractRefs } from './templateExtractRef';\nimport { createContainedTemplateMap } from './templateMap';\nimport { populateIntoTemplates } from './populateIntoTemplates';\nimport { allocateIdsForExtract } from './extractAllocateId';\nimport { buildTransactionBundle } from './buildBundle';\nimport { createOutputParameters } from './createOutputParameters';\nimport { createFhirPathContext } from './createFhirPathContext';\nimport { getComparisonSourceResponse } from './getComparisonSourceResponse';\n\nexport async function extract(\n  inputParameters: InputParameters | QuestionnaireResponse,\n  fetchQuestionnaireCallback: FetchQuestionnaireCallback,\n  fetchQuestionnaireRequestConfig: FetchQuestionnaireRequestConfig\n): Promise<OutputParameters | OperationOutcome> {\n  // Get QuestionnaireResponse from input parameters\n  const questionnaireResponse = getQuestionnaireResponse(inputParameters);\n  if (questionnaireResponse.resourceType === 'OperationOutcome') {\n    // Return as FHIR OperationOutcome\n    return questionnaireResponse;\n  }\n\n  // Get Questionnaire from input parameters or from QuestionnaireResponse.questionnaire\n  const questionnaire = await fetchQuestionnaire(\n    inputParameters,\n    questionnaireResponse,\n    fetchQuestionnaireCallback,\n    fetchQuestionnaireRequestConfig\n  );\n  if (questionnaire.resourceType === 'OperationOutcome') {\n    // Return as FHIR OperationOutcome\n    return questionnaire;\n  }\n\n  // set extractAllocateIds to UUIDs\n  const extractAllocateIds = allocateIdsForExtract(questionnaire);\n\n  // Validation\n  if (!questionnaire.item || questionnaire.item.length === 0) {\n    return createErrorOutcome(`Questionnaire.item is empty, there are no items to process`);\n  }\n\n  // Check if questionnaire can be template-extracted\n  if (!canBeTemplateExtracted(questionnaire)) {\n    return createWarningOutcomeWithInvalid(\n      `Questionnaire does not contain any \"sdc-questionnaire-templateExtract\" extensions. Skipping extraction.`\n    );\n  }\n\n  // Check if questionnaire.contained is provided and not empty\n  if (!questionnaire.contained || questionnaire.contained.length === 0) {\n    return createWarningOutcomeWithInvalid(\n      `Questionnaire.contained is empty, an extraction template should be provided as a contained resource. Skipping extraction.`\n    );\n  }\n\n  // Check if questionnaireResponse.item is provided and not empty\n  if (!questionnaireResponse.item || questionnaireResponse.item.length === 0) {\n    return createWarningOutcomeWithInvalid(\n      `QuestionnaireResponse.item is empty, there are no answers to process. Skipping extraction.`\n    );\n  }\n\n  const combinedWarnings: OperationOutcomeIssue[] = [];\n\n  // Get extract templates from questionnaire and all its items\n  const { templateExtractRefMap: linkIdToTemplateExtractRefMap, templateExtractRefWarnings } =\n    collectTemplateExtractRefs(questionnaire);\n  if (linkIdToTemplateExtractRefMap.size === 0) {\n    return createWarningOutcomeWithInvalid(\n      `Questionnaire does not contain any \"sdc-questionnaire-templateExtract\" extensions. Skipping extraction.`\n    );\n  }\n  combinedWarnings.push(...templateExtractRefWarnings);\n\n  // Create a template details map with details like templateResource, targetLinkId, targetQItem, targetQRItem (if available)\n  const containedTemplateMap = createContainedTemplateMap(\n    questionnaire,\n    questionnaireResponse,\n    linkIdToTemplateExtractRefMap\n  );\n\n  // Create a fhirPathContext object that acts as envVars for fhirpath.evaluate\n  const fhirPathContext = createFhirPathContext(questionnaireResponse, extractAllocateIds);\n\n  // Evaluate and populate answers from questionnaireResponse into contained templates\n  const { extractedResourceMap, populateIntoTemplateWarnings, templateIdToExtractPaths } =\n    populateIntoTemplates(questionnaireResponse, containedTemplateMap, fhirPathContext);\n  combinedWarnings.push(...populateIntoTemplateWarnings);\n\n  // If a comparison-source-response is provided, use it for comparisons during the filtering process\n  // We run another evaluation + populate step, but for comparisonSourceResponse to generate a comparisonResourceMap\n  const comparisonSourceResponse = getComparisonSourceResponse(inputParameters);\n  let comparisonResourceMap: Map<string, FhirResource[]> | null = null;\n  if (comparisonSourceResponse) {\n    comparisonResourceMap = populateIntoTemplates(\n      comparisonSourceResponse,\n      containedTemplateMap,\n      fhirPathContext\n    ).extractedResourceMap;\n  }\n\n  // Build transaction bundle with extracted resources\n  const { outputBundle, templateIdToExtractPathTuples } = buildTransactionBundle(\n    extractedResourceMap,\n    comparisonResourceMap,\n    containedTemplateMap,\n    templateIdToExtractPaths,\n    fhirPathContext,\n    questionnaireResponse\n  );\n\n  const customDebugInfo: TemplateExtractDebugInfo = {\n    templateIdToExtractPathTuples: templateIdToExtractPathTuples\n  };\n\n  // Create output parameters\n  return createOutputParameters(outputBundle, combinedWarnings, customDebugInfo);\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Questionnaire, QuestionnaireResponse } from 'fhir/r4';\nimport type {\n  CustomComparisonSourceResponseParameter,\n  CustomQuestionnaireParameter,\n  InputParamArray,\n  InputParameters,\n  QuestionnaireResponseParameter\n} from '../interfaces/inputParameters.interface';\n\n/**\n * Create input parameters to be passed to sdc-template-extract extract(). Questionnaire parameter is optional.\n * Refer to https://build.fhir.org/ig/HL7/sdc/OperationDefinition-QuestionnaireResponse-extract.html.\n */\nexport function createInputParameters(\n  questionnaireResponse: QuestionnaireResponse,\n  questionnaire: Questionnaire | undefined,\n  comparisonSourceResponse: QuestionnaireResponse | undefined\n): InputParameters {\n  return {\n    resourceType: 'Parameters',\n    parameter: createInputParamArray(questionnaireResponse, questionnaire, comparisonSourceResponse)\n  };\n}\n\n/**\n * Builds the input parameter array for the extract() function.\n * Includes the QuestionnaireResponse and optionally the Questionnaire.\n */\nfunction createInputParamArray(\n  questionnaireResponse: QuestionnaireResponse,\n  questionnaire: Questionnaire | undefined,\n  comparisonSourceResponse: QuestionnaireResponse | undefined\n): InputParamArray {\n  const questionnaireResponseParam: QuestionnaireResponseParameter = {\n    name: 'questionnaire-response',\n    resource: questionnaireResponse\n  };\n\n  const questionnaireParam: CustomQuestionnaireParameter | undefined = questionnaire\n    ? { name: 'questionnaire', resource: questionnaire }\n    : undefined;\n\n  const comparisonResponseParam: CustomComparisonSourceResponseParameter | undefined =\n    comparisonSourceResponse\n      ? { name: 'comparison-source-response', resource: comparisonSourceResponse }\n      : undefined;\n\n  if (questionnaireParam && comparisonResponseParam) {\n    return [questionnaireResponseParam, questionnaireParam, comparisonResponseParam];\n  }\n\n  if (questionnaireParam) {\n    return [questionnaireResponseParam, questionnaireParam];\n  }\n\n  if (comparisonResponseParam) {\n    return [questionnaireResponseParam, comparisonResponseParam];\n  }\n\n  return [questionnaireResponseParam];\n}\n","import type {\n  TemplateExtractPath,\n  TemplateExtractPathJsObject\n} from '../interfaces/templateExtractPath.interface';\n\n/**\n * Logs a summary table of all extractable context and value paths from a given template.\n * Useful for debugging or inspecting the structure of a `TemplateExtractPath` map.\n *\n * Each row of the table includes:\n * - the entry path (FHIRPath to the context element),\n * - the context location, expression and result\n * - the value path and corresponding extract expression + result.\n *\n * @param {string} templateId - The identifier for the template being logged.\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - A map of FHIRPath entries to `TemplateExtractPath` objects, representing extract contexts and value expressions.\n *\n * @example\n * Example output:\n *\n * ```\n * 🔢 All columns for: PatientTemplate\n *\n * | entryPath             | contextPath                        | contextExpression                                | valuePath                                 | valueExpression                                                      | valueResult            |\n * |-----------------------|----------------------------------- |------------------------------------------------- |------------------------------------------ |--------------------------------------------------------------------- |------------------------|\n * | Patient.identifier[0] | Patient.identifier[0].extension[0] | item.where(linkId = 'ihi').answer.value          | Patient.identifier[0]._value.extension[0] | first()                                                              | [ \"8003608833357361\" ] |\n * | Patient.name[0]       | Patient.name[0].extension[0]       | item.where(linkId = 'name')                      | Patient.name[0]._text.extension[0]        | item.where(linkId='given' or linkId='family').answer.value.join(' ') | [ \"Jane\" ]             |\n * | Patient.name[0]       | Patient.name[0].extension[0]       | item.where(linkId = 'name')                      | Patient.name[0]._family.extension[0]      | item.where(linkId = 'family').answer.value.first()                   | [ \"Doe\" ]              |\n * | Patient.telecom[0]    | Patient.telecom[0].extension[0]    | item.where(linkId = 'mobile-phone').answer.value | Patient.telecom[0]._value.extension[0]    | first()                                                              | [ \"0491 572 665\" ]     |\n * | Patient._gender       | null                               | null                                             | Patient._gender.extension[0]              | item.where(linkId = 'gender').answer.value.first().code              | [ \"female\" ]           |\n * ```\n */\nexport function logTemplateExtractPathMapFull(\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>\n) {\n  const table: {\n    entryPath: string;\n    contextPath: string | null;\n    contextExpression: string | null;\n    valuePath: string | null;\n    valueExpression: string | null;\n    valueResult: any;\n  }[] = [];\n\n  for (const [entryPath, { contextPathTuple, valuePathMap }] of templateExtractPathMap.entries()) {\n    const contextPath = contextPathTuple?.[0] ?? null;\n    const contextExpression = contextPathTuple?.[1] ?? null;\n\n    for (const [valuePath, valueEvaluation] of valuePathMap.entries()) {\n      const { valueExpression, valueResult } = valueEvaluation;\n      table.push({\n        entryPath: entryPath,\n        contextPath: contextPath,\n        contextExpression: contextExpression,\n        valuePath: valuePath,\n        valueExpression: valueExpression,\n        valueResult: valueResult\n      });\n    }\n\n    if (valuePathMap.size === 0) {\n      table.push({\n        entryPath: entryPath,\n        contextPath: contextPath,\n        contextExpression: contextExpression,\n        valuePath: null,\n        valueExpression: null,\n        valueResult: null\n      });\n    }\n  }\n\n  console.log(`\\n📋 Contexts and values for template: ${templateId}`);\n  console.table(table);\n}\n\n// JS Object version\nexport function logTemplateExtractPathMapJsObjectFull(\n  templateId: string,\n  templateExtractPathMap: Record<string, TemplateExtractPathJsObject>\n) {\n  const table: {\n    entryPath: string;\n    contextPath: string | null;\n    contextExpression: string | null;\n    valuePath: string | null;\n    valueExpression: string | null;\n    valueResult: any;\n  }[] = [];\n\n  for (const [entryPath, { contextPathTuple, valuePathMap }] of Object.entries(\n    templateExtractPathMap\n  )) {\n    const contextPath = contextPathTuple?.[0] ?? null;\n    const contextExpression = contextPathTuple?.[1] ?? null;\n\n    const valuePaths = Object.entries(valuePathMap ?? {});\n\n    if (valuePaths.length > 0) {\n      for (const [valuePath, { valueExpression, valueResult }] of valuePaths) {\n        table.push({\n          entryPath,\n          contextPath,\n          contextExpression,\n          valuePath,\n          valueExpression,\n          valueResult\n        });\n      }\n    } else {\n      table.push({\n        entryPath,\n        contextPath,\n        contextExpression,\n        valuePath: null,\n        valueExpression: null,\n        valueResult: null\n      });\n    }\n  }\n\n  console.log(`\\n📋 Contexts and values for template: ${templateId}`);\n  console.table(table);\n}\n\n/**\n * Logs a simplified table showing only the entry path, evaluated context result,\n * and the evaluated value result for each extractable template path.\n *\n * This is useful for quickly verifying extracted values without inspecting the full expression logic.\n *\n * Each row includes:\n * - `entryPath`: The FHIRPath location in the resource,\n * - `valueResult`: The result of evaluating the value expression.\n *\n * @param {string} templateId - The identifier for the template being logged.\n * @param {Map<string, TemplateExtractPath>} templateExtractPathMap - A map of FHIRPath entries to `TemplateExtractPath` objects, representing extract contexts and value expressions.\n *\n * @example\n * Example output:\n *\n * ```\n * 🔹 Result columns for: PatientTemplate\n *\n * | entryPath             | valueResult            |\n * |-----------------------|------------------------|\n * | Patient.identifier[0] | [ \"8003608833357361\" ] |\n * | Patient.name[0]       | [ \"Jane\" ]             |\n * | Patient.name[0]       | [ \"Doe\" ]              |\n * | Patient.telecom[0]    | [ \"0491 572 665\" ]     |\n * | Patient._gender       | [ \"female\" ]           |\n * ```\n */\nexport function logTemplateExtractPathMapResults(\n  templateId: string,\n  templateExtractPathMap: Map<string, TemplateExtractPath>\n) {\n  const table: {\n    entryPath: string;\n    valueResult: any;\n  }[] = [];\n\n  for (const [entryPath, templateExtractPath] of templateExtractPathMap.entries()) {\n    const { valuePathMap } = templateExtractPath;\n\n    for (const [, valueEvaluation] of valuePathMap.entries()) {\n      const { valueResult } = valueEvaluation;\n      table.push({\n        entryPath,\n        valueResult\n      });\n    }\n\n    if (valuePathMap.size === 0) {\n      table.push({\n        entryPath,\n        valueResult: null\n      });\n    }\n  }\n\n  console.log(`\\n🔹Context and value results for: ${templateId}`);\n  console.table(table);\n}\n\n// JS Object version\nexport function logTemplateExtractPathMapJsObjectResults(\n  templateId: string,\n  templateExtractPathMap: Record<string, TemplateExtractPathJsObject>\n) {\n  const table: {\n    entryPath: string;\n    valueResult: any;\n  }[] = [];\n\n  for (const [entryPath, templateExtractPath] of Object.entries(templateExtractPathMap)) {\n    const { valuePathMap } = templateExtractPath;\n\n    const valuePaths = Object.values(valuePathMap ?? {});\n    if (valuePaths.length > 0) {\n      for (const { valueResult } of valuePaths) {\n        table.push({\n          entryPath,\n          valueResult\n        });\n      }\n    } else {\n      table.push({\n        entryPath,\n        valueResult: null\n      });\n    }\n  }\n\n  console.log(`\\n🔹Context and value results for: ${templateId}`);\n  console.table(table);\n}\n","import type {\n  ExtractResult,\n  FetchQuestionnaireResolver,\n  QuestionnaireOrCallback\n} from '../interfaces';\nimport type { OperationOutcome, Questionnaire } from 'fhir/r4';\nimport type { TemplateExtractDebugInfo } from '../../SDCExtractQuestionnaireResponseOperation';\n\nexport function questionnaireOrCallbackIsFetchQuestionnaireResolver(\n  questionnaireOrCallback: QuestionnaireOrCallback\n): questionnaireOrCallback is FetchQuestionnaireResolver {\n  return (\n    typeof questionnaireOrCallback === 'object' &&\n    questionnaireOrCallback !== null &&\n    'fetchQuestionnaireCallback' in questionnaireOrCallback &&\n    'fetchQuestionnaireRequestConfig' in questionnaireOrCallback\n  );\n}\n\nexport function questionnaireOrCallbackIsQuestionnaire(\n  questionnaireOrCallback: QuestionnaireOrCallback\n): questionnaireOrCallback is Questionnaire {\n  return (\n    typeof questionnaireOrCallback === 'object' &&\n    questionnaireOrCallback !== null &&\n    'resourceType' in questionnaireOrCallback &&\n    questionnaireOrCallback.resourceType === 'Questionnaire'\n  );\n}\n\nexport function extractResultIsOperationOutcome(\n  extractResult: ExtractResult | OperationOutcome\n): extractResult is OperationOutcome {\n  return 'resourceType' in extractResult && extractResult.resourceType === 'OperationOutcome';\n}\n\nexport function objIsTemplateExtractDebugInfo(obj: object): obj is TemplateExtractDebugInfo {\n  return typeof obj === 'object' && obj !== null && 'templateIdToExtractPathTuples' in obj;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Questionnaire, QuestionnaireResponse } from 'fhir/r4';\nimport type {\n  CustomDebugInfoParameter,\n  FetchQuestionnaireCallback,\n  FetchQuestionnaireRequestConfig,\n  IssuesParameter,\n  ReturnParameter\n} from '../../SDCExtractQuestionnaireResponseOperation';\nimport { createInputParameters, extract } from '../../SDCExtractQuestionnaireResponseOperation';\nimport { createErrorOutcome } from '../../SDCExtractQuestionnaireResponseOperation/utils/operationOutcome';\nimport type { ExtractResult, InAppExtractOutput, QuestionnaireOrCallback } from '../interfaces';\nimport {\n  objIsTemplateExtractDebugInfo,\n  questionnaireOrCallbackIsFetchQuestionnaireResolver,\n  questionnaireOrCallbackIsQuestionnaire\n} from './typePredicates';\nimport { Base64 } from 'js-base64';\n\n/**\n * An abstraction layer over the SDC `extract()` function, which implements the `$extract` operation.\n *\n * This utility handles:\n * - Packing of input parameters (e.g., QuestionnaireResponse, Questionnaire, comparison source).\n * - Unpacking of output parameters (e.g., return Bundle, issues, debug info).\n * - Optional fallback handling when a Questionnaire resource is not provided directly.\n *\n * @param questionnaireResponse - The primary `QuestionnaireResponse` to extract data from.\n * @param questionnaireOrCallback - Either a `Questionnaire` resource or a fetch/callback configuration for dynamic retrieval.\n * @param comparisonSourceResponse - An optional `QuestionnaireResponse` used for comparison when extracting. If this is provided, only \"modified\" items will be extracted.\n *\n * @returns A promise resolving to an `InAppExtractOutput`:\n * - On success: `{ extractSuccess: true, extractResult: { extractedBundle, issues?, debugInfo? } }`\n * - On failure: `{ extractSuccess: false, extractResult: OperationOutcome }`\n */\nexport async function inAppExtract(\n  questionnaireResponse: QuestionnaireResponse,\n  questionnaireOrCallback: QuestionnaireOrCallback,\n  comparisonSourceResponse: QuestionnaireResponse | null\n): Promise<InAppExtractOutput> {\n  // Questionnaire resource is provided, create InputParameters with \"questionnaire\" parameter\n  let questionnaire: Questionnaire | undefined;\n  if (questionnaireOrCallbackIsQuestionnaire(questionnaireOrCallback)) {\n    questionnaire = questionnaireOrCallback;\n  }\n\n  // Questionnaire resource not provided, need to pass the callback and config along\n  let fetchQuestionnaireCallback: FetchQuestionnaireCallback = () =>\n    Promise.resolve({\n      message:\n        'This is a placeholder result for sdc-template-extract inAppExtract(). This function should not be called if you have provided a Questionnaire resource.'\n    });\n  let fetchQuestionnaireRequestConfig: FetchQuestionnaireRequestConfig = {\n    sourceServerUrl: ''\n  };\n  if (questionnaireOrCallbackIsFetchQuestionnaireResolver(questionnaireOrCallback)) {\n    fetchQuestionnaireCallback = questionnaireOrCallback.fetchQuestionnaireCallback;\n    fetchQuestionnaireRequestConfig = questionnaireOrCallback.fetchQuestionnaireRequestConfig;\n  }\n\n  const inputParameters = createInputParameters(\n    questionnaireResponse,\n    questionnaire,\n    comparisonSourceResponse ?? undefined\n  );\n\n  // Call extract() function from SDCExtractQuestionnaireResponseOperation\n  const outputParameters = await extract(\n    inputParameters,\n    fetchQuestionnaireCallback,\n    fetchQuestionnaireRequestConfig\n  );\n\n  // outputParameters is OperationOutcome, return it directly\n  if (outputParameters.resourceType === 'OperationOutcome') {\n    return { extractSuccess: false, extractResult: outputParameters };\n  }\n\n  // At this point outputParameters is a Parameters resource\n  const returnParameter = outputParameters.parameter.find(\n    (param) => param.name === 'return'\n  ) as ReturnParameter;\n  const issuesParameter = outputParameters.parameter.find((param) => param.name === 'issues') as\n    | IssuesParameter\n    | undefined;\n  const customDebugInfoParameter = outputParameters.parameter.find(\n    (param) => param.name === 'debugInfo-custom'\n  ) as CustomDebugInfoParameter | undefined;\n\n  // ReturnParameter resource is not a Bundle - should not happen, but handle it gracefully\n  if (returnParameter.resource.resourceType !== 'Bundle') {\n    console.error(returnParameter.resource);\n    return {\n      extractSuccess: false,\n      extractResult: createErrorOutcome(\n        `Expected return parameter to contain a Bundle resource, but got: ${returnParameter.resource.resourceType}.\\nSee resource logged above.`\n      )\n    };\n  }\n\n  // Create ExtractResult object\n  const extractResult: ExtractResult = {\n    extractedBundle: returnParameter.resource,\n    issues: null,\n    debugInfo: null\n  };\n\n  // Handle issuesParameter\n  const hasIssues =\n    !!issuesParameter?.resource?.issue && issuesParameter?.resource?.issue?.length > 0;\n  if (hasIssues) {\n    extractResult.issues = issuesParameter.resource;\n  }\n\n  // Handle customDebugInfoParameter\n  if (customDebugInfoParameter?.valueAttachment.data) {\n    const debugInfo = JSON.parse(Base64.decode(customDebugInfoParameter.valueAttachment.data));\n\n    if (objIsTemplateExtractDebugInfo(debugInfo)) {\n      extractResult.debugInfo = debugInfo;\n    }\n  }\n\n  return {\n    extractSuccess: true,\n    extractResult: extractResult\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACyCO,SAAS,iCACd,WAC6C;AA3C/C;AA4CE,SACE,UAAU,SAAS,8BACnB,eAAU,aAAV,mBAAoB,kBAAiB;AAEzC;AAEO,SAAS,+BACd,WAC2C;AApD7C;AAqDE,SAAO,UAAU,SAAS,qBAAmB,eAAU,aAAV,mBAAoB,kBAAiB;AACpF;AAEO,SAAS,0CACd,WACsD;AA1DxD;AA2DE,SACE,UAAU,SAAS,kCACnB,eAAU,aAAV,mBAAoB,kBAAiB;AAEzC;AASO,SAAS,yBACd,WACqC;AA1EvC;AA2EE,SACE,UAAU,QAAQ,cAClB,oBAAoB,aACpB,CAAC,GAAC,eAAU,mBAAV,mBAA0B,cAC5B,UAAU,eAAe,UAAU,W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