libxmq for javascript

The TypeScript
api.

libxmq for javascript: parse xmq into a W3C DOM, print a DOM as xmq and convert a DOM to json. A port of the Java implementation of libxmq (org.libxmq), which gives the same output as the C implementation.

Examples:LoadConfigFile.ts CreateDom.ts CreateHtml.ts CreateJson.ts DefaultNamespace.ts NamespacePrefixes.ts AddNamespace.ts

Functions

functionParse, print, render and convert.
parse(xmq, options?)Parse xmq into a new W3C Document.
function parse<D = Document>(xmq: string, options: ParseOptions & { dom?: DOMImplementationLike<D>; } = {}): D
Parse xmq into a new W3C Document. Entity references (eg &nbsp;) become text nodes whose text is the entity, which the library remembers (see entityName), since a W3C DOM cannot store entity references.

Parameters

xmq
The xmq text.
options
The DOM implementation, the source name for errors, the xml parser for embedded xml, the implicit root.

Returns

The document, of the type of the DOM implementation (Document in a browser).

Throws

XMQParseError
If the xmq cannot be parsed, with the same message as the C xmq.
XMQDomError
If the content cannot be stored in a Document, eg two root elements or text outside of the root element (give the root option).
Error
If there is no DOM implementation (node without the dom option).
attrParts(a)The parts of an attribute value that contains entity references, null if the attribute has no value, undefined if nothing is remembered (the value is plain text).
function attrParts(a: object): AttrPart[] | null | undefined
The parts of an attribute value that contains entity references, null if the attribute has no value, undefined if nothing is remembered (the value is plain text).
doctypeText(dt)The full doctype text that the parser read, or undefined.
function doctypeText(dt: object): string | undefined
The full doctype text that the parser read, or undefined.
entityName(n)The name of the entity (without & and ;) if the node is a text node that the parser created for an entity reference, otherwise null.
function entityName(n: object): string | null
The name of the entity (without & and ;) if the node is a text node that the parser created for an entity reference, otherwise null.
expandEntities(doc, options?)Expand the entities declared in the doctype of a document that parse made, like xmq FILE expand-entities (xmqExpandEntities in C).
function expandEntities(doc: DOMNodeLike, options: ExpandEntitiesOptions = {}): void
Expand the entities declared in the doctype of a document that parse made, like xmq FILE expand-entities (xmqExpandEntities in C). The document is changed: every reference to an entity declared in the internal subset, eg &logo; for <!ENTITY logo "<b>xmq</b>">, also inside an attribute value, is replaced by its replacement text parsed as xml content (text, elements, comments...), at the place of the reference, so the namespaces in scope there are used. The references inside the replacement text are expanded too. Character references (&#65;), undeclared entities (eg &nbsp; without a declaration) and external entities are kept. Adjacent texts are merged. The limits are those of C (libxml2): an entity loop, more than 19 nested entities, or an expansion beyond 1MB and five times the size of the xmq is an error; the references expanded before the error stay expanded. A document without a doctype that parse read is not changed.

Parameters

doc
The document.
options
The source name of the messages and a receiver of the warnings.

Throws

XmlParseError
If the doctype cannot be parsed or an entity cannot be expanded, the message is the one xmq prints after "xmq: ", eg "Detected an entity reference loop".
parseErrorToString(code)xmqParseErrorToString in C (src/main/c/parts/xmq_internals.c).
function parseErrorToString(code: ParseErrorCode): string
xmqParseErrorToString in C (src/main/c/parts/xmq_internals.c).
print(node, options?)Print a DOM node as xmq, like xmq FILE to-xmq: a document or a fragment with all its nodes, or a single node with its descendants, with compact: true in the compact form on one line.
function print(node: DOMNodeLike, options: PrintOptions = {}): string
Print a DOM node as xmq, like xmq FILE to-xmq: a document or a fragment with all its nodes, or a single node with its descendants, with compact: true in the compact form on one line. The text nodes that parse created for entities are printed as entities. A DOM that parse did not make, eg the page of a browser, is printed trimmed like xmq trims the xml and html it reads (see PrintOptions.trim), the elements of html with their lower case localName. A cdata section is text, one text with the text and cdata nodes next to it.

Parameters

node
The document, fragment, element or other node.
options
The indentation, the escapes and compact, as the to-xmq options of xmq.

Returns

The xmq text, without a final newline.
renderHtml(node, options?)Render a DOM node as syntax colored xmq in html, like xmq FILE render-html --nostyle: the xmq that print gives (the same options), inside a <pre class="xmq xmq_auto">, every part in an element of its kind, eg <xmqEN>car</xmqEN> for an element name, <xmqC> a comment, <xmqQ> a quote.
function renderHtml(node: DOMNodeLike, options: RenderHtmlOptions = {}): string
Render a DOM node as syntax colored xmq in html, like xmq FILE render-html --nostyle: the xmq that print gives (the same options), inside a <pre class="xmq xmq_auto">, every part in an element of its kind, eg <xmqEN>car</xmqEN> for an element name, <xmqC> a comment, <xmqQ> a quote. The colors come from the style sheet of renderHtmlStyle, add it once to the page. With the option page: true the result is a whole html page with the style sheet, like xmq FILE render-html.

Parameters

node
The document, fragment, element or other node.
options
The options of print, and theme, bg, id, class and page.

Returns

The html, without a final newline.

Throws

Error
If the theme is not valid.
renderHtmlStyle(options?)The css of the html rendering, like xmq render-html --onlystyle: the colors of the theme for the dark and the light background, following the preference of the browser (prefers-color-scheme) for the class xmq_auto, forced for xmq_dark and xmq_light.
function renderHtmlStyle(options: RenderHtmlOptions = {}): string
The css of the html rendering, like xmq render-html --onlystyle: the colors of the theme for the dark and the light background, following the preference of the browser (prefers-color-scheme) for the class xmq_auto, forced for xmq_dark and xmq_light. Put it in a <style> element of the page that shows the result of renderHtml.

Parameters

options
The theme.

Returns

The css.

Throws

Error
If the theme is not valid.
toJson(node, options?)Convert a DOM node to a javascript value with the json conventions of xmq, the value of the json that xmq FILE to-json prints: eg car { model = Volvo year = 1999 } gives { _: "car", model: "Volvo", year: 1999 }.
function toJson(node: DOMNodeLike, options: JsonOptions = {}): JsonValue | undefined
Convert a DOM node to a javascript value with the json conventions of xmq, the value of the json that xmq FILE to-json prints: eg car { model = Volvo year = 1999 } gives { _: "car", model: "Volvo", year: 1999 }. The root element name is "_", attributes are "_name", repeated names get [n], text among elements is "|", a comment "//". Numbers become numbers, true false null become booleans and null. A DOM that parse did not make is trimmed like print trims it. Where xmq prints text that is not one json value: a comment, text or entity at the top or in an array is an object with its key, eg { "//": "comment" }, and several values at the top (eg a processing instruction before the root element) are an array.

Parameters

node
The document, fragment or element.
options
trim, onWarning.

Returns

The value, undefined for an empty document.
tokenize(xmq, type, source?)The token output of xmq tokenize --type=debugtokens or --type=debugcontent, with the final newline that the command line prints.
function tokenize(xmq: string, type: TokenizeType, source: string = "-"): string
The token output of xmq tokenize --type=debugtokens or --type=debugcontent, with the final newline that the command line prints.

Throws

XMQParseError
If the xmq cannot be parsed.
tokenizeHtml(xmq, options?)Syntax color an xmq text without pretty printing it, like xmq FILE tokenize --type=html: the text exactly as it is (its whitespace, comments and quoting), every token in an element of its kind inside a <pre class="xmq xmq_auto">, the same elements as renderHtml.
function tokenizeHtml(xmq: string, options: TokenizeHtmlOptions = {}): string
Syntax color an xmq text without pretty printing it, like xmq FILE tokenize --type=html: the text exactly as it is (its whitespace, comments and quoting), every token in an element of its kind inside a <pre class="xmq xmq_auto">, the same elements as renderHtml. The colors come from the style sheet of renderHtmlStyle, add it once to the page. The text is only tokenized, not built into a DOM, so it needs no DOM and embedded xml is not parsed (it is colored as a value).

Parameters

xmq
The xmq text.
options
The source for the error messages, and theme, bg, id and class.

Returns

The html.

Throws

XMQParseError
If the xmq cannot be tokenized, the same message as xmq.
Error
If the text is xml, html or json, or the theme is not valid.
xmqToJson(xmq, options?)Parse xmq and convert it to a javascript value, toJson(parse(xmq, options), options).
function xmqToJson(xmq: string, options: ParseOptions & JsonOptions = {}): JsonValue | undefined
Parse xmq and convert it to a javascript value, toJson(parse(xmq, options), options).

Parameters

xmq
The xmq text.
options
The options of parse and of toJson.

Returns

The value, undefined for empty xmq.

Throws

XMQParseError,
XMQDomError, Error Like parse.

AttrPart

typeAn attribute value as its parts: text, or an entity reference.
type AttrPart = { text: string; } | { entity: string; };
An attribute value as its parts: text, or an entity reference.

DOMImplementationLike

interfaceA DOM implementation, the methods that parse uses: document.implementation of a browser, or eg the DOMImplementation of @xmldom/xmldom or jsdom.
interface DOMImplementationLike<D = Document>
A DOM implementation, the methods that parse uses: document.implementation of a browser, or eg the DOMImplementation of @xmldom/xmldom or jsdom. D is its document type.
createDocument(namespace, qualifiedName, doctype?)
createDocument(namespace: string | null, qualifiedName: string, doctype?: null): D;
createDocumentType(qualifiedName, publicId, systemId)
createDocumentType(qualifiedName: string, publicId: string, systemId: string): object;

DOMNodeLike

interfaceA DOM node, of the browser or of another DOM implementation (eg @xmldom/xmldom), whose types are not the DOM types of typescript.
interface DOMNodeLike
A DOM node, of the browser or of another DOM implementation (eg @xmldom/xmldom), whose types are not the DOM types of typescript. The nodes must have the W3C DOM api.
nodeType
readonly nodeType: number;

ExpandEntitiesOptions

interfaceThe options of expandEntities.
interface ExpandEntitiesOptions
The options of expandEntities.
sourceThe source name in the messages, default the source given to parse (C names the file that was read).
source?: string;
The source name in the messages, default the source given to parse (C names the file that was read).
onWarningReceives the warnings and recoverable errors of the xml parser, each a full report like the ones xmq prints to stderr, eg a namespace prefix that is not defined in a replacement text.
onWarning?: (message: string) => void;
Receives the warnings and recoverable errors of the xml parser, each a full report like the ones xmq prints to stderr, eg a namespace prefix that is not defined in a replacement text. Default: no warnings.

HtmlColorOptions

interfaceThe colors of the html: the options of renderHtml, renderHtmlStyle and tokenizeHtml.
interface HtmlColorOptions
The colors of the html: the options of renderHtml, renderHtmlStyle and tokenizeHtml.
themeThe colors, like --theme= of xmq: a list of NAME=#rrggbb separated by colons, with _B (bold) and _U (underline) after a color, eg "EN=#ff0000:EK=#00ff00_B".
theme?: string;
The colors, like --theme= of xmq: a list of NAME=#rrggbb separated by colons, with _B (bold) and _U (underline) after a color, eg "EN=#ff0000:EK=#00ff00_B". The names are C (comment), Q (quote), E (entity), NS (namespace), EN (element name), EK (element key), EKV (element value), AK (attribute key), AKV (attribute value), CP (compound parentheses), NSD (namespace declaration), UW (unicode whitespace), XSL (the xsl namespace), FG and BG (the text and background of the pre). A theme can start with dark+ or light+ to set the colors of one background only, and two themes can be given separated by a comma. The default colors are those of xmq.
bgThe background: "auto" (the default) follows the preference of the browser (prefers-color-scheme), "dark" and "light" force it (--bg=dark|light), the pre gets the class xmq_auto, xmq_dark or xmq_light.
bg?: "auto" | "dark" | "light";
The background: "auto" (the default) follows the preference of the browser (prefers-color-scheme), "dark" and "light" force it (--bg=dark|light), the pre gets the class xmq_auto, xmq_dark or xmq_light.
idThe id of the pre element (--id=).
id?: string;
The id of the pre element (--id=).
classAn extra class of the pre element (--class=).
class?: string;
An extra class of the pre element (--class=).

JsonOptions

interfaceThe options of toJson.
interface JsonOptions
The options of toJson.
trimTrim the whitespace like print does (see PrintOptions.trim).
trim?: boolean;
Trim the whitespace like print does (see PrintOptions.trim).
onWarningCalled with the warnings that xmq prints on stderr, eg when an element name is lost in a json array.
onWarning?: (message: string) => void;
Called with the warnings that xmq prints on stderr, eg when an element name is lost in a json array. Default: no warnings.

JsonValue

typeA json value.
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue; };
A json value.

ParseErrorCode

enumThe parse errors of the xmq parser, the same codes as XMQStatus in the C xmq.h and ParseErrorCode in Java, and the same messages as xmqParseErrorToString in C.
enum ParseErrorCode {
    XMQ_ERROR_NONE = 0,
    XMQ_ERROR_QUOTE_NOT_CLOSED = 4,
    XMQ_ERROR_ENTITY_NOT_CLOSED = 5,
    XMQ_ERROR_COMMENT_NOT_CLOSED = 6,
    XMQ_ERROR_COMMENT_CLOSED_WITH_TOO_MANY_SLASHES = 7,
    XMQ_ERROR_BODY_NOT_CLOSED = 8,
    XMQ_ERROR_ATTRIBUTES_NOT_CLOSED = 9,
    XMQ_ERROR_COMPOUND_NOT_CLOSED = 10,
    XMQ_ERROR_COMPOUND_MAY_NOT_CONTAIN = 11,
    XMQ_ERROR_QUOTE_CLOSED_WITH_TOO_MANY_QUOTES = 12,
    XMQ_ERROR_UNEXPECTED_CLOSING_BRACE = 13,
    XMQ_ERROR_EXPECTED_CONTENT_AFTER_EQUALS = 14,
    XMQ_ERROR_UNEXPECTED_TAB = 15,
    XMQ_ERROR_INVALID_CHAR = 16,
    XMQ_ERROR_BAD_DOCTYPE = 17,
    XMQ_ERROR_PARSING_XML = 28,
    XMQ_ERROR_VALUE_CANNOT_START_WITH = 30,
    XMQ_ERROR_XML_FRAGMENT_NOT_CLOSED = 37,
    XMQ_ERROR_TOO_DEEP = 40,
    XMQ_WARNING_QUOTES_NEEDED = 100
}
The parse errors of the xmq parser, the same codes as XMQStatus in the C xmq.h and ParseErrorCode in Java, and the same messages as xmqParseErrorToString in C.

ParseOptions

interfaceThe options of parse.
interface ParseOptions
The options of parse.
domThe DOM implementation that creates the document.
dom?: DOMImplementationLike<unknown>;
The DOM implementation that creates the document. In a browser the default is document.implementation, node has no DOM: pass eg new DOMImplementation() of
sourceWhere the xmq comes from, eg a file name, used in the error messages.
source?: string;
Where the xmq comes from, eg a file name, used in the error messages. Default "-".
xmlParserParses the xml fragments embedded in xmq (<b>bold</b>), default a new DOMParser if there is one (a browser).
xmlParser?: XmlTextParser;
Parses the xml fragments embedded in xmq (<b>bold</b>), default a new DOMParser if there is one (a browser). Without one an embedded fragment is an error.
rootThe implicit root element, like the --root option of the xmq command line: unless the first element of the xmq has this name, it and everything after it is placed inside a new root element with this name.
root?: string;
The implicit root element, like the --root option of the xmq command line: unless the first element of the xmq has this name, it and everything after it is placed inside a new root element with this name. Needed for xmq with several elements at the top level, eg a = 1 b = 2, since a W3C Document has only one root element.

PrintOptions

interfaceThe options of print, like the to-xmq options of the xmq command line.
interface PrintOptions
The options of print, like the to-xmq options of the xmq command line.
indentThe number of spaces to indent the content of an element, default 4 (--indent=n).
indent?: number;
The number of spaces to indent the content of an element, default 4 (--indent=n).
escapeNewlinesPrint newlines inside quotes as &#10; (--escape-newlines).
escapeNewlines?: boolean;
Print newlines inside quotes as &#10; (--escape-newlines).
escapeNon7bitPrint the characters above 126 as character references (--escape-non-7bit).
escapeNon7bit?: boolean;
Print the characters above 126 as character references (--escape-non-7bit).
compactPrint the compact form, on one line with as few spaces as possible, eg car{model=Volvo year=1999} (--compact).
compact?: boolean;
Print the compact form, on one line with as few spaces as possible, eg car{model=Volvo year=1999} (--compact). Newlines are always escaped as &#10;.
escapeTabsPrint tabs as &#9; (--escape-tabs).
escapeTabs?: boolean;
Print tabs as &#9; (--escape-tabs).
preferDoubleQuotesUse double quotes when single and double quotes are equally good (--prefer-double-quotes).
preferDoubleQuotes?: boolean;
Use double quotes when single and double quotes are equally good (--prefer-double-quotes).
trimTrim the whitespace like xmq does when it reads xml or html (the default --trim): skip the text nodes with only whitespace, remove the incidental indentation of the text and the comments, and the leading and ending spaces of the comments.
trim?: boolean;
Trim the whitespace like xmq does when it reads xml or html (the default --trim): skip the text nodes with only whitespace, remove the incidental indentation of the text and the comments, and the leading and ending spaces of the comments. The DOM is not changed. The default is to trim, unless the document was parsed from xmq by this library (xmq is never trimmed by C either).

RenderHtmlOptions

interfaceThe options of renderHtml and renderHtmlStyle, the render-html options of xmq.
interface RenderHtmlOptions extends PrintOptions, HtmlColorOptions
The options of renderHtml and renderHtmlStyle, the render-html options of xmq.
page
page?: boolean;

TokenizeHtmlOptions

interfaceThe options of tokenizeHtml.
interface TokenizeHtmlOptions extends HtmlColorOptions
The options of tokenizeHtml.
sourceWhere the xmq comes from, eg a file name, used in the error messages.
source?: string;
Where the xmq comes from, eg a file name, used in the error messages. Default "-".

TokenizeType

typeThe kinds of token output.
type TokenizeType = "debugtokens" | "debugcontent";
The kinds of token output.

XMQDomError

classThe xmq content cannot be stored in a W3C DOM: a Document has at most one element and no text, and the names must be valid xml names.
class XMQDomError extends Error
The xmq content cannot be stored in a W3C DOM: a Document has at most one element and no text, and the names must be valid xml names.
constructor(message)
constructor(message: string);

XMQParseError

classA parse error.
class XMQParseError extends Error
A parse error. The message is the same text as the C xmq prints (generate_state_error_message in C): source:line:col: error: what, followed by the line of the input and a ^ under the error. A warning that C prints before the error (perhaps you need more quotes) is part of the message.
codeThe error code.
readonly code: ParseErrorCode;
The error code.
lineThe line number, the first line is 1.
readonly line: number;
The line number, the first line is 1.
columnThe column in characters (code points), the first column is 1.
readonly column: number;
The column in characters (code points), the first column is 1.
sourceWhere the input came from, eg a file name, "stdin" or "-i argument".
readonly source: string;
Where the input came from, eg a file name, "stdin" or "-i argument".
constructor(code, message, line, column, source)
constructor(code: ParseErrorCode, message: string, line: number, column: number, source: string);

XmlParseError

classAn error of the xml parser (Java XmlParseException).
class XmlParseError extends Error
An error of the xml parser (Java XmlParseException). The message is the message of libxml2, eg "Detected an entity reference loop", which xmq prints after "xmq: ". The context is the full report, like libxml2 prints it: source:line: parser error : message, the line of the input and a ^ under the position.
contextThe full report with the source, the line and the ^.
readonly context: string;
The full report with the source, the line and the ^.
lineThe line of the error in the parsed text, the first line is 1.
readonly line: number;
The line of the error in the parsed text, the first line is 1.
constructor(message, context, line)
constructor(message: string, context: string, line: number);

XmlTextParser

interfaceSomething that can parse xml text, a DOMParser.
interface XmlTextParser
Something that can parse xml text, a DOMParser.
parseFromString(text, mimeType)Parse the xml text, the result must be a Document (of any DOM implementation).
parseFromString(text: string, mimeType: "text/xml"): object;
Parse the xml text, the result must be a Document (of any DOM implementation).