UNPKG

libxml2-wasm

Version:

WebAssembly-based libxml2 javascript wrapper

248 lines 11.9 kB
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; import { error, xmlCtxtSetErrorHandler, xmlDocGetRootElement, xmlDocSetRootElement, XmlError, xmlFreeDoc, xmlFreeNode, xmlFreeParserCtxt, XmlLibError, xmlNewDoc, xmlNewDocNode, xmlNewParserCtxt, xmlOutputBufferCreate, xmlReadMemory, xmlReadString, xmlSaveFormatFileTo, xmlXIncludeFreeContext, xmlXIncludeNewContext, xmlXIncludeProcessNode, xmlXIncludeSetErrorHandler, } from './libxml2.mjs'; import { XmlElement } from './nodes.mjs'; import { disposeBy, XmlDisposable } from './disposable.mjs'; export var ParseOption; (function (ParseOption) { ParseOption[ParseOption["XML_PARSE_DEFAULT"] = 0] = "XML_PARSE_DEFAULT"; /** recover on errors */ ParseOption[ParseOption["XML_PARSE_RECOVER"] = 1] = "XML_PARSE_RECOVER"; /** substitute entities */ ParseOption[ParseOption["XML_PARSE_NOENT"] = 2] = "XML_PARSE_NOENT"; /** load the external subset */ ParseOption[ParseOption["XML_PARSE_DTDLOAD"] = 4] = "XML_PARSE_DTDLOAD"; /** default DTD attributes */ ParseOption[ParseOption["XML_PARSE_DTDATTR"] = 8] = "XML_PARSE_DTDATTR"; /** validate with the DTD */ ParseOption[ParseOption["XML_PARSE_DTDVALID"] = 16] = "XML_PARSE_DTDVALID"; /** suppress error reports */ ParseOption[ParseOption["XML_PARSE_NOERROR"] = 32] = "XML_PARSE_NOERROR"; /** suppress warning reports */ ParseOption[ParseOption["XML_PARSE_NOWARNING"] = 64] = "XML_PARSE_NOWARNING"; /** pedantic error reporting */ ParseOption[ParseOption["XML_PARSE_PEDANTIC"] = 128] = "XML_PARSE_PEDANTIC"; /** remove blank nodes */ ParseOption[ParseOption["XML_PARSE_NOBLANKS"] = 256] = "XML_PARSE_NOBLANKS"; /** use the SAX1 interface internally */ ParseOption[ParseOption["XML_PARSE_SAX1"] = 512] = "XML_PARSE_SAX1"; /** Implement XInclude substitution */ ParseOption[ParseOption["XML_PARSE_XINCLUDE"] = 1024] = "XML_PARSE_XINCLUDE"; /** Forbid network access */ ParseOption[ParseOption["XML_PARSE_NONET"] = 2048] = "XML_PARSE_NONET"; /** Do not reuse the context dictionary */ ParseOption[ParseOption["XML_PARSE_NODICT"] = 4096] = "XML_PARSE_NODICT"; /** remove redundant namespaces declarations */ ParseOption[ParseOption["XML_PARSE_NSCLEAN"] = 8192] = "XML_PARSE_NSCLEAN"; /** merge CDATA as text nodes */ ParseOption[ParseOption["XML_PARSE_NOCDATA"] = 16384] = "XML_PARSE_NOCDATA"; /** do not generate XINCLUDE START/END nodes */ ParseOption[ParseOption["XML_PARSE_NOXINCNODE"] = 32768] = "XML_PARSE_NOXINCNODE"; /** compact small text nodes; * no modification of the tree allowed afterward * (will possibly crash if you try to modify the tree) */ ParseOption[ParseOption["XML_PARSE_COMPACT"] = 65536] = "XML_PARSE_COMPACT"; /** parse using XML-1.0 before update 5 */ ParseOption[ParseOption["XML_PARSE_OLD10"] = 131072] = "XML_PARSE_OLD10"; /** do not fixup XINCLUDE xml:base uris */ ParseOption[ParseOption["XML_PARSE_NOBASEFIX"] = 262144] = "XML_PARSE_NOBASEFIX"; /** relax any hardcoded limit from the parser */ ParseOption[ParseOption["XML_PARSE_HUGE"] = 524288] = "XML_PARSE_HUGE"; /* parse using SAX2 interface before 2.7.0 */ ParseOption[ParseOption["XML_PARSE_OLDSAX"] = 1048576] = "XML_PARSE_OLDSAX"; /** ignore internal document encoding hint */ ParseOption[ParseOption["XML_PARSE_IGNORE_ENC"] = 2097152] = "XML_PARSE_IGNORE_ENC"; /** Store big lines numbers in text PSVI field */ ParseOption[ParseOption["XML_PARSE_BIG_LINES"] = 4194304] = "XML_PARSE_BIG_LINES"; })(ParseOption || (ParseOption = {})); export class XmlParseError extends XmlLibError { } function parse(parser, source, url, options) { const ctxt = xmlNewParserCtxt(); const parseErr = error.storage.allocate([]); xmlCtxtSetErrorHandler(ctxt, error.errorCollector, parseErr); const xml = parser(ctxt, source, url, null, options.option ?? ParseOption.XML_PARSE_DEFAULT); try { if (!xml) { const errDetails = error.storage.get(parseErr); throw new XmlParseError(errDetails.map((d) => d.message).join(''), errDetails); } } finally { error.storage.free(parseErr); xmlFreeParserCtxt(ctxt); } const incErr = error.storage.allocate([]); const xinc = xmlXIncludeNewContext(xml); xmlXIncludeSetErrorHandler(xinc, error.errorCollector, incErr); try { if (xmlXIncludeProcessNode(xinc, xml) < 0) { const errDetails = error.storage.get(incErr); throw new XmlParseError(errDetails.map((d) => d.message).join(''), errDetails); } } finally { error.storage.free(incErr); xmlXIncludeFreeContext(xinc); } return XmlDocument.getInstance(xml); } /** * The XML document. */ let XmlDocument = (() => { let _classDecorators = [disposeBy(xmlFreeDoc)]; let _classDescriptor; let _classExtraInitializers = []; let _classThis; let _classSuper = XmlDisposable; var XmlDocument = _classThis = class extends _classSuper { /** Create a new document from scratch. * To parse an existing xml, use {@link fromBuffer} or {@link fromString}. */ static create() { return XmlDocument.getInstance(xmlNewDoc()); } /** * Parse and create an {@link XmlDocument} from an XML string. * @param source The XML string * @param options Parsing options */ static fromString(source, options = {}) { return parse(xmlReadString, source, options.url ?? null, options); } /** * Parse and create an {@link XmlDocument} from an XML buffer. * @param source The XML buffer * @param options Parsing options */ static fromBuffer(source, options = {}) { return parse(xmlReadMemory, source, options.url ?? null, options); } /** * Save the XmlDocument to a string * @param options options to adjust the saving behavior */ toString(options) { const decoder = new TextDecoder(); const handler = { result: '', write(buf) { this.result += decoder.decode(buf); return buf.length; }, close() { return true; }, }; this.toBuffer(handler, options); return handler.result; } /** * Save the XmlDocument to a buffer and invoke the callbacks to process. * * @param handler handlers to process the content in the buffer * @param options options to adjust the saving behavior */ toBuffer(handler, options) { const buf = xmlOutputBufferCreate(handler); xmlSaveFormatFileTo(buf, this._ptr, null, options?.format ?? true ? 1 : 0); } get(xpath, namespaces) { return this.root.get(xpath, namespaces); } find(xpath, namespaces) { return this.root.find(xpath, namespaces); } /** * The root element of the document. * If the document is newly created and hasn’t been set up with a root, * an {@link XmlError} will be thrown. */ get root() { const root = xmlDocGetRootElement(this._ptr); if (!root) { // TODO: get error information from libxml2 throw new XmlError(); } return new XmlElement(root); } /** * Set the root element of the document. * @param value The new root. * If the node is from another document, * it and its subtree will be removed from the previous document. */ set root(value) { const old = xmlDocSetRootElement(this._ptr, value._nodePtr); if (old) { xmlFreeNode(old); } } /** * Create the root element. * @param name The name of the root element. * @param namespace The namespace of the root element. * @param prefix The prefix of the root node that represents the given namespace. * If not provided, the given namespace will be the default. */ createRoot(name, namespace, prefix) { const elem = xmlNewDocNode(this._ptr, 0, name); const root = new XmlElement(elem); if (namespace) { root.addLocalNamespace(namespace, prefix); root.namespacePrefix = prefix ?? ''; } this.root = root; return root; } }; __setFunctionName(_classThis, "XmlDocument"); (() => { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); XmlDocument = _classThis = _classDescriptor.value; if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); __runInitializers(_classThis, _classExtraInitializers); })(); return XmlDocument = _classThis; })(); export { XmlDocument }; //# sourceMappingURL=document.mjs.map