import { o as logger } from "./chunks/dav-Co9y-hkg.mjs"; import { q, F, s, N, t, P, c, l, m, n, a, g, p, b, r, d, h, f, k, j, e, i } from "./chunks/dav-Co9y-hkg.mjs"; import { getCapabilities } from "@nextcloud/capabilities"; import { extname, basename } from "path"; import { getCanonicalLocale, getLanguage } from "@nextcloud/l10n"; import { TypedEventTarget } from "typescript-event-target"; var NewMenuEntryCategory = /* @__PURE__ */ ((NewMenuEntryCategory2) => { NewMenuEntryCategory2[NewMenuEntryCategory2["UploadFromDevice"] = 0] = "UploadFromDevice"; NewMenuEntryCategory2[NewMenuEntryCategory2["CreateNew"] = 1] = "CreateNew"; NewMenuEntryCategory2[NewMenuEntryCategory2["Other"] = 2] = "Other"; return NewMenuEntryCategory2; })(NewMenuEntryCategory || {}); class NewFileMenu { _entries = []; registerEntry(entry) { this.validateEntry(entry); entry.category = entry.category ?? 1; this._entries.push(entry); } unregisterEntry(entry) { const entryIndex = typeof entry === "string" ? this.getEntryIndex(entry) : this.getEntryIndex(entry.id); if (entryIndex === -1) { logger.warn("Entry not found, nothing removed", { entry, entries: this.getEntries() }); return; } this._entries.splice(entryIndex, 1); } /** * Get the list of registered entries * * @param {Folder} context the creation context. Usually the current folder */ getEntries(context) { if (context) { return this._entries.filter((entry) => typeof entry.enabled === "function" ? entry.enabled(context) : true); } return this._entries; } getEntryIndex(id) { return this._entries.findIndex((entry) => entry.id === id); } validateEntry(entry) { if (!entry.id || !entry.displayName || !(entry.iconSvgInline || entry.iconClass) || !entry.handler) { throw new Error("Invalid entry"); } if (typeof entry.id !== "string" || typeof entry.displayName !== "string") { throw new Error("Invalid id or displayName property"); } if (entry.iconClass && typeof entry.iconClass !== "string" || entry.iconSvgInline && typeof entry.iconSvgInline !== "string") { throw new Error("Invalid icon provided"); } if (entry.enabled !== void 0 && typeof entry.enabled !== "function") { throw new Error("Invalid enabled property"); } if (typeof entry.handler !== "function") { throw new Error("Invalid handler property"); } if ("order" in entry && typeof entry.order !== "number") { throw new Error("Invalid order property"); } if (this.getEntryIndex(entry.id) !== -1) { throw new Error("Duplicate entry"); } } } const getNewFileMenu = function() { if (typeof window._nc_newfilemenu === "undefined") { window._nc_newfilemenu = new NewFileMenu(); logger.debug("NewFileMenu initialized"); } return window._nc_newfilemenu; }; var DefaultType = /* @__PURE__ */ ((DefaultType2) => { DefaultType2["DEFAULT"] = "default"; DefaultType2["HIDDEN"] = "hidden"; return DefaultType2; })(DefaultType || {}); class FileAction { _action; constructor(action) { this.validateAction(action); this._action = action; } get id() { return this._action.id; } get displayName() { return this._action.displayName; } get title() { return this._action.title; } get iconSvgInline() { return this._action.iconSvgInline; } get enabled() { return this._action.enabled; } get exec() { return this._action.exec; } get execBatch() { return this._action.execBatch; } get order() { return this._action.order; } get parent() { return this._action.parent; } get default() { return this._action.default; } get destructive() { return this._action.destructive; } get inline() { return this._action.inline; } get renderInline() { return this._action.renderInline; } validateAction(action) { if (!action.id || typeof action.id !== "string") { throw new Error("Invalid id"); } if (!action.displayName || typeof action.displayName !== "function") { throw new Error("Invalid displayName function"); } if ("title" in action && typeof action.title !== "function") { throw new Error("Invalid title function"); } if (!action.iconSvgInline || typeof action.iconSvgInline !== "function") { throw new Error("Invalid iconSvgInline function"); } if (!action.exec || typeof action.exec !== "function") { throw new Error("Invalid exec function"); } if ("enabled" in action && typeof action.enabled !== "function") { throw new Error("Invalid enabled function"); } if ("execBatch" in action && typeof action.execBatch !== "function") { throw new Error("Invalid execBatch function"); } if ("order" in action && typeof action.order !== "number") { throw new Error("Invalid order"); } if (action.destructive !== void 0 && typeof action.destructive !== "boolean") { throw new Error("Invalid destructive flag"); } if ("parent" in action && typeof action.parent !== "string") { throw new Error("Invalid parent"); } if (action.default && !Object.values(DefaultType).includes(action.default)) { throw new Error("Invalid default"); } if ("inline" in action && typeof action.inline !== "function") { throw new Error("Invalid inline function"); } if ("renderInline" in action && typeof action.renderInline !== "function") { throw new Error("Invalid renderInline function"); } } } const registerFileAction = function(action) { if (typeof window._nc_fileactions === "undefined") { window._nc_fileactions = []; logger.debug("FileActions initialized"); } if (window._nc_fileactions.find((search) => search.id === action.id)) { logger.error(`FileAction ${action.id} already registered`, { action }); return; } window._nc_fileactions.push(action); }; const getFileActions = function() { if (typeof window._nc_fileactions === "undefined") { window._nc_fileactions = []; logger.debug("FileActions initialized"); } return window._nc_fileactions; }; class FileListAction { _action; constructor(action) { this.validateAction(action); this._action = action; } get id() { return this._action.id; } get displayName() { return this._action.displayName; } get iconSvgInline() { return this._action.iconSvgInline; } get order() { return this._action.order; } get enabled() { return this._action.enabled; } get exec() { return this._action.exec; } validateAction(action) { if (!action.id || typeof action.id !== "string") { throw new Error("Invalid id"); } if (!action.displayName || typeof action.displayName !== "function") { throw new Error("Invalid displayName function"); } if ("iconSvgInline" in action && typeof action.iconSvgInline !== "function") { throw new Error("Invalid iconSvgInline function"); } if ("order" in action && typeof action.order !== "number") { throw new Error("Invalid order"); } if ("enabled" in action && typeof action.enabled !== "function") { throw new Error("Invalid enabled function"); } if (!action.exec || typeof action.exec !== "function") { throw new Error("Invalid exec function"); } } } const registerFileListAction = (action) => { if (typeof window._nc_filelistactions === "undefined") { window._nc_filelistactions = []; } if (window._nc_filelistactions.find((listAction) => listAction.id === action.id)) { logger.error(`FileListAction with id "${action.id}" is already registered`, { action }); return; } window._nc_filelistactions.push(action); }; const getFileListActions = () => { if (typeof window._nc_filelistactions === "undefined") { window._nc_filelistactions = []; } return window._nc_filelistactions; }; class Header { _header; constructor(header) { this.validateHeader(header); this._header = header; } get id() { return this._header.id; } get order() { return this._header.order; } get enabled() { return this._header.enabled; } get render() { return this._header.render; } get updated() { return this._header.updated; } validateHeader(header) { if (!header.id || !header.render || !header.updated) { throw new Error("Invalid header: id, render and updated are required"); } if (typeof header.id !== "string") { throw new Error("Invalid id property"); } if (header.enabled !== void 0 && typeof header.enabled !== "function") { throw new Error("Invalid enabled property"); } if (header.render && typeof header.render !== "function") { throw new Error("Invalid render property"); } if (header.updated && typeof header.updated !== "function") { throw new Error("Invalid updated property"); } } } const registerFileListHeaders = function(header) { if (typeof window._nc_filelistheader === "undefined") { window._nc_filelistheader = []; logger.debug("FileListHeaders initialized"); } if (window._nc_filelistheader.find((search) => search.id === header.id)) { logger.error(`Header ${header.id} already registered`, { header }); return; } window._nc_filelistheader.push(header); }; const getFileListHeaders = function() { if (typeof window._nc_filelistheader === "undefined") { window._nc_filelistheader = []; logger.debug("FileListHeaders initialized"); } return window._nc_filelistheader; }; var InvalidFilenameErrorReason = /* @__PURE__ */ ((InvalidFilenameErrorReason2) => { InvalidFilenameErrorReason2["ReservedName"] = "reserved name"; InvalidFilenameErrorReason2["Character"] = "character"; InvalidFilenameErrorReason2["Extension"] = "extension"; return InvalidFilenameErrorReason2; })(InvalidFilenameErrorReason || {}); class InvalidFilenameError extends Error { constructor(options) { super(`Invalid ${options.reason} '${options.segment}' in filename '${options.filename}'`, { cause: options }); } /** * The filename that was validated */ get filename() { return this.cause.filename; } /** * Reason why the validation failed */ get reason() { return this.cause.reason; } /** * Part of the filename that caused this error */ get segment() { return this.cause.segment; } } function validateFilename(filename) { const capabilities = getCapabilities().files; const forbiddenCharacters = capabilities.forbidden_filename_characters ?? window._oc_config?.forbidden_filenames_characters ?? ["/", "\\"]; for (const character of forbiddenCharacters) { if (filename.includes(character)) { throw new InvalidFilenameError({ segment: character, reason: "character", filename }); } } filename = filename.toLocaleLowerCase(); const forbiddenFilenames = capabilities.forbidden_filenames ?? [".htaccess"]; if (forbiddenFilenames.includes(filename)) { throw new InvalidFilenameError({ filename, segment: filename, reason: "reserved name" /* ReservedName */ }); } const endOfBasename = filename.indexOf(".", 1); const basename2 = filename.substring(0, endOfBasename === -1 ? void 0 : endOfBasename); const forbiddenFilenameBasenames = capabilities.forbidden_filename_basenames ?? []; if (forbiddenFilenameBasenames.includes(basename2)) { throw new InvalidFilenameError({ filename, segment: basename2, reason: "reserved name" /* ReservedName */ }); } const forbiddenFilenameExtensions = capabilities.forbidden_filename_extensions ?? [".part", ".filepart"]; for (const extension of forbiddenFilenameExtensions) { if (filename.length > extension.length && filename.endsWith(extension)) { throw new InvalidFilenameError({ segment: extension, reason: "extension", filename }); } } } function isFilenameValid(filename) { try { validateFilename(filename); return true; } catch (error) { if (error instanceof InvalidFilenameError) { return false; } throw error; } } function getUniqueName(name, otherNames, options) { const opts = { suffix: (n2) => `(${n2})`, ignoreFileExtension: false, ...options }; let newName = name; let i2 = 1; while (otherNames.includes(newName)) { const ext = opts.ignoreFileExtension ? "" : extname(name); const base = basename(name, ext); newName = `${base} ${opts.suffix(i2++)}${ext}`; } return newName; } const humanList = ["B", "KB", "MB", "GB", "TB", "PB"]; const humanListBinary = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; function formatFileSize(size, skipSmallSizes = false, binaryPrefixes = false, base1000 = false) { binaryPrefixes = binaryPrefixes && !base1000; if (typeof size === "string") { size = Number(size); } let order = size > 0 ? Math.floor(Math.log(size) / Math.log(base1000 ? 1e3 : 1024)) : 0; order = Math.min((binaryPrefixes ? humanListBinary.length : humanList.length) - 1, order); const readableFormat = binaryPrefixes ? humanListBinary[order] : humanList[order]; let relativeSize = (size / Math.pow(base1000 ? 1e3 : 1024, order)).toFixed(1); if (skipSmallSizes === true && order === 0) { return (relativeSize !== "0.0" ? "< 1 " : "0 ") + (binaryPrefixes ? humanListBinary[1] : humanList[1]); } if (order < 2) { relativeSize = parseFloat(relativeSize).toFixed(0); } else { relativeSize = parseFloat(relativeSize).toLocaleString(getCanonicalLocale()); } return relativeSize + " " + readableFormat; } function parseFileSize(value, forceBinary = false) { try { value = `${value}`.toLocaleLowerCase().replaceAll(/\s+/g, "").replaceAll(",", "."); } catch (e2) { return null; } const match = value.match(/^([0-9]*(\.[0-9]*)?)([kmgtp]?)(i?)b?$/); if (match === null || match[1] === "." || match[1] === "") { return null; } const bytesArray = { "": 0, k: 1, m: 2, g: 3, t: 4, p: 5, e: 6 }; const decimalString = `${match[1]}`; const base = match[4] === "i" || forceBinary ? 1024 : 1e3; return Math.round(Number.parseFloat(decimalString) * base ** bytesArray[match[3]]); } function stringify(value) { if (value instanceof Date) { return value.toISOString(); } return String(value); } function orderBy(collection, identifiers2, orders) { identifiers2 = identifiers2 ?? [(value) => value]; orders = orders ?? []; const sorting = identifiers2.map((_, index) => (orders[index] ?? "asc") === "asc" ? 1 : -1); const collator = Intl.Collator( [getLanguage(), getCanonicalLocale()], { // handle 10 as ten and not as one-zero numeric: true, usage: "sort" } ); return [...collection].sort((a2, b2) => { for (const [index, identifier] of identifiers2.entries()) { const value = collator.compare(stringify(identifier(a2)), stringify(identifier(b2))); if (value !== 0) { return value * sorting[index]; } } return 0; }); } var FilesSortingMode = /* @__PURE__ */ ((FilesSortingMode2) => { FilesSortingMode2["Name"] = "basename"; FilesSortingMode2["Modified"] = "mtime"; FilesSortingMode2["Size"] = "size"; return FilesSortingMode2; })(FilesSortingMode || {}); function sortNodes(nodes, options = {}) { const sortingOptions = { // Default to sort by name sortingMode: "basename", // Default to sort ascending sortingOrder: "asc", ...options }; const basename2 = (name) => name.lastIndexOf(".") > 0 ? name.slice(0, name.lastIndexOf(".")) : name; const identifiers2 = [ // 1: Sort favorites first if enabled ...sortingOptions.sortFavoritesFirst ? [(v) => v.attributes?.favorite !== 1] : [], // 2: Sort folders first if sorting by name ...sortingOptions.sortFoldersFirst ? [(v) => v.type !== "folder"] : [], // 3: Use sorting mode if NOT basename (to be able to use display name too) ...sortingOptions.sortingMode !== "basename" ? [(v) => v[sortingOptions.sortingMode]] : [], // 4: Use display name if available, fallback to name (v) => basename2(v.displayname || v.attributes?.displayname || v.basename), // 5: Finally, use basename if all previous sorting methods failed (v) => v.basename ]; const orders = [ // (for 1): always sort favorites before normal files ...sortingOptions.sortFavoritesFirst ? ["asc"] : [], // (for 2): always sort folders before files ...sortingOptions.sortFoldersFirst ? ["asc"] : [], // (for 3): Reverse if sorting by mtime as mtime higher means edited more recent -> lower ...sortingOptions.sortingMode === "mtime" ? [sortingOptions.sortingOrder === "asc" ? "desc" : "asc"] : [], // (also for 3 so make sure not to conflict with 2 and 3) ...sortingOptions.sortingMode !== "mtime" && sortingOptions.sortingMode !== "basename" ? [sortingOptions.sortingOrder] : [], // for 4: use configured sorting direction sortingOptions.sortingOrder, // for 5: use configured sorting direction sortingOptions.sortingOrder ]; return orderBy(nodes, identifiers2, orders); } class Navigation extends TypedEventTarget { _views = []; _currentView = null; /** * Register a new view on the navigation * @param view The view to register * @throws `Error` is thrown if a view with the same id is already registered */ register(view) { if (this._views.find((search) => search.id === view.id)) { throw new Error(`View id ${view.id} is already registered`); } this._views.push(view); this.dispatchTypedEvent("update", new CustomEvent("update")); } /** * Remove a registered view * @param id The id of the view to remove */ remove(id) { const index = this._views.findIndex((view) => view.id === id); if (index !== -1) { this._views.splice(index, 1); this.dispatchTypedEvent("update", new CustomEvent("update")); } } /** * Set the currently active view * @fires UpdateActiveViewEvent * @param view New active view */ setActive(view) { this._currentView = view; const event = new CustomEvent("updateActive", { detail: view }); this.dispatchTypedEvent("updateActive", event); } /** * The currently active files view */ get active() { return this._currentView; } /** * All registered views */ get views() { return this._views; } } const getNavigation = function() { if (typeof window._nc_navigation === "undefined") { window._nc_navigation = new Navigation(); logger.debug("Navigation service initialized"); } return window._nc_navigation; }; class Column { _column; constructor(column) { isValidColumn(column); this._column = column; } get id() { return this._column.id; } get title() { return this._column.title; } get render() { return this._column.render; } get sort() { return this._column.sort; } get summary() { return this._column.summary; } } const isValidColumn = function(column) { if (!column.id || typeof column.id !== "string") { throw new Error("A column id is required"); } if (!column.title || typeof column.title !== "string") { throw new Error("A column title is required"); } if (!column.render || typeof column.render !== "function") { throw new Error("A render function is required"); } if (column.sort && typeof column.sort !== "function") { throw new Error("Column sortFunction must be a function"); } if (column.summary && typeof column.summary !== "function") { throw new Error("Column summary must be a function"); } return true; }; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } var validator = {}; var util = {}; var hasRequiredUtil; function requireUtil() { if (hasRequiredUtil) return util; hasRequiredUtil = 1; (function(exports) { const nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; const nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; const nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; const regexName = new RegExp("^" + nameRegexp + "$"); const getAllMatches = function(string, regex) { const matches = []; let match = regex.exec(string); while (match) { const allmatches = []; allmatches.startIndex = regex.lastIndex - match[0].length; const len = match.length; for (let index = 0; index < len; index++) { allmatches.push(match[index]); } matches.push(allmatches); match = regex.exec(string); } return matches; }; const isName = function(string) { const match = regexName.exec(string); return !(match === null || typeof match === "undefined"); }; exports.isExist = function(v) { return typeof v !== "undefined"; }; exports.isEmptyObject = function(obj) { return Object.keys(obj).length === 0; }; exports.merge = function(target, a2, arrayMode) { if (a2) { const keys = Object.keys(a2); const len = keys.length; for (let i2 = 0; i2 < len; i2++) { if (arrayMode === "strict") { target[keys[i2]] = [a2[keys[i2]]]; } else { target[keys[i2]] = a2[keys[i2]]; } } } }; exports.getValue = function(v) { if (exports.isExist(v)) { return v; } else { return ""; } }; exports.isName = isName; exports.getAllMatches = getAllMatches; exports.nameRegexp = nameRegexp; })(util); return util; } var hasRequiredValidator; function requireValidator() { if (hasRequiredValidator) return validator; hasRequiredValidator = 1; const util2 = requireUtil(); const defaultOptions = { allowBooleanAttributes: false, //A tag can have attributes without any value unpairedTags: [] }; validator.validate = function(xmlData, options) { options = Object.assign({}, defaultOptions, options); const tags = []; let tagFound = false; let reachedRoot = false; if (xmlData[0] === "\uFEFF") { xmlData = xmlData.substr(1); } for (let i2 = 0; i2 < xmlData.length; i2++) { if (xmlData[i2] === "<" && xmlData[i2 + 1] === "?") { i2 += 2; i2 = readPI(xmlData, i2); if (i2.err) return i2; } else if (xmlData[i2] === "<") { let tagStartPos = i2; i2++; if (xmlData[i2] === "!") { i2 = readCommentAndCDATA(xmlData, i2); continue; } else { let closingTag = false; if (xmlData[i2] === "/") { closingTag = true; i2++; } let tagName = ""; for (; i2 < xmlData.length && xmlData[i2] !== ">" && xmlData[i2] !== " " && xmlData[i2] !== " " && xmlData[i2] !== "\n" && xmlData[i2] !== "\r"; i2++) { tagName += xmlData[i2]; } tagName = tagName.trim(); if (tagName[tagName.length - 1] === "/") { tagName = tagName.substring(0, tagName.length - 1); i2--; } if (!validateTagName(tagName)) { let msg; if (tagName.trim().length === 0) { msg = "Invalid space after '<'."; } else { msg = "Tag '" + tagName + "' is an invalid name."; } return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i2)); } const result = readAttributeStr(xmlData, i2); if (result === false) { return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i2)); } let attrStr = result.value; i2 = result.index; if (attrStr[attrStr.length - 1] === "/") { const attrStrStart = i2 - attrStr.length; attrStr = attrStr.substring(0, attrStr.length - 1); const isValid = validateAttributeString(attrStr, options); if (isValid === true) { tagFound = true; } else { return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); } } else if (closingTag) { if (!result.tagClosed) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i2)); } else if (attrStr.trim().length > 0) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); } else if (tags.length === 0) { return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); } else { const otg = tags.pop(); if (tagName !== otg.tagName) { let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); return getErrorObject( "InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos) ); } if (tags.length == 0) { reachedRoot = true; } } } else { const isValid = validateAttributeString(attrStr, options); if (isValid !== true) { return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i2 - attrStr.length + isValid.err.line)); } if (reachedRoot === true) { return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i2)); } else if (options.unpairedTags.indexOf(tagName) !== -1) ; else { tags.push({ tagName, tagStartPos }); } tagFound = true; } for (i2++; i2 < xmlData.length; i2++) { if (xmlData[i2] === "<") { if (xmlData[i2 + 1] === "!") { i2++; i2 = readCommentAndCDATA(xmlData, i2); continue; } else if (xmlData[i2 + 1] === "?") { i2 = readPI(xmlData, ++i2); if (i2.err) return i2; } else { break; } } else if (xmlData[i2] === "&") { const afterAmp = validateAmpersand(xmlData, i2); if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i2)); i2 = afterAmp; } else { if (reachedRoot === true && !isWhiteSpace(xmlData[i2])) { return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i2)); } } } if (xmlData[i2] === "<") { i2--; } } } else { if (isWhiteSpace(xmlData[i2])) { continue; } return getErrorObject("InvalidChar", "char '" + xmlData[i2] + "' is not expected.", getLineNumberForPosition(xmlData, i2)); } } if (!tagFound) { return getErrorObject("InvalidXml", "Start tag expected.", 1); } else if (tags.length == 1) { return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); } else if (tags.length > 0) { return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t2) => t2.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); } return true; }; function isWhiteSpace(char) { return char === " " || char === " " || char === "\n" || char === "\r"; } function readPI(xmlData, i2) { const start = i2; for (; i2 < xmlData.length; i2++) { if (xmlData[i2] == "?" || xmlData[i2] == " ") { const tagname = xmlData.substr(start, i2 - start); if (i2 > 5 && tagname === "xml") { return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i2)); } else if (xmlData[i2] == "?" && xmlData[i2 + 1] == ">") { i2++; break; } else { continue; } } } return i2; } function readCommentAndCDATA(xmlData, i2) { if (xmlData.length > i2 + 5 && xmlData[i2 + 1] === "-" && xmlData[i2 + 2] === "-") { for (i2 += 3; i2 < xmlData.length; i2++) { if (xmlData[i2] === "-" && xmlData[i2 + 1] === "-" && xmlData[i2 + 2] === ">") { i2 += 2; break; } } } else if (xmlData.length > i2 + 8 && xmlData[i2 + 1] === "D" && xmlData[i2 + 2] === "O" && xmlData[i2 + 3] === "C" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "Y" && xmlData[i2 + 6] === "P" && xmlData[i2 + 7] === "E") { let angleBracketsCount = 1; for (i2 += 8; i2 < xmlData.length; i2++) { if (xmlData[i2] === "<") { angleBracketsCount++; } else if (xmlData[i2] === ">") { angleBracketsCount--; if (angleBracketsCount === 0) { break; } } } } else if (xmlData.length > i2 + 9 && xmlData[i2 + 1] === "[" && xmlData[i2 + 2] === "C" && xmlData[i2 + 3] === "D" && xmlData[i2 + 4] === "A" && xmlData[i2 + 5] === "T" && xmlData[i2 + 6] === "A" && xmlData[i2 + 7] === "[") { for (i2 += 8; i2 < xmlData.length; i2++) { if (xmlData[i2] === "]" && xmlData[i2 + 1] === "]" && xmlData[i2 + 2] === ">") { i2 += 2; break; } } } return i2; } const doubleQuote = '"'; const singleQuote = "'"; function readAttributeStr(xmlData, i2) { let attrStr = ""; let startChar = ""; let tagClosed = false; for (; i2 < xmlData.length; i2++) { if (xmlData[i2] === doubleQuote || xmlData[i2] === singleQuote) { if (startChar === "") { startChar = xmlData[i2]; } else if (startChar !== xmlData[i2]) ; else { startChar = ""; } } else if (xmlData[i2] === ">") { if (startChar === "") { tagClosed = true; break; } } attrStr += xmlData[i2]; } if (startChar !== "") { return false; } return { value: attrStr, index: i2, tagClosed }; } const validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); function validateAttributeString(attrStr, options) { const matches = util2.getAllMatches(attrStr, validAttrStrRegxp); const attrNames = {}; for (let i2 = 0; i2 < matches.length; i2++) { if (matches[i2][1].length === 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches[i2][2] + "' has no space in starting.", getPositionFromMatch(matches[i2])); } else if (matches[i2][3] !== void 0 && matches[i2][4] === void 0) { return getErrorObject("InvalidAttr", "Attribute '" + matches[i2][2] + "' is without value.", getPositionFromMatch(matches[i2])); } else if (matches[i2][3] === void 0 && !options.allowBooleanAttributes) { return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i2][2] + "' is not allowed.", getPositionFromMatch(matches[i2])); } const attrName = matches[i2][2]; if (!validateAttrName(attrName)) { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i2])); } if (!attrNames.hasOwnProperty(attrName)) { attrNames[attrName] = 1; } else { return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i2])); } } return true; } function validateNumberAmpersand(xmlData, i2) { let re2 = /\d/; if (xmlData[i2] === "x") { i2++; re2 = /[\da-fA-F]/; } for (; i2 < xmlData.length; i2++) { if (xmlData[i2] === ";") return i2; if (!xmlData[i2].match(re2)) break; } return -1; } function validateAmpersand(xmlData, i2) { i2++; if (xmlData[i2] === ";") return -1; if (xmlData[i2] === "#") { i2++; return validateNumberAmpersand(xmlData, i2); } let count = 0; for (; i2 < xmlData.length; i2++, count++) { if (xmlData[i2].match(/\w/) && count < 20) continue; if (xmlData[i2] === ";") break; return -1; } return i2; } function getErrorObject(code, message, lineNumber) { return { err: { code, msg: message, line: lineNumber.line || lineNumber, col: lineNumber.col } }; } function validateAttrName(attrName) { return util2.isName(attrName); } function validateTagName(tagname) { return util2.isName(tagname); } function getLineNumberForPosition(xmlData, index) { const lines = xmlData.substring(0, index).split(/\r?\n/); return { line: lines.length, // column number is last line's length + 1, because column numbering starts at 1: col: lines[lines.length - 1].length + 1 }; } function getPositionFromMatch(match) { return match.startIndex + match[1].length; } return validator; } var OptionsBuilder = {}; var hasRequiredOptionsBuilder; function requireOptionsBuilder() { if (hasRequiredOptionsBuilder) return OptionsBuilder; hasRequiredOptionsBuilder = 1; const defaultOptions = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, // remove NS from tag name or attribute name if true allowBooleanAttributes: false, //a tag can have attributes without any value //ignoreRootElement : false, parseTagValue: true, parseAttributeValue: false, trimValues: true, //Trim string values of tag and attributes cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(tagName, val) { return val; }, attributeValueProcessor: function(attrName, val) { return val; }, stopNodes: [], //nested tags will not be parsed even for errors alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(tagName, jPath, attrs) { return tagName; } // skipEmptyListItem: false }; const buildOptions = function(options) { return Object.assign({}, defaultOptions, options); }; OptionsBuilder.buildOptions = buildOptions; OptionsBuilder.defaultOptions = defaultOptions; return OptionsBuilder; } var xmlNode; var hasRequiredXmlNode; function requireXmlNode() { if (hasRequiredXmlNode) return xmlNode; hasRequiredXmlNode = 1; class XmlNode { constructor(tagname) { this.tagname = tagname; this.child = []; this[":@"] = {}; } add(key, val) { if (key === "__proto__") key = "#__proto__"; this.child.push({ [key]: val }); } addChild(node) { if (node.tagname === "__proto__") node.tagname = "#__proto__"; if (node[":@"] && Object.keys(node[":@"]).length > 0) { this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); } else { this.child.push({ [node.tagname]: node.child }); } } } xmlNode = XmlNode; return xmlNode; } var DocTypeReader; var hasRequiredDocTypeReader; function requireDocTypeReader() { if (hasRequiredDocTypeReader) return DocTypeReader; hasRequiredDocTypeReader = 1; const util2 = requireUtil(); function readDocType(xmlData, i2) { const entities = {}; if (xmlData[i2 + 3] === "O" && xmlData[i2 + 4] === "C" && xmlData[i2 + 5] === "T" && xmlData[i2 + 6] === "Y" && xmlData[i2 + 7] === "P" && xmlData[i2 + 8] === "E") { i2 = i2 + 9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = ""; for (; i2 < xmlData.length; i2++) { if (xmlData[i2] === "<" && !comment) { if (hasBody && isEntity(xmlData, i2)) { i2 += 7; let entityName, val; [entityName, val, i2] = readEntityExp(xmlData, i2 + 1); if (val.indexOf("&") === -1) entities[validateEntityName(entityName)] = { regx: RegExp(`&${entityName};`, "g"), val }; } else if (hasBody && isElement(xmlData, i2)) i2 += 8; else if (hasBody && isAttlist(xmlData, i2)) i2 += 8; else if (hasBody && isNotation(xmlData, i2)) i2 += 9; else comment = true; angleBracketsCount++; exp = ""; } else if (xmlData[i2] === ">") { if (comment) { if (xmlData[i2 - 1] === "-" && xmlData[i2 - 2] === "-") { comment = false; angleBracketsCount--; } } else { angleBracketsCount--; } if (angleBracketsCount === 0) { break; } } else if (xmlData[i2] === "[") { hasBody = true; } else { exp += xmlData[i2]; } } if (angleBracketsCount !== 0) { throw new Error(`Unclosed DOCTYPE`); } } else { throw new Error(`Invalid Tag instead of DOCTYPE`); } return { entities, i: i2 }; } function readEntityExp(xmlData, i2) { let entityName = ""; for (; i2 < xmlData.length && (xmlData[i2] !== "'" && xmlData[i2] !== '"'); i2++) { entityName += xmlData[i2]; } entityName = entityName.trim(); if (entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); const startChar = xmlData[i2++]; let val = ""; for (; i2 < xmlData.length && xmlData[i2] !== startChar; i2++) { val += xmlData[i2]; } return [entityName, val, i2]; } function isEntity(xmlData, i2) { if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "E" && xmlData[i2 + 3] === "N" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "I" && xmlData[i2 + 6] === "T" && xmlData[i2 + 7] === "Y") return true; return false; } function isElement(xmlData, i2) { if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "E" && xmlData[i2 + 3] === "L" && xmlData[i2 + 4] === "E" && xmlData[i2 + 5] === "M" && xmlData[i2 + 6] === "E" && xmlData[i2 + 7] === "N" && xmlData[i2 + 8] === "T") return true; return false; } function isAttlist(xmlData, i2) { if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "A" && xmlData[i2 + 3] === "T" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "L" && xmlData[i2 + 6] === "I" && xmlData[i2 + 7] === "S" && xmlData[i2 + 8] === "T") return true; return false; } function isNotation(xmlData, i2) { if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "N" && xmlData[i2 + 3] === "O" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "A" && xmlData[i2 + 6] === "T" && xmlData[i2 + 7] === "I" && xmlData[i2 + 8] === "O" && xmlData[i2 + 9] === "N") return true; return false; } function validateEntityName(name) { if (util2.isName(name)) return name; else throw new Error(`Invalid entity name ${name}`); } DocTypeReader = readDocType; return DocTypeReader; } var strnum; var hasRequiredStrnum; function requireStrnum() { if (hasRequiredStrnum) return strnum; hasRequiredStrnum = 1; const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/; if (!Number.parseInt && window.parseInt) { Number.parseInt = window.parseInt; } if (!Number.parseFloat && window.parseFloat) { Number.parseFloat = window.parseFloat; } const consider = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true //skipLike: /regex/ }; function toNumber(str, options = {}) { options = Object.assign({}, consider, options); if (!str || typeof str !== "string") return str; let trimmedStr = str.trim(); if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str; else if (options.hex && hexRegex.test(trimmedStr)) { return Number.parseInt(trimmedStr, 16); } else { const match = numRegex.exec(trimmedStr); if (match) { const sign = match[1]; const leadingZeros = match[2]; let numTrimmedByZeros = trimZeros(match[3]); const eNotation = match[4] || match[6]; if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; else { const num = Number(trimmedStr); const numStr = "" + num; if (numStr.search(/[eE]/) !== -1) { if (options.eNotation) return num; else return str; } else if (eNotation) { if (options.eNotation) return num; else return str; } else if (trimmedStr.indexOf(".") !== -1) { if (numStr === "0" && numTrimmedByZeros === "") return num; else if (numStr === numTrimmedByZeros) return num; else if (sign && numStr === "-" + numTrimmedByZeros) return num; else return str; } if (leadingZeros) { if (numTrimmedByZeros === numStr) return num; else if (sign + numTrimmedByZeros === numStr) return num; else return str; } if (trimmedStr === numStr) return num; else if (trimmedStr === sign + numStr) return num; return str; } } else { return str; } } } function trimZeros(numStr) { if (numStr && numStr.indexOf(".") !== -1) { numStr = numStr.replace(/0+$/, ""); if (numStr === ".") numStr = "0"; else if (numStr[0] === ".") numStr = "0" + numStr; else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); return numStr; } return numStr; } strnum = toNumber; return strnum; } var ignoreAttributes; var hasRequiredIgnoreAttributes; function requireIgnoreAttributes() { if (hasRequiredIgnoreAttributes) return ignoreAttributes; hasRequiredIgnoreAttributes = 1; function getIgnoreAttributesFn(ignoreAttributes2) { if (typeof ignoreAttributes2 === "function") { return ignoreAttributes2; } if (Array.isArray(ignoreAttributes2)) { return (attrName) => { for (const pattern of ignoreAttributes2) { if (typeof pattern === "string" && attrName === pattern) { return true; } if (pattern instanceof RegExp && pattern.test(attrName)) { return true; } } }; } return () => false; } ignoreAttributes = getIgnoreAttributesFn; return ignoreAttributes; } var OrderedObjParser_1; var hasRequiredOrderedObjParser; function requireOrderedObjParser() { if (hasRequiredOrderedObjParser) return OrderedObjParser_1; hasRequiredOrderedObjParser = 1; const util2 = requireUtil(); const xmlNode2 = requireXmlNode(); const readDocType = requireDocTypeReader(); const toNumber = requireStrnum(); const getIgnoreAttributesFn = requireIgnoreAttributes(); class OrderedObjParser { constructor(options) { this.options = options; this.currentNode = null; this.tagsNodeStack = []; this.docTypeEntities = {}; this.lastEntities = { "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, "quot": { regex: /&(quot|#34|#x22);/g, val: '"' } }; this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; this.htmlEntities = { "space": { regex: /&(nbsp|#160);/g, val: " " }, // "lt" : { regex: /&(lt|#60);/g, val: "<" }, // "gt" : { regex: /&(gt|#62);/g, val: ">" }, // "amp" : { regex: /&(amp|#38);/g, val: "&" }, // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, // "apos" : { regex: /&(apos|#39);/g, val: "'" }, "cent": { regex: /&(cent|#162);/g, val: "¢" }, "pound": { regex: /&(pound|#163);/g, val: "£" }, "yen": { regex: /&(yen|#165);/g, val: "¥" }, "euro": { regex: /&(euro|#8364);/g, val: "€" }, "copyright": { regex: /&(copy|#169);/g, val: "©" }, "reg": { regex: /&(reg|#174);/g, val: "®" }, "inr": { regex: /&(inr|#8377);/g, val: "₹" }, "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCharCode(Number.parseInt(str, 16)) } }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; this.parseTextData = parseTextData; this.resolveNameSpace = resolveNameSpace; this.buildAttributesMap = buildAttributesMap; this.isItStopNode = isItStopNode; this.replaceEntitiesValue = replaceEntitiesValue; this.readStopNodeData = readStopNodeData; this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); } } function addExternalEntities(externalEntities) { const entKeys = Object.keys(externalEntities); for (let i2 = 0; i2 < entKeys.length; i2++) { const ent = entKeys[i2]; this.lastEntities[ent] = { regex: new RegExp("&" + ent + ";", "g"), val: externalEntities[ent] }; } } function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { if (val !== void 0) { if (this.options.trimValues && !dontTrim) { val = val.trim(); } if (val.length > 0) { if (!escapeEntities) val = this.replaceEntitiesValue(val); const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); if (newval === null || newval === void 0) { return val; } else if (typeof newval !== typeof val || newval !== val) { return newval; } else if (this.options.trimValues) { return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); } else { const trimmedVal = val.trim(); if (trimmedVal === val) { return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); } else { return val; } } } } } function resolveNameSpace(tagname) { if (this.options.removeNSPrefix) { const tags = tagname.split(":"); const prefix = tagname.charAt(0) === "/" ? "/" : ""; if (tags[0] === "xmlns") { return ""; } if (tags.length === 2) { tagname = prefix + tags[1]; } } return tagname; } const attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); function buildAttributesMap(attrStr, jPath, tagName) { if (this.options.ignoreAttributes !== true && typeof attrStr === "string") { const matches = util2.getAllMatches(attrStr, attrsRegx); const len = matches.length; const attrs = {}; for (let i2 = 0; i2 < len; i2++) { const attrName = this.resolveNameSpace(matches[i2][1]); if (this.ignoreAttributesFn(attrName, jPath)) { continue; } let oldVal = matches[i2][4]; let aName = this.options.attributeNamePrefix + attrName; if (attrName.length) { if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } if (aName === "__proto__") aName = "#__proto__"; if (oldVal !== void 0) { if (this.options.trimValues) { oldVal = oldVal.trim(); } oldVal = this.replaceEntitiesValue(oldVal); const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); if (newVal === null || newVal === void 0) { attrs[aName] = oldVal; } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { attrs[aName] = newVal; } else { attrs[aName] = parseValue( oldVal, this.options.parseAttributeValue, this.options.numberParseOptions ); } } else if (this.options.allowBooleanAttributes) { attrs[aName] = true; } } } if (!Object.keys(attrs).length) { return; } if (this.options.attributesGroupName) { const attrCollection = {}; attrCollection[this.options.attributesGroupName] = attrs; return attrCollection; } return attrs; } } const parseXml = function(xmlData) { xmlData = xmlData.replace(/\r\n?/g, "\n"); const xmlObj = new xmlNode2("!xml"); let currentNode = xmlObj; let textData = ""; let jPath = ""; for (let i2 = 0; i2 < xmlData.length; i2++) { const ch = xmlData[i2]; if (ch === "<") { if (xmlData[i2 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i2, "Closing Tag is not closed."); let tagName = xmlData.substring(i2 + 2, closeIndex).trim(); if (this.options.removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); } } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode) { textData = this.saveTextToParentTag(textData, currentNode, jPath); } const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { throw new Error(`Unpaired tag can not be used as closing tag: `); } let propIndex = 0; if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1); this.tagsNodeStack.pop(); } else { propIndex = jPath.lastIndexOf("."); } jPath = jPath.substring(0, propIndex); currentNode = this.tagsNodeStack.pop(); textData = ""; i2 = closeIndex; } else if (xmlData[i2 + 1] === "?") { let tagData = readTagExp(xmlData, i2, false, "?>"); if (!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) ; else { const childNode = new xmlNode2(tagData.tagName); childNode.add(this.options.textNodeName, ""); if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); } this.addChild(currentNode, childNode, jPath); } i2 = tagData.closeIndex + 1; } else if (xmlData.substr(i2 + 1, 3) === "!--") { const endIndex = findClosingIndex(xmlData, "-->", i2 + 4, "Comment is not closed."); if (this.options.commentPropName) { const comment = xmlData.substring(i2 + 4, endIndex - 2); textData = this.saveTextToParentTag(textData, currentNode, jPath); currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); } i2 = endIndex; } else if (xmlData.substr(i2 + 1, 2) === "!D") { const result = readDocType(xmlData, i2); this.docTypeEntities = result.entities; i2 = result.i; } else if (xmlData.substr(i2 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i2, "CDATA is not closed.") - 2; const tagExp = xmlData.substring(i2 + 9, closeIndex); textData = this.saveTextToParentTag(textData, currentNode, jPath); let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); if (val == void 0) val = ""; if (this.options.cdataPropName) { currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); } else { currentNode.add(this.options.textNodeName, val); } i2 = closeIndex + 2; } else { let result = readTagExp(xmlData, i2, this.options.removeNSPrefix); let tagName = result.tagName; const rawTagName = result.rawTagName; let tagExp = result.tagExp; let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if (currentNode && textData) { if (currentNode.tagname !== "!xml") { textData = this.saveTextToParentTag(textData, currentNode, jPath, false); } } const lastTag = currentNode; if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { currentNode = this.tagsNodeStack.pop(); jPath = jPath.substring(0, jPath.lastIndexOf(".")); } if (tagName !== xmlObj.tagname) { jPath += jPath ? "." + tagName : tagName; } if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { let tagContent = ""; if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; } else { tagExp = tagExp.substr(0, tagExp.length - 1); } i2 = result.closeIndex; } else if (this.options.unpairedTags.indexOf(tagName) !== -1) { i2 = result.closeIndex; } else { const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); if (!result2) throw new Error(`Unexpected end of ${rawTagName}`); i2 = result2.i; tagContent = result2.tagContent; } const childNode = new xmlNode2(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } if (tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); } jPath = jPath.substr(0, jPath.lastIndexOf(".")); childNode.add(this.options.textNodeName, tagContent); this.addChild(currentNode, childNode, jPath); } else { if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; } else { tagExp = tagExp.substr(0, tagExp.length - 1); } if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } const childNode = new xmlNode2(tagName); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); jPath = jPath.substr(0, jPath.lastIndexOf(".")); } else { const childNode = new xmlNode2(tagName); this.tagsNodeStack.push(currentNode); if (tagName !== tagExp && attrExpPresent) { childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath); currentNode = childNode; } textData = ""; i2 = closeIndex; } } } else { textData += xmlData[i2]; } } return xmlObj.child; }; function addChild(currentNode, childNode, jPath) { const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); if (result === false) ; else if (typeof result === "string") { childNode.tagname = result; currentNode.addChild(childNode); } else { currentNode.addChild(childNode); } } const replaceEntitiesValue = function(val) { if (this.options.processEntities) { for (let entityName in this.docTypeEntities) { const entity = this.docTypeEntities[entityName]; val = val.replace(entity.regx, entity.val); } for (let entityName in this.lastEntities) { const entity = this.lastEntities[entityName]; val = val.replace(entity.regex, entity.val); } if (this.options.htmlEntities) { for (let entityName in this.htmlEntities) { const entity = this.htmlEntities[entityName]; val = val.replace(entity.regex, entity.val); } } val = val.replace(this.ampEntity.regex, this.ampEntity.val); } return val; }; function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; textData = this.parseTextData( textData, currentNode.tagname, jPath, false, currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, isLeafNode ); if (textData !== void 0 && textData !== "") currentNode.add(this.options.textNodeName, textData); textData = ""; } return textData; } function isItStopNode(stopNodes, jPath, currentTagName) { const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; } return false; } function tagExpWithClosingIndex(xmlData, i2, closingChar = ">") { let attrBoundary; let tagExp = ""; for (let index = i2; index < xmlData.length; index++) { let ch = xmlData[index]; if (attrBoundary) { if (ch === attrBoundary) attrBoundary = ""; } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { if (closingChar[1]) { if (xmlData[index + 1] === closingChar[1]) { return { data: tagExp, index }; } } else { return { data: tagExp, index }; } } else if (ch === " ") { ch = " "; } tagExp += ch; } } function findClosingIndex(xmlData, str, i2, errMsg) { const closingIndex = xmlData.indexOf(str, i2); if (closingIndex === -1) { throw new Error(errMsg); } else { return closingIndex + str.length - 1; } } function readTagExp(xmlData, i2, removeNSPrefix, closingChar = ">") { const result = tagExpWithClosingIndex(xmlData, i2 + 1, closingChar); if (!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); let tagName = tagExp; let attrExpPresent = true; if (separatorIndex !== -1) { tagName = tagExp.substring(0, separatorIndex); tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } const rawTagName = tagName; if (removeNSPrefix) { const colonIndex = tagName.indexOf(":"); if (colonIndex !== -1) { tagName = tagName.substr(colonIndex + 1); attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } } return { tagName, tagExp, closeIndex, attrExpPresent, rawTagName }; } function readStopNodeData(xmlData, tagName, i2) { const startIndex = i2; let openTagCount = 1; for (; i2 < xmlData.length; i2++) { if (xmlData[i2] === "<") { if (xmlData[i2 + 1] === "/") { const closeIndex = findClosingIndex(xmlData, ">", i2, `${tagName} is not closed`); let closeTagName = xmlData.substring(i2 + 2, closeIndex).trim(); if (closeTagName === tagName) { openTagCount--; if (openTagCount === 0) { return { tagContent: xmlData.substring(startIndex, i2), i: closeIndex }; } } i2 = closeIndex; } else if (xmlData[i2 + 1] === "?") { const closeIndex = findClosingIndex(xmlData, "?>", i2 + 1, "StopNode is not closed."); i2 = closeIndex; } else if (xmlData.substr(i2 + 1, 3) === "!--") { const closeIndex = findClosingIndex(xmlData, "-->", i2 + 3, "StopNode is not closed."); i2 = closeIndex; } else if (xmlData.substr(i2 + 1, 2) === "![") { const closeIndex = findClosingIndex(xmlData, "]]>", i2, "StopNode is not closed.") - 2; i2 = closeIndex; } else { const tagData = readTagExp(xmlData, i2, ">"); if (tagData) { const openTagName = tagData && tagData.tagName; if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { openTagCount++; } i2 = tagData.closeIndex; } } } } } function parseValue(val, shouldParse, options) { if (shouldParse && typeof val === "string") { const newval = val.trim(); if (newval === "true") return true; else if (newval === "false") return false; else return toNumber(val, options); } else { if (util2.isExist(val)) { return val; } else { return ""; } } } OrderedObjParser_1 = OrderedObjParser; return OrderedObjParser_1; } var node2json = {}; var hasRequiredNode2json; function requireNode2json() { if (hasRequiredNode2json) return node2json; hasRequiredNode2json = 1; function prettify(node, options) { return compress(node, options); } function compress(arr, options, jPath) { let text; const compressedObj = {}; for (let i2 = 0; i2 < arr.length; i2++) { const tagObj = arr[i2]; const property = propName(tagObj); let newJpath = ""; if (jPath === void 0) newJpath = property; else newJpath = jPath + "." + property; if (property === options.textNodeName) { if (text === void 0) text = tagObj[property]; else text += "" + tagObj[property]; } else if (property === void 0) { continue; } else if (tagObj[property]) { let val = compress(tagObj[property], options, newJpath); const isLeaf = isLeafTag(val, options); if (tagObj[":@"]) { assignAttributes(val, tagObj[":@"], newJpath, options); } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { val = val[options.textNodeName]; } else if (Object.keys(val).length === 0) { if (options.alwaysCreateTextNode) val[options.textNodeName] = ""; else val = ""; } if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { if (!Array.isArray(compressedObj[property])) { compressedObj[property] = [compressedObj[property]]; } compressedObj[property].push(val); } else { if (options.isArray(property, newJpath, isLeaf)) { compressedObj[property] = [val]; } else { compressedObj[property] = val; } } } } if (typeof text === "string") { if (text.length > 0) compressedObj[options.textNodeName] = text; } else if (text !== void 0) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj) { const keys = Object.keys(obj); for (let i2 = 0; i2 < keys.length; i2++) { const key = keys[i2]; if (key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options) { if (attrMap) { const keys = Object.keys(attrMap); const len = keys.length; for (let i2 = 0; i2 < len; i2++) { const atrrName = keys[i2]; if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { obj[atrrName] = [attrMap[atrrName]]; } else { obj[atrrName] = attrMap[atrrName]; } } } } function isLeafTag(obj, options) { const { textNodeName } = options; const propCount = Object.keys(obj).length; if (propCount === 0) { return true; } if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) { return true; } return false; } node2json.prettify = prettify; return node2json; } var XMLParser_1; var hasRequiredXMLParser; function requireXMLParser() { if (hasRequiredXMLParser) return XMLParser_1; hasRequiredXMLParser = 1; const { buildOptions } = requireOptionsBuilder(); const OrderedObjParser = requireOrderedObjParser(); const { prettify } = requireNode2json(); const validator2 = requireValidator(); class XMLParser { constructor(options) { this.externalEntities = {}; this.options = buildOptions(options); } /** * Parse XML dats to JS object * @param {string|Buffer} xmlData * @param {boolean|Object} validationOption */ parse(xmlData, validationOption) { if (typeof xmlData === "string") ; else if (xmlData.toString) { xmlData = xmlData.toString(); } else { throw new Error("XML data is accepted in String or Bytes[] form."); } if (validationOption) { if (validationOption === true) validationOption = {}; const result = validator2.validate(xmlData, validationOption); if (result !== true) { throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); } } const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; else return prettify(orderedResult, this.options); } /** * Add Entity which is not by default supported by this library * @param {string} key * @param {string} value */ addEntity(key, value) { if (value.indexOf("&") !== -1) { throw new Error("Entity value can't have '&'"); } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) { throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); } else if (value === "&") { throw new Error("An entity with value '&' is not permitted"); } else { this.externalEntities[key] = value; } } } XMLParser_1 = XMLParser; return XMLParser_1; } var orderedJs2Xml; var hasRequiredOrderedJs2Xml; function requireOrderedJs2Xml() { if (hasRequiredOrderedJs2Xml) return orderedJs2Xml; hasRequiredOrderedJs2Xml = 1; const EOL = "\n"; function toXml(jArray, options) { let indentation = ""; if (options.format && options.indentBy.length > 0) { indentation = EOL; } return arrToStr(jArray, options, "", indentation); } function arrToStr(arr, options, jPath, indentation) { let xmlStr = ""; let isPreviousElementTag = false; for (let i2 = 0; i2 < arr.length; i2++) { const tagObj = arr[i2]; const tagName = propName(tagObj); if (tagName === void 0) continue; let newJPath = ""; if (jPath.length === 0) newJPath = tagName; else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { tagText = options.tagValueProcessor(tagName, tagText); tagText = replaceEntitiesValue(tagText, options); } if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += tagText; isPreviousElementTag = false; continue; } else if (tagName === options.cdataPropName) { if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += ``; isPreviousElementTag = false; continue; } else if (tagName === options.commentPropName) { xmlStr += indentation + ``; isPreviousElementTag = true; continue; } else if (tagName[0] === "?") { const attStr2 = attr_to_str(tagObj[":@"], options); const tempInd = tagName === "?xml" ? "" : indentation; let piTextNodeName = tagObj[tagName][0][options.textNodeName]; piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`; isPreviousElementTag = true; continue; } let newIdentation = indentation; if (newIdentation !== "") { newIdentation += options.indentBy; } const attStr = attr_to_str(tagObj[":@"], options); const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { xmlStr += tagStart + `>${tagValue}${indentation}`; } else { xmlStr += tagStart + ">"; if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; } isPreviousElementTag = true; } return xmlStr; } function propName(obj) { const keys = Object.keys(obj); for (let i2 = 0; i2 < keys.length; i2++) { const key = keys[i2]; if (!obj.hasOwnProperty(key)) continue; if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { if (!attrMap.hasOwnProperty(attr)) continue; let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); attrVal = replaceEntitiesValue(attrVal, options); if (attrVal === true && options.suppressBooleanAttributes) { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; } else { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } } return attrStr; } function isStopNode(jPath, options) { jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index in options.stopNodes) { if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } return false; } function replaceEntitiesValue(textValue, options) { if (textValue && textValue.length > 0 && options.processEntities) { for (let i2 = 0; i2 < options.entities.length; i2++) { const entity = options.entities[i2]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; } orderedJs2Xml = toXml; return orderedJs2Xml; } var json2xml; var hasRequiredJson2xml; function requireJson2xml() { if (hasRequiredJson2xml) return json2xml; hasRequiredJson2xml = 1; const buildFromOrderedJs = requireOrderedJs2Xml(); const getIgnoreAttributesFn = requireIgnoreAttributes(); const defaultOptions = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(key, a2) { return a2; }, attributeValueProcessor: function(attrName, a2) { return a2; }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [ { regex: new RegExp("&", "g"), val: "&" }, //it must be on top { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ } ], processEntities: true, stopNodes: [], // transformTagName: false, // transformAttributeName: false, oneListGroup: false }; function Builder(options) { this.options = Object.assign({}, defaultOptions, options); if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { this.isAttribute = function() { return false; }; } else { this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); this.attrPrefixLen = this.options.attributeNamePrefix.length; this.isAttribute = isAttribute; } this.processTextOrObjNode = processTextOrObjNode; if (this.options.format) { this.indentate = indentate; this.tagEndChar = ">\n"; this.newLine = "\n"; } else { this.indentate = function() { return ""; }; this.tagEndChar = ">"; this.newLine = ""; } } Builder.prototype.build = function(jObj) { if (this.options.preserveOrder) { return buildFromOrderedJs(jObj, this.options); } else { if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) { jObj = { [this.options.arrayNodeName]: jObj }; } return this.j2x(jObj, 0, []).val; } }; Builder.prototype.j2x = function(jObj, level, ajPath) { let attrStr = ""; let val = ""; const jPath = ajPath.join("."); for (let key in jObj) { if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue; if (typeof jObj[key] === "undefined") { if (this.isAttribute(key)) { val += ""; } } else if (jObj[key] === null) { if (this.isAttribute(key)) { val += ""; } else if (key[0] === "?") { val += this.indentate(level) + "<" + key + "?" + this.tagEndChar; } else { val += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } } else if (jObj[key] instanceof Date) { val += this.buildTextValNode(jObj[key], key, "", level); } else if (typeof jObj[key] !== "object") { const attr = this.isAttribute(key); if (attr && !this.ignoreAttributesFn(attr, jPath)) { attrStr += this.buildAttrPairStr(attr, "" + jObj[key]); } else if (!attr) { if (key === this.options.textNodeName) { let newval = this.options.tagValueProcessor(key, "" + jObj[key]); val += this.replaceEntitiesValue(newval); } else { val += this.buildTextValNode(jObj[key], key, "", level); } } } else if (Array.isArray(jObj[key])) { const arrLen = jObj[key].length; let listTagVal = ""; let listTagAttr = ""; for (let j2 = 0; j2 < arrLen; j2++) { const item = jObj[key][j2]; if (typeof item === "undefined") ; else if (item === null) { if (key[0] === "?") val += this.indentate(level) + "<" + key + "?" + this.tagEndChar; else val += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } else if (typeof item === "object") { if (this.options.oneListGroup) { const result = this.j2x(item, level + 1, ajPath.concat(key)); listTagVal += result.val; if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { listTagAttr += result.attrStr; } } else { listTagVal += this.processTextOrObjNode(item, key, level, ajPath); } } else { if (this.options.oneListGroup) { let textValue = this.options.tagValueProcessor(key, item); textValue = this.replaceEntitiesValue(textValue); listTagVal += textValue; } else { listTagVal += this.buildTextValNode(item, key, "", level); } } } if (this.options.oneListGroup) { listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); } val += listTagVal; } else { if (this.options.attributesGroupName && key === this.options.attributesGroupName) { const Ks = Object.keys(jObj[key]); const L = Ks.length; for (let j2 = 0; j2 < L; j2++) { attrStr += this.buildAttrPairStr(Ks[j2], "" + jObj[key][Ks[j2]]); } } else { val += this.processTextOrObjNode(jObj[key], key, level, ajPath); } } } return { attrStr, val }; }; Builder.prototype.buildAttrPairStr = function(attrName, val) { val = this.options.attributeValueProcessor(attrName, "" + val); val = this.replaceEntitiesValue(val); if (this.options.suppressBooleanAttributes && val === "true") { return " " + attrName; } else return " " + attrName + '="' + val + '"'; }; function processTextOrObjNode(object, key, level, ajPath) { const result = this.j2x(object, level + 1, ajPath.concat(key)); if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) { return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); } else { return this.buildObjectNode(result.val, key, result.attrStr, level); } } Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { if (val === "") { if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; else { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } } else { let tagEndExp = "" + val + tagEndExp; } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { return this.indentate(level) + `` + this.newLine; } else { return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val + this.indentate(level) + tagEndExp; } } }; Builder.prototype.closeTag = function(key) { let closeTag = ""; if (this.options.unpairedTags.indexOf(key) !== -1) { if (!this.options.suppressUnpairedNode) closeTag = "/"; } else if (this.options.suppressEmptyNode) { closeTag = "/"; } else { closeTag = `>` + this.newLine; } else if (this.options.commentPropName !== false && key === this.options.commentPropName) { return this.indentate(level) + `` + this.newLine; } else if (key[0] === "?") { return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; } else { let textValue = this.options.tagValueProcessor(key, val); textValue = this.replaceEntitiesValue(textValue); if (textValue === "") { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } else { return this.indentate(level) + "<" + key + attrStr + ">" + textValue + " 0 && this.options.processEntities) { for (let i2 = 0; i2 < this.options.entities.length; i2++) { const entity = this.options.entities[i2]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; }; function indentate(level) { return this.options.indentBy.repeat(level); } function isAttribute(name) { if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { return name.substr(this.attrPrefixLen); } else { return false; } } json2xml = Builder; return json2xml; } var fxp; var hasRequiredFxp; function requireFxp() { if (hasRequiredFxp) return fxp; hasRequiredFxp = 1; const validator2 = requireValidator(); const XMLParser = requireXMLParser(); const XMLBuilder = requireJson2xml(); fxp = { XMLParser, XMLValidator: validator2, XMLBuilder }; return fxp; } var fxpExports = requireFxp(); function isSvg(string) { if (typeof string !== "string") { throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); } string = string.trim(); if (string.length === 0) { return false; } if (fxpExports.XMLValidator.validate(string) !== true) { return false; } let jsonObject; const parser = new fxpExports.XMLParser(); try { jsonObject = parser.parse(string); } catch { return false; } if (!jsonObject) { return false; } if (!Object.keys(jsonObject).some((x) => x.toLowerCase() === "svg")) { return false; } return true; } class View { _view; constructor(view) { isValidView(view); this._view = view; } get id() { return this._view.id; } get name() { return this._view.name; } get caption() { return this._view.caption; } get emptyTitle() { return this._view.emptyTitle; } get emptyCaption() { return this._view.emptyCaption; } get getContents() { return this._view.getContents; } get icon() { return this._view.icon; } set icon(icon) { this._view.icon = icon; } get order() { return this._view.order; } set order(order) { this._view.order = order; } get params() { return this._view.params; } set params(params) { this._view.params = params; } get columns() { return this._view.columns; } get emptyView() { return this._view.emptyView; } get parent() { return this._view.parent; } get sticky() { return this._view.sticky; } get expanded() { return this._view.expanded; } set expanded(expanded) { this._view.expanded = expanded; } get defaultSortKey() { return this._view.defaultSortKey; } get loadChildViews() { return this._view.loadChildViews; } } const isValidView = function(view) { if (!view.id || typeof view.id !== "string") { throw new Error("View id is required and must be a string"); } if (!view.name || typeof view.name !== "string") { throw new Error("View name is required and must be a string"); } if ("caption" in view && typeof view.caption !== "string") { throw new Error("View caption must be a string"); } if (!view.getContents || typeof view.getContents !== "function") { throw new Error("View getContents is required and must be a function"); } if (!view.icon || typeof view.icon !== "string" || !isSvg(view.icon)) { throw new Error("View icon is required and must be a valid svg string"); } if ("order" in view && typeof view.order !== "number") { throw new Error("View order must be a number"); } if (view.columns) { view.columns.forEach((column) => { if (!(column instanceof Column)) { throw new Error("View columns must be an array of Column. Invalid column found"); } }); } if (view.emptyView && typeof view.emptyView !== "function") { throw new Error("View emptyView must be a function"); } if (view.parent && typeof view.parent !== "string") { throw new Error("View parent must be a string"); } if ("sticky" in view && typeof view.sticky !== "boolean") { throw new Error("View sticky must be a boolean"); } if ("expanded" in view && typeof view.expanded !== "boolean") { throw new Error("View expanded must be a boolean"); } if (view.defaultSortKey && typeof view.defaultSortKey !== "string") { throw new Error("View defaultSortKey must be a string"); } if (view.loadChildViews && typeof view.loadChildViews !== "function") { throw new Error("View loadChildViews must be a function"); } return true; }; var debug_1; var hasRequiredDebug; function requireDebug() { if (hasRequiredDebug) return debug_1; hasRequiredDebug = 1; const debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { }; debug_1 = debug; return debug_1; } var constants; var hasRequiredConstants; function requireConstants() { if (hasRequiredConstants) return constants; hasRequiredConstants = 1; const SEMVER_SPEC_VERSION = "2.0.0"; const MAX_LENGTH = 256; const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; const MAX_SAFE_COMPONENT_LENGTH = 16; const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; const RELEASE_TYPES = [ "major", "premajor", "minor", "preminor", "patch", "prepatch", "prerelease" ]; constants = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 1, FLAG_LOOSE: 2 }; return constants; } var re = { exports: {} }; var hasRequiredRe; function requireRe() { if (hasRequiredRe) return re.exports; hasRequiredRe = 1; (function(module, exports) { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = requireConstants(); const debug = requireDebug(); exports = module.exports = {}; const re2 = exports.re = []; const safeRe = exports.safeRe = []; const src = exports.src = []; const t2 = exports.t = {}; let R = 0; const LETTERDASHNUMBER = "[a-zA-Z0-9-]"; const safeRegexReplacements = [ ["\\s", 1], ["\\d", MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] ]; const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); } return value; }; const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value); const index = R++; debug(name, index, value); t2[name] = index; src[index] = value; re2[index] = new RegExp(value, isGlobal ? "g" : void 0); safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); }; createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); createToken("MAINVERSION", `(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`); createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NUMERICIDENTIFIER]}|${src[t2.NONNUMERICIDENTIFIER]})`); createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NUMERICIDENTIFIERLOOSE]}|${src[t2.NONNUMERICIDENTIFIER]})`); createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`); createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`); createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`); createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`); createToken("FULL", `^${src[t2.FULLPLAIN]}$`); createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`); createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`); createToken("GTLT", "((?:<|>)?=?)"); createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`); createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`); createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`); createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`); createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAINLOOSE]}$`); createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); createToken("COERCE", `${src[t2.COERCEPLAIN]}(?:$|[^\\d])`); createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`); createToken("COERCERTL", src[t2.COERCE], true); createToken("COERCERTLFULL", src[t2.COERCEFULL], true); createToken("LONETILDE", "(?:~>?)"); createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true); exports.tildeTrimReplace = "$1~"; createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`); createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`); createToken("LONECARET", "(?:\\^)"); createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true); exports.caretTrimReplace = "$1^"; createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`); createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`); createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`); createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`); createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true); exports.comparatorTrimReplace = "$1$2$3"; createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`); createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.XRANGEPLAINLOOSE]})\\s*$`); createToken("STAR", "(<|>)?=?\\s*\\*"); createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); })(re, re.exports); return re.exports; } var parseOptions_1; var hasRequiredParseOptions; function requireParseOptions() { if (hasRequiredParseOptions) return parseOptions_1; hasRequiredParseOptions = 1; const looseOption = Object.freeze({ loose: true }); const emptyOpts = Object.freeze({}); const parseOptions = (options) => { if (!options) { return emptyOpts; } if (typeof options !== "object") { return looseOption; } return options; }; parseOptions_1 = parseOptions; return parseOptions_1; } var identifiers; var hasRequiredIdentifiers; function requireIdentifiers() { if (hasRequiredIdentifiers) return identifiers; hasRequiredIdentifiers = 1; const numeric = /^[0-9]+$/; const compareIdentifiers = (a2, b2) => { const anum = numeric.test(a2); const bnum = numeric.test(b2); if (anum && bnum) { a2 = +a2; b2 = +b2; } return a2 === b2 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a2 < b2 ? -1 : 1; }; const rcompareIdentifiers = (a2, b2) => compareIdentifiers(b2, a2); identifiers = { compareIdentifiers, rcompareIdentifiers }; return identifiers; } var semver; var hasRequiredSemver; function requireSemver() { if (hasRequiredSemver) return semver; hasRequiredSemver = 1; const debug = requireDebug(); const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants(); const { safeRe: re2, t: t2 } = requireRe(); const parseOptions = requireParseOptions(); const { compareIdentifiers } = requireIdentifiers(); class SemVer { constructor(version, options) { options = parseOptions(options); if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== "string") { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ); } debug("SemVer", version, options); this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; const m2 = version.trim().match(options.loose ? re2[t2.LOOSE] : re2[t2.FULL]); if (!m2) { throw new TypeError(`Invalid Version: ${version}`); } this.raw = version; this.major = +m2[1]; this.minor = +m2[2]; this.patch = +m2[3]; if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError("Invalid major version"); } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError("Invalid minor version"); } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError("Invalid patch version"); } if (!m2[4]) { this.prerelease = []; } else { this.prerelease = m2[4].split(".").map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER) { return num; } } return id; }); } this.build = m2[5] ? m2[5].split(".") : []; this.format(); } format() { this.version = `${this.major}.${this.minor}.${this.patch}`; if (this.prerelease.length) { this.version += `-${this.prerelease.join(".")}`; } return this.version; } toString() { return this.version; } compare(other) { debug("SemVer.compare", this.version, this.options, other); if (!(other instanceof SemVer)) { if (typeof other === "string" && other === this.version) { return 0; } other = new SemVer(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); } comparePre(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i2 = 0; do { const a2 = this.prerelease[i2]; const b2 = other.prerelease[i2]; debug("prerelease compare", i2, a2, b2); if (a2 === void 0 && b2 === void 0) { return 0; } else if (b2 === void 0) { return 1; } else if (a2 === void 0) { return -1; } else if (a2 === b2) { continue; } else { return compareIdentifiers(a2, b2); } } while (++i2); } compareBuild(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } let i2 = 0; do { const a2 = this.build[i2]; const b2 = other.build[i2]; debug("build compare", i2, a2, b2); if (a2 === void 0 && b2 === void 0) { return 0; } else if (b2 === void 0) { return 1; } else if (a2 === void 0) { return -1; } else if (a2 === b2) { continue; } else { return compareIdentifiers(a2, b2); } } while (++i2); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier, identifierBase) { switch (release) { case "premajor": this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc("pre", identifier, identifierBase); break; case "preminor": this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc("pre", identifier, identifierBase); break; case "prepatch": this.prerelease.length = 0; this.inc("patch", identifier, identifierBase); this.inc("pre", identifier, identifierBase); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case "prerelease": if (this.prerelease.length === 0) { this.inc("patch", identifier, identifierBase); } this.inc("pre", identifier, identifierBase); break; case "major": if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case "minor": if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case "patch": if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case "pre": { const base = Number(identifierBase) ? 1 : 0; if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } if (this.prerelease.length === 0) { this.prerelease = [base]; } else { let i2 = this.prerelease.length; while (--i2 >= 0) { if (typeof this.prerelease[i2] === "number") { this.prerelease[i2]++; i2 = -2; } } if (i2 === -1) { if (identifier === this.prerelease.join(".") && identifierBase === false) { throw new Error("invalid increment argument: identifier already exists"); } this.prerelease.push(base); } } if (identifier) { let prerelease = [identifier, base]; if (identifierBase === false) { prerelease = [identifier]; } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease; } } else { this.prerelease = prerelease; } } break; } default: throw new Error(`invalid increment argument: ${release}`); } this.raw = this.format(); if (this.build.length) { this.raw += `+${this.build.join(".")}`; } return this; } } semver = SemVer; return semver; } var parse_1; var hasRequiredParse; function requireParse() { if (hasRequiredParse) return parse_1; hasRequiredParse = 1; const SemVer = requireSemver(); const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version; } try { return new SemVer(version, options); } catch (er) { if (!throwErrors) { return null; } throw er; } }; parse_1 = parse; return parse_1; } var valid_1; var hasRequiredValid; function requireValid() { if (hasRequiredValid) return valid_1; hasRequiredValid = 1; const parse = requireParse(); const valid2 = (version, options) => { const v = parse(version, options); return v ? v.version : null; }; valid_1 = valid2; return valid_1; } var validExports = requireValid(); const valid = /* @__PURE__ */ getDefaultExportFromCjs(validExports); var major_1; var hasRequiredMajor; function requireMajor() { if (hasRequiredMajor) return major_1; hasRequiredMajor = 1; const SemVer = requireSemver(); const major2 = (a2, loose) => new SemVer(a2, loose).major; major_1 = major2; return major_1; } var majorExports = requireMajor(); const major = /* @__PURE__ */ getDefaultExportFromCjs(majorExports); class ProxyBus { bus; constructor(bus2) { if (typeof bus2.getVersion !== "function" || !valid(bus2.getVersion())) { console.warn("Proxying an event bus with an unknown or invalid version"); } else if (major(bus2.getVersion()) !== major(this.getVersion())) { console.warn( "Proxying an event bus of version " + bus2.getVersion() + " with " + this.getVersion() ); } this.bus = bus2; } getVersion() { return "3.3.1"; } subscribe(name, handler) { this.bus.subscribe(name, handler); } unsubscribe(name, handler) { this.bus.unsubscribe(name, handler); } emit(name, event) { this.bus.emit(name, event); } } class SimpleBus { handlers = /* @__PURE__ */ new Map(); getVersion() { return "3.3.1"; } subscribe(name, handler) { this.handlers.set( name, (this.handlers.get(name) || []).concat( handler ) ); } unsubscribe(name, handler) { this.handlers.set( name, (this.handlers.get(name) || []).filter((h2) => h2 !== handler) ); } emit(name, event) { (this.handlers.get(name) || []).forEach((h2) => { try { h2(event); } catch (e2) { console.error("could not invoke event listener", e2); } }); } } let bus = null; function getBus() { if (bus !== null) { return bus; } if (typeof window === "undefined") { return new Proxy({}, { get: () => { return () => console.error( "Window not available, EventBus can not be established!" ); } }); } if (window.OC?._eventBus && typeof window._nc_event_bus === "undefined") { console.warn( "found old event bus instance at OC._eventBus. Update your version!" ); window._nc_event_bus = window.OC._eventBus; } if (typeof window?._nc_event_bus !== "undefined") { bus = new ProxyBus(window._nc_event_bus); } else { bus = window._nc_event_bus = new SimpleBus(); } return bus; } function emit(name, event) { getBus().emit(name, event); } /*! * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ class FileListFilter extends TypedEventTarget { id; order; constructor(id, order = 100) { super(); this.id = id; this.order = order; } filter(nodes) { throw new Error("Not implemented"); } updateChips(chips) { this.dispatchTypedEvent("update:chips", new CustomEvent("update:chips", { detail: chips })); } filterUpdated() { this.dispatchTypedEvent("update:filter", new CustomEvent("update:filter")); } } function registerFileListFilter(filter) { if (!window._nc_filelist_filters) { window._nc_filelist_filters = /* @__PURE__ */ new Map(); } if (window._nc_filelist_filters.has(filter.id)) { throw new Error(`File list filter "${filter.id}" already registered`); } window._nc_filelist_filters.set(filter.id, filter); emit("files:filter:added", filter); } function unregisterFileListFilter(filterId) { if (window._nc_filelist_filters && window._nc_filelist_filters.has(filterId)) { window._nc_filelist_filters.delete(filterId); emit("files:filter:removed", filterId); } } function getFileListFilters() { if (!window._nc_filelist_filters) { return []; } return [...window._nc_filelist_filters.values()]; } const addNewFileMenuEntry = function(entry) { const newFileMenu = getNewFileMenu(); return newFileMenu.registerEntry(entry); }; const removeNewFileMenuEntry = function(entry) { const newFileMenu = getNewFileMenu(); return newFileMenu.unregisterEntry(entry); }; const getNewFileMenuEntries = function(context) { const newFileMenu = getNewFileMenu(); return newFileMenu.getEntries(context).sort((a2, b2) => { if (a2.order !== void 0 && b2.order !== void 0 && a2.order !== b2.order) { return a2.order - b2.order; } return a2.displayName.localeCompare(b2.displayName, void 0, { numeric: true, sensitivity: "base" }); }); }; export { Column, DefaultType, q as File, FileAction, FileListAction, FileListFilter, F as FileType, FilesSortingMode, s as Folder, Header, InvalidFilenameError, InvalidFilenameErrorReason, Navigation, NewMenuEntryCategory, N as Node, t as NodeStatus, P as Permission, View, addNewFileMenuEntry, c as davGetClient, l as davGetDefaultPropfind, m as davGetFavoritesReport, n as davGetRecentSearch, a as davGetRemoteURL, g as davGetRootPath, p as davParsePermissions, b as davRemoteURL, r as davResultToNode, d as davRootPath, h as defaultDavNamespaces, f as defaultDavProperties, formatFileSize, k as getDavNameSpaces, j as getDavProperties, e as getFavoriteNodes, getFileActions, getFileListActions, getFileListFilters, getFileListHeaders, getNavigation, getNewFileMenuEntries, getUniqueName, isFilenameValid, orderBy, parseFileSize, i as registerDavProperty, registerFileAction, registerFileListAction, registerFileListFilter, registerFileListHeaders, removeNewFileMenuEntry, sortNodes, unregisterFileListFilter, validateFilename };