import { XMLParser } from 'fast-xml-parser' export const CWMP_VERSIONS: Record = { 'urn:dslforum-org:cwmp-1-0': '1.0', 'urn:dslforum-org:cwmp-1-1': '1.1', 'urn:dslforum-org:cwmp-1-2': '1.2', 'urn:dslforum-org:cwmp-1-3': '1.3', 'urn:dslforum-org:cwmp-1-4': '1.4', } const xmlParser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '$', textNodeName: '_', numberParseOptions: { leadingZeros: false, hex: false }, isArray: (name) => { const arrayTags = ['ParameterValueStruct', 'ParameterInfoStruct', 'EventStruct', 'string'] return arrayTags.includes(name) }, }) export interface SoapEnvelope { header: SoapHeader body: any cwmpVersion: string } export interface SoapHeader { id?: string holdRequests?: boolean noMoreRequests?: boolean } export interface CwmpMessage { type: string data: any } export function parseSoapXml(xml: string): SoapEnvelope { const parsed = xmlParser.parse(xml) const envelope = parsed['soap-env:Envelope'] || parsed['SOAP-ENV:Envelope'] || parsed['soapenv:Envelope'] || {} const header = envelope['soap-env:Header'] || envelope['SOAP-ENV:Header'] || envelope['soapenv:Header'] || {} const body = envelope['soap-env:Body'] || envelope['SOAP-ENV:Body'] || envelope['soapenv:Body'] || {} // Detect CWMP version from namespace let cwmpVersion = '1.0' for (const [, value] of Object.entries(envelope)) { if (typeof value === 'string' && value.startsWith('urn:dslforum-org:cwmp-')) { cwmpVersion = CWMP_VERSIONS[value] || '1.0' break } } const soapHeader: SoapHeader = {} const idNode = header['cwmp:ID'] || header['cwmp:Id'] if (idNode) { soapHeader.id = typeof idNode === 'string' ? idNode : idNode._ || idNode } return { header: soapHeader, body, cwmpVersion } } export function extractCwmpMessage(body: any): CwmpMessage | null { for (const key of Object.keys(body)) { if (key.startsWith('cwmp:')) { const type = key.replace('cwmp:', '') return { type, data: body[key] } } } // Detect SOAP Fault (CPE sends soap-env:Fault / SOAP-ENV:Fault when it cannot process a request) const faultKey = Object.keys(body).find( (k) => k.toLowerCase().endsWith(':fault') || k === 'Fault' ) if (faultKey) { return { type: 'Fault', data: body[faultKey] } } return null } export function buildSoapEnvelope(cwmpId: string | undefined, bodyContent: string): string { const id = cwmpId || Math.random().toString(36).substring(2, 10) return ` ${id} ${bodyContent} ` }