/** * Genomic Testing Platform Integrations * * Connects to major genomic testing providers: * - Foundation Medicine (FoundationOne CDx, FoundationOne Liquid CDx) * - Guardant Health (Guardant360, GuardantOMNI) * - Tempus (xT, xF, xR panels) * - Caris Life Sciences (Caris Molecular Intelligence) * - NeoGenomics * * All data handling complies with HIPAA and CAP/CLIA requirements. */ import { EventEmitter } from 'events'; // ═══════════════════════════════════════════════════════════════════════════════ // COMMON GENOMIC DATA TYPES // ═══════════════════════════════════════════════════════════════════════════════ export interface GenomicTestOrder { orderId: string; patientId: string; testType: string; panelName: string; specimenType: 'tissue' | 'blood' | 'bone-marrow' | 'other'; specimenId?: string; orderDate: Date; clinicalIndication: string; icdCodes: string[]; orderingPhysician: { name: string; npi: string; facility: string; }; status: 'ordered' | 'specimen-received' | 'in-process' | 'completed' | 'failed' | 'cancelled'; } export interface GenomicTestResult { reportId: string; orderId: string; patientId: string; testType: string; panelName: string; specimenInfo: { type: 'tissue' | 'blood' | 'bone-marrow' | 'other'; site?: string; collectionDate: Date; tumorPurity?: number; cellularity?: number; }; reportDate: Date; variants: GenomicVariant[]; copyNumberAlterations: CopyNumberAlteration[]; fusions: GeneFusion[]; biomarkers: GenomicBiomarker[]; therapyMatches: TherapyMatch[]; clinicalTrialMatches: ClinicalTrialMatch[]; signatures?: { microsatelliteInstability?: MSIResult; tumorMutationalBurden?: TMBResult; homologousRecombinationDeficiency?: HRDResult; lossOfHeterozygosity?: LOHResult; }; qualityMetrics: { meanCoverage?: number; percentBases100x?: number; tumorFraction?: number; contamination?: number; mappingRate?: number; }; reportPdf?: string; // Base64 encoded PDF rawData?: { vcfUrl?: string; bamUrl?: string; fastqUrl?: string; }; } export interface GenomicVariant { gene: string; hgvsC?: string; // cDNA change hgvsP?: string; // Protein change transcript?: string; chromosome?: string; position?: number; refAllele?: string; altAllele?: string; variantType: 'SNV' | 'insertion' | 'deletion' | 'indel' | 'MNV' | 'complex'; variantAlleleFrequency: number; coverage?: number; zygosity?: 'heterozygous' | 'homozygous' | 'hemizygous'; clinicalSignificance: 'pathogenic' | 'likely-pathogenic' | 'vus' | 'likely-benign' | 'benign'; tier?: 'I' | 'II' | 'III' | 'IV'; // AMP/ASCO/CAP tiering oncogenicity?: 'oncogenic' | 'likely-oncogenic' | 'vus' | 'likely-neutral' | 'neutral'; functionalEffect?: 'loss-of-function' | 'gain-of-function' | 'switch-of-function' | 'unknown'; somaticStatus?: 'somatic' | 'germline' | 'unknown'; actionability?: { level: 'FDA-approved' | 'clinical-guideline' | 'clinical-evidence' | 'preclinical'; therapies: string[]; evidence: string[]; }; annotations?: { cosmic?: string; dbSNP?: string; clinVar?: string; gnomAD?: { frequency: number; popMax?: number }; oncokb?: { level: string; description: string }; }; } export interface CopyNumberAlteration { gene: string; chromosome?: string; startPosition?: number; endPosition?: number; type: 'amplification' | 'gain' | 'loss' | 'deep-deletion'; copyNumber?: number; logRatio?: number; clinicalSignificance: 'pathogenic' | 'likely-pathogenic' | 'vus' | 'likely-benign' | 'benign'; actionability?: { level: 'FDA-approved' | 'clinical-guideline' | 'clinical-evidence' | 'preclinical'; therapies: string[]; }; } export interface GeneFusion { gene5Prime: string; gene3Prime: string; fusionName: string; breakpoint5Prime?: string; breakpoint3Prime?: string; readsSupporting?: number; inFrame?: boolean; clinicalSignificance: 'pathogenic' | 'likely-pathogenic' | 'vus'; actionability?: { level: 'FDA-approved' | 'clinical-guideline' | 'clinical-evidence' | 'preclinical'; therapies: string[]; }; } export interface GenomicBiomarker { name: string; value: number | string; unit?: string; status: 'positive' | 'negative' | 'equivocal' | 'indeterminate'; threshold?: number; method?: string; clinicalImplication?: string; } export interface MSIResult { status: 'MSI-H' | 'MSI-L' | 'MSS' | 'indeterminate'; score?: number; markersAnalyzed?: number; markersUnstable?: number; method: 'NGS' | 'PCR' | 'IHC'; } export interface TMBResult { value: number; unit: 'mutations/Mb'; status: 'high' | 'intermediate' | 'low'; threshold: number; percentile?: number; } export interface HRDResult { status: 'positive' | 'negative' | 'indeterminate'; score?: number; components?: { loh?: number; tai?: number; lst?: number; }; brcaStatus?: 'BRCA1-mut' | 'BRCA2-mut' | 'BRCA-wt'; } export interface LOHResult { percentage: number; status: 'high' | 'intermediate' | 'low'; genomeFraction?: number; } export interface TherapyMatch { therapy: string; drugs: string[]; biomarkers: string[]; evidenceLevel: 'FDA-approved' | 'NCCN-guideline' | 'clinical-evidence' | 'case-report' | 'preclinical'; cancerType: string; approvalStatus?: string; clinicalTrials?: string[]; responseRate?: number; references: string[]; } export interface ClinicalTrialMatch { trialId: string; // NCT number title: string; phase: 'I' | 'I/II' | 'II' | 'II/III' | 'III' | 'IV'; matchingBiomarkers: string[]; status: 'recruiting' | 'active-not-recruiting' | 'enrolling-by-invitation'; locations?: { name: string; city: string; state: string; country: string }[]; sponsor?: string; drugs?: string[]; } // ═══════════════════════════════════════════════════════════════════════════════ // PLATFORM CONFIGURATION // ═══════════════════════════════════════════════════════════════════════════════ export interface GenomicPlatformConfig { platform: 'foundation-medicine' | 'guardant' | 'tempus' | 'caris' | 'neogenomics' | 'generic'; apiBaseUrl: string; apiKey?: string; clientId?: string; clientSecret?: string; organizationId?: string; webhookUrl?: string; timeout?: number; } // ═══════════════════════════════════════════════════════════════════════════════ // ABSTRACT GENOMIC PLATFORM CLIENT // ═══════════════════════════════════════════════════════════════════════════════ export abstract class GenomicPlatformClient extends EventEmitter { protected config: GenomicPlatformConfig; protected accessToken?: string; protected tokenExpiry?: Date; constructor(config: GenomicPlatformConfig) { super(); this.config = { timeout: 60000, ...config }; } abstract authenticate(): Promise; abstract submitOrder(order: GenomicTestOrder): Promise<{ orderId: string; status: string }>; abstract getOrderStatus(orderId: string): Promise; abstract getResults(orderId: string): Promise; abstract listPatientResults(patientId: string): Promise; protected async httpRequest(url: string, options: { method: string; headers?: Record; body?: string; }): Promise { const response = await fetch(url, { method: options.method, headers: { 'Content-Type': 'application/json', ...options.headers }, body: options.body, signal: AbortSignal.timeout(this.config.timeout || 60000) }); if (!response.ok) { const errorBody = await response.text(); throw new Error(`API request failed: ${response.status} ${response.statusText} - ${errorBody}`); } return await response.text(); } protected async getAuthHeaders(): Promise> { if (this.tokenExpiry && new Date() >= this.tokenExpiry) { await this.authenticate(); } if (this.accessToken) { return { 'Authorization': `Bearer ${this.accessToken}` }; } if (this.config.apiKey) { return { 'X-API-Key': this.config.apiKey }; } return {}; } } // ═══════════════════════════════════════════════════════════════════════════════ // FOUNDATION MEDICINE CLIENT // ═══════════════════════════════════════════════════════════════════════════════ export class FoundationMedicineClient extends GenomicPlatformClient { constructor(config: Omit) { super({ ...config, platform: 'foundation-medicine' }); } async authenticate(): Promise { const tokenUrl = `${this.config.apiBaseUrl}/oauth/token`; const response = await this.httpRequest(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'client_credentials', client_id: this.config.clientId || '', client_secret: this.config.clientSecret || '' }).toString() }); const data = JSON.parse(response); this.accessToken = data.access_token; this.tokenExpiry = new Date(Date.now() + (data.expires_in * 1000)); } async submitOrder(order: GenomicTestOrder): Promise<{ orderId: string; status: string }> { const url = `${this.config.apiBaseUrl}/v1/orders`; const fmiOrder = this.mapToFMIOrder(order); const response = await this.httpRequest(url, { method: 'POST', headers: await this.getAuthHeaders(), body: JSON.stringify(fmiOrder) }); const result = JSON.parse(response); return { orderId: result.orderId || result.id, status: result.status || 'submitted' }; } async getOrderStatus(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/orders/${orderId}`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const fmiOrder = JSON.parse(response); return this.mapFromFMIOrder(fmiOrder); } async getResults(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/orders/${orderId}/report`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const fmiReport = JSON.parse(response); return this.mapFromFMIReport(fmiReport, orderId); } async listPatientResults(patientId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/patients/${patientId}/reports`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const reports = JSON.parse(response); return reports.map((r: any) => this.mapFromFMIReport(r, r.orderId)); } /** * Get FoundationOne CDx specific data */ async getFoundationOneCDxReport(orderId: string): Promise<{ variants: GenomicVariant[]; cnvs: CopyNumberAlteration[]; fusions: GeneFusion[]; msi: MSIResult; tmb: TMBResult; loh: LOHResult; therapies: TherapyMatch[]; }> { const result = await this.getResults(orderId); return { variants: result.variants, cnvs: result.copyNumberAlterations, fusions: result.fusions, msi: result.signatures?.microsatelliteInstability || { status: 'MSS', method: 'NGS' }, tmb: result.signatures?.tumorMutationalBurden || { value: 0, unit: 'mutations/Mb', status: 'low', threshold: 10 }, loh: result.signatures?.lossOfHeterozygosity || { percentage: 0, status: 'low' }, therapies: result.therapyMatches }; } private mapToFMIOrder(order: GenomicTestOrder): Record { return { externalOrderId: order.orderId, patient: { externalId: order.patientId }, specimen: { type: order.specimenType, externalId: order.specimenId }, test: { code: this.mapPanelToFMICode(order.panelName) }, diagnosis: { icdCodes: order.icdCodes, clinicalHistory: order.clinicalIndication }, orderingPhysician: { name: order.orderingPhysician.name, npi: order.orderingPhysician.npi, facility: order.orderingPhysician.facility } }; } private mapPanelToFMICode(panelName: string): string { const mapping: Record = { 'FoundationOne CDx': 'F1CDX', 'FoundationOne Liquid CDx': 'F1LCDX', 'FoundationOne Heme': 'F1HEME', 'FoundationACT': 'FACT' }; return mapping[panelName] || 'F1CDX'; } private mapFromFMIOrder(fmiOrder: any): GenomicTestOrder { return { orderId: fmiOrder.externalOrderId || fmiOrder.id, patientId: fmiOrder.patient?.externalId, testType: 'comprehensive-genomic-profiling', panelName: this.mapFMICodeToPanel(fmiOrder.test?.code), specimenType: fmiOrder.specimen?.type || 'tissue', specimenId: fmiOrder.specimen?.externalId, orderDate: new Date(fmiOrder.createdAt), clinicalIndication: fmiOrder.diagnosis?.clinicalHistory || '', icdCodes: fmiOrder.diagnosis?.icdCodes || [], orderingPhysician: { name: fmiOrder.orderingPhysician?.name || '', npi: fmiOrder.orderingPhysician?.npi || '', facility: fmiOrder.orderingPhysician?.facility || '' }, status: this.mapFMIStatus(fmiOrder.status) }; } private mapFMICodeToPanel(code: string): string { const mapping: Record = { 'F1CDX': 'FoundationOne CDx', 'F1LCDX': 'FoundationOne Liquid CDx', 'F1HEME': 'FoundationOne Heme', 'FACT': 'FoundationACT' }; return mapping[code] || 'FoundationOne CDx'; } private mapFMIStatus(status: string): GenomicTestOrder['status'] { const mapping: Record = { 'ORDERED': 'ordered', 'SPECIMEN_RECEIVED': 'specimen-received', 'IN_PROCESS': 'in-process', 'COMPLETE': 'completed', 'FAILED': 'failed', 'CANCELLED': 'cancelled' }; return mapping[status] || 'ordered'; } private mapFromFMIReport(fmiReport: any, orderId: string): GenomicTestResult { const variants: GenomicVariant[] = (fmiReport.shortVariants || []).map((v: any) => ({ gene: v.gene, hgvsC: v.cdsEffect, hgvsP: v.proteinEffect, transcript: v.transcript, variantType: this.mapVariantType(v.variantType), variantAlleleFrequency: v.alleleFrequency || 0, coverage: v.depth, clinicalSignificance: this.mapPathogenicity(v.pathogenicity), tier: this.mapTier(v.tier), actionability: v.therapies ? { level: v.fdaApproved ? 'FDA-approved' : 'clinical-evidence', therapies: v.therapies, evidence: v.evidenceSummary ? [v.evidenceSummary] : [] } : undefined })); const cnvs: CopyNumberAlteration[] = (fmiReport.copyNumberAlterations || []).map((c: any) => ({ gene: c.gene, type: c.type?.toLowerCase() === 'amplification' ? 'amplification' : 'deep-deletion', copyNumber: c.copyNumber, clinicalSignificance: this.mapPathogenicity(c.pathogenicity), actionability: c.therapies ? { level: c.fdaApproved ? 'FDA-approved' : 'clinical-evidence', therapies: c.therapies } : undefined })); const fusions: GeneFusion[] = (fmiReport.rearrangements || []).map((r: any) => ({ gene5Prime: r.gene1, gene3Prime: r.gene2, fusionName: `${r.gene1}-${r.gene2}`, inFrame: r.inFrame, clinicalSignificance: this.mapPathogenicity(r.pathogenicity), actionability: r.therapies ? { level: r.fdaApproved ? 'FDA-approved' : 'clinical-evidence', therapies: r.therapies } : undefined })); return { reportId: fmiReport.reportId || fmiReport.id, orderId, patientId: fmiReport.patient?.externalId, testType: 'comprehensive-genomic-profiling', panelName: this.mapFMICodeToPanel(fmiReport.testCode), specimenInfo: { type: fmiReport.specimen?.type || 'tissue', site: fmiReport.specimen?.site, collectionDate: new Date(fmiReport.specimen?.collectionDate || Date.now()), tumorPurity: fmiReport.specimen?.tumorPurity, cellularity: fmiReport.specimen?.cellularity }, reportDate: new Date(fmiReport.reportDate || Date.now()), variants, copyNumberAlterations: cnvs, fusions, biomarkers: [], therapyMatches: (fmiReport.therapyMatches || []).map((t: any) => ({ therapy: t.therapy, drugs: t.drugs || [t.therapy], biomarkers: t.biomarkers || [], evidenceLevel: t.fdaApproved ? 'FDA-approved' : 'clinical-evidence', cancerType: t.indication || '', references: t.references || [] })), clinicalTrialMatches: (fmiReport.clinicalTrials || []).map((ct: any) => ({ trialId: ct.nctId, title: ct.title, phase: ct.phase, matchingBiomarkers: ct.matchingBiomarkers || [], status: ct.status || 'recruiting' })), signatures: { microsatelliteInstability: fmiReport.msi ? { status: fmiReport.msi.status, score: fmiReport.msi.score, method: 'NGS' } : undefined, tumorMutationalBurden: fmiReport.tmb ? { value: fmiReport.tmb.score, unit: 'mutations/Mb', status: fmiReport.tmb.score >= 10 ? 'high' : fmiReport.tmb.score >= 6 ? 'intermediate' : 'low', threshold: 10, percentile: fmiReport.tmb.percentile } : undefined, lossOfHeterozygosity: fmiReport.loh ? { percentage: fmiReport.loh.percentage, status: fmiReport.loh.percentage >= 16 ? 'high' : 'low', genomeFraction: fmiReport.loh.genomeFraction } : undefined }, qualityMetrics: { meanCoverage: fmiReport.qc?.meanCoverage, percentBases100x: fmiReport.qc?.percentBases100x, tumorFraction: fmiReport.qc?.tumorFraction } }; } private mapVariantType(type: string): GenomicVariant['variantType'] { const mapping: Record = { 'SNV': 'SNV', 'INSERTION': 'insertion', 'DELETION': 'deletion', 'INDEL': 'indel', 'MNV': 'MNV' }; return mapping[type?.toUpperCase()] || 'SNV'; } private mapPathogenicity(path: string): GenomicVariant['clinicalSignificance'] { const mapping: Record = { 'PATHOGENIC': 'pathogenic', 'LIKELY_PATHOGENIC': 'likely-pathogenic', 'VUS': 'vus', 'LIKELY_BENIGN': 'likely-benign', 'BENIGN': 'benign' }; return mapping[path?.toUpperCase()] || 'vus'; } private mapTier(tier: string): GenomicVariant['tier'] { if (tier === '1' || tier === 'I') return 'I'; if (tier === '2' || tier === 'II') return 'II'; if (tier === '3' || tier === 'III') return 'III'; return 'IV'; } } // ═══════════════════════════════════════════════════════════════════════════════ // GUARDANT HEALTH CLIENT // ═══════════════════════════════════════════════════════════════════════════════ export class GuardantHealthClient extends GenomicPlatformClient { constructor(config: Omit) { super({ ...config, platform: 'guardant' }); } async authenticate(): Promise { // Guardant uses API key authentication if (!this.config.apiKey) { throw new Error('Guardant Health API requires an API key'); } // No token fetch needed for API key auth } async submitOrder(order: GenomicTestOrder): Promise<{ orderId: string; status: string }> { const url = `${this.config.apiBaseUrl}/v2/orders`; const guardantOrder = { externalOrderId: order.orderId, patient: { externalId: order.patientId }, test: this.mapPanelToGuardantTest(order.panelName), specimen: { type: 'blood', // Guardant is primarily liquid biopsy collectionDate: new Date().toISOString() }, diagnosis: { icdCodes: order.icdCodes, cancerType: order.clinicalIndication }, orderingProvider: { name: order.orderingPhysician.name, npi: order.orderingPhysician.npi, organization: order.orderingPhysician.facility } }; const response = await this.httpRequest(url, { method: 'POST', headers: { ...await this.getAuthHeaders() }, body: JSON.stringify(guardantOrder) }); const result = JSON.parse(response); return { orderId: result.orderId, status: 'ordered' }; } async getOrderStatus(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v2/orders/${orderId}`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const data = JSON.parse(response); return this.mapFromGuardantOrder(data); } async getResults(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v2/orders/${orderId}/results`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const data = JSON.parse(response); return this.mapFromGuardantReport(data, orderId); } async listPatientResults(patientId: string): Promise { const url = `${this.config.apiBaseUrl}/v2/patients/${patientId}/results`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const reports = JSON.parse(response); return reports.map((r: any) => this.mapFromGuardantReport(r, r.orderId)); } /** * Get Guardant360 specific metrics including ctDNA fraction */ async getGuardant360Metrics(orderId: string): Promise<{ ctDNAFraction: number; maxMAF: number; somatic: GenomicVariant[]; clonalHematopoiesis: GenomicVariant[]; msi: MSIResult; }> { const result = await this.getResults(orderId); // Filter for clonal hematopoiesis variants (common in blood-based testing) const chVariants = result.variants.filter(v => ['DNMT3A', 'TET2', 'ASXL1', 'PPM1D', 'TP53', 'SF3B1', 'SRSF2'].includes(v.gene) && v.variantAlleleFrequency < 0.1 ); const somaticVariants = result.variants.filter(v => !chVariants.includes(v) ); return { ctDNAFraction: result.qualityMetrics.tumorFraction || 0, maxMAF: Math.max(...result.variants.map(v => v.variantAlleleFrequency), 0), somatic: somaticVariants, clonalHematopoiesis: chVariants, msi: result.signatures?.microsatelliteInstability || { status: 'MSS', method: 'NGS' } }; } private mapPanelToGuardantTest(panelName: string): string { const mapping: Record = { 'Guardant360': 'G360', 'Guardant360 CDx': 'G360CDX', 'GuardantOMNI': 'GOMNI', 'Guardant360 TissueNext': 'G360TN', 'GuardantReveal': 'GREVEAL' }; return mapping[panelName] || 'G360'; } private mapFromGuardantOrder(data: any): GenomicTestOrder { return { orderId: data.externalOrderId || data.orderId, patientId: data.patient?.externalId, testType: 'liquid-biopsy', panelName: 'Guardant360', specimenType: 'blood', specimenId: data.specimen?.id, orderDate: new Date(data.orderDate), clinicalIndication: data.diagnosis?.cancerType || '', icdCodes: data.diagnosis?.icdCodes || [], orderingPhysician: { name: data.orderingProvider?.name || '', npi: data.orderingProvider?.npi || '', facility: data.orderingProvider?.organization || '' }, status: this.mapGuardantStatus(data.status) }; } private mapGuardantStatus(status: string): GenomicTestOrder['status'] { const mapping: Record = { 'ORDERED': 'ordered', 'RECEIVED': 'specimen-received', 'PROCESSING': 'in-process', 'COMPLETE': 'completed', 'FAILED': 'failed', 'CANCELLED': 'cancelled' }; return mapping[status?.toUpperCase()] || 'ordered'; } private mapFromGuardantReport(data: any, orderId: string): GenomicTestResult { const variants: GenomicVariant[] = (data.alterations || []) .filter((a: any) => a.type === 'SNV' || a.type === 'INDEL') .map((v: any) => ({ gene: v.gene, hgvsP: v.proteinChange, hgvsC: v.cdsChange, variantType: v.type === 'INDEL' ? 'indel' : 'SNV', variantAlleleFrequency: v.plasmaAF || v.af || 0, clinicalSignificance: 'likely-pathogenic', actionability: v.therapies ? { level: v.fdaApproved ? 'FDA-approved' : 'clinical-evidence', therapies: v.therapies, evidence: [] } : undefined })); const cnvs: CopyNumberAlteration[] = (data.alterations || []) .filter((a: any) => a.type === 'AMPLIFICATION' || a.type === 'LOSS') .map((c: any) => ({ gene: c.gene, type: c.type === 'AMPLIFICATION' ? 'amplification' : 'deep-deletion', copyNumber: c.copyNumber, clinicalSignificance: 'likely-pathogenic' })); const fusions: GeneFusion[] = (data.alterations || []) .filter((a: any) => a.type === 'FUSION') .map((f: any) => ({ gene5Prime: f.gene.split('-')[0] || f.gene, gene3Prime: f.gene.split('-')[1] || f.partner, fusionName: f.gene, clinicalSignificance: 'pathogenic' })); return { reportId: data.reportId, orderId, patientId: data.patient?.externalId, testType: 'liquid-biopsy', panelName: 'Guardant360', specimenInfo: { type: 'blood', collectionDate: new Date(data.collectionDate || Date.now()), tumorPurity: data.ctDNAFraction }, reportDate: new Date(data.reportDate || Date.now()), variants, copyNumberAlterations: cnvs, fusions, biomarkers: [], therapyMatches: (data.therapyAssociations || []).map((t: any) => ({ therapy: t.therapy, drugs: t.drugs || [t.therapy], biomarkers: [t.biomarker], evidenceLevel: t.level || 'clinical-evidence', cancerType: t.indication || '', references: t.references || [] })), clinicalTrialMatches: [], signatures: { microsatelliteInstability: data.msi ? { status: data.msi.status, method: 'NGS' } : undefined, tumorMutationalBurden: data.bTMB ? { value: data.bTMB.score, unit: 'mutations/Mb', status: data.bTMB.score >= 16 ? 'high' : 'low', threshold: 16 } : undefined }, qualityMetrics: { tumorFraction: data.ctDNAFraction, meanCoverage: data.qc?.meanCoverage } }; } } // ═══════════════════════════════════════════════════════════════════════════════ // TEMPUS CLIENT // ═══════════════════════════════════════════════════════════════════════════════ export class TempusClient extends GenomicPlatformClient { constructor(config: Omit) { super({ ...config, platform: 'tempus' }); } async authenticate(): Promise { const tokenUrl = `${this.config.apiBaseUrl}/auth/token`; const response = await this.httpRequest(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: this.config.clientId, client_secret: this.config.clientSecret, grant_type: 'client_credentials' }) }); const data = JSON.parse(response); this.accessToken = data.access_token; this.tokenExpiry = new Date(Date.now() + (data.expires_in * 1000)); } async submitOrder(order: GenomicTestOrder): Promise<{ orderId: string; status: string }> { const url = `${this.config.apiBaseUrl}/v1/orders`; const tempusOrder = { externalId: order.orderId, patient: { externalId: order.patientId }, testCode: this.mapPanelToTempusCode(order.panelName), specimen: { type: order.specimenType, externalId: order.specimenId }, indication: { codes: order.icdCodes, description: order.clinicalIndication }, provider: { name: order.orderingPhysician.name, npi: order.orderingPhysician.npi, facility: order.orderingPhysician.facility } }; const response = await this.httpRequest(url, { method: 'POST', headers: await this.getAuthHeaders(), body: JSON.stringify(tempusOrder) }); const result = JSON.parse(response); return { orderId: result.id, status: 'ordered' }; } async getOrderStatus(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/orders/${orderId}`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const data = JSON.parse(response); return this.mapFromTempusOrder(data); } async getResults(orderId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/orders/${orderId}/report`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const data = JSON.parse(response); return this.mapFromTempusReport(data, orderId); } async listPatientResults(patientId: string): Promise { const url = `${this.config.apiBaseUrl}/v1/patients/${patientId}/reports`; const response = await this.httpRequest(url, { method: 'GET', headers: await this.getAuthHeaders() }); const reports = JSON.parse(response); return reports.map((r: any) => this.mapFromTempusReport(r, r.orderId)); } /** * Get Tempus xT/xF specific analysis including RNA expression */ async getTempusAnalysis(orderId: string): Promise<{ dnaFindings: GenomicVariant[]; rnaExpression?: { gene: string; zscore: number; percentile: number }[]; immuneProfile?: { pdl1: { score: number; method: string }; tils: number; immuneScore: number; }; hrd: HRDResult; }> { const result = await this.getResults(orderId); // Tempus provides RNA expression data for xT panel let rnaExpression; if (result.biomarkers.some(b => b.name.toLowerCase().includes('expression'))) { rnaExpression = result.biomarkers .filter(b => b.name.toLowerCase().includes('expression')) .map(b => ({ gene: b.name.replace(' expression', ''), zscore: typeof b.value === 'number' ? b.value : 0, percentile: 50 // Would come from actual data })); } return { dnaFindings: result.variants, rnaExpression, immuneProfile: result.biomarkers.some(b => b.name === 'PD-L1') ? { pdl1: { score: Number(result.biomarkers.find(b => b.name === 'PD-L1')?.value || 0), method: 'IHC' }, tils: Number(result.biomarkers.find(b => b.name === 'TILs')?.value || 0), immuneScore: 0 } : undefined, hrd: result.signatures?.homologousRecombinationDeficiency || { status: 'indeterminate' } }; } private mapPanelToTempusCode(panelName: string): string { const mapping: Record = { 'Tempus xT': 'XT', 'Tempus xF': 'XF', 'Tempus xR': 'XR', 'Tempus xG': 'XG', 'Tempus xE': 'XE' }; return mapping[panelName] || 'XT'; } private mapFromTempusOrder(data: any): GenomicTestOrder { return { orderId: data.externalId || data.id, patientId: data.patient?.externalId, testType: 'comprehensive-genomic-profiling', panelName: this.mapTempusCodeToPanel(data.testCode), specimenType: data.specimen?.type || 'tissue', specimenId: data.specimen?.externalId, orderDate: new Date(data.createdAt), clinicalIndication: data.indication?.description || '', icdCodes: data.indication?.codes || [], orderingPhysician: { name: data.provider?.name || '', npi: data.provider?.npi || '', facility: data.provider?.facility || '' }, status: this.mapTempusStatus(data.status) }; } private mapTempusCodeToPanel(code: string): string { const mapping: Record = { 'XT': 'Tempus xT', 'XF': 'Tempus xF', 'XR': 'Tempus xR', 'XG': 'Tempus xG', 'XE': 'Tempus xE' }; return mapping[code] || 'Tempus xT'; } private mapTempusStatus(status: string): GenomicTestOrder['status'] { const mapping: Record = { 'ordered': 'ordered', 'received': 'specimen-received', 'processing': 'in-process', 'completed': 'completed', 'failed': 'failed', 'cancelled': 'cancelled' }; return mapping[status?.toLowerCase()] || 'ordered'; } private mapFromTempusReport(data: any, orderId: string): GenomicTestResult { // Map Tempus report format to our common format const variants: GenomicVariant[] = (data.somaticVariants || []).map((v: any) => ({ gene: v.gene, hgvsP: v.proteinChange, hgvsC: v.codingChange, transcript: v.transcript, variantType: v.type || 'SNV', variantAlleleFrequency: v.vaf || 0, coverage: v.depth, clinicalSignificance: v.pathogenicity || 'vus', tier: v.tier, oncogenicity: v.oncogenicity, functionalEffect: v.functionalEffect, somaticStatus: 'somatic' })); return { reportId: data.reportId || data.id, orderId, patientId: data.patient?.externalId, testType: 'comprehensive-genomic-profiling', panelName: this.mapTempusCodeToPanel(data.testCode), specimenInfo: { type: data.specimen?.type || 'tissue', site: data.specimen?.site, collectionDate: new Date(data.specimen?.collectionDate || Date.now()), tumorPurity: data.specimen?.tumorContent }, reportDate: new Date(data.reportDate || Date.now()), variants, copyNumberAlterations: (data.copyNumberVariants || []).map((c: any) => ({ gene: c.gene, type: c.type, copyNumber: c.copyNumber, clinicalSignificance: c.pathogenicity || 'vus' })), fusions: (data.fusions || []).map((f: any) => ({ gene5Prime: f.gene1, gene3Prime: f.gene2, fusionName: `${f.gene1}-${f.gene2}`, inFrame: f.inFrame, clinicalSignificance: f.pathogenicity || 'pathogenic' })), biomarkers: (data.biomarkers || []).map((b: any) => ({ name: b.name, value: b.value, unit: b.unit, status: b.status, method: b.method })), therapyMatches: (data.therapyOptions || []).map((t: any) => ({ therapy: t.name, drugs: t.drugs || [t.name], biomarkers: t.biomarkers || [], evidenceLevel: t.evidenceLevel || 'clinical-evidence', cancerType: t.indication || '', references: t.references || [] })), clinicalTrialMatches: (data.clinicalTrials || []).map((ct: any) => ({ trialId: ct.nctNumber, title: ct.title, phase: ct.phase, matchingBiomarkers: ct.matchingBiomarkers || [], status: ct.status || 'recruiting', locations: ct.sites })), signatures: { microsatelliteInstability: data.msi, tumorMutationalBurden: data.tmb ? { value: data.tmb.score, unit: 'mutations/Mb', status: data.tmb.score >= 10 ? 'high' : 'low', threshold: 10 } : undefined, homologousRecombinationDeficiency: data.hrd }, qualityMetrics: data.qcMetrics }; } } // ═══════════════════════════════════════════════════════════════════════════════ // UNIFIED GENOMICS SERVICE // ═══════════════════════════════════════════════════════════════════════════════ export class UnifiedGenomicsService { private clients: Map = new Map(); /** * Register a genomic platform client */ registerClient(name: string, client: GenomicPlatformClient): void { this.clients.set(name, client); } /** * Get results from all platforms for a patient */ async getAllPatientResults(patientId: string): Promise<{ platform: string; results: GenomicTestResult[]; }[]> { const allResults: { platform: string; results: GenomicTestResult[] }[] = []; for (const [platform, client] of this.clients) { try { const results = await client.listPatientResults(patientId); allResults.push({ platform, results }); } catch (error) { console.error(`Failed to get results from ${platform}:`, error); } } return allResults; } /** * Aggregate and deduplicate variants across all platforms */ async getAggregatedVariants(patientId: string): Promise<{ variants: GenomicVariant[]; cnvs: CopyNumberAlteration[]; fusions: GeneFusion[]; biomarkers: { msi?: MSIResult; tmb?: TMBResult; hrd?: HRDResult; pdl1?: { score: number; scoreType: string }; }; }> { const allResults = await this.getAllPatientResults(patientId); const variantMap = new Map(); const cnvMap = new Map(); const fusionMap = new Map(); let latestMsi: MSIResult | undefined; let latestTmb: TMBResult | undefined; let latestHrd: HRDResult | undefined; let latestReportDate = new Date(0); for (const { results } of allResults) { for (const result of results) { // Track latest report for biomarkers if (result.reportDate > latestReportDate) { latestReportDate = result.reportDate; latestMsi = result.signatures?.microsatelliteInstability; latestTmb = result.signatures?.tumorMutationalBurden; latestHrd = result.signatures?.homologousRecombinationDeficiency; } // Deduplicate variants by gene + protein change for (const variant of result.variants) { const key = `${variant.gene}:${variant.hgvsP || variant.hgvsC}`; const existing = variantMap.get(key); // Keep the variant with higher VAF or better evidence if (!existing || variant.variantAlleleFrequency > existing.variantAlleleFrequency) { variantMap.set(key, variant); } } // Deduplicate CNVs for (const cnv of result.copyNumberAlterations) { const key = `${cnv.gene}:${cnv.type}`; if (!cnvMap.has(key)) { cnvMap.set(key, cnv); } } // Deduplicate fusions for (const fusion of result.fusions) { const key = fusion.fusionName; if (!fusionMap.has(key)) { fusionMap.set(key, fusion); } } } } return { variants: Array.from(variantMap.values()), cnvs: Array.from(cnvMap.values()), fusions: Array.from(fusionMap.values()), biomarkers: { msi: latestMsi, tmb: latestTmb, hrd: latestHrd } }; } /** * Match patient genomics to actionable therapies */ async matchToTherapies(patientId: string, cancerType: string): Promise { const genomics = await this.getAggregatedVariants(patientId); const therapyMatches: TherapyMatch[] = []; // FDA-approved biomarker-drug matches const fdaMatches = this.getFDAApprovedMatches(genomics, cancerType); therapyMatches.push(...fdaMatches); // NCCN guideline matches const nccnMatches = this.getNCCNMatches(genomics, cancerType); therapyMatches.push(...nccnMatches); // Deduplicate and sort by evidence level const evidenceOrder = { 'FDA-approved': 0, 'NCCN-guideline': 1, 'clinical-evidence': 2, 'case-report': 3, 'preclinical': 4 }; const uniqueMatches = new Map(); for (const match of therapyMatches) { const key = `${match.therapy}:${match.biomarkers.join(',')}`; const existing = uniqueMatches.get(key); if (!existing || evidenceOrder[match.evidenceLevel] < evidenceOrder[existing.evidenceLevel]) { uniqueMatches.set(key, match); } } return Array.from(uniqueMatches.values()) .sort((a, b) => evidenceOrder[a.evidenceLevel] - evidenceOrder[b.evidenceLevel]); } private getFDAApprovedMatches(genomics: { variants: GenomicVariant[]; cnvs: CopyNumberAlteration[]; fusions: GeneFusion[]; biomarkers: { msi?: MSIResult; tmb?: TMBResult; hrd?: HRDResult }; }, cancerType: string): TherapyMatch[] { const matches: TherapyMatch[] = []; // Check MSI-H for pembrolizumab (tumor-agnostic) if (genomics.biomarkers.msi?.status === 'MSI-H') { matches.push({ therapy: 'Pembrolizumab', drugs: ['Pembrolizumab'], biomarkers: ['MSI-H'], evidenceLevel: 'FDA-approved', cancerType: 'Tumor-agnostic', approvalStatus: 'FDA-approved for MSI-H/dMMR solid tumors', references: ['KEYNOTE-158', 'KEYNOTE-177'] }); } // Check TMB-H for pembrolizumab if (genomics.biomarkers.tmb?.status === 'high' && genomics.biomarkers.tmb.value >= 10) { matches.push({ therapy: 'Pembrolizumab', drugs: ['Pembrolizumab'], biomarkers: ['TMB-H (' + genomics.biomarkers.tmb.value + ' mut/Mb)'], evidenceLevel: 'FDA-approved', cancerType: 'Tumor-agnostic', approvalStatus: 'FDA-approved for TMB-H solid tumors', references: ['KEYNOTE-158'] }); } // Check NTRK fusions const ntrkFusion = genomics.fusions.find(f => f.gene5Prime.includes('NTRK') || f.gene3Prime.includes('NTRK') ); if (ntrkFusion) { matches.push({ therapy: 'Larotrectinib or Entrectinib', drugs: ['Larotrectinib', 'Entrectinib'], biomarkers: [ntrkFusion.fusionName], evidenceLevel: 'FDA-approved', cancerType: 'Tumor-agnostic', approvalStatus: 'FDA-approved for NTRK fusion-positive solid tumors', references: ['NAVIGATE', 'STARTRK-2'] }); } // Check BRAF V600E const brafV600 = genomics.variants.find(v => v.gene === 'BRAF' && v.hgvsP?.includes('V600') ); if (brafV600) { if (cancerType.toLowerCase().includes('melanoma')) { matches.push({ therapy: 'Dabrafenib + Trametinib', drugs: ['Dabrafenib', 'Trametinib'], biomarkers: ['BRAF V600E/K'], evidenceLevel: 'FDA-approved', cancerType: 'Melanoma', references: ['COMBI-d', 'COMBI-v'] }); } else if (cancerType.toLowerCase().includes('nsclc') || cancerType.toLowerCase().includes('lung')) { matches.push({ therapy: 'Dabrafenib + Trametinib', drugs: ['Dabrafenib', 'Trametinib'], biomarkers: ['BRAF V600E'], evidenceLevel: 'FDA-approved', cancerType: 'NSCLC', references: ['BRF113928'] }); } } // Check EGFR mutations const egfrMut = genomics.variants.find(v => v.gene === 'EGFR'); if (egfrMut && (cancerType.toLowerCase().includes('nsclc') || cancerType.toLowerCase().includes('lung'))) { matches.push({ therapy: 'Osimertinib', drugs: ['Osimertinib'], biomarkers: [`EGFR ${egfrMut.hgvsP || 'mutation'}`], evidenceLevel: 'FDA-approved', cancerType: 'NSCLC', references: ['FLAURA', 'ADAURA'] }); } // Check ALK fusions const alkFusion = genomics.fusions.find(f => f.gene5Prime === 'ALK' || f.gene3Prime === 'ALK' ); if (alkFusion && (cancerType.toLowerCase().includes('nsclc') || cancerType.toLowerCase().includes('lung'))) { matches.push({ therapy: 'Alectinib', drugs: ['Alectinib'], biomarkers: [alkFusion.fusionName], evidenceLevel: 'FDA-approved', cancerType: 'NSCLC', references: ['ALEX', 'J-ALEX'] }); } // Check HER2 amplification const her2Amp = genomics.cnvs.find(c => c.gene === 'HER2' || c.gene === 'ERBB2'); if (her2Amp && cancerType.toLowerCase().includes('breast')) { matches.push({ therapy: 'Trastuzumab + Pertuzumab', drugs: ['Trastuzumab', 'Pertuzumab'], biomarkers: ['HER2 amplification'], evidenceLevel: 'FDA-approved', cancerType: 'Breast', references: ['CLEOPATRA', 'APHINITY'] }); } // Check BRCA1/2 mutations const brcaMut = genomics.variants.find(v => (v.gene === 'BRCA1' || v.gene === 'BRCA2') && (v.clinicalSignificance === 'pathogenic' || v.clinicalSignificance === 'likely-pathogenic') ); if (brcaMut || genomics.biomarkers.hrd?.status === 'positive') { const biomarker = brcaMut ? `${brcaMut.gene} ${brcaMut.hgvsP || 'mutation'}` : 'HRD-positive'; if (cancerType.toLowerCase().includes('ovarian')) { matches.push({ therapy: 'Olaparib', drugs: ['Olaparib'], biomarkers: [biomarker], evidenceLevel: 'FDA-approved', cancerType: 'Ovarian', references: ['SOLO-1', 'PAOLA-1'] }); } else if (cancerType.toLowerCase().includes('breast')) { matches.push({ therapy: 'Olaparib or Talazoparib', drugs: ['Olaparib', 'Talazoparib'], biomarkers: [biomarker], evidenceLevel: 'FDA-approved', cancerType: 'Breast', references: ['OlympiAD', 'EMBRACA'] }); } else if (cancerType.toLowerCase().includes('prostate')) { matches.push({ therapy: 'Olaparib or Rucaparib', drugs: ['Olaparib', 'Rucaparib'], biomarkers: [biomarker], evidenceLevel: 'FDA-approved', cancerType: 'Prostate', references: ['PROfound', 'TRITON2'] }); } } // Check KRAS G12C const krasG12C = genomics.variants.find(v => v.gene === 'KRAS' && v.hgvsP?.includes('G12C') ); if (krasG12C) { if (cancerType.toLowerCase().includes('nsclc') || cancerType.toLowerCase().includes('lung')) { matches.push({ therapy: 'Sotorasib or Adagrasib', drugs: ['Sotorasib', 'Adagrasib'], biomarkers: ['KRAS G12C'], evidenceLevel: 'FDA-approved', cancerType: 'NSCLC', references: ['CodeBreaK 100', 'KRYSTAL-1'] }); } } return matches; } private getNCCNMatches(genomics: { variants: GenomicVariant[]; cnvs: CopyNumberAlteration[]; fusions: GeneFusion[]; biomarkers: { msi?: MSIResult; tmb?: TMBResult; hrd?: HRDResult }; }, cancerType: string): TherapyMatch[] { // Additional NCCN guideline-based matches would go here // This is a simplified version return []; } } // ═══════════════════════════════════════════════════════════════════════════════ // FACTORY FUNCTION // ═══════════════════════════════════════════════════════════════════════════════ export function createGenomicClient(config: GenomicPlatformConfig): GenomicPlatformClient { switch (config.platform) { case 'foundation-medicine': return new FoundationMedicineClient(config); case 'guardant': return new GuardantHealthClient(config); case 'tempus': return new TempusClient(config); default: throw new Error(`Unsupported genomic platform: ${config.platform}`); } } export default UnifiedGenomicsService;