phylotree 2.6.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/phylotree.js CHANGED
@@ -6842,6 +6842,612 @@
6842
6842
  return match.startIndex + match[1].length;
6843
6843
  }
6844
6844
 
6845
+ // ---------------------------------------------------------------------------
6846
+ // Complete HTML5 named entity reference
6847
+ // Organized by logical categories for easy maintenance and selective importing
6848
+ // ---------------------------------------------------------------------------
6849
+
6850
+
6851
+ /**
6852
+ * Currency Symbols
6853
+ * @type {Record<string, string>}
6854
+ */
6855
+ const CURRENCY = {
6856
+ cent: '¢',
6857
+ pound: '£',
6858
+ curren: '¤',
6859
+ yen: '¥',
6860
+ euro: '€',
6861
+ dollar: '$',
6862
+ euro: '€',
6863
+ fnof: 'ƒ',
6864
+ inr: '₹',
6865
+ af: '؋',
6866
+ birr: 'ብር',
6867
+ peso: '₱',
6868
+ rub: '₽',
6869
+ won: '₩',
6870
+ yuan: '¥',
6871
+ cedil: '¸',
6872
+ };
6873
+
6874
+ const XML = {
6875
+ amp: "&",
6876
+ apos: "'",
6877
+ gt: ">",
6878
+ lt: "<",
6879
+ quot: "\""
6880
+ };
6881
+ const COMMON_HTML = {
6882
+ nbsp: '\u00a0',
6883
+ copy: '\u00a9',
6884
+ reg: '\u00ae',
6885
+ trade: '\u2122',
6886
+ mdash: '\u2014',
6887
+ ndash: '\u2013',
6888
+ hellip: '\u2026',
6889
+ laquo: '\u00ab',
6890
+ raquo: '\u00bb',
6891
+ lsquo: '\u2018',
6892
+ rsquo: '\u2019',
6893
+ ldquo: '\u201c',
6894
+ rdquo: '\u201d',
6895
+ bull: '\u2022',
6896
+ para: '\u00b6',
6897
+ sect: '\u00a7',
6898
+ deg: '\u00b0',
6899
+ frac12: '\u00bd',
6900
+ frac14: '\u00bc',
6901
+ frac34: '\u00be',
6902
+ };
6903
+ // ---------------------------------------------------------------------------
6904
+ // Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly
6905
+ // via String.fromCodePoint() without any map lookup.
6906
+ // ---------------------------------------------------------------------------
6907
+
6908
+ // ---------------------------------------------------------------------------
6909
+ // Built-in named entity map (name → replacement string)
6910
+ // No regex, no {regex,val} objects — just flat key/value pairs.
6911
+ // ---------------------------------------------------------------------------
6912
+
6913
+
6914
+ // ---------------------------------------------------------------------------
6915
+ // Helpers
6916
+ // ---------------------------------------------------------------------------
6917
+
6918
+ const SPECIAL_CHARS = new Set('!?\\\\/[]$%{}^&*()<>|+');
6919
+
6920
+ /**
6921
+ * Validate that an entity name contains no dangerous characters.
6922
+ * @param {string} name
6923
+ * @returns {string} the name, unchanged
6924
+ * @throws {Error} on invalid characters
6925
+ */
6926
+ function validateEntityName$1(name) {
6927
+ if (name[0] === '#') {
6928
+ throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);
6929
+ }
6930
+ for (const ch of name) {
6931
+ if (SPECIAL_CHARS.has(ch)) {
6932
+ throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);
6933
+ }
6934
+ }
6935
+ return name;
6936
+ }
6937
+
6938
+ /**
6939
+ * Merge one or more entity maps into a flat name→string map.
6940
+ * Accepts either:
6941
+ * - plain string values: { amp: '&' }
6942
+ * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }
6943
+ *
6944
+ * Values containing '&' are skipped (recursive expansion risk).
6945
+ *
6946
+ * @param {...object} maps
6947
+ * @returns {Record<string, string>}
6948
+ */
6949
+ function mergeEntityMaps(...maps) {
6950
+ const out = Object.create(null);
6951
+ for (const map of maps) {
6952
+ if (!map) continue;
6953
+ for (const key of Object.keys(map)) {
6954
+ const raw = map[key];
6955
+ if (typeof raw === 'string') {
6956
+ out[key] = raw;
6957
+ } else if (raw && typeof raw === 'object' && raw.val !== undefined) {
6958
+ // Legacy {regex,val} or {regx,val} — extract the string val only
6959
+ const val = raw.val;
6960
+ if (typeof val === 'string') {
6961
+ out[key] = val;
6962
+ }
6963
+ // function vals are not supported in the scanner — skip
6964
+ }
6965
+ }
6966
+ }
6967
+ return out;
6968
+ }
6969
+
6970
+ // ---------------------------------------------------------------------------
6971
+ // applyLimitsTo helpers
6972
+ // ---------------------------------------------------------------------------
6973
+
6974
+ const LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps
6975
+ const LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps
6976
+ const LIMIT_TIER_ALL = 'all'; // every entity regardless of tier
6977
+
6978
+ /**
6979
+ * Resolve `applyLimitsTo` option into a normalised Set of tier strings.
6980
+ * Accepted values: 'external' | 'base' | 'all' | string[]
6981
+ * Default: 'external' (only untrusted injected entities are counted).
6982
+ * @param {string|string[]|undefined} raw
6983
+ * @returns {Set<string>}
6984
+ */
6985
+ function parseLimitTiers(raw) {
6986
+ if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);
6987
+ if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);
6988
+ if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);
6989
+ if (Array.isArray(raw)) return new Set(raw);
6990
+ return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values
6991
+ }
6992
+
6993
+ // ---------------------------------------------------------------------------
6994
+ // NCR (Numeric Character Reference) classification
6995
+ // ---------------------------------------------------------------------------
6996
+
6997
+ // Severity order — higher number = stricter action.
6998
+ // Used to enforce minimum action levels for specific codepoint ranges.
6999
+ const NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });
7000
+
7001
+ // XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
7002
+ // Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D
7003
+ const XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);
7004
+
7005
+ /**
7006
+ * Parse the `ncr` constructor option into flat, hot-path-friendly fields.
7007
+ * @param {object|undefined} ncr
7008
+ * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}
7009
+ */
7010
+ function parseNCRConfig(ncr) {
7011
+ if (!ncr) {
7012
+ return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };
7013
+ }
7014
+ const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;
7015
+ const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;
7016
+ const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;
7017
+ // 'allow' is not meaningful for null — clamp to at least 'remove'
7018
+ const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);
7019
+ return { xmlVersion, onLevel, nullLevel: clampedNull };
7020
+ }
7021
+
7022
+ // ---------------------------------------------------------------------------
7023
+ // EntityReplacer
7024
+ // ---------------------------------------------------------------------------
7025
+
7026
+ /**
7027
+ * Single-pass, zero-regex entity replacer for XML/HTML content.
7028
+ *
7029
+ * Algorithm: scan the string once for '&', read to ';', resolve via map
7030
+ * or direct codepoint conversion, build output chunks, join once at the end.
7031
+ *
7032
+ * Entity lookup priority (highest → lowest):
7033
+ * 1. input / runtime (DOCTYPE entities for current document)
7034
+ * 2. persistent external (survive across documents)
7035
+ * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)
7036
+ *
7037
+ * Both input and external resolve as the 'external' tier for limit purposes.
7038
+ * Base map entities resolve as the 'base' tier.
7039
+ *
7040
+ * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via
7041
+ * String.fromCodePoint() — no map needed. They count as 'base' tier.
7042
+ *
7043
+ * @example
7044
+ * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });
7045
+ * replacer.setExternalEntities({ brand: 'Acme' });
7046
+ *
7047
+ * const instance = replacer.reset();
7048
+ * instance.addInputEntities({ version: '1.0' });
7049
+ * instance.encode('&brand; v&version; &lt;'); // 'Acme v1.0 <'
7050
+ */
7051
+ class EntityDecoder {
7052
+ /**
7053
+ * @param {object} [options]
7054
+ * @param {object|null} [options.namedEntities] — extra named entities merged into base map
7055
+ * @param {object} [options.limit] — security limits
7056
+ * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited
7057
+ * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited
7058
+ * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']
7059
+ * Which entity tiers count against the security limits:
7060
+ * - 'external' (default) — only input/runtime + persistent external entities
7061
+ * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities
7062
+ * - 'all' — every entity regardless of tier
7063
+ * - string[] — explicit combination, e.g. ['external', 'base']
7064
+ * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]
7065
+ * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)
7066
+ * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)
7067
+ * @param {object} [options.ncr] — Numeric Character Reference controls
7068
+ * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]
7069
+ * XML version governing which codepoint ranges are restricted:
7070
+ * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited
7071
+ * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is
7072
+ * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']
7073
+ * Base action for numeric references. Severity order: allow < leave < remove < throw.
7074
+ * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),
7075
+ * the effective action is max(onNCR, rangeMinimum).
7076
+ * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']
7077
+ * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.
7078
+ */
7079
+ constructor(options = {}) {
7080
+ this._limit = options.limit || {};
7081
+ this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;
7082
+ this._maxExpandedLength = this._limit.maxExpandedLength || 0;
7083
+ this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;
7084
+ this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);
7085
+ this._numericAllowed = options.numericAllowed ?? true;
7086
+ // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.
7087
+ this._baseMap = mergeEntityMaps(XML, options.namedEntities || null);
7088
+
7089
+ // Persistent external entities — survive across documents.
7090
+ // Stored as a separate map so reset() never touches them.
7091
+ /** @type {Record<string, string>} */
7092
+ this._externalMap = Object.create(null);
7093
+
7094
+ // Input / runtime entities — current document only, wiped on reset().
7095
+ /** @type {Record<string, string>} */
7096
+ this._inputMap = Object.create(null);
7097
+
7098
+ // Per-document counters
7099
+ this._totalExpansions = 0;
7100
+ this._expandedLength = 0;
7101
+
7102
+ // --- New: remove / leave sets ---
7103
+ /** @type {Set<string>} */
7104
+ this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);
7105
+ /** @type {Set<string>} */
7106
+ this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);
7107
+
7108
+ // --- NCR config (parsed into flat fields for hot-path speed) ---
7109
+ const ncrCfg = parseNCRConfig(options.ncr);
7110
+ this._ncrXmlVersion = ncrCfg.xmlVersion;
7111
+ this._ncrOnLevel = ncrCfg.onLevel;
7112
+ this._ncrNullLevel = ncrCfg.nullLevel;
7113
+ }
7114
+
7115
+ // -------------------------------------------------------------------------
7116
+ // Persistent external entity registration
7117
+ // -------------------------------------------------------------------------
7118
+
7119
+ /**
7120
+ * Replace the full set of persistent external entities.
7121
+ * All keys are validated — throws on invalid characters.
7122
+ * @param {Record<string, string | { regex?: RegExp, val: string }>} map
7123
+ */
7124
+ setExternalEntities(map) {
7125
+ if (map) {
7126
+ for (const key of Object.keys(map)) {
7127
+ validateEntityName$1(key);
7128
+ }
7129
+ }
7130
+ this._externalMap = mergeEntityMaps(map);
7131
+ }
7132
+
7133
+ /**
7134
+ * Add a single persistent external entity.
7135
+ * @param {string} key
7136
+ * @param {string} value
7137
+ */
7138
+ addExternalEntity(key, value) {
7139
+ validateEntityName$1(key);
7140
+ if (typeof value === 'string' && value.indexOf('&') === -1) {
7141
+ this._externalMap[key] = value;
7142
+ }
7143
+ }
7144
+
7145
+ // -------------------------------------------------------------------------
7146
+ // Input / runtime entity registration (per document)
7147
+ // -------------------------------------------------------------------------
7148
+
7149
+ /**
7150
+ * Inject DOCTYPE entities for the current document.
7151
+ * Also resets per-document expansion counters.
7152
+ * @param {Record<string, string | { regx?: RegExp, regex?: RegExp, val: string }>} map
7153
+ */
7154
+ addInputEntities(map) {
7155
+ this._totalExpansions = 0;
7156
+ this._expandedLength = 0;
7157
+ this._inputMap = mergeEntityMaps(map);
7158
+ }
7159
+
7160
+ // -------------------------------------------------------------------------
7161
+ // Per-document reset
7162
+ // -------------------------------------------------------------------------
7163
+
7164
+ /**
7165
+ * Wipe input/runtime entities and reset counters.
7166
+ * Call this before processing each new document.
7167
+ * @returns {this}
7168
+ */
7169
+ reset() {
7170
+ this._inputMap = Object.create(null);
7171
+ this._totalExpansions = 0;
7172
+ this._expandedLength = 0;
7173
+ return this;
7174
+ }
7175
+
7176
+ // -------------------------------------------------------------------------
7177
+ // XML version (can be set after construction, e.g. once parser reads <?xml?>)
7178
+ // -------------------------------------------------------------------------
7179
+
7180
+ /**
7181
+ * Update the XML version used for NCR classification.
7182
+ * Call this as soon as the document's `<?xml version="...">` declaration is parsed.
7183
+ * @param {1.0|1.1|number} version
7184
+ */
7185
+ setXmlVersion(version) {
7186
+ this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;
7187
+ }
7188
+
7189
+ // -------------------------------------------------------------------------
7190
+ // Primary API
7191
+ // -------------------------------------------------------------------------
7192
+
7193
+ /**
7194
+ * Replace all entity references in `str` in a single pass.
7195
+ *
7196
+ * @param {string} str
7197
+ * @returns {string}
7198
+ */
7199
+ decode(str) {
7200
+ if (typeof str !== 'string' || str.length === 0) return str;
7201
+ //TODO: check if needed
7202
+ //if (str.indexOf('&') === -1) return str; // fast path — no entities at all
7203
+
7204
+ const original = str;
7205
+ const chunks = [];
7206
+ const len = str.length;
7207
+ let last = 0; // start of next unprocessed literal chunk
7208
+ let i = 0;
7209
+
7210
+ const limitExpansions = this._maxTotalExpansions > 0;
7211
+ const limitLength = this._maxExpandedLength > 0;
7212
+ const checkLimits = limitExpansions || limitLength;
7213
+
7214
+ while (i < len) {
7215
+ // Scan forward to next '&'
7216
+ if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }
7217
+
7218
+ // --- Found '&' at position i ---
7219
+
7220
+ // Scan forward to ';'
7221
+ let j = i + 1;
7222
+ while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;
7223
+
7224
+ if (j >= len || str.charCodeAt(j) !== 59) {
7225
+ // No closing ';' within window — treat '&' as literal
7226
+ i++;
7227
+ continue;
7228
+ }
7229
+
7230
+ // Raw token between '&' and ';' (exclusive)
7231
+ const token = str.slice(i + 1, j);
7232
+ if (token.length === 0) { i++; continue; }
7233
+
7234
+ let replacement;
7235
+ let tier; // which limit tier this entity belongs to
7236
+
7237
+ if (this._removeSet.has(token)) {
7238
+ // Remove entity: replace with empty string
7239
+ replacement = '';
7240
+ // If entity was unknown (replacement undefined), we still need a tier for limits.
7241
+ // Treat as external tier because it's user-directed removal of an unknown reference.
7242
+ if (tier === undefined) {
7243
+ tier = LIMIT_TIER_EXTERNAL;
7244
+ }
7245
+ } else if (this._leaveSet.has(token)) {
7246
+ // Do not replace — keep original &token; as literal
7247
+ i++;
7248
+ continue;
7249
+ } else if (token.charCodeAt(0) === 35 /* '#' */) {
7250
+ // ---- Numeric / NCR reference ----
7251
+ // NCR classification always runs first — prohibited codepoints must be
7252
+ // caught regardless of numericAllowed.
7253
+ const ncrResult = this._resolveNCR(token);
7254
+ if (ncrResult === undefined) {
7255
+ // 'leave' action — keep original &token; as-is
7256
+ i++;
7257
+ continue;
7258
+ }
7259
+ replacement = ncrResult; // '' for remove, char string for allow
7260
+ tier = LIMIT_TIER_BASE;
7261
+ } else {
7262
+ // ---- Named reference ----
7263
+ const resolved = this._resolveName(token);
7264
+ replacement = resolved?.value;
7265
+ tier = resolved?.tier;
7266
+ }
7267
+
7268
+ if (replacement === undefined) {
7269
+ // Unknown entity — leave as-is, advance past '&' only
7270
+ i++;
7271
+ continue;
7272
+ }
7273
+
7274
+ // Flush literal chunk before this entity
7275
+ if (i > last) chunks.push(str.slice(last, i));
7276
+ chunks.push(replacement);
7277
+ last = j + 1; // skip past ';'
7278
+ i = last;
7279
+
7280
+ // Apply expansion limits only if this tier is being tracked
7281
+ if (checkLimits && this._tierCounts(tier)) {
7282
+ if (limitExpansions) {
7283
+ this._totalExpansions++;
7284
+ if (this._totalExpansions > this._maxTotalExpansions) {
7285
+ throw new Error(
7286
+ `[EntityReplacer] Entity expansion count limit exceeded: ` +
7287
+ `${this._totalExpansions} > ${this._maxTotalExpansions}`
7288
+ );
7289
+ }
7290
+ }
7291
+ if (limitLength) {
7292
+ // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')
7293
+ const delta = replacement.length - (token.length + 2);
7294
+ if (delta > 0) {
7295
+ this._expandedLength += delta;
7296
+ if (this._expandedLength > this._maxExpandedLength) {
7297
+ throw new Error(
7298
+ `[EntityReplacer] Expanded content length limit exceeded: ` +
7299
+ `${this._expandedLength} > ${this._maxExpandedLength}`
7300
+ );
7301
+ }
7302
+ }
7303
+ }
7304
+ }
7305
+ }
7306
+
7307
+ // Flush trailing literal
7308
+ if (last < len) chunks.push(str.slice(last));
7309
+
7310
+ // If nothing was replaced, chunks is empty — return original
7311
+ const result = chunks.length === 0 ? str : chunks.join('');
7312
+
7313
+ return this._postCheck(result, original);
7314
+ }
7315
+
7316
+ // -------------------------------------------------------------------------
7317
+ // Private: limit tier check
7318
+ // -------------------------------------------------------------------------
7319
+
7320
+ /**
7321
+ * Returns true if a resolved entity of the given tier should count
7322
+ * against the expansion/length limits.
7323
+ * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE
7324
+ * @returns {boolean}
7325
+ */
7326
+ _tierCounts(tier) {
7327
+ if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;
7328
+ return this._limitTiers.has(tier);
7329
+ }
7330
+
7331
+ // -------------------------------------------------------------------------
7332
+ // Private: entity resolution
7333
+ // -------------------------------------------------------------------------
7334
+
7335
+ /**
7336
+ * Resolve a named entity token (without & and ;).
7337
+ * Priority: inputMap > externalMap > baseMap
7338
+ * Returns the resolved value tagged with its limit tier.
7339
+ *
7340
+ * @param {string} name
7341
+ * @returns {{ value: string, tier: string }|undefined}
7342
+ */
7343
+ _resolveName(name) {
7344
+ // input and external both count as 'external' tier for limit purposes —
7345
+ // they are injected at runtime and are the untrusted surface.
7346
+ if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };
7347
+ if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };
7348
+ if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };
7349
+ return undefined;
7350
+ }
7351
+
7352
+ /**
7353
+ * Classify a codepoint and return the minimum action level that must be applied.
7354
+ * Returns -1 when no minimum is imposed (normal allow path).
7355
+ *
7356
+ * Ranges checked (in priority order):
7357
+ * 1. U+0000 — null, governed by nullNCR (always ≥ remove)
7358
+ * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)
7359
+ * 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)
7360
+ * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)
7361
+ *
7362
+ * @param {number} cp — codepoint
7363
+ * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction
7364
+ */
7365
+ _classifyNCR(cp) {
7366
+ // 1. Null
7367
+ if (cp === 0) return this._ncrNullLevel;
7368
+
7369
+ // 2. Surrogates — always prohibited, minimum 'remove'
7370
+ if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;
7371
+
7372
+ // 3. XML 1.0 restricted C0 controls
7373
+ if (this._ncrXmlVersion === 1.0) {
7374
+ if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;
7375
+ }
7376
+
7377
+ return -1; // no restriction
7378
+ }
7379
+
7380
+ /**
7381
+ * Execute a resolved NCR action.
7382
+ *
7383
+ * @param {number} action — NCR_LEVEL value
7384
+ * @param {string} token — raw token (e.g. '#38') for error messages
7385
+ * @param {number} cp — codepoint, used only for error messages
7386
+ * @returns {string|undefined}
7387
+ * - decoded character string → 'allow'
7388
+ * - '' → 'remove'
7389
+ * - undefined → 'leave' (caller must skip past '&' only)
7390
+ * - throws Error → 'throw'
7391
+ */
7392
+ _applyNCRAction(action, token, cp) {
7393
+ switch (action) {
7394
+ case NCR_LEVEL.allow: return String.fromCodePoint(cp);
7395
+ case NCR_LEVEL.remove: return '';
7396
+ case NCR_LEVEL.leave: return undefined; // signal: keep literal
7397
+ case NCR_LEVEL.throw:
7398
+ throw new Error(
7399
+ `[EntityDecoder] Prohibited numeric character reference ` +
7400
+ `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`
7401
+ );
7402
+ default: return String.fromCodePoint(cp);
7403
+ }
7404
+ }
7405
+
7406
+ /**
7407
+ * Full NCR resolution pipeline for a numeric token.
7408
+ *
7409
+ * Steps:
7410
+ * 1. Parse the codepoint (decimal or hex).
7411
+ * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).
7412
+ * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.
7413
+ * 4. Classify the codepoint to find the minimum required action level.
7414
+ * 5. Resolve effective action = max(onNCR, minimum).
7415
+ * 6. Apply and return.
7416
+ *
7417
+ * @param {string} token — e.g. '#38', '#x26', '#X26'
7418
+ * @returns {string|undefined}
7419
+ * - string (incl. '') — replacement ('' = remove)
7420
+ * - undefined — leave original &token; as-is
7421
+ */
7422
+ _resolveNCR(token) {
7423
+ // Step 1: parse codepoint
7424
+ const second = token.charCodeAt(1);
7425
+ let cp;
7426
+ if (second === 120 /* x */ || second === 88 /* X */) {
7427
+ cp = parseInt(token.slice(2), 16);
7428
+ } else {
7429
+ cp = parseInt(token.slice(1), 10);
7430
+ }
7431
+
7432
+ // Step 2: out-of-range → leave as-is unconditionally
7433
+ if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;
7434
+
7435
+ // Step 3: classify to get minimum action level
7436
+ const minimum = this._classifyNCR(cp);
7437
+
7438
+ // Step 4: if numericAllowed is false and no hard minimum → leave
7439
+ if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;
7440
+
7441
+ // Step 5: effective action = max(configured onNCR, range minimum)
7442
+ const effective = minimum === -1
7443
+ ? this._ncrOnLevel
7444
+ : Math.max(this._ncrOnLevel, minimum);
7445
+
7446
+ // Step 6: apply
7447
+ return this._applyNCRAction(effective, token, cp);
7448
+ }
7449
+ }
7450
+
6845
7451
  const defaultOnDangerousProperty = (name) => {
6846
7452
  if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
6847
7453
  return "__" + name;
@@ -6881,6 +7487,7 @@
6881
7487
  unpairedTags: [],
6882
7488
  processEntities: true,
6883
7489
  htmlEntities: false,
7490
+ entityDecoder: null,
6884
7491
  ignoreDeclaration: false,
6885
7492
  ignorePiTags: false,
6886
7493
  transformTagName: false,
@@ -6927,32 +7534,34 @@
6927
7534
  * @param {boolean|object} value
6928
7535
  * @returns {object} Always returns normalized object
6929
7536
  */
6930
- function normalizeProcessEntities(value) {
7537
+ function normalizeProcessEntities(value, htmlEntities) {
6931
7538
  // Boolean backward compatibility
6932
7539
  if (typeof value === 'boolean') {
6933
7540
  return {
6934
7541
  enabled: value, // true or false
6935
7542
  maxEntitySize: 10000,
6936
- maxExpansionDepth: 10,
6937
- maxTotalExpansions: 1000,
7543
+ maxExpansionDepth: 10000,
7544
+ maxTotalExpansions: Infinity,
6938
7545
  maxExpandedLength: 100000,
6939
- maxEntityCount: 100,
7546
+ maxEntityCount: 1000,
6940
7547
  allowedTags: null,
6941
- tagFilter: null
7548
+ tagFilter: null,
7549
+ appliesTo: "all",
6942
7550
  };
6943
7551
  }
6944
7552
 
6945
7553
  // Object config - merge with defaults
6946
7554
  if (typeof value === 'object' && value !== null) {
6947
7555
  return {
6948
- enabled: value.enabled !== false, // default true if not specified
6949
- maxEntitySize: value.maxEntitySize ?? 10000,
6950
- maxExpansionDepth: value.maxExpansionDepth ?? 10,
6951
- maxTotalExpansions: value.maxTotalExpansions ?? 1000,
6952
- maxExpandedLength: value.maxExpandedLength ?? 100000,
6953
- maxEntityCount: value.maxEntityCount ?? 100,
7556
+ enabled: value.enabled !== false,
7557
+ maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),
7558
+ maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),
7559
+ maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),
7560
+ maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),
7561
+ maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),
6954
7562
  allowedTags: value.allowedTags ?? null,
6955
- tagFilter: value.tagFilter ?? null
7563
+ tagFilter: value.tagFilter ?? null,
7564
+ appliesTo: value.appliesTo ?? "all",
6956
7565
  };
6957
7566
  }
6958
7567
 
@@ -6983,8 +7592,8 @@
6983
7592
  }
6984
7593
 
6985
7594
  // Always normalize processEntities for backward compatibility and validation
6986
- built.processEntities = normalizeProcessEntities(built.processEntities);
6987
-
7595
+ built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);
7596
+ built.unpairedTagsSet = new Set(built.unpairedTags);
6988
7597
  // Convert old-style stopNodes for backward compatibility
6989
7598
  if (built.stopNodes && Array.isArray(built.stopNodes)) {
6990
7599
  built.stopNodes = built.stopNodes.map(node => {
@@ -7067,17 +7676,15 @@
7067
7676
  [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);
7068
7677
  if (val.indexOf("&") === -1) { //Parameter entities are not supported
7069
7678
  if (this.options.enabled !== false &&
7070
- this.options.maxEntityCount &&
7679
+ this.options.maxEntityCount != null &&
7071
7680
  entityCount >= this.options.maxEntityCount) {
7072
7681
  throw new Error(
7073
7682
  `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`
7074
7683
  );
7075
7684
  }
7076
- const escaped = entityName.replace(/[.\-+*:]/g, '\\.');
7077
- entities[entityName] = {
7078
- regx: RegExp(`&${escaped};`, "g"),
7079
- val: val
7080
- };
7685
+ //const escaped = entityName.replace(/[.\-+*:]/g, '\\.');
7686
+ //const escaped = entityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
7687
+ entities[entityName] = val;
7081
7688
  entityCount++;
7082
7689
  }
7083
7690
  }
@@ -7138,11 +7745,12 @@
7138
7745
  i = skipWhitespace(xmlData, i);
7139
7746
 
7140
7747
  // Read entity name
7141
- let entityName = "";
7748
+ const startIndex = i;
7142
7749
  while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") {
7143
- entityName += xmlData[i];
7144
7750
  i++;
7145
7751
  }
7752
+ let entityName = xmlData.substring(startIndex, i);
7753
+
7146
7754
  validateEntityName(entityName);
7147
7755
 
7148
7756
  // Skip whitespace after entity name
@@ -7163,7 +7771,7 @@
7163
7771
 
7164
7772
  // Validate entity size
7165
7773
  if (this.options.enabled !== false &&
7166
- this.options.maxEntitySize &&
7774
+ this.options.maxEntitySize != null &&
7167
7775
  entityValue.length > this.options.maxEntitySize) {
7168
7776
  throw new Error(
7169
7777
  `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`
@@ -7179,11 +7787,13 @@
7179
7787
  i = skipWhitespace(xmlData, i);
7180
7788
 
7181
7789
  // Read notation name
7182
- let notationName = "";
7790
+
7791
+ const startIndex = i;
7183
7792
  while (i < xmlData.length && !/\s/.test(xmlData[i])) {
7184
- notationName += xmlData[i];
7185
7793
  i++;
7186
7794
  }
7795
+ let notationName = xmlData.substring(startIndex, i);
7796
+
7187
7797
  !this.suppressValidationErr && validateEntityName(notationName);
7188
7798
 
7189
7799
  // Skip whitespace after notation name
@@ -7233,10 +7843,11 @@
7233
7843
  }
7234
7844
  i++;
7235
7845
 
7846
+ const startIndex = i;
7236
7847
  while (i < xmlData.length && xmlData[i] !== startChar) {
7237
- identifierVal += xmlData[i];
7238
7848
  i++;
7239
7849
  }
7850
+ identifierVal = xmlData.substring(startIndex, i);
7240
7851
 
7241
7852
  if (xmlData[i] !== startChar) {
7242
7853
  throw new Error(`Unterminated ${type} value`);
@@ -7256,11 +7867,11 @@
7256
7867
  i = skipWhitespace(xmlData, i);
7257
7868
 
7258
7869
  // Read element name
7259
- let elementName = "";
7870
+ const startIndex = i;
7260
7871
  while (i < xmlData.length && !/\s/.test(xmlData[i])) {
7261
- elementName += xmlData[i];
7262
7872
  i++;
7263
7873
  }
7874
+ let elementName = xmlData.substring(startIndex, i);
7264
7875
 
7265
7876
  // Validate element name
7266
7877
  if (!this.suppressValidationErr && !isName(elementName)) {
@@ -7277,10 +7888,12 @@
7277
7888
  i++; // Move past '('
7278
7889
 
7279
7890
  // Read content model
7891
+ const startIndex = i;
7280
7892
  while (i < xmlData.length && xmlData[i] !== ")") {
7281
- contentModel += xmlData[i];
7282
7893
  i++;
7283
7894
  }
7895
+ contentModel = xmlData.substring(startIndex, i);
7896
+
7284
7897
  if (xmlData[i] !== ")") {
7285
7898
  throw new Error("Unterminated content model");
7286
7899
  }
@@ -7301,11 +7914,11 @@
7301
7914
  i = skipWhitespace(xmlData, i);
7302
7915
 
7303
7916
  // Read element name
7304
- let elementName = "";
7917
+ let startIndex = i;
7305
7918
  while (i < xmlData.length && !/\s/.test(xmlData[i])) {
7306
- elementName += xmlData[i];
7307
7919
  i++;
7308
7920
  }
7921
+ let elementName = xmlData.substring(startIndex, i);
7309
7922
 
7310
7923
  // Validate element name
7311
7924
  validateEntityName(elementName);
@@ -7314,11 +7927,11 @@
7314
7927
  i = skipWhitespace(xmlData, i);
7315
7928
 
7316
7929
  // Read attribute name
7317
- let attributeName = "";
7930
+ startIndex = i;
7318
7931
  while (i < xmlData.length && !/\s/.test(xmlData[i])) {
7319
- attributeName += xmlData[i];
7320
7932
  i++;
7321
7933
  }
7934
+ let attributeName = xmlData.substring(startIndex, i);
7322
7935
 
7323
7936
  // Validate attribute name
7324
7937
  if (!validateEntityName(attributeName)) {
@@ -7346,11 +7959,13 @@
7346
7959
  // Read the list of allowed notations
7347
7960
  let allowedNotations = [];
7348
7961
  while (i < xmlData.length && xmlData[i] !== ")") {
7349
- let notation = "";
7962
+
7963
+
7964
+ const startIndex = i;
7350
7965
  while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") {
7351
- notation += xmlData[i];
7352
7966
  i++;
7353
7967
  }
7968
+ let notation = xmlData.substring(startIndex, i);
7354
7969
 
7355
7970
  // Validate notation name
7356
7971
  notation = notation.trim();
@@ -7376,10 +7991,11 @@
7376
7991
  attributeType += " (" + allowedNotations.join("|") + ")";
7377
7992
  } else {
7378
7993
  // Handle simple types (e.g., CDATA, ID, IDREF, etc.)
7994
+ const startIndex = i;
7379
7995
  while (i < xmlData.length && !/\s/.test(xmlData[i])) {
7380
- attributeType += xmlData[i];
7381
7996
  i++;
7382
7997
  }
7998
+ attributeType += xmlData.substring(startIndex, i);
7383
7999
 
7384
8000
  // Validate simple attribute type
7385
8001
  const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
@@ -7443,48 +8059,52 @@
7443
8059
  // const octRegex = /^0x[a-z0-9]+/;
7444
8060
  // const binRegex = /0x[a-z0-9]+/;
7445
8061
 
7446
-
8062
+
7447
8063
  const consider = {
7448
- hex : true,
8064
+ hex: true,
7449
8065
  // oct: false,
7450
8066
  leadingZeros: true,
7451
8067
  decimalPoint: "\.",
7452
8068
  eNotation: true,
7453
- //skipLike: /regex/
8069
+ //skipLike: /regex/,
8070
+ infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal))
7454
8071
  };
7455
8072
 
7456
- function toNumber(str, options = {}){
7457
- options = Object.assign({}, consider, options );
7458
- if(!str || typeof str !== "string" ) return str;
7459
-
7460
- let trimmedStr = str.trim();
7461
-
7462
- if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
7463
- else if(str==="0") return 0;
8073
+ function toNumber(str, options = {}) {
8074
+ options = Object.assign({}, consider, options);
8075
+ if (!str || typeof str !== "string") return str;
8076
+
8077
+ let trimmedStr = str.trim();
8078
+
8079
+ if (trimmedStr.length === 0) return str;
8080
+ else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
8081
+ else if (trimmedStr === "0") return 0;
7464
8082
  else if (options.hex && hexRegex.test(trimmedStr)) {
7465
8083
  return parse_int(trimmedStr, 16);
7466
- // }else if (options.oct && octRegex.test(str)) {
7467
- // return Number.parseInt(val, 8);
7468
- }else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation
7469
- return resolveEnotation(str,trimmedStr,options);
7470
- // }else if (options.parseBin && binRegex.test(str)) {
7471
- // return Number.parseInt(val, 2);
7472
- }else {
8084
+ // }else if (options.oct && octRegex.test(str)) {
8085
+ // return Number.parseInt(val, 8);
8086
+ } else if (!isFinite(trimmedStr)) { //Infinity
8087
+ return handleInfinity(str, Number(trimmedStr), options);
8088
+ } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation
8089
+ return resolveEnotation(str, trimmedStr, options);
8090
+ // }else if (options.parseBin && binRegex.test(str)) {
8091
+ // return Number.parseInt(val, 2);
8092
+ } else {
7473
8093
  //separate negative sign, leading zeros, and rest number
7474
8094
  const match = numRegex.exec(trimmedStr);
7475
8095
  // +00.123 => [ , '+', '00', '.123', ..
7476
- if(match){
8096
+ if (match) {
7477
8097
  const sign = match[1] || "";
7478
8098
  const leadingZeros = match[2];
7479
8099
  let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
7480
8100
  const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.
7481
- str[leadingZeros.length+1] === "."
8101
+ str[leadingZeros.length + 1] === "."
7482
8102
  : str[leadingZeros.length] === ".";
7483
8103
 
7484
8104
  //trim ending zeros for floating number
7485
- if(!options.leadingZeros //leading zeros are not allowed
7486
- && (leadingZeros.length > 1
7487
- || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))){
8105
+ if (!options.leadingZeros //leading zeros are not allowed
8106
+ && (leadingZeros.length > 1
8107
+ || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) {
7488
8108
  // 00, 00.3, +03.24, 03, 03.24
7489
8109
  return str;
7490
8110
  }
@@ -7492,54 +8112,59 @@
7492
8112
  const num = Number(trimmedStr);
7493
8113
  const parsedStr = String(num);
7494
8114
 
7495
- if( num === 0) return num;
7496
- if(parsedStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
7497
- if(options.eNotation) return num;
8115
+ if (num === 0) return num;
8116
+ if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation
8117
+ if (options.eNotation) return num;
7498
8118
  else return str;
7499
- }else if(trimmedStr.indexOf(".") !== -1){ //floating number
7500
- if(parsedStr === "0") return num; //0.0
7501
- else if(parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000
7502
- else if( parsedStr === `${sign}${numTrimmedByZeros}`) return num;
8119
+ } else if (trimmedStr.indexOf(".") !== -1) { //floating number
8120
+ if (parsedStr === "0") return num; //0.0
8121
+ else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000
8122
+ else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;
7503
8123
  else return str;
7504
8124
  }
7505
-
7506
- let n = leadingZeros? numTrimmedByZeros : trimmedStr;
7507
- if(leadingZeros){
8125
+
8126
+ let n = leadingZeros ? numTrimmedByZeros : trimmedStr;
8127
+ if (leadingZeros) {
7508
8128
  // -009 => -9
7509
- return (n === parsedStr) || (sign+n === parsedStr) ? num : str
7510
- }else {
8129
+ return (n === parsedStr) || (sign + n === parsedStr) ? num : str
8130
+ } else {
7511
8131
  // +9
7512
- return (n === parsedStr) || (n === sign+parsedStr) ? num : str
8132
+ return (n === parsedStr) || (n === sign + parsedStr) ? num : str
7513
8133
  }
7514
8134
  }
7515
- }else { //non-numeric string
8135
+ } else { //non-numeric string
7516
8136
  return str;
7517
8137
  }
7518
8138
  }
7519
8139
  }
7520
8140
 
7521
8141
  const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
7522
- function resolveEnotation(str,trimmedStr,options){
7523
- if(!options.eNotation) return str;
7524
- const notation = trimmedStr.match(eNotationRegx);
7525
- if(notation){
8142
+ function resolveEnotation(str, trimmedStr, options) {
8143
+ if (!options.eNotation) return str;
8144
+ const notation = trimmedStr.match(eNotationRegx);
8145
+ if (notation) {
7526
8146
  let sign = notation[1] || "";
7527
8147
  const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
7528
8148
  const leadingZeros = notation[2];
7529
8149
  const eAdjacentToLeadingZeros = sign ? // 0E.
7530
- str[leadingZeros.length+1] === eChar
8150
+ str[leadingZeros.length + 1] === eChar
7531
8151
  : str[leadingZeros.length] === eChar;
7532
8152
 
7533
- if(leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;
7534
- else if(leadingZeros.length === 1
7535
- && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)){
8153
+ if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;
8154
+ else if (leadingZeros.length === 1
8155
+ && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {
8156
+ return Number(trimmedStr);
8157
+ } else if (leadingZeros.length > 0) {
8158
+ // Has leading zeros — only accept if leadingZeros option allows it
8159
+ if (options.leadingZeros && !eAdjacentToLeadingZeros) {
8160
+ trimmedStr = (notation[1] || "") + notation[3];
7536
8161
  return Number(trimmedStr);
7537
- }else if(options.leadingZeros && !eAdjacentToLeadingZeros){ //accept with leading zeros
7538
- //remove leading 0s
7539
- trimmedStr = (notation[1] || "") + notation[3];
8162
+ } else return str;
8163
+ } else {
8164
+ // No leading zeros — always valid e-notation, parse it
7540
8165
  return Number(trimmedStr);
7541
- }else return str;
7542
- }else {
8166
+ }
8167
+ } else {
7543
8168
  return str;
7544
8169
  }
7545
8170
  }
@@ -7549,25 +8174,48 @@
7549
8174
  * @param {string} numStr without leading zeros
7550
8175
  * @returns
7551
8176
  */
7552
- function trimZeros(numStr){
7553
- if(numStr && numStr.indexOf(".") !== -1){//float
8177
+ function trimZeros(numStr) {
8178
+ if (numStr && numStr.indexOf(".") !== -1) {//float
7554
8179
  numStr = numStr.replace(/0+$/, ""); //remove ending zeros
7555
- if(numStr === ".") numStr = "0";
7556
- else if(numStr[0] === ".") numStr = "0"+numStr;
7557
- else if(numStr[numStr.length-1] === ".") numStr = numStr.substring(0,numStr.length-1);
8180
+ if (numStr === ".") numStr = "0";
8181
+ else if (numStr[0] === ".") numStr = "0" + numStr;
8182
+ else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1);
7558
8183
  return numStr;
7559
8184
  }
7560
8185
  return numStr;
7561
8186
  }
7562
8187
 
7563
- function parse_int(numStr, base){
8188
+ function parse_int(numStr, base) {
7564
8189
  //polyfill
7565
- if(parseInt) return parseInt(numStr, base);
7566
- else if(Number.parseInt) return Number.parseInt(numStr, base);
7567
- else if(window && window.parseInt) return window.parseInt(numStr, base);
8190
+ if (parseInt) return parseInt(numStr, base);
8191
+ else if (Number.parseInt) return Number.parseInt(numStr, base);
8192
+ else if (window && window.parseInt) return window.parseInt(numStr, base);
7568
8193
  else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")
7569
8194
  }
7570
8195
 
8196
+ /**
8197
+ * Handle infinite values based on user option
8198
+ * @param {string} str - original input string
8199
+ * @param {number} num - parsed number (Infinity or -Infinity)
8200
+ * @param {object} options - user options
8201
+ * @returns {string|number|null} based on infinity option
8202
+ */
8203
+ function handleInfinity(str, num, options) {
8204
+ const isPositive = num === Infinity;
8205
+
8206
+ switch (options.infinity.toLowerCase()) {
8207
+ case "null":
8208
+ return null;
8209
+ case "infinity":
8210
+ return num; // Return Infinity or -Infinity
8211
+ case "string":
8212
+ return isPositive ? "Infinity" : "-Infinity";
8213
+ case "original":
8214
+ default:
8215
+ return str; // Return original string like "1e1000"
8216
+ }
8217
+ }
8218
+
7571
8219
  function getIgnoreAttributesFn(ignoreAttributes) {
7572
8220
  if (typeof ignoreAttributes === 'function') {
7573
8221
  return ignoreAttributes
@@ -7604,11 +8252,11 @@
7604
8252
  * @param {Object} options - Configuration options
7605
8253
  * @param {string} options.separator - Path separator (default: '.')
7606
8254
  */
7607
- constructor(pattern, options = {}) {
8255
+ constructor(pattern, options = {}, data) {
7608
8256
  this.pattern = pattern;
7609
8257
  this.separator = options.separator || '.';
7610
8258
  this.segments = this._parse(pattern);
7611
-
8259
+ this.data = data;
7612
8260
  // Cache expensive checks for performance (O(1) instead of O(n))
7613
8261
  this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');
7614
8262
  this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);
@@ -7776,92 +8424,458 @@
7776
8424
  }
7777
8425
  }
7778
8426
 
7779
- return segment;
8427
+ return segment;
8428
+ }
8429
+
8430
+ /**
8431
+ * Get the number of segments
8432
+ * @returns {number}
8433
+ */
8434
+ get length() {
8435
+ return this.segments.length;
8436
+ }
8437
+
8438
+ /**
8439
+ * Check if expression contains deep wildcard
8440
+ * @returns {boolean}
8441
+ */
8442
+ hasDeepWildcard() {
8443
+ return this._hasDeepWildcard;
8444
+ }
8445
+
8446
+ /**
8447
+ * Check if expression has attribute conditions
8448
+ * @returns {boolean}
8449
+ */
8450
+ hasAttributeCondition() {
8451
+ return this._hasAttributeCondition;
8452
+ }
8453
+
8454
+ /**
8455
+ * Check if expression has position selectors
8456
+ * @returns {boolean}
8457
+ */
8458
+ hasPositionSelector() {
8459
+ return this._hasPositionSelector;
8460
+ }
8461
+
8462
+ /**
8463
+ * Get string representation
8464
+ * @returns {string}
8465
+ */
8466
+ toString() {
8467
+ return this.pattern;
8468
+ }
8469
+ }
8470
+
8471
+ /**
8472
+ * ExpressionSet - An indexed collection of Expressions for efficient bulk matching
8473
+ *
8474
+ * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes
8475
+ * them at insertion time by depth and terminal tag name. At match time, only
8476
+ * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)
8477
+ * lookup plus O(small bucket) matches.
8478
+ *
8479
+ * Three buckets are maintained:
8480
+ * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)
8481
+ * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)
8482
+ * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)
8483
+ *
8484
+ * @example
8485
+ * import { Expression, ExpressionSet } from 'fast-xml-tagger';
8486
+ *
8487
+ * // Build once at config time
8488
+ * const stopNodes = new ExpressionSet();
8489
+ * stopNodes.add(new Expression('root.users.user'));
8490
+ * stopNodes.add(new Expression('root.config.setting'));
8491
+ * stopNodes.add(new Expression('..script'));
8492
+ *
8493
+ * // Query on every tag — hot path
8494
+ * if (stopNodes.matchesAny(matcher)) { ... }
8495
+ */
8496
+ class ExpressionSet {
8497
+ constructor() {
8498
+ /** @type {Map<string, import('./Expression.js').default[]>} depth:tag → expressions */
8499
+ this._byDepthAndTag = new Map();
8500
+
8501
+ /** @type {Map<number, import('./Expression.js').default[]>} depth → wildcard-tag expressions */
8502
+ this._wildcardByDepth = new Map();
8503
+
8504
+ /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */
8505
+ this._deepWildcards = [];
8506
+
8507
+ /** @type {Set<string>} pattern strings already added — used for deduplication */
8508
+ this._patterns = new Set();
8509
+
8510
+ /** @type {boolean} whether the set is sealed against further additions */
8511
+ this._sealed = false;
8512
+ }
8513
+
8514
+ /**
8515
+ * Add an Expression to the set.
8516
+ * Duplicate patterns (same pattern string) are silently ignored.
8517
+ *
8518
+ * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance
8519
+ * @returns {this} for chaining
8520
+ * @throws {TypeError} if called after seal()
8521
+ *
8522
+ * @example
8523
+ * set.add(new Expression('root.users.user'));
8524
+ * set.add(new Expression('..script'));
8525
+ */
8526
+ add(expression) {
8527
+ if (this._sealed) {
8528
+ throw new TypeError(
8529
+ 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'
8530
+ );
8531
+ }
8532
+
8533
+ // Deduplicate by pattern string
8534
+ if (this._patterns.has(expression.pattern)) return this;
8535
+ this._patterns.add(expression.pattern);
8536
+
8537
+ if (expression.hasDeepWildcard()) {
8538
+ this._deepWildcards.push(expression);
8539
+ return this;
8540
+ }
8541
+
8542
+ const depth = expression.length;
8543
+ const lastSeg = expression.segments[expression.segments.length - 1];
8544
+ const tag = lastSeg?.tag;
8545
+
8546
+ if (!tag || tag === '*') {
8547
+ // Can index by depth but not by tag
8548
+ if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);
8549
+ this._wildcardByDepth.get(depth).push(expression);
8550
+ } else {
8551
+ // Tightest bucket: depth + tag
8552
+ const key = `${depth}:${tag}`;
8553
+ if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);
8554
+ this._byDepthAndTag.get(key).push(expression);
8555
+ }
8556
+
8557
+ return this;
8558
+ }
8559
+
8560
+ /**
8561
+ * Add multiple expressions at once.
8562
+ *
8563
+ * @param {import('./Expression.js').default[]} expressions - Array of Expression instances
8564
+ * @returns {this} for chaining
8565
+ *
8566
+ * @example
8567
+ * set.addAll([
8568
+ * new Expression('root.users.user'),
8569
+ * new Expression('root.config.setting'),
8570
+ * ]);
8571
+ */
8572
+ addAll(expressions) {
8573
+ for (const expr of expressions) this.add(expr);
8574
+ return this;
8575
+ }
8576
+
8577
+ /**
8578
+ * Check whether a pattern string is already present in the set.
8579
+ *
8580
+ * @param {import('./Expression.js').default} expression
8581
+ * @returns {boolean}
8582
+ */
8583
+ has(expression) {
8584
+ return this._patterns.has(expression.pattern);
8585
+ }
8586
+
8587
+ /**
8588
+ * Number of expressions in the set.
8589
+ * @type {number}
8590
+ */
8591
+ get size() {
8592
+ return this._patterns.size;
8593
+ }
8594
+
8595
+ /**
8596
+ * Seal the set against further modifications.
8597
+ * Useful to prevent accidental mutations after config is built.
8598
+ * Calling add() or addAll() on a sealed set throws a TypeError.
8599
+ *
8600
+ * @returns {this}
8601
+ */
8602
+ seal() {
8603
+ this._sealed = true;
8604
+ return this;
8605
+ }
8606
+
8607
+ /**
8608
+ * Whether the set has been sealed.
8609
+ * @type {boolean}
8610
+ */
8611
+ get isSealed() {
8612
+ return this._sealed;
8613
+ }
8614
+
8615
+ /**
8616
+ * Test whether the matcher's current path matches any expression in the set.
8617
+ *
8618
+ * Evaluation order (cheapest → most expensive):
8619
+ * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions
8620
+ * 2. Depth-only wildcard bucket — O(1) lookup, rare
8621
+ * 3. Deep-wildcard list — always checked, but usually small
8622
+ *
8623
+ * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)
8624
+ * @returns {boolean} true if any expression matches the current path
8625
+ *
8626
+ * @example
8627
+ * if (stopNodes.matchesAny(matcher)) {
8628
+ * // handle stop node
8629
+ * }
8630
+ */
8631
+ matchesAny(matcher) {
8632
+ return this.findMatch(matcher) !== null;
8633
+ }
8634
+ /**
8635
+ * Find and return the first Expression that matches the matcher's current path.
8636
+ *
8637
+ * Uses the same evaluation order as matchesAny (cheapest → most expensive):
8638
+ * 1. Exact depth + tag bucket
8639
+ * 2. Depth-only wildcard bucket
8640
+ * 3. Deep-wildcard list
8641
+ *
8642
+ * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)
8643
+ * @returns {import('./Expression.js').default | null} the first matching Expression, or null
8644
+ *
8645
+ * @example
8646
+ * const expr = stopNodes.findMatch(matcher);
8647
+ * if (expr) {
8648
+ * // access expr.config, expr.pattern, etc.
8649
+ * }
8650
+ */
8651
+ findMatch(matcher) {
8652
+ const depth = matcher.getDepth();
8653
+ const tag = matcher.getCurrentTag();
8654
+
8655
+ // 1. Tightest bucket — most expressions live here
8656
+ const exactKey = `${depth}:${tag}`;
8657
+ const exactBucket = this._byDepthAndTag.get(exactKey);
8658
+ if (exactBucket) {
8659
+ for (let i = 0; i < exactBucket.length; i++) {
8660
+ if (matcher.matches(exactBucket[i])) return exactBucket[i];
8661
+ }
8662
+ }
8663
+
8664
+ // 2. Depth-matched wildcard-tag expressions
8665
+ const wildcardBucket = this._wildcardByDepth.get(depth);
8666
+ if (wildcardBucket) {
8667
+ for (let i = 0; i < wildcardBucket.length; i++) {
8668
+ if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];
8669
+ }
8670
+ }
8671
+
8672
+ // 3. Deep wildcards — cannot be pre-filtered by depth or tag
8673
+ for (let i = 0; i < this._deepWildcards.length; i++) {
8674
+ if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];
8675
+ }
8676
+
8677
+ return null;
8678
+ }
8679
+ }
8680
+
8681
+ /**
8682
+ * MatcherView - A lightweight read-only view over a Matcher's internal state.
8683
+ *
8684
+ * Created once by Matcher and reused across all callbacks. Holds a direct
8685
+ * reference to the parent Matcher so it always reflects current parser state
8686
+ * with zero copying or freezing overhead.
8687
+ *
8688
+ * Users receive this via {@link Matcher#readOnly} or directly from parser
8689
+ * callbacks. It exposes all query and matching methods but has no mutation
8690
+ * methods — misuse is caught at the TypeScript level rather than at runtime.
8691
+ *
8692
+ * @example
8693
+ * const matcher = new Matcher();
8694
+ * const view = matcher.readOnly();
8695
+ *
8696
+ * matcher.push("root", {});
8697
+ * view.getCurrentTag(); // "root"
8698
+ * view.getDepth(); // 1
8699
+ */
8700
+ class MatcherView {
8701
+ /**
8702
+ * @param {Matcher} matcher - The parent Matcher instance to read from.
8703
+ */
8704
+ constructor(matcher) {
8705
+ this._matcher = matcher;
8706
+ }
8707
+
8708
+ /**
8709
+ * Get the path separator used by the parent matcher.
8710
+ * @returns {string}
8711
+ */
8712
+ get separator() {
8713
+ return this._matcher.separator;
8714
+ }
8715
+
8716
+ /**
8717
+ * Get current tag name.
8718
+ * @returns {string|undefined}
8719
+ */
8720
+ getCurrentTag() {
8721
+ const path = this._matcher.path;
8722
+ return path.length > 0 ? path[path.length - 1].tag : undefined;
8723
+ }
8724
+
8725
+ /**
8726
+ * Get current namespace.
8727
+ * @returns {string|undefined}
8728
+ */
8729
+ getCurrentNamespace() {
8730
+ const path = this._matcher.path;
8731
+ return path.length > 0 ? path[path.length - 1].namespace : undefined;
8732
+ }
8733
+
8734
+ /**
8735
+ * Get current node's attribute value.
8736
+ * @param {string} attrName
8737
+ * @returns {*}
8738
+ */
8739
+ getAttrValue(attrName) {
8740
+ const path = this._matcher.path;
8741
+ if (path.length === 0) return undefined;
8742
+ return path[path.length - 1].values?.[attrName];
8743
+ }
8744
+
8745
+ /**
8746
+ * Check if current node has an attribute.
8747
+ * @param {string} attrName
8748
+ * @returns {boolean}
8749
+ */
8750
+ hasAttr(attrName) {
8751
+ const path = this._matcher.path;
8752
+ if (path.length === 0) return false;
8753
+ const current = path[path.length - 1];
8754
+ return current.values !== undefined && attrName in current.values;
8755
+ }
8756
+
8757
+ /**
8758
+ * Get current node's sibling position (child index in parent).
8759
+ * @returns {number}
8760
+ */
8761
+ getPosition() {
8762
+ const path = this._matcher.path;
8763
+ if (path.length === 0) return -1;
8764
+ return path[path.length - 1].position ?? 0;
8765
+ }
8766
+
8767
+ /**
8768
+ * Get current node's repeat counter (occurrence count of this tag name).
8769
+ * @returns {number}
8770
+ */
8771
+ getCounter() {
8772
+ const path = this._matcher.path;
8773
+ if (path.length === 0) return -1;
8774
+ return path[path.length - 1].counter ?? 0;
8775
+ }
8776
+
8777
+ /**
8778
+ * Get current node's sibling index (alias for getPosition).
8779
+ * @returns {number}
8780
+ * @deprecated Use getPosition() or getCounter() instead
8781
+ */
8782
+ getIndex() {
8783
+ return this.getPosition();
7780
8784
  }
7781
8785
 
7782
8786
  /**
7783
- * Get the number of segments
8787
+ * Get current path depth.
7784
8788
  * @returns {number}
7785
8789
  */
7786
- get length() {
7787
- return this.segments.length;
8790
+ getDepth() {
8791
+ return this._matcher.path.length;
7788
8792
  }
7789
8793
 
7790
8794
  /**
7791
- * Check if expression contains deep wildcard
7792
- * @returns {boolean}
8795
+ * Get path as string.
8796
+ * @param {string} [separator] - Optional separator (uses default if not provided)
8797
+ * @param {boolean} [includeNamespace=true]
8798
+ * @returns {string}
7793
8799
  */
7794
- hasDeepWildcard() {
7795
- return this._hasDeepWildcard;
8800
+ toString(separator, includeNamespace = true) {
8801
+ return this._matcher.toString(separator, includeNamespace);
7796
8802
  }
7797
8803
 
7798
8804
  /**
7799
- * Check if expression has attribute conditions
7800
- * @returns {boolean}
8805
+ * Get path as array of tag names.
8806
+ * @returns {string[]}
7801
8807
  */
7802
- hasAttributeCondition() {
7803
- return this._hasAttributeCondition;
8808
+ toArray() {
8809
+ return this._matcher.path.map(n => n.tag);
7804
8810
  }
7805
8811
 
7806
8812
  /**
7807
- * Check if expression has position selectors
8813
+ * Match current path against an Expression.
8814
+ * @param {Expression} expression
7808
8815
  * @returns {boolean}
7809
8816
  */
7810
- hasPositionSelector() {
7811
- return this._hasPositionSelector;
8817
+ matches(expression) {
8818
+ return this._matcher.matches(expression);
7812
8819
  }
7813
8820
 
7814
8821
  /**
7815
- * Get string representation
7816
- * @returns {string}
8822
+ * Match any expression in the given set against the current path.
8823
+ * @param {ExpressionSet} exprSet
8824
+ * @returns {boolean}
7817
8825
  */
7818
- toString() {
7819
- return this.pattern;
8826
+ matchesAny(exprSet) {
8827
+ return exprSet.matchesAny(this._matcher);
7820
8828
  }
7821
8829
  }
7822
8830
 
7823
8831
  /**
7824
- * Matcher - Tracks current path in XML/JSON tree and matches against Expressions
7825
- *
8832
+ * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.
8833
+ *
7826
8834
  * The matcher maintains a stack of nodes representing the current path from root to
7827
8835
  * current tag. It only stores attribute values for the current (top) node to minimize
7828
8836
  * memory usage. Sibling tracking is used to auto-calculate position and counter.
7829
- *
8837
+ *
8838
+ * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to
8839
+ * user callbacks — it always reflects current state with no Proxy overhead.
8840
+ *
7830
8841
  * @example
7831
8842
  * const matcher = new Matcher();
7832
8843
  * matcher.push("root", {});
7833
8844
  * matcher.push("users", {});
7834
8845
  * matcher.push("user", { id: "123", type: "admin" });
7835
- *
8846
+ *
7836
8847
  * const expr = new Expression("root.users.user");
7837
8848
  * matcher.matches(expr); // true
7838
8849
  */
7839
8850
  class Matcher {
7840
8851
  /**
7841
- * Create a new Matcher
7842
- * @param {Object} options - Configuration options
7843
- * @param {string} options.separator - Default path separator (default: '.')
8852
+ * Create a new Matcher.
8853
+ * @param {Object} [options={}]
8854
+ * @param {string} [options.separator='.'] - Default path separator
7844
8855
  */
7845
8856
  constructor(options = {}) {
7846
8857
  this.separator = options.separator || '.';
7847
8858
  this.path = [];
7848
8859
  this.siblingStacks = [];
7849
- // Each path node: { tag: string, values: object, position: number, counter: number }
8860
+ // Each path node: { tag, values, position, counter, namespace? }
7850
8861
  // values only present for current (last) node
7851
8862
  // Each siblingStacks entry: Map<tagName, count> tracking occurrences at each level
8863
+ this._pathStringCache = null;
8864
+ this._view = new MatcherView(this);
7852
8865
  }
7853
8866
 
7854
8867
  /**
7855
- * Push a new tag onto the path
7856
- * @param {string} tagName - Name of the tag
7857
- * @param {Object} attrValues - Attribute key-value pairs for current node (optional)
7858
- * @param {string} namespace - Namespace for the tag (optional)
8868
+ * Push a new tag onto the path.
8869
+ * @param {string} tagName
8870
+ * @param {Object|null} [attrValues=null]
8871
+ * @param {string|null} [namespace=null]
7859
8872
  */
7860
8873
  push(tagName, attrValues = null, namespace = null) {
8874
+ this._pathStringCache = null;
8875
+
7861
8876
  // Remove values from previous current node (now becoming ancestor)
7862
8877
  if (this.path.length > 0) {
7863
- const prev = this.path[this.path.length - 1];
7864
- prev.values = undefined;
8878
+ this.path[this.path.length - 1].values = undefined;
7865
8879
  }
7866
8880
 
7867
8881
  // Get or create sibling tracking for current level
@@ -7894,12 +8908,10 @@
7894
8908
  counter: counter
7895
8909
  };
7896
8910
 
7897
- // Store namespace if provided
7898
8911
  if (namespace !== null && namespace !== undefined) {
7899
8912
  node.namespace = namespace;
7900
8913
  }
7901
8914
 
7902
- // Store values only for current node
7903
8915
  if (attrValues !== null && attrValues !== undefined) {
7904
8916
  node.values = attrValues;
7905
8917
  }
@@ -7908,19 +8920,15 @@
7908
8920
  }
7909
8921
 
7910
8922
  /**
7911
- * Pop the last tag from the path
8923
+ * Pop the last tag from the path.
7912
8924
  * @returns {Object|undefined} The popped node
7913
8925
  */
7914
8926
  pop() {
7915
- if (this.path.length === 0) {
7916
- return undefined;
7917
- }
8927
+ if (this.path.length === 0) return undefined;
8928
+ this._pathStringCache = null;
7918
8929
 
7919
8930
  const node = this.path.pop();
7920
8931
 
7921
- // Clean up sibling tracking for levels deeper than current
7922
- // After pop, path.length is the new depth
7923
- // We need to clean up siblingStacks[path.length + 1] and beyond
7924
8932
  if (this.siblingStacks.length > this.path.length + 1) {
7925
8933
  this.siblingStacks.length = this.path.length + 1;
7926
8934
  }
@@ -7929,9 +8937,9 @@
7929
8937
  }
7930
8938
 
7931
8939
  /**
7932
- * Update current node's attribute values
7933
- * Useful when attributes are parsed after push
7934
- * @param {Object} attrValues - Attribute values
8940
+ * Update current node's attribute values.
8941
+ * Useful when attributes are parsed after push.
8942
+ * @param {Object} attrValues
7935
8943
  */
7936
8944
  updateCurrent(attrValues) {
7937
8945
  if (this.path.length > 0) {
@@ -7943,7 +8951,7 @@
7943
8951
  }
7944
8952
 
7945
8953
  /**
7946
- * Get current tag name
8954
+ * Get current tag name.
7947
8955
  * @returns {string|undefined}
7948
8956
  */
7949
8957
  getCurrentTag() {
@@ -7951,7 +8959,7 @@
7951
8959
  }
7952
8960
 
7953
8961
  /**
7954
- * Get current namespace
8962
+ * Get current namespace.
7955
8963
  * @returns {string|undefined}
7956
8964
  */
7957
8965
  getCurrentNamespace() {
@@ -7959,19 +8967,18 @@
7959
8967
  }
7960
8968
 
7961
8969
  /**
7962
- * Get current node's attribute value
7963
- * @param {string} attrName - Attribute name
7964
- * @returns {*} Attribute value or undefined
8970
+ * Get current node's attribute value.
8971
+ * @param {string} attrName
8972
+ * @returns {*}
7965
8973
  */
7966
8974
  getAttrValue(attrName) {
7967
8975
  if (this.path.length === 0) return undefined;
7968
- const current = this.path[this.path.length - 1];
7969
- return current.values?.[attrName];
8976
+ return this.path[this.path.length - 1].values?.[attrName];
7970
8977
  }
7971
8978
 
7972
8979
  /**
7973
- * Check if current node has an attribute
7974
- * @param {string} attrName - Attribute name
8980
+ * Check if current node has an attribute.
8981
+ * @param {string} attrName
7975
8982
  * @returns {boolean}
7976
8983
  */
7977
8984
  hasAttr(attrName) {
@@ -7981,7 +8988,7 @@
7981
8988
  }
7982
8989
 
7983
8990
  /**
7984
- * Get current node's sibling position (child index in parent)
8991
+ * Get current node's sibling position (child index in parent).
7985
8992
  * @returns {number}
7986
8993
  */
7987
8994
  getPosition() {
@@ -7990,7 +8997,7 @@
7990
8997
  }
7991
8998
 
7992
8999
  /**
7993
- * Get current node's repeat counter (occurrence count of this tag name)
9000
+ * Get current node's repeat counter (occurrence count of this tag name).
7994
9001
  * @returns {number}
7995
9002
  */
7996
9003
  getCounter() {
@@ -7999,7 +9006,7 @@
7999
9006
  }
8000
9007
 
8001
9008
  /**
8002
- * Get current node's sibling index (alias for getPosition for backward compatibility)
9009
+ * Get current node's sibling index (alias for getPosition).
8003
9010
  * @returns {number}
8004
9011
  * @deprecated Use getPosition() or getCounter() instead
8005
9012
  */
@@ -8008,7 +9015,7 @@
8008
9015
  }
8009
9016
 
8010
9017
  /**
8011
- * Get current path depth
9018
+ * Get current path depth.
8012
9019
  * @returns {number}
8013
9020
  */
8014
9021
  getDepth() {
@@ -8016,23 +9023,33 @@
8016
9023
  }
8017
9024
 
8018
9025
  /**
8019
- * Get path as string
8020
- * @param {string} separator - Optional separator (uses default if not provided)
8021
- * @param {boolean} includeNamespace - Whether to include namespace in output (default: true)
9026
+ * Get path as string.
9027
+ * @param {string} [separator] - Optional separator (uses default if not provided)
9028
+ * @param {boolean} [includeNamespace=true]
8022
9029
  * @returns {string}
8023
9030
  */
8024
9031
  toString(separator, includeNamespace = true) {
8025
9032
  const sep = separator || this.separator;
8026
- return this.path.map(n => {
8027
- if (includeNamespace && n.namespace) {
8028
- return `${n.namespace}:${n.tag}`;
9033
+ const isDefault = (sep === this.separator && includeNamespace === true);
9034
+
9035
+ if (isDefault) {
9036
+ if (this._pathStringCache !== null) {
9037
+ return this._pathStringCache;
8029
9038
  }
8030
- return n.tag;
8031
- }).join(sep);
9039
+ const result = this.path.map(n =>
9040
+ (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag
9041
+ ).join(sep);
9042
+ this._pathStringCache = result;
9043
+ return result;
9044
+ }
9045
+
9046
+ return this.path.map(n =>
9047
+ (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag
9048
+ ).join(sep);
8032
9049
  }
8033
9050
 
8034
9051
  /**
8035
- * Get path as array of tag names
9052
+ * Get path as array of tag names.
8036
9053
  * @returns {string[]}
8037
9054
  */
8038
9055
  toArray() {
@@ -8040,17 +9057,18 @@
8040
9057
  }
8041
9058
 
8042
9059
  /**
8043
- * Reset the path to empty
9060
+ * Reset the path to empty.
8044
9061
  */
8045
9062
  reset() {
9063
+ this._pathStringCache = null;
8046
9064
  this.path = [];
8047
9065
  this.siblingStacks = [];
8048
9066
  }
8049
9067
 
8050
9068
  /**
8051
- * Match current path against an Expression
8052
- * @param {Expression} expression - The expression to match against
8053
- * @returns {boolean} True if current path matches the expression
9069
+ * Match current path against an Expression.
9070
+ * @param {Expression} expression
9071
+ * @returns {boolean}
8054
9072
  */
8055
9073
  matches(expression) {
8056
9074
  const segments = expression.segments;
@@ -8059,32 +9077,23 @@
8059
9077
  return false;
8060
9078
  }
8061
9079
 
8062
- // Handle deep wildcard patterns
8063
9080
  if (expression.hasDeepWildcard()) {
8064
9081
  return this._matchWithDeepWildcard(segments);
8065
9082
  }
8066
9083
 
8067
- // Simple path matching (no deep wildcards)
8068
9084
  return this._matchSimple(segments);
8069
9085
  }
8070
9086
 
8071
9087
  /**
8072
- * Match simple path (no deep wildcards)
8073
9088
  * @private
8074
9089
  */
8075
9090
  _matchSimple(segments) {
8076
- // Path must be same length as segments
8077
9091
  if (this.path.length !== segments.length) {
8078
9092
  return false;
8079
9093
  }
8080
9094
 
8081
- // Match each segment bottom-to-top
8082
9095
  for (let i = 0; i < segments.length; i++) {
8083
- const segment = segments[i];
8084
- const node = this.path[i];
8085
- const isCurrentNode = (i === this.path.length - 1);
8086
-
8087
- if (!this._matchSegment(segment, node, isCurrentNode)) {
9096
+ if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {
8088
9097
  return false;
8089
9098
  }
8090
9099
  }
@@ -8093,32 +9102,27 @@
8093
9102
  }
8094
9103
 
8095
9104
  /**
8096
- * Match path with deep wildcards
8097
9105
  * @private
8098
9106
  */
8099
9107
  _matchWithDeepWildcard(segments) {
8100
- let pathIdx = this.path.length - 1; // Start from current node (bottom)
8101
- let segIdx = segments.length - 1; // Start from last segment
9108
+ let pathIdx = this.path.length - 1;
9109
+ let segIdx = segments.length - 1;
8102
9110
 
8103
9111
  while (segIdx >= 0 && pathIdx >= 0) {
8104
9112
  const segment = segments[segIdx];
8105
9113
 
8106
9114
  if (segment.type === 'deep-wildcard') {
8107
- // ".." matches zero or more levels
8108
9115
  segIdx--;
8109
9116
 
8110
9117
  if (segIdx < 0) {
8111
- // Pattern ends with "..", always matches
8112
9118
  return true;
8113
9119
  }
8114
9120
 
8115
- // Find where next segment matches in the path
8116
9121
  const nextSeg = segments[segIdx];
8117
9122
  let found = false;
8118
9123
 
8119
9124
  for (let i = pathIdx; i >= 0; i--) {
8120
- const isCurrentNode = (i === this.path.length - 1);
8121
- if (this._matchSegment(nextSeg, this.path[i], isCurrentNode)) {
9125
+ if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {
8122
9126
  pathIdx = i - 1;
8123
9127
  segIdx--;
8124
9128
  found = true;
@@ -8130,9 +9134,7 @@
8130
9134
  return false;
8131
9135
  }
8132
9136
  } else {
8133
- // Regular segment
8134
- const isCurrentNode = (pathIdx === this.path.length - 1);
8135
- if (!this._matchSegment(segment, this.path[pathIdx], isCurrentNode)) {
9137
+ if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {
8136
9138
  return false;
8137
9139
  }
8138
9140
  pathIdx--;
@@ -8140,38 +9142,25 @@
8140
9142
  }
8141
9143
  }
8142
9144
 
8143
- // All segments must be consumed
8144
9145
  return segIdx < 0;
8145
9146
  }
8146
9147
 
8147
9148
  /**
8148
- * Match a single segment against a node
8149
9149
  * @private
8150
- * @param {Object} segment - Segment from Expression
8151
- * @param {Object} node - Node from path
8152
- * @param {boolean} isCurrentNode - Whether this is the current (last) node
8153
- * @returns {boolean}
8154
9150
  */
8155
9151
  _matchSegment(segment, node, isCurrentNode) {
8156
- // Match tag name (* is wildcard)
8157
9152
  if (segment.tag !== '*' && segment.tag !== node.tag) {
8158
9153
  return false;
8159
9154
  }
8160
9155
 
8161
- // Match namespace if specified in segment
8162
9156
  if (segment.namespace !== undefined) {
8163
- // Segment has namespace - node must match it
8164
9157
  if (segment.namespace !== '*' && segment.namespace !== node.namespace) {
8165
9158
  return false;
8166
9159
  }
8167
9160
  }
8168
- // If segment has no namespace, it matches nodes with or without namespace
8169
9161
 
8170
- // Match attribute name (check if node has this attribute)
8171
- // Can only check for current node since ancestors don't have values
8172
9162
  if (segment.attrName !== undefined) {
8173
9163
  if (!isCurrentNode) {
8174
- // Can't check attributes for ancestor nodes (values not stored)
8175
9164
  return false;
8176
9165
  }
8177
9166
 
@@ -8179,20 +9168,15 @@
8179
9168
  return false;
8180
9169
  }
8181
9170
 
8182
- // Match attribute value (only possible for current node)
8183
9171
  if (segment.attrValue !== undefined) {
8184
- const actualValue = node.values[segment.attrName];
8185
- // Both should be strings
8186
- if (String(actualValue) !== String(segment.attrValue)) {
9172
+ if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {
8187
9173
  return false;
8188
9174
  }
8189
9175
  }
8190
9176
  }
8191
9177
 
8192
- // Match position (only for current node)
8193
9178
  if (segment.position !== undefined) {
8194
9179
  if (!isCurrentNode) {
8195
- // Can't check position for ancestor nodes
8196
9180
  return false;
8197
9181
  }
8198
9182
 
@@ -8204,10 +9188,8 @@
8204
9188
  return false;
8205
9189
  } else if (segment.position === 'even' && counter % 2 !== 0) {
8206
9190
  return false;
8207
- } else if (segment.position === 'nth') {
8208
- if (counter !== segment.positionValue) {
8209
- return false;
8210
- }
9191
+ } else if (segment.position === 'nth' && counter !== segment.positionValue) {
9192
+ return false;
8211
9193
  }
8212
9194
  }
8213
9195
 
@@ -8215,8 +9197,17 @@
8215
9197
  }
8216
9198
 
8217
9199
  /**
8218
- * Create a snapshot of current state
8219
- * @returns {Object} State snapshot
9200
+ * Match any expression in the given set against the current path.
9201
+ * @param {ExpressionSet} exprSet
9202
+ * @returns {boolean}
9203
+ */
9204
+ matchesAny(exprSet) {
9205
+ return exprSet.matchesAny(this);
9206
+ }
9207
+
9208
+ /**
9209
+ * Create a snapshot of current state.
9210
+ * @returns {Object}
8220
9211
  */
8221
9212
  snapshot() {
8222
9213
  return {
@@ -8226,13 +9217,34 @@
8226
9217
  }
8227
9218
 
8228
9219
  /**
8229
- * Restore state from snapshot
8230
- * @param {Object} snapshot - State snapshot
9220
+ * Restore state from snapshot.
9221
+ * @param {Object} snapshot
8231
9222
  */
8232
9223
  restore(snapshot) {
9224
+ this._pathStringCache = null;
8233
9225
  this.path = snapshot.path.map(node => ({ ...node }));
8234
9226
  this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));
8235
9227
  }
9228
+
9229
+ /**
9230
+ * Return the read-only {@link MatcherView} for this matcher.
9231
+ *
9232
+ * The same instance is returned on every call — no allocation occurs.
9233
+ * It always reflects the current parser state and is safe to pass to
9234
+ * user callbacks without risk of accidental mutation.
9235
+ *
9236
+ * @returns {MatcherView}
9237
+ *
9238
+ * @example
9239
+ * const view = matcher.readOnly();
9240
+ * // pass view to callbacks — it stays in sync automatically
9241
+ * view.matches(expr); // ✓
9242
+ * view.getCurrentTag(); // ✓
9243
+ * // view.push(...) // ✗ method does not exist — caught by TypeScript
9244
+ */
9245
+ readOnly() {
9246
+ return this._view;
9247
+ }
8236
9248
  }
8237
9249
 
8238
9250
  // const regx =
@@ -8298,32 +9310,6 @@
8298
9310
  this.options = options;
8299
9311
  this.currentNode = null;
8300
9312
  this.tagsNodeStack = [];
8301
- this.docTypeEntities = {};
8302
- this.lastEntities = {
8303
- "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
8304
- "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
8305
- "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
8306
- "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" },
8307
- };
8308
- this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
8309
- this.htmlEntities = {
8310
- "space": { regex: /&(nbsp|#160);/g, val: " " },
8311
- // "lt" : { regex: /&(lt|#60);/g, val: "<" },
8312
- // "gt" : { regex: /&(gt|#62);/g, val: ">" },
8313
- // "amp" : { regex: /&(amp|#38);/g, val: "&" },
8314
- // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
8315
- // "apos" : { regex: /&(apos|#39);/g, val: "'" },
8316
- "cent": { regex: /&(cent|#162);/g, val: "¢" },
8317
- "pound": { regex: /&(pound|#163);/g, val: "£" },
8318
- "yen": { regex: /&(yen|#165);/g, val: "¥" },
8319
- "euro": { regex: /&(euro|#8364);/g, val: "€" },
8320
- "copyright": { regex: /&(copy|#169);/g, val: "©" },
8321
- "reg": { regex: /&(reg|#174);/g, val: "®" },
8322
- "inr": { regex: /&(inr|#8377);/g, val: "₹" },
8323
- "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => fromCodePoint(str, 10, "&#") },
8324
- "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => fromCodePoint(str, 16, "&#x") },
8325
- };
8326
- this.addExternalEntities = addExternalEntities;
8327
9313
  this.parseXml = parseXml;
8328
9314
  this.parseTextData = parseTextData;
8329
9315
  this.resolveNameSpace = resolveNameSpace;
@@ -8336,42 +9322,54 @@
8336
9322
  this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
8337
9323
  this.entityExpansionCount = 0;
8338
9324
  this.currentExpandedLength = 0;
9325
+ let namedEntities = { ...XML };
9326
+ if (this.options.entityDecoder) {
9327
+ this.entityDecoder = this.options.entityDecoder;
9328
+ } else {
9329
+ if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities;
9330
+ else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };
9331
+ this.entityDecoder = new EntityDecoder({
9332
+ namedEntities: namedEntities,
9333
+ numericAllowed: this.options.htmlEntities,
9334
+ limit: {
9335
+ maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
9336
+ maxExpandedLength: this.options.processEntities.maxExpandedLength,
9337
+ applyLimitsTo: this.options.processEntities.appliesTo,
9338
+ }
9339
+ //postCheck: resolved => resolved
9340
+ });
9341
+ }
8339
9342
 
8340
9343
  // Initialize path matcher for path-expression-matcher
8341
9344
  this.matcher = new Matcher();
8342
9345
 
9346
+ // Live read-only proxy of matcher — PEM creates and caches this internally.
9347
+ // All user callbacks receive this instead of the mutable matcher.
9348
+ this.readonlyMatcher = this.matcher.readOnly();
9349
+
8343
9350
  // Flag to track if current node is a stop node (optimization)
8344
9351
  this.isCurrentNodeStopNode = false;
8345
9352
 
8346
9353
  // Pre-compile stopNodes expressions
8347
- if (this.options.stopNodes && this.options.stopNodes.length > 0) {
8348
- this.stopNodeExpressions = [];
8349
- for (let i = 0; i < this.options.stopNodes.length; i++) {
8350
- const stopNodeExp = this.options.stopNodes[i];
9354
+ this.stopNodeExpressionsSet = new ExpressionSet();
9355
+ const stopNodesOpts = this.options.stopNodes;
9356
+ if (stopNodesOpts && stopNodesOpts.length > 0) {
9357
+ for (let i = 0; i < stopNodesOpts.length; i++) {
9358
+ const stopNodeExp = stopNodesOpts[i];
8351
9359
  if (typeof stopNodeExp === 'string') {
8352
9360
  // Convert string to Expression object
8353
- this.stopNodeExpressions.push(new Expression(stopNodeExp));
9361
+ this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
8354
9362
  } else if (stopNodeExp instanceof Expression) {
8355
9363
  // Already an Expression object
8356
- this.stopNodeExpressions.push(stopNodeExp);
9364
+ this.stopNodeExpressionsSet.add(stopNodeExp);
8357
9365
  }
8358
9366
  }
9367
+ this.stopNodeExpressionsSet.seal();
8359
9368
  }
8360
9369
  }
8361
9370
 
8362
9371
  }
8363
9372
 
8364
- function addExternalEntities(externalEntities) {
8365
- const entKeys = Object.keys(externalEntities);
8366
- for (let i = 0; i < entKeys.length; i++) {
8367
- const ent = entKeys[i];
8368
- const escaped = ent.replace(/[.\-+*:]/g, '\\.');
8369
- this.lastEntities[ent] = {
8370
- regex: new RegExp("&" + escaped + ";", "g"),
8371
- val: externalEntities[ent]
8372
- };
8373
- }
8374
- }
8375
9373
 
8376
9374
  /**
8377
9375
  * @param {string} val
@@ -8383,28 +9381,29 @@
8383
9381
  * @param {boolean} escapeEntities
8384
9382
  */
8385
9383
  function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
9384
+ const options = this.options;
8386
9385
  if (val !== undefined) {
8387
- if (this.options.trimValues && !dontTrim) {
9386
+ if (options.trimValues && !dontTrim) {
8388
9387
  val = val.trim();
8389
9388
  }
8390
9389
  if (val.length > 0) {
8391
9390
  if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);
8392
9391
 
8393
9392
  // Pass jPath string or matcher based on options.jPath setting
8394
- const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
8395
- const newval = this.options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
9393
+ const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
9394
+ const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
8396
9395
  if (newval === null || newval === undefined) {
8397
9396
  //don't parse
8398
9397
  return val;
8399
9398
  } else if (typeof newval !== typeof val || newval !== val) {
8400
9399
  //overwrite
8401
9400
  return newval;
8402
- } else if (this.options.trimValues) {
8403
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
9401
+ } else if (options.trimValues) {
9402
+ return parseValue(val, options.parseTagValue, options.numberParseOptions);
8404
9403
  } else {
8405
9404
  const trimmedVal = val.trim();
8406
9405
  if (trimmedVal === val) {
8407
- return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
9406
+ return parseValue(val, options.parseTagValue, options.numberParseOptions);
8408
9407
  } else {
8409
9408
  return val;
8410
9409
  }
@@ -8431,8 +9430,9 @@
8431
9430
  //const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
8432
9431
  const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
8433
9432
 
8434
- function buildAttributesMap(attrStr, jPath, tagName) {
8435
- if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
9433
+ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
9434
+ const options = this.options;
9435
+ if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {
8436
9436
  // attrStr = attrStr.replace(/\r?\n/g, ' ');
8437
9437
  //attrStr = attrStr || attrStr.trim();
8438
9438
 
@@ -8440,89 +9440,80 @@
8440
9440
  const len = matches.length; //don't make it inline
8441
9441
  const attrs = {};
8442
9442
 
8443
- // First pass: parse all attributes and update matcher with raw values
8444
- // This ensures the matcher has all attribute values when processors run
9443
+ // Pre-process values once: trim + entity replacement
9444
+ // Reused in both matcher update and second pass
9445
+ const processedVals = new Array(len);
9446
+ let hasRawAttrs = false;
8445
9447
  const rawAttrsForMatcher = {};
9448
+
8446
9449
  for (let i = 0; i < len; i++) {
8447
9450
  const attrName = this.resolveNameSpace(matches[i][1]);
8448
9451
  const oldVal = matches[i][4];
8449
9452
 
8450
9453
  if (attrName.length && oldVal !== undefined) {
8451
- let parsedVal = oldVal;
8452
- if (this.options.trimValues) {
8453
- parsedVal = parsedVal.trim();
8454
- }
8455
- parsedVal = this.replaceEntitiesValue(parsedVal, tagName, jPath);
8456
- rawAttrsForMatcher[attrName] = parsedVal;
9454
+ let val = oldVal;
9455
+ if (options.trimValues) val = val.trim();
9456
+ val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
9457
+ processedVals[i] = val;
9458
+
9459
+ rawAttrsForMatcher[attrName] = val;
9460
+ hasRawAttrs = true;
8457
9461
  }
8458
9462
  }
8459
9463
 
8460
- // Update matcher with raw attribute values BEFORE running processors
8461
- if (Object.keys(rawAttrsForMatcher).length > 0 && typeof jPath === 'object' && jPath.updateCurrent) {
9464
+ // Update matcher ONCE before second pass, if applicable
9465
+ if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {
8462
9466
  jPath.updateCurrent(rawAttrsForMatcher);
8463
9467
  }
8464
9468
 
8465
- // Second pass: now process attributes with matcher having full attribute context
9469
+ // Hoist toString() once — path doesn't change during attribute processing
9470
+ const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
9471
+
9472
+ // Second pass: apply processors, build final attrs
9473
+ let hasAttrs = false;
8466
9474
  for (let i = 0; i < len; i++) {
8467
9475
  const attrName = this.resolveNameSpace(matches[i][1]);
8468
9476
 
8469
- // Convert jPath to string if needed for ignoreAttributesFn
8470
- const jPathStr = this.options.jPath ? jPath.toString() : jPath;
8471
- if (this.ignoreAttributesFn(attrName, jPathStr)) {
8472
- continue
8473
- }
9477
+ if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
8474
9478
 
8475
- let oldVal = matches[i][4];
8476
- let aName = this.options.attributeNamePrefix + attrName;
9479
+ let aName = options.attributeNamePrefix + attrName;
8477
9480
 
8478
9481
  if (attrName.length) {
8479
- if (this.options.transformAttributeName) {
8480
- aName = this.options.transformAttributeName(aName);
9482
+ if (options.transformAttributeName) {
9483
+ aName = options.transformAttributeName(aName);
8481
9484
  }
8482
- //if (aName === "__proto__") aName = "#__proto__";
8483
- aName = sanitizeName(aName, this.options);
9485
+ aName = sanitizeName(aName, options);
8484
9486
 
8485
- if (oldVal !== undefined) {
8486
- if (this.options.trimValues) {
8487
- oldVal = oldVal.trim();
8488
- }
8489
- oldVal = this.replaceEntitiesValue(oldVal, tagName, jPath);
9487
+ if (matches[i][4] !== undefined) {
9488
+ // Reuse already-processed value — no double entity replacement
9489
+ const oldVal = processedVals[i];
8490
9490
 
8491
- // Pass jPath string or matcher based on options.jPath setting
8492
- const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
8493
- const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPathOrMatcher);
9491
+ const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
8494
9492
  if (newVal === null || newVal === undefined) {
8495
- //don't parse
8496
9493
  attrs[aName] = oldVal;
8497
9494
  } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
8498
- //overwrite
8499
9495
  attrs[aName] = newVal;
8500
9496
  } else {
8501
- //parse
8502
- attrs[aName] = parseValue(
8503
- oldVal,
8504
- this.options.parseAttributeValue,
8505
- this.options.numberParseOptions
8506
- );
9497
+ attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
8507
9498
  }
8508
- } else if (this.options.allowBooleanAttributes) {
9499
+ hasAttrs = true;
9500
+ } else if (options.allowBooleanAttributes) {
8509
9501
  attrs[aName] = true;
9502
+ hasAttrs = true;
8510
9503
  }
8511
9504
  }
8512
9505
  }
8513
9506
 
8514
- if (!Object.keys(attrs).length) {
8515
- return;
8516
- }
8517
- if (this.options.attributesGroupName) {
9507
+ if (!hasAttrs) return;
9508
+
9509
+ if (options.attributesGroupName) {
8518
9510
  const attrCollection = {};
8519
- attrCollection[this.options.attributesGroupName] = attrs;
9511
+ attrCollection[options.attributesGroupName] = attrs;
8520
9512
  return attrCollection;
8521
9513
  }
8522
- return attrs
9514
+ return attrs;
8523
9515
  }
8524
9516
  }
8525
-
8526
9517
  const parseXml = function (xmlData) {
8527
9518
  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
8528
9519
  const xmlObj = new XmlNode('!xml');
@@ -8531,40 +9522,43 @@
8531
9522
 
8532
9523
  // Reset matcher for new document
8533
9524
  this.matcher.reset();
9525
+ this.entityDecoder.reset();
8534
9526
 
8535
9527
  // Reset entity expansion counters for this document
8536
9528
  this.entityExpansionCount = 0;
8537
9529
  this.currentExpandedLength = 0;
8538
-
8539
- const docTypeReader = new DocTypeReader(this.options.processEntities);
8540
- for (let i = 0; i < xmlData.length; i++) {//for each char in XML data
9530
+ const options = this.options;
9531
+ const docTypeReader = new DocTypeReader(options.processEntities);
9532
+ const xmlLen = xmlData.length;
9533
+ for (let i = 0; i < xmlLen; i++) {//for each char in XML data
8541
9534
  const ch = xmlData[i];
8542
9535
  if (ch === '<') {
8543
9536
  // const nextIndex = i+1;
8544
9537
  // const _2ndChar = xmlData[nextIndex];
8545
- if (xmlData[i + 1] === '/') {//Closing Tag
9538
+ const c1 = xmlData.charCodeAt(i + 1);
9539
+ if (c1 === 47) {//Closing Tag '/'
8546
9540
  const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.");
8547
9541
  let tagName = xmlData.substring(i + 2, closeIndex).trim();
8548
9542
 
8549
- if (this.options.removeNSPrefix) {
9543
+ if (options.removeNSPrefix) {
8550
9544
  const colonIndex = tagName.indexOf(":");
8551
9545
  if (colonIndex !== -1) {
8552
9546
  tagName = tagName.substr(colonIndex + 1);
8553
9547
  }
8554
9548
  }
8555
9549
 
8556
- tagName = transformTagName(this.options.transformTagName, tagName, "", this.options).tagName;
9550
+ tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
8557
9551
 
8558
9552
  if (currentNode) {
8559
- textData = this.saveTextToParentTag(textData, currentNode, this.matcher);
9553
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
8560
9554
  }
8561
9555
 
8562
9556
  //check if last tag of nested tag was unpaired tag
8563
9557
  const lastTagName = this.matcher.getCurrentTag();
8564
- if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
9558
+ if (tagName && options.unpairedTagsSet.has(tagName)) {
8565
9559
  throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
8566
9560
  }
8567
- if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
9561
+ if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
8568
9562
  // Pop the unpaired tag
8569
9563
  this.matcher.pop();
8570
9564
  this.tagsNodeStack.pop();
@@ -8576,63 +9570,72 @@
8576
9570
  currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
8577
9571
  textData = "";
8578
9572
  i = closeIndex;
8579
- } else if (xmlData[i + 1] === '?') {
9573
+ } else if (c1 === 63) { //'?'
8580
9574
 
8581
9575
  let tagData = readTagExp(xmlData, i, false, "?>");
8582
9576
  if (!tagData) throw new Error("Pi Tag is not closed.");
8583
9577
 
8584
- textData = this.saveTextToParentTag(textData, currentNode, this.matcher);
8585
- if ((this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags) ; else {
9578
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
9579
+ const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);
9580
+ if (attsMap) {
9581
+ const ver = attsMap[this.options.attributeNamePrefix + "version"];
9582
+ this.entityDecoder.setXmlVersion(Number(ver) || 1.0);
9583
+ }
9584
+ if ((options.ignoreDeclaration && tagData.tagName === "?xml") || options.ignorePiTags) ; else {
8586
9585
 
8587
9586
  const childNode = new XmlNode(tagData.tagName);
8588
- childNode.add(this.options.textNodeName, "");
9587
+ childNode.add(options.textNodeName, "");
8589
9588
 
8590
- if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
8591
- childNode[":@"] = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName);
9589
+ if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {
9590
+ childNode[":@"] = attsMap;
8592
9591
  }
8593
- this.addChild(currentNode, childNode, this.matcher, i);
9592
+ this.addChild(currentNode, childNode, this.readonlyMatcher, i);
8594
9593
  }
8595
9594
 
8596
9595
 
8597
9596
  i = tagData.closeIndex + 1;
8598
- } else if (xmlData.substr(i + 1, 3) === '!--') {
9597
+ } else if (c1 === 33
9598
+ && xmlData.charCodeAt(i + 2) === 45
9599
+ && xmlData.charCodeAt(i + 3) === 45) { //'!--'
8599
9600
  const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.");
8600
- if (this.options.commentPropName) {
9601
+ if (options.commentPropName) {
8601
9602
  const comment = xmlData.substring(i + 4, endIndex - 2);
8602
9603
 
8603
- textData = this.saveTextToParentTag(textData, currentNode, this.matcher);
9604
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
8604
9605
 
8605
- currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
9606
+ currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
8606
9607
  }
8607
9608
  i = endIndex;
8608
- } else if (xmlData.substr(i + 1, 2) === '!D') {
9609
+ } else if (c1 === 33
9610
+ && xmlData.charCodeAt(i + 2) === 68) { //'!D'
8609
9611
  const result = docTypeReader.readDocType(xmlData, i);
8610
- this.docTypeEntities = result.entities;
9612
+ this.entityDecoder.addInputEntities(result.entities);
8611
9613
  i = result.i;
8612
- } else if (xmlData.substr(i + 1, 2) === '![') {
9614
+ } else if (c1 === 33
9615
+ && xmlData.charCodeAt(i + 2) === 91) { // '!['
8613
9616
  const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
8614
9617
  const tagExp = xmlData.substring(i + 9, closeIndex);
8615
9618
 
8616
- textData = this.saveTextToParentTag(textData, currentNode, this.matcher);
9619
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
8617
9620
 
8618
- let val = this.parseTextData(tagExp, currentNode.tagname, this.matcher, true, false, true, true);
9621
+ let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
8619
9622
  if (val == undefined) val = "";
8620
9623
 
8621
9624
  //cdata should be set even if it is 0 length string
8622
- if (this.options.cdataPropName) {
8623
- currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
9625
+ if (options.cdataPropName) {
9626
+ currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
8624
9627
  } else {
8625
- currentNode.add(this.options.textNodeName, val);
9628
+ currentNode.add(options.textNodeName, val);
8626
9629
  }
8627
9630
 
8628
9631
  i = closeIndex + 2;
8629
9632
  } else {//Opening tag
8630
- let result = readTagExp(xmlData, i, this.options.removeNSPrefix);
9633
+ let result = readTagExp(xmlData, i, options.removeNSPrefix);
8631
9634
 
8632
9635
  // Safety check: readTagExp can return undefined
8633
9636
  if (!result) {
8634
9637
  // Log context for debugging
8635
- const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlData.length, i + 50));
9638
+ const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
8636
9639
  throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
8637
9640
  }
8638
9641
 
@@ -8642,11 +9645,13 @@
8642
9645
  let attrExpPresent = result.attrExpPresent;
8643
9646
  let closeIndex = result.closeIndex;
8644
9647
 
8645
- ({ tagName, tagExp } = transformTagName(this.options.transformTagName, tagName, tagExp, this.options));
9648
+ ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
8646
9649
 
8647
- if (this.options.strictReservedNames &&
8648
- (tagName === this.options.commentPropName
8649
- || tagName === this.options.cdataPropName
9650
+ if (options.strictReservedNames &&
9651
+ (tagName === options.commentPropName
9652
+ || tagName === options.cdataPropName
9653
+ || tagName === options.textNodeName
9654
+ || tagName === options.attributesGroupName
8650
9655
  )) {
8651
9656
  throw new Error(`Invalid tag name: ${tagName}`);
8652
9657
  }
@@ -8655,13 +9660,13 @@
8655
9660
  if (currentNode && textData) {
8656
9661
  if (currentNode.tagname !== '!xml') {
8657
9662
  //when nested tag is found
8658
- textData = this.saveTextToParentTag(textData, currentNode, this.matcher, false);
9663
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
8659
9664
  }
8660
9665
  }
8661
9666
 
8662
9667
  //check if last tag was unpaired tag
8663
9668
  const lastTag = currentNode;
8664
- if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
9669
+ if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
8665
9670
  currentNode = this.tagsNodeStack.pop();
8666
9671
  this.matcher.pop();
8667
9672
  }
@@ -8702,13 +9707,14 @@
8702
9707
 
8703
9708
  if (prefixedAttrs) {
8704
9709
  // Extract raw attributes (without prefix) for our use
8705
- extractRawAttributes(prefixedAttrs, this.options);
9710
+ //TODO: seems a performance overhead
9711
+ extractRawAttributes(prefixedAttrs, options);
8706
9712
  }
8707
9713
  }
8708
9714
 
8709
9715
  // Now check if this is a stop node (after attributes are set)
8710
9716
  if (tagName !== xmlObj.tagname) {
8711
- this.isCurrentNodeStopNode = this.isItStopNode(this.stopNodeExpressions, this.matcher);
9717
+ this.isCurrentNodeStopNode = this.isItStopNode();
8712
9718
  }
8713
9719
 
8714
9720
  const startIndex = i;
@@ -8720,7 +9726,7 @@
8720
9726
  i = result.closeIndex;
8721
9727
  }
8722
9728
  //unpaired tag
8723
- else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
9729
+ else if (options.unpairedTagsSet.has(tagName)) {
8724
9730
  i = result.closeIndex;
8725
9731
  }
8726
9732
  //normal tag
@@ -8739,31 +9745,31 @@
8739
9745
  }
8740
9746
 
8741
9747
  // For stop nodes, store raw content as-is without any processing
8742
- childNode.add(this.options.textNodeName, tagContent);
9748
+ childNode.add(options.textNodeName, tagContent);
8743
9749
 
8744
9750
  this.matcher.pop(); // Pop the stop node tag
8745
9751
  this.isCurrentNodeStopNode = false; // Reset flag
8746
9752
 
8747
- this.addChild(currentNode, childNode, this.matcher, startIndex);
9753
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
8748
9754
  } else {
8749
9755
  //selfClosing tag
8750
9756
  if (isSelfClosing) {
8751
- ({ tagName, tagExp } = transformTagName(this.options.transformTagName, tagName, tagExp, this.options));
9757
+ ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
8752
9758
 
8753
9759
  const childNode = new XmlNode(tagName);
8754
9760
  if (prefixedAttrs) {
8755
9761
  childNode[":@"] = prefixedAttrs;
8756
9762
  }
8757
- this.addChild(currentNode, childNode, this.matcher, startIndex);
9763
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
8758
9764
  this.matcher.pop(); // Pop self-closing tag
8759
9765
  this.isCurrentNodeStopNode = false; // Reset flag
8760
9766
  }
8761
- else if (this.options.unpairedTags.indexOf(tagName) !== -1) {//unpaired tag
9767
+ else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag
8762
9768
  const childNode = new XmlNode(tagName);
8763
9769
  if (prefixedAttrs) {
8764
9770
  childNode[":@"] = prefixedAttrs;
8765
9771
  }
8766
- this.addChild(currentNode, childNode, this.matcher, startIndex);
9772
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
8767
9773
  this.matcher.pop(); // Pop unpaired tag
8768
9774
  this.isCurrentNodeStopNode = false; // Reset flag
8769
9775
  i = result.closeIndex;
@@ -8773,7 +9779,7 @@
8773
9779
  //opening tag
8774
9780
  else {
8775
9781
  const childNode = new XmlNode(tagName);
8776
- if (this.tagsNodeStack.length > this.options.maxNestedTags) {
9782
+ if (this.tagsNodeStack.length > options.maxNestedTags) {
8777
9783
  throw new Error("Maximum nested tags exceeded");
8778
9784
  }
8779
9785
  this.tagsNodeStack.push(currentNode);
@@ -8781,7 +9787,7 @@
8781
9787
  if (prefixedAttrs) {
8782
9788
  childNode[":@"] = prefixedAttrs;
8783
9789
  }
8784
- this.addChild(currentNode, childNode, this.matcher, startIndex);
9790
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
8785
9791
  currentNode = childNode;
8786
9792
  }
8787
9793
  textData = "";
@@ -8842,60 +9848,7 @@
8842
9848
  }
8843
9849
  }
8844
9850
 
8845
- // Replace DOCTYPE entities
8846
- for (let entityName in this.docTypeEntities) {
8847
- const entity = this.docTypeEntities[entityName];
8848
- const matches = val.match(entity.regx);
8849
-
8850
- if (matches) {
8851
- // Track expansions
8852
- this.entityExpansionCount += matches.length;
8853
-
8854
- // Check expansion limit
8855
- if (entityConfig.maxTotalExpansions &&
8856
- this.entityExpansionCount > entityConfig.maxTotalExpansions) {
8857
- throw new Error(
8858
- `Entity expansion limit exceeded: ${this.entityExpansionCount} > ${entityConfig.maxTotalExpansions}`
8859
- );
8860
- }
8861
-
8862
- // Store length before replacement
8863
- const lengthBefore = val.length;
8864
- val = val.replace(entity.regx, entity.val);
8865
-
8866
- // Check expanded length immediately after replacement
8867
- if (entityConfig.maxExpandedLength) {
8868
- this.currentExpandedLength += (val.length - lengthBefore);
8869
-
8870
- if (this.currentExpandedLength > entityConfig.maxExpandedLength) {
8871
- throw new Error(
8872
- `Total expanded content size exceeded: ${this.currentExpandedLength} > ${entityConfig.maxExpandedLength}`
8873
- );
8874
- }
8875
- }
8876
- }
8877
- }
8878
- if (val.indexOf('&') === -1) return val; // Early exit
8879
-
8880
- // Replace standard entities
8881
- for (let entityName in this.lastEntities) {
8882
- const entity = this.lastEntities[entityName];
8883
- val = val.replace(entity.regex, entity.val);
8884
- }
8885
- if (val.indexOf('&') === -1) return val; // Early exit
8886
-
8887
- // Replace HTML entities if enabled
8888
- if (this.options.htmlEntities) {
8889
- for (let entityName in this.htmlEntities) {
8890
- const entity = this.htmlEntities[entityName];
8891
- val = val.replace(entity.regex, entity.val);
8892
- }
8893
- }
8894
-
8895
- // Replace ampersand entity last
8896
- val = val.replace(this.ampEntity.regex, this.ampEntity.val);
8897
-
8898
- return val;
9851
+ return this.entityDecoder.decode(val);
8899
9852
  }
8900
9853
 
8901
9854
 
@@ -8917,20 +9870,14 @@
8917
9870
  return textData;
8918
9871
  }
8919
9872
 
8920
- //TODO: use jPath to simplify the logic
8921
9873
  /**
8922
9874
  * @param {Array<Expression>} stopNodeExpressions - Array of compiled Expression objects
8923
9875
  * @param {Matcher} matcher - Current path matcher
8924
9876
  */
8925
- function isItStopNode(stopNodeExpressions, matcher) {
8926
- if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;
9877
+ function isItStopNode() {
9878
+ if (this.stopNodeExpressionsSet.size === 0) return false;
8927
9879
 
8928
- for (let i = 0; i < stopNodeExpressions.length; i++) {
8929
- if (matcher.matches(stopNodeExpressions[i])) {
8930
- return true;
8931
- }
8932
- }
8933
- return false;
9880
+ return this.matcher.matchesAny(this.stopNodeExpressionsSet);
8934
9881
  }
8935
9882
 
8936
9883
  /**
@@ -8940,32 +9887,33 @@
8940
9887
  * @returns
8941
9888
  */
8942
9889
  function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
8943
- let attrBoundary;
8944
- let tagExp = "";
8945
- for (let index = i; index < xmlData.length; index++) {
8946
- let ch = xmlData[index];
9890
+ let attrBoundary = 0;
9891
+ const chars = [];
9892
+ const len = xmlData.length;
9893
+ const closeCode0 = closingChar.charCodeAt(0);
9894
+ const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
9895
+
9896
+ for (let index = i; index < len; index++) {
9897
+ const code = xmlData.charCodeAt(index);
9898
+
8947
9899
  if (attrBoundary) {
8948
- if (ch === attrBoundary) attrBoundary = "";//reset
8949
- } else if (ch === '"' || ch === "'") {
8950
- attrBoundary = ch;
8951
- } else if (ch === closingChar[0]) {
8952
- if (closingChar[1]) {
8953
- if (xmlData[index + 1] === closingChar[1]) {
8954
- return {
8955
- data: tagExp,
8956
- index: index
8957
- }
9900
+ if (code === attrBoundary) attrBoundary = 0;
9901
+ } else if (code === 34 || code === 39) { // " or '
9902
+ attrBoundary = code;
9903
+ } else if (code === closeCode0) {
9904
+ if (closeCode1 !== -1) {
9905
+ if (xmlData.charCodeAt(index + 1) === closeCode1) {
9906
+ return { data: String.fromCharCode(...chars), index };
8958
9907
  }
8959
9908
  } else {
8960
- return {
8961
- data: tagExp,
8962
- index: index
8963
- }
9909
+ return { data: String.fromCharCode(...chars), index };
8964
9910
  }
8965
- } else if (ch === '\t') {
8966
- ch = " ";
9911
+ } else if (code === 9) { // \t
9912
+ chars.push(32); // space
9913
+ continue;
8967
9914
  }
8968
- tagExp += ch;
9915
+
9916
+ chars.push(code);
8969
9917
  }
8970
9918
  }
8971
9919
 
@@ -8978,6 +9926,12 @@
8978
9926
  }
8979
9927
  }
8980
9928
 
9929
+ function findClosingChar(xmlData, char, i, errMsg) {
9930
+ const closingIndex = xmlData.indexOf(char, i);
9931
+ if (closingIndex === -1) throw new Error(errMsg);
9932
+ return closingIndex; // no offset needed
9933
+ }
9934
+
8981
9935
  function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
8982
9936
  const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
8983
9937
  if (!result) return;
@@ -9019,10 +9973,12 @@
9019
9973
  // Starting at 1 since we already have an open tag
9020
9974
  let openTagCount = 1;
9021
9975
 
9022
- for (; i < xmlData.length; i++) {
9976
+ const xmllen = xmlData.length;
9977
+ for (; i < xmllen; i++) {
9023
9978
  if (xmlData[i] === "<") {
9024
- if (xmlData[i + 1] === "/") {//close tag
9025
- const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
9979
+ const c1 = xmlData.charCodeAt(i + 1);
9980
+ if (c1 === 47) {//close tag '/'
9981
+ const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
9026
9982
  let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
9027
9983
  if (closeTagName === tagName) {
9028
9984
  openTagCount--;
@@ -9034,13 +9990,16 @@
9034
9990
  }
9035
9991
  }
9036
9992
  i = closeIndex;
9037
- } else if (xmlData[i + 1] === '?') {
9993
+ } else if (c1 === 63) { //?
9038
9994
  const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.");
9039
9995
  i = closeIndex;
9040
- } else if (xmlData.substr(i + 1, 3) === '!--') {
9996
+ } else if (c1 === 33
9997
+ && xmlData.charCodeAt(i + 2) === 45
9998
+ && xmlData.charCodeAt(i + 3) === 45) { // '!--'
9041
9999
  const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
9042
10000
  i = closeIndex;
9043
- } else if (xmlData.substr(i + 1, 2) === '![') {
10001
+ } else if (c1 === 33
10002
+ && xmlData.charCodeAt(i + 2) === 91) { // '!['
9044
10003
  const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
9045
10004
  i = closeIndex;
9046
10005
  } else {
@@ -9074,16 +10033,6 @@
9074
10033
  }
9075
10034
  }
9076
10035
 
9077
- function fromCodePoint(str, base, prefix) {
9078
- const codePoint = Number.parseInt(str, base);
9079
-
9080
- if (codePoint >= 0 && codePoint <= 0x10FFFF) {
9081
- return String.fromCodePoint(codePoint);
9082
- } else {
9083
- return prefix + str + ";";
9084
- }
9085
- }
9086
-
9087
10036
  function transformTagName(fn, tagName, tagExp, options) {
9088
10037
  if (fn) {
9089
10038
  const newTagName = fn(tagName);
@@ -9139,18 +10088,17 @@
9139
10088
  * @param {Matcher} matcher - Path matcher instance
9140
10089
  * @returns
9141
10090
  */
9142
- function prettify(node, options, matcher) {
9143
- return compress(node, options, matcher);
10091
+ function prettify(node, options, matcher, readonlyMatcher) {
10092
+ return compress(node, options, matcher, readonlyMatcher);
9144
10093
  }
9145
10094
 
9146
10095
  /**
9147
- *
9148
10096
  * @param {array} arr
9149
10097
  * @param {object} options
9150
10098
  * @param {Matcher} matcher - Path matcher instance
9151
10099
  * @returns object
9152
10100
  */
9153
- function compress(arr, options, matcher) {
10101
+ function compress(arr, options, matcher, readonlyMatcher) {
9154
10102
  let text;
9155
10103
  const compressedObj = {}; //This is intended to be a plain object
9156
10104
  for (let i = 0; i < arr.length; i++) {
@@ -9173,11 +10121,11 @@
9173
10121
  continue;
9174
10122
  } else if (tagObj[property]) {
9175
10123
 
9176
- let val = compress(tagObj[property], options, matcher);
10124
+ let val = compress(tagObj[property], options, matcher, readonlyMatcher);
9177
10125
  const isLeaf = isLeafTag(val, options);
9178
10126
 
9179
10127
  if (tagObj[":@"]) {
9180
- assignAttributes$1(val, tagObj[":@"], matcher, options);
10128
+ assignAttributes$1(val, tagObj[":@"], readonlyMatcher, options);
9181
10129
  } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {
9182
10130
  val = val[options.textNodeName];
9183
10131
  } else if (Object.keys(val).length === 0) {
@@ -9199,8 +10147,8 @@
9199
10147
  //TODO: if a node is not an array, then check if it should be an array
9200
10148
  //also determine if it is a leaf node
9201
10149
 
9202
- // Pass jPath string or matcher based on options.jPath setting
9203
- const jPathOrMatcher = options.jPath ? matcher.toString() : matcher;
10150
+ // Pass jPath string or readonlyMatcher based on options.jPath setting
10151
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
9204
10152
  if (options.isArray(property, jPathOrMatcher, isLeaf)) {
9205
10153
  compressedObj[property] = [val];
9206
10154
  } else {
@@ -9232,7 +10180,7 @@
9232
10180
  }
9233
10181
  }
9234
10182
 
9235
- function assignAttributes$1(obj, attrMap, matcher, options) {
10183
+ function assignAttributes$1(obj, attrMap, readonlyMatcher, options) {
9236
10184
  if (attrMap) {
9237
10185
  const keys = Object.keys(attrMap);
9238
10186
  const len = keys.length; //don't make it inline
@@ -9247,8 +10195,8 @@
9247
10195
  // For attributes, we need to create a temporary path
9248
10196
  // Pass jPath string or matcher based on options.jPath setting
9249
10197
  const jPathOrMatcher = options.jPath
9250
- ? matcher.toString() + "." + rawAttrName
9251
- : matcher;
10198
+ ? readonlyMatcher.toString() + "." + rawAttrName
10199
+ : readonlyMatcher;
9252
10200
 
9253
10201
  if (options.isArray(atrrName, jPathOrMatcher, true, true)) {
9254
10202
  obj[atrrName] = [attrMap[atrrName]];
@@ -9305,10 +10253,10 @@
9305
10253
  }
9306
10254
  }
9307
10255
  const orderedObjParser = new OrderedObjParser(this.options);
9308
- orderedObjParser.addExternalEntities(this.externalEntities);
10256
+ orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);
9309
10257
  const orderedResult = orderedObjParser.parseXml(xmlData);
9310
10258
  if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;
9311
- else return prettify(orderedResult, this.options, orderedObjParser.matcher);
10259
+ else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
9312
10260
  }
9313
10261
 
9314
10262
  /**
@@ -10889,6 +11837,9 @@
10889
11837
  // retain selection
10890
11838
  let selectionName = this.display.selection_attribute_name;
10891
11839
 
11840
+ // retain class names, including any set at runtime with css()
11841
+ options["css-classes"] = Object.assign({}, this.display.css_classes);
11842
+
10892
11843
  delete this.display;
10893
11844
 
10894
11845
  let rendered_tree = this.render(options);
@@ -11171,193 +12122,37 @@
11171
12122
  /**
11172
12123
  * Draw a straight line edge between two nodes (for unrooted layout).
11173
12124
  *
11174
- * @param {Array} points - Array of [source, target] node objects
11175
- * @returns {String} SVG path string
11176
- */
11177
- function drawUnrootedEdge(points) {
11178
- return (
11179
- "M " + xCoord(points[0]) + "," + yCoord(points[0]) +
11180
- " L " + xCoord(points[1]) + "," + yCoord(points[1])
11181
- );
11182
- }
11183
-
11184
- /**
11185
- * Place a label along an unrooted edge via linear interpolation.
11186
- *
11187
- * @param {Object} edge - Edge object with source and target
11188
- * @param {Number} where - Interpolation factor (0 = target, 1 = source)
11189
- * @returns {Object} {x, y} screen coordinates
11190
- */
11191
- function unrootedSegmentPlacer(edge, where) {
11192
- return {
11193
- x: xCoord(edge.target) + (xCoord(edge.source) - xCoord(edge.target)) * where,
11194
- y: yCoord(edge.target) + (yCoord(edge.source) - yCoord(edge.target)) * where
11195
- };
11196
- }
11197
-
11198
- function itemTagged(item) {
11199
- return item.tag || false;
11200
- }
11201
-
11202
- function itemSelected(item, tag) {
11203
- return item[tag] || false;
11204
- }
11205
-
11206
- const css_classes = {
11207
- "tree-container": "phylotree-container",
11208
- "tree-scale-bar": "tree-scale-bar",
11209
- node: "node",
11210
- "internal-node": "internal-node",
11211
- "tagged-node": "node-tagged",
11212
- "selected-node": "node-selected",
11213
- "collapsed-node": "node-collapsed",
11214
- "root-node": "root-node",
11215
- branch: "branch",
11216
- "selected-branch": "branch-selected",
11217
- "tagged-branch": "branch-tagged",
11218
- "tree-selection-brush": "tree-selection-brush",
11219
- "branch-tracer": "branch-tracer",
11220
- clade: "clade",
11221
- node_text: "phylotree-node-text"
11222
- };
11223
-
11224
- function initializeCssClasses(classes = {}) {
11225
- Object.keys(classes).forEach(key => {
11226
- css_classes[key] = classes[key];
11227
- });
11228
- }
11229
-
11230
- function internalNames(attr) {
11231
- if (!arguments.length) return this.options["internal-names"];
11232
- this.options["internal-names"] = attr;
11233
- return this;
11234
- }
11235
-
11236
- function radial(attr) {
11237
- if (!arguments.length) return this.options["is-radial"];
11238
- this.options["is-radial"] = attr;
11239
- return this;
11240
- }
11241
-
11242
- function unrooted(attr) {
11243
- if (!arguments.length) return this.options["is-unrooted"];
11244
- this.options["is-unrooted"] = attr;
11245
- return this;
11246
- }
11247
-
11248
- function alignTips(attr) {
11249
- if (!arguments.length) return this.options["align-tips"];
11250
- this.options["align-tips"] = attr;
11251
- return this;
11252
- }
11253
-
11254
- /**
11255
- * Return the bubble size of the current node.
11256
- *
11257
- * @param {Node} A node in the phylotree.
11258
- * @returns {Float} The size of the bubble associated to this node.
11259
- */
11260
- function nodeBubbleSize(node) {
11261
-
11262
- // if a custom bubble styler, use that instead
11263
-
11264
- if(this.options["draw-size-bubbles"] && this.options["bubble-styler"]) {
11265
- return this.options["bubble-styler"](node);
11266
- } else {
11267
- return this.options["draw-size-bubbles"]
11268
- ? this.relative_nodeSpan(node) * this.scales[0] * 0.25
11269
- : 0;
11270
- }
11271
- }
11272
-
11273
- // shiftTip function is defined in nodes.js - removed duplicate here
11274
-
11275
- function layoutHandler(attr) {
11276
- if (!arguments.length) return this.layout_listener_handler;
11277
- this.layout_listener_handler = attr;
11278
- return this;
11279
- }
11280
-
11281
- /**
11282
- * Getter/setter for the selection label. Useful when allowing
11283
- * users to make multiple selections.
11284
- *
11285
- * @param {String} attr (Optional) If setting, the new selection label.
11286
- * @returns The current selection label if getting, or the current ``phylotree`` if setting.
11287
- */
11288
- function selectionLabel(attr) {
11289
- if (!arguments.length) return this.selection_attribute_name;
11290
- this.selection_attribute_name = attr;
11291
- this.syncEdgeLabels();
11292
- return this;
11293
- }
11294
-
11295
- /**
11296
- * Get or set the current node span. If setting, the argument should
11297
- * be a function of a node which returns a number, so that node spans
11298
- * can be determined dynamically. Alternatively, the argument can be the
11299
- * string ``"equal"``, to give all nodes an equal span.
11300
- *
11301
- * @param {Function} attr Optional; if setting, the nodeSpan function.
11302
- * @returns The ``nodeSpan`` if getting, or the current ``phylotree`` if setting.
12125
+ * @param {Array} points - Array of [source, target] node objects
12126
+ * @returns {String} SVG path string
11303
12127
  */
11304
- function nodeSpan$1(attr) {
11305
- if (!arguments.length) return nodeSpan$1;
11306
- if (typeof attr == "string" && attr == "equal") {
11307
- nodeSpan$1 = function(d) { // eslint-disable-line
11308
- return 1;
11309
- };
11310
- } else {
11311
- nodeSpan$1 = attr; // eslint-disable-line
11312
- }
11313
- return this;
12128
+ function drawUnrootedEdge(points) {
12129
+ return (
12130
+ "M " + xCoord(points[0]) + "," + yCoord(points[0]) +
12131
+ " L " + xCoord(points[1]) + "," + yCoord(points[1])
12132
+ );
11314
12133
  }
11315
12134
 
11316
- // List of all selecters that can be used with the restricted-selectable option
11317
- var predefined_selecters = {
11318
- all: d => {
11319
- return true;
11320
- },
11321
- none: d => {
11322
- return false;
11323
- },
11324
- "all-leaf-nodes": d => {
11325
- return isLeafNode(d.target);
11326
- },
11327
- "all-internal-nodes": d => {
11328
- return !isLeafNode(d.target);
11329
- }
11330
- };
11331
-
11332
12135
  /**
11333
- * Getter/setter for the selection callback. This function is called
11334
- * every time the current selection is modified, and its argument is
11335
- * an array of nodes that make up the current selection.
12136
+ * Place a label along an unrooted edge via linear interpolation.
11336
12137
  *
11337
- * @param {Function} callback (Optional) The selection callback function.
11338
- * @returns The current ``_selectionCallback`` if getting, or the current ``this`` if setting.
12138
+ * @param {Object} edge - Edge object with source and target
12139
+ * @param {Number} where - Interpolation factor (0 = target, 1 = source)
12140
+ * @returns {Object} {x, y} screen coordinates
11339
12141
  */
11340
- function selectionCallback$1(callback) {
11341
- if (!callback) return this._selectionCallback;
11342
- this._selectionCallback = callback;
11343
- return this;
12142
+ function unrootedSegmentPlacer(edge, where) {
12143
+ return {
12144
+ x: xCoord(edge.target) + (xCoord(edge.source) - xCoord(edge.target)) * where,
12145
+ y: yCoord(edge.target) + (yCoord(edge.source) - yCoord(edge.target)) * where
12146
+ };
11344
12147
  }
11345
12148
 
11346
- var opt = /*#__PURE__*/Object.freeze({
11347
- __proto__: null,
11348
- alignTips: alignTips,
11349
- css_classes: css_classes,
11350
- initializeCssClasses: initializeCssClasses,
11351
- internalNames: internalNames,
11352
- layoutHandler: layoutHandler,
11353
- nodeBubbleSize: nodeBubbleSize,
11354
- get nodeSpan () { return nodeSpan$1; },
11355
- predefined_selecters: predefined_selecters,
11356
- radial: radial,
11357
- selectionCallback: selectionCallback$1,
11358
- selectionLabel: selectionLabel,
11359
- unrooted: unrooted
11360
- });
12149
+ function itemTagged(item) {
12150
+ return item.tag || false;
12151
+ }
12152
+
12153
+ function itemSelected(item, tag) {
12154
+ return item[tag] || false;
12155
+ }
11361
12156
 
11362
12157
  function shiftTip(d) {
11363
12158
 
@@ -11612,7 +12407,7 @@
11612
12407
  * @param {Function} attr Optional; if setting, the nodeSpan function.
11613
12408
  * @returns The ``nodeSpan`` if getting, or the current ``phylotree`` if setting.
11614
12409
  */
11615
- function nodeSpan(attr) {
12410
+ function nodeSpan$1(attr) {
11616
12411
  if (!arguments.length) return this.nodeSpan;
11617
12412
  if (typeof attr == "string" && attr == "equal") {
11618
12413
  this.nodeSpan = function(d) {
@@ -11626,35 +12421,56 @@
11626
12421
 
11627
12422
  function reclassNode(node) {
11628
12423
 
11629
- let class_var = css_classes[isLeafNode(node) ? "node" : "internal-node"];
12424
+ let class_var = this.css_classes[isLeafNode(node) ? "node" : "internal-node"];
11630
12425
 
11631
12426
  if (itemTagged(node)) {
11632
- class_var += " " + css_classes["tagged-node"];
12427
+ class_var += " " + this.css_classes["tagged-node"];
11633
12428
  }
11634
12429
 
11635
12430
  if (itemSelected(node, this.selection_attribute_name)) {
11636
- class_var += " " + css_classes["selected-node"];
12431
+ class_var += " " + this.css_classes["selected-node"];
11637
12432
  }
11638
12433
 
11639
12434
  if (!node["parent"]) {
11640
- class_var += " " + css_classes["root-node"];
12435
+ class_var += " " + this.css_classes["root-node"];
11641
12436
  }
11642
12437
 
11643
12438
  if (isNodeCollapsed(node) || hasHiddenNodes(node)) {
11644
- class_var += " " + css_classes["collapsed-node"];
12439
+ class_var += " " + this.css_classes["collapsed-node"];
11645
12440
  }
11646
12441
 
11647
12442
  return class_var;
11648
12443
  }
11649
12444
 
11650
12445
  function nodeVisible(node) {
11651
- return !(node.hidden || node.notshown || false);
12446
+ return !(node.hidden || nodeOrAncestorNotshown(node));
11652
12447
  }
11653
12448
 
11654
12449
  function nodeNotshown(node) {
11655
12450
  return node.notshown;
11656
12451
  }
11657
12452
 
12453
+ // true if the node or any of its ancestors is hidden (notshown); the layout
12454
+ // skips a hidden node's whole subtree, so its descendants are hidden too.
12455
+ // Reads the flag cached by markNotshownSubtrees() (run by placenodes) so the
12456
+ // check stays O(1) on deep trees; walks the ancestors if it is not set yet.
12457
+ function nodeOrAncestorNotshown(node) {
12458
+ if (node.notshown) return true;
12459
+ if (node.notshown_ancestor !== undefined) return node.notshown_ancestor;
12460
+ for (let n = node.parent; n; n = n.parent) {
12461
+ if (n.notshown) return true;
12462
+ }
12463
+ return false;
12464
+ }
12465
+
12466
+ // cache, on every node, whether one of its ancestors is notshown
12467
+ function markNotshownSubtrees(root) {
12468
+ root.eachBefore(d => {
12469
+ d.notshown_ancestor =
12470
+ !!d.parent && (!!d.parent.notshown || d.parent.notshown_ancestor);
12471
+ });
12472
+ }
12473
+
11658
12474
  function hasHiddenNodes(node) {
11659
12475
  return node.hasHiddenNodes || false;
11660
12476
  }
@@ -11734,10 +12550,12 @@
11734
12550
  hasHiddenNodes: hasHiddenNodes,
11735
12551
  internalLabel: internalLabel,
11736
12552
  isNodeCollapsed: isNodeCollapsed,
12553
+ markNotshownSubtrees: markNotshownSubtrees,
11737
12554
  nodeCssSelectors: nodeCssSelectors,
11738
12555
  nodeLabel: nodeLabel,
11739
12556
  nodeNotshown: nodeNotshown,
11740
- nodeSpan: nodeSpan,
12557
+ nodeOrAncestorNotshown: nodeOrAncestorNotshown,
12558
+ nodeSpan: nodeSpan$1,
11741
12559
  nodeVisible: nodeVisible,
11742
12560
  reclassNode: reclassNode,
11743
12561
  shiftTip: shiftTip,
@@ -11759,7 +12577,10 @@
11759
12577
  let collapsed_clades = enclosure
11760
12578
  .selectAll(cladeCssSelectors(this.css_classes))
11761
12579
  .data(
11762
- this.phylotree.nodes.descendants().filter(isNodeCollapsed),
12580
+ // a hidden clade is not laid out, so do not draw its stale polygon
12581
+ this.phylotree.nodes
12582
+ .descendants()
12583
+ .filter(d => isNodeCollapsed(d) && !nodeOrAncestorNotshown(d)),
11763
12584
  function(d) {
11764
12585
  return d.id || (d.id = ++node_id);
11765
12586
  }
@@ -11922,14 +12743,14 @@
11922
12743
 
11923
12744
  function reclassEdge(edge) {
11924
12745
 
11925
- let class_var = css_classes["branch"];
12746
+ let class_var = this.css_classes["branch"];
11926
12747
 
11927
12748
  if (itemTagged(edge)) {
11928
- class_var += " " + css_classes["tagged-branch"];
12749
+ class_var += " " + this.css_classes["tagged-branch"];
11929
12750
  }
11930
12751
 
11931
12752
  if (itemSelected(edge, this.selection_attribute_name)) {
11932
- class_var += " " + css_classes["selected-branch"];
12753
+ class_var += " " + this.css_classes["selected-branch"];
11933
12754
  }
11934
12755
 
11935
12756
  // Multi-set selection mode: add set-specific class
@@ -11988,7 +12809,7 @@
11988
12809
  }
11989
12810
 
11990
12811
  function edgeVisible(edge) {
11991
- return !(edge.target.hidden || edge.target.notshown || false);
12812
+ return !(edge.target.hidden || nodeOrAncestorNotshown(edge.target));
11992
12813
  }
11993
12814
 
11994
12815
  function edgeCssSelectors(css_classes) {
@@ -12071,7 +12892,7 @@
12071
12892
  }
12072
12893
 
12073
12894
  svg
12074
- .selectAll("." + css_classes["tree-container"])
12895
+ .selectAll("." + this.css_classes["tree-container"])
12075
12896
  .attr("transform", transform);
12076
12897
  }
12077
12898
  } else if (this.radial()) {
@@ -12103,7 +12924,7 @@
12103
12924
  }
12104
12925
 
12105
12926
  svg
12106
- .selectAll("." + css_classes["tree-container"])
12927
+ .selectAll("." + this.css_classes["tree-container"])
12107
12928
  .attr("transform", transform);
12108
12929
  }
12109
12930
  } else {
@@ -12230,6 +13051,164 @@
12230
13051
  triggerRefresh: triggerRefresh
12231
13052
  });
12232
13053
 
13054
+ // Default class names. Each TreeRender works on its own copy
13055
+ // (this.css_classes), so this object is never mutated.
13056
+ const css_classes = {
13057
+ "tree-container": "phylotree-container",
13058
+ "tree-scale-bar": "tree-scale-bar",
13059
+ node: "node",
13060
+ "internal-node": "internal-node",
13061
+ "tagged-node": "node-tagged",
13062
+ "selected-node": "node-selected",
13063
+ "collapsed-node": "node-collapsed",
13064
+ "root-node": "root-node",
13065
+ branch: "branch",
13066
+ "selected-branch": "branch-selected",
13067
+ "tagged-branch": "branch-tagged",
13068
+ "tree-selection-brush": "tree-selection-brush",
13069
+ "branch-tracer": "branch-tracer",
13070
+ clade: "clade",
13071
+ node_text: "phylotree-node-text"
13072
+ };
13073
+
13074
+ function initializeCssClasses(classes = {}) {
13075
+ Object.keys(classes).forEach(key => {
13076
+ this.css_classes[key] = classes[key];
13077
+ });
13078
+ }
13079
+
13080
+ function internalNames(attr) {
13081
+ if (!arguments.length) return this.options["internal-names"];
13082
+ this.options["internal-names"] = attr;
13083
+ return this;
13084
+ }
13085
+
13086
+ function radial(attr) {
13087
+ if (!arguments.length) return this.options["is-radial"];
13088
+ this.options["is-radial"] = attr;
13089
+ return this;
13090
+ }
13091
+
13092
+ function unrooted(attr) {
13093
+ if (!arguments.length) return this.options["is-unrooted"];
13094
+ this.options["is-unrooted"] = attr;
13095
+ return this;
13096
+ }
13097
+
13098
+ function alignTips(attr) {
13099
+ if (!arguments.length) return this.options["align-tips"];
13100
+ this.options["align-tips"] = attr;
13101
+ return this;
13102
+ }
13103
+
13104
+ /**
13105
+ * Return the bubble size of the current node.
13106
+ *
13107
+ * @param {Node} A node in the phylotree.
13108
+ * @returns {Float} The size of the bubble associated to this node.
13109
+ */
13110
+ function nodeBubbleSize(node) {
13111
+
13112
+ // if a custom bubble styler, use that instead
13113
+
13114
+ if(this.options["draw-size-bubbles"] && this.options["bubble-styler"]) {
13115
+ return this.options["bubble-styler"](node);
13116
+ } else {
13117
+ return this.options["draw-size-bubbles"]
13118
+ ? this.relative_nodeSpan(node) * this.scales[0] * 0.25
13119
+ : 0;
13120
+ }
13121
+ }
13122
+
13123
+ // shiftTip function is defined in nodes.js - removed duplicate here
13124
+
13125
+ function layoutHandler(attr) {
13126
+ if (!arguments.length) return this.layout_listener_handler;
13127
+ this.layout_listener_handler = attr;
13128
+ return this;
13129
+ }
13130
+
13131
+ /**
13132
+ * Getter/setter for the selection label. Useful when allowing
13133
+ * users to make multiple selections.
13134
+ *
13135
+ * @param {String} attr (Optional) If setting, the new selection label.
13136
+ * @returns The current selection label if getting, or the current ``phylotree`` if setting.
13137
+ */
13138
+ function selectionLabel(attr) {
13139
+ if (!arguments.length) return this.selection_attribute_name;
13140
+ this.selection_attribute_name = attr;
13141
+ this.syncEdgeLabels();
13142
+ return this;
13143
+ }
13144
+
13145
+ /**
13146
+ * Get or set the current node span. If setting, the argument should
13147
+ * be a function of a node which returns a number, so that node spans
13148
+ * can be determined dynamically. Alternatively, the argument can be the
13149
+ * string ``"equal"``, to give all nodes an equal span.
13150
+ *
13151
+ * @param {Function} attr Optional; if setting, the nodeSpan function.
13152
+ * @returns The ``nodeSpan`` if getting, or the current ``phylotree`` if setting.
13153
+ */
13154
+ function nodeSpan(attr) {
13155
+ if (!arguments.length) return nodeSpan;
13156
+ if (typeof attr == "string" && attr == "equal") {
13157
+ nodeSpan = function(d) { // eslint-disable-line
13158
+ return 1;
13159
+ };
13160
+ } else {
13161
+ nodeSpan = attr; // eslint-disable-line
13162
+ }
13163
+ return this;
13164
+ }
13165
+
13166
+ // List of all selecters that can be used with the restricted-selectable option
13167
+ var predefined_selecters = {
13168
+ all: d => {
13169
+ return true;
13170
+ },
13171
+ none: d => {
13172
+ return false;
13173
+ },
13174
+ "all-leaf-nodes": d => {
13175
+ return isLeafNode(d.target);
13176
+ },
13177
+ "all-internal-nodes": d => {
13178
+ return !isLeafNode(d.target);
13179
+ }
13180
+ };
13181
+
13182
+ /**
13183
+ * Getter/setter for the selection callback. This function is called
13184
+ * every time the current selection is modified, and its argument is
13185
+ * an array of nodes that make up the current selection.
13186
+ *
13187
+ * @param {Function} callback (Optional) The selection callback function.
13188
+ * @returns The current ``_selectionCallback`` if getting, or the current ``this`` if setting.
13189
+ */
13190
+ function selectionCallback$1(callback) {
13191
+ if (!callback) return this._selectionCallback;
13192
+ this._selectionCallback = callback;
13193
+ return this;
13194
+ }
13195
+
13196
+ var opt = /*#__PURE__*/Object.freeze({
13197
+ __proto__: null,
13198
+ alignTips: alignTips,
13199
+ css_classes: css_classes,
13200
+ initializeCssClasses: initializeCssClasses,
13201
+ internalNames: internalNames,
13202
+ layoutHandler: layoutHandler,
13203
+ nodeBubbleSize: nodeBubbleSize,
13204
+ get nodeSpan () { return nodeSpan; },
13205
+ predefined_selecters: predefined_selecters,
13206
+ radial: radial,
13207
+ selectionCallback: selectionCallback$1,
13208
+ selectionLabel: selectionLabel,
13209
+ unrooted: unrooted
13210
+ });
13211
+
12233
13212
  let d3_layout_phylotree_context_menu_id = "d3_layout_phylotree_context_menu";
12234
13213
 
12235
13214
  function nodeDropdownMenu(node, container, phylotree, options, event) {
@@ -12389,7 +13368,14 @@
12389
13368
  .text("Hide this " + (isLeafNode(node) ? "node" : "subtree"))
12390
13369
  .on("click", d => {
12391
13370
  menu_object.style("display", "none");
12392
- this.modifySelection([node], "notshown", true, true)
13371
+ // hide the whole subtree, mirroring "Show all descendant nodes"
13372
+ this.modifySelection(
13373
+ [node].concat(selectAllDescendants(node, true, true)),
13374
+ "notshown",
13375
+ true,
13376
+ true,
13377
+ "true"
13378
+ )
12393
13379
  .updateHasHiddenNodes()
12394
13380
  .update();
12395
13381
  });
@@ -12576,8 +13562,12 @@
12576
13562
  }
12577
13563
  }
12578
13564
  } else if (this.options["binary-selectable"]) {
13565
+ // Only selection attributes are mutually exclusive; hiding ("notshown")
13566
+ // or brushing ("tag") must not clear the attributes in attribute-list.
13567
+ const exclusive = attr != "notshown" && attr != "tag";
13568
+
12579
13569
  if (typeof node_selecter === "function") {
12580
- this.links.forEach(function(d) {
13570
+ this.links.forEach(d => {
12581
13571
  var select_me = node_selecter(d);
12582
13572
  d[attr] = d[attr] || false;
12583
13573
 
@@ -12587,6 +13577,7 @@
12587
13577
  d.target[attr] = select_me;
12588
13578
  }
12589
13579
 
13580
+ if (!exclusive) return;
12590
13581
  this.options["attribute-list"].forEach(function(type) {
12591
13582
  if (type != attr && d[attr] === true) {
12592
13583
  d[type] = false;
@@ -12597,7 +13588,17 @@
12597
13588
  } else {
12598
13589
  node_selecter.forEach(function(d) {
12599
13590
  var new_value;
12600
- new_value = !d[attr];
13591
+ switch (mode) {
13592
+ case "true":
13593
+ new_value = true;
13594
+ break;
13595
+ case "false":
13596
+ new_value = false;
13597
+ break;
13598
+ default:
13599
+ new_value = !d[attr];
13600
+ break;
13601
+ }
12601
13602
 
12602
13603
  if (d[attr] != new_value) {
12603
13604
  d[attr] = new_value;
@@ -12605,8 +13606,9 @@
12605
13606
  }
12606
13607
  });
12607
13608
 
12608
- this.links.forEach(function(d) {
13609
+ this.links.forEach(d => {
12609
13610
  d[attr] = d.target[attr];
13611
+ if (!exclusive) return;
12610
13612
  this.options["attribute-list"].forEach(function(type) {
12611
13613
  if (type != attr && d[attr] !== true) {
12612
13614
  d[type] = false;
@@ -12956,9 +13958,9 @@
12956
13958
  return [];
12957
13959
  }
12958
13960
 
12959
- const memberNames = this._selectionSets[setName].members;
13961
+ const members = this._selectionSets[setName].members;
12960
13962
  return this.phylotree.nodes.descendants()
12961
- .filter(node => memberNames.has(node.data.name));
13963
+ .filter(node => members.has(node));
12962
13964
  }
12963
13965
 
12964
13966
  /**
@@ -12977,7 +13979,8 @@
12977
13979
  return this;
12978
13980
  }
12979
13981
 
12980
- const nodeName = typeof node === "string" ? node : node.data.name;
13982
+ // Membership is keyed by node identity; names are resolved here so that
13983
+ // unnamed or duplicate-named nodes do not share membership.
12981
13984
  const nodeObj = typeof node === "string"
12982
13985
  ? this.phylotree.getNodeByName(node)
12983
13986
  : node;
@@ -12985,10 +13988,10 @@
12985
13988
  if (nodeObj) {
12986
13989
  // Remove from all other sets (mutually exclusive)
12987
13990
  Object.keys(this._selectionSets).forEach(otherSet => {
12988
- this._selectionSets[otherSet].members.delete(nodeName);
13991
+ this._selectionSets[otherSet].members.delete(nodeObj);
12989
13992
  });
12990
13993
 
12991
- this._selectionSets[setName].members.add(nodeName);
13994
+ this._selectionSets[setName].members.add(nodeObj);
12992
13995
  nodeObj._selectionSet = setName;
12993
13996
 
12994
13997
  this.emit("setChange", {
@@ -13019,16 +14022,13 @@
13019
14022
  return this;
13020
14023
  }
13021
14024
 
13022
- const nodeName = typeof node === "string" ? node : node.data.name;
13023
14025
  const nodeObj = typeof node === "string"
13024
14026
  ? this.phylotree.getNodeByName(node)
13025
14027
  : node;
13026
14028
 
13027
- if (this._selectionSets[setName].members.has(nodeName)) {
13028
- this._selectionSets[setName].members.delete(nodeName);
13029
- if (nodeObj) {
13030
- delete nodeObj._selectionSet;
13031
- }
14029
+ if (nodeObj && this._selectionSets[setName].members.has(nodeObj)) {
14030
+ this._selectionSets[setName].members.delete(nodeObj);
14031
+ delete nodeObj._selectionSet;
13032
14032
 
13033
14033
  this.emit("setChange", {
13034
14034
  action: "remove",
@@ -13054,7 +14054,8 @@
13054
14054
  const summary = {};
13055
14055
  if (this._selectionSets) {
13056
14056
  Object.keys(this._selectionSets).forEach(setName => {
13057
- summary[setName] = Array.from(this._selectionSets[setName].members);
14057
+ summary[setName] = Array.from(this._selectionSets[setName].members,
14058
+ node => node.data.name);
13058
14059
  });
13059
14060
  }
13060
14061
  return summary;
@@ -13072,7 +14073,6 @@
13072
14073
  return;
13073
14074
  }
13074
14075
 
13075
- node.data.name;
13076
14076
  const currentSet = node._selectionSet;
13077
14077
 
13078
14078
  if (currentSet === this._activeSetName) {
@@ -13095,7 +14095,7 @@
13095
14095
  if (!this._selectionSets || !this._selectionSets[setName]) {
13096
14096
  return false;
13097
14097
  }
13098
- return this._selectionSets[setName].members.has(node.data.name);
14098
+ return this._selectionSets[setName].members.has(node);
13099
14099
  }
13100
14100
 
13101
14101
  /**
@@ -13132,8 +14132,7 @@
13132
14132
 
13133
14133
  class TreeRender {
13134
14134
  constructor(phylotree, options = {}) {
13135
- initializeCssClasses(options['css-classes']);
13136
- this.css_classes = css_classes;
14135
+ this.css_classes = Object.assign({}, css_classes, options["css-classes"]);
13137
14136
  this.phylotree = phylotree;
13138
14137
  this.container = options.container;
13139
14138
  this.separation = function(_node, _previous) {
@@ -13435,7 +14434,7 @@
13435
14434
  let node_id = 0;
13436
14435
 
13437
14436
  let enclosure = this.svg
13438
- .selectAll("." + css_classes["tree-container"])
14437
+ .selectAll("." + this.css_classes["tree-container"])
13439
14438
  .data([0]);
13440
14439
 
13441
14440
  // Store base transform for composition with zoom
@@ -13447,7 +14446,7 @@
13447
14446
  enclosure = enclosure
13448
14447
  .enter()
13449
14448
  .append("g")
13450
- .attr("class", css_classes["tree-container"])
14449
+ .attr("class", this.css_classes["tree-container"])
13451
14450
  .merge(enclosure)
13452
14451
  .attr("transform", d => {
13453
14452
  // Compose base transform with current zoom transform if present
@@ -13463,13 +14462,13 @@
13463
14462
 
13464
14463
  if (this.draw_scale_bar) {
13465
14464
  let scale_bar = this.svg
13466
- .selectAll("." + css_classes["tree-scale-bar"])
14465
+ .selectAll("." + this.css_classes["tree-scale-bar"])
13467
14466
  .data([0]);
13468
14467
 
13469
14468
  scale_bar
13470
14469
  .enter()
13471
14470
  .append("g")
13472
- .attr("class", css_classes["tree-scale-bar"])
14471
+ .attr("class", this.css_classes["tree-scale-bar"])
13473
14472
  .style("font-size", this.ensure_size_is_in_px(this.scale_bar_font_size))
13474
14473
  .merge(scale_bar)
13475
14474
  .attr("transform", d => {
@@ -13482,17 +14481,17 @@
13482
14481
 
13483
14482
  scale_bar.selectAll("text").style("text-anchor", "end");
13484
14483
  } else {
13485
- this.svg.selectAll("." + css_classes["tree-scale-bar"]).remove();
14484
+ this.svg.selectAll("." + this.css_classes["tree-scale-bar"]).remove();
13486
14485
  }
13487
14486
 
13488
14487
  enclosure = this.svg
13489
- .selectAll("." + css_classes["tree-container"])
14488
+ .selectAll("." + this.css_classes["tree-container"])
13490
14489
  .data([0]);
13491
14490
 
13492
14491
  this.updateCollapsedClades(transitions);
13493
14492
 
13494
14493
  let drawn_links = enclosure
13495
- .selectAll(edgeCssSelectors(css_classes))
14494
+ .selectAll(edgeCssSelectors(this.css_classes))
13496
14495
  .data(this.links.filter(edgeVisible), d => {
13497
14496
  return d.target.id || (d.target.id = ++node_id);
13498
14497
  });
@@ -13512,7 +14511,7 @@
13512
14511
  });
13513
14512
 
13514
14513
  let drawn_nodes = enclosure
13515
- .selectAll(nodeCssSelectors(css_classes))
14514
+ .selectAll(nodeCssSelectors(this.css_classes))
13516
14515
  .data(
13517
14516
  this.phylotree.nodes.descendants().filter(nodeVisible),
13518
14517
  d => {
@@ -13525,8 +14524,8 @@
13525
14524
  drawn_nodes = drawn_nodes
13526
14525
  .enter()
13527
14526
  .append("g")
13528
- .attr("class", this.reclassNode)
13529
14527
  .merge(drawn_nodes)
14528
+ .attr("class", d => this.reclassNode(d))
13530
14529
  .attr("transform", d => {
13531
14530
  const should_shift =
13532
14531
  this.options["layout"] == "right-to-left" && isLeafNode(d);
@@ -13558,11 +14557,11 @@
13558
14557
 
13559
14558
  if (this.options["brush"]) {
13560
14559
  var brush = enclosure
13561
- .selectAll("." + css_classes["tree-selection-brush"])
14560
+ .selectAll("." + this.css_classes["tree-selection-brush"])
13562
14561
  .data([0])
13563
14562
  .enter()
13564
14563
  .insert("g", ":first-child")
13565
- .attr("class", css_classes["tree-selection-brush"]);
14564
+ .attr("class", this.css_classes["tree-selection-brush"]);
13566
14565
 
13567
14566
  var brush_object = brush_default()
13568
14567
  .on("brush", (event, d) => {
@@ -13623,10 +14622,10 @@
13623
14622
  const composedTransform = `translate(${zt.x + this.baseTransform.x * zt.k}, ${zt.y + this.baseTransform.y * zt.k}) scale(${zt.k})`;
13624
14623
 
13625
14624
  // Use this.svg.select() to target only this tree instance (not global d3.select)
13626
- this.svg.select("." + css_classes["tree-container"]).attr("transform", composedTransform);
14625
+ this.svg.select("." + this.css_classes["tree-container"]).attr("transform", composedTransform);
13627
14626
 
13628
14627
  // Apply same transform to scale bar
13629
- this.svg.select("." + css_classes["tree-scale-bar"]).attr("transform", d => {
14628
+ this.svg.select("." + this.css_classes["tree-scale-bar"]).attr("transform", d => {
13630
14629
  return `translate(${zt.x + this.baseTransform.x * zt.k}, ${zt.y + (this.baseTransform.y - 10) * zt.k}) scale(${zt.k})`;
13631
14630
  });
13632
14631
  });
@@ -13933,6 +14932,8 @@
13933
14932
  * @returns The current ``phylotree``.
13934
14933
  */
13935
14934
  placenodes() {
14935
+ markNotshownSubtrees(this.phylotree.nodes);
14936
+
13936
14937
  this._extents = [
13937
14938
  [0, 0],
13938
14939
  [0, 0]
@@ -14045,7 +15046,12 @@
14045
15046
 
14046
15047
  let max_r = 0;
14047
15048
 
15049
+ // hidden (notshown) nodes and their descendants are not laid out and
15050
+ // keep stale coordinates; leave them out of the transforms and extents
15051
+ const shown = d => !nodeOrAncestorNotshown(d);
15052
+
14048
15053
  this.phylotree.nodes.each(d => {
15054
+ if (!shown(d)) return;
14049
15055
  let my_circ_position = d.x * this.scales[0];
14050
15056
  d.angle = (2 * Math.PI * my_circ_position) / effective_span;
14051
15057
  d.text_angle = d.angle - Math.PI / 2;
@@ -14057,6 +15063,7 @@
14057
15063
  this.do_lr(at_least_one_dimension_fixed);
14058
15064
 
14059
15065
  this.phylotree.nodes.each(d => {
15066
+ if (!shown(d)) return;
14060
15067
  d.radius = (d.y * this.scales[1]) / this.size[1];
14061
15068
  max_r = Math.max(d.radius, max_r);
14062
15069
  });
@@ -14064,7 +15071,7 @@
14064
15071
  let annular_shift = 0;
14065
15072
 
14066
15073
  this.phylotree.nodes.each(d => {
14067
- if (!d.children) {
15074
+ if (!d.children && shown(d)) {
14068
15075
  let my_circ_position = d.x * this.scales[0];
14069
15076
  if (last_child_angle !== null) {
14070
15077
  let required_spacing = my_circ_position - last_circ_position,
@@ -14136,6 +15143,7 @@
14136
15143
  }
14137
15144
 
14138
15145
  this.phylotree.nodes.each(d => {
15146
+ if (!shown(d)) return;
14139
15147
  cartesianToPolar(
14140
15148
  d,
14141
15149
  this.radius,
@@ -14203,6 +15211,9 @@
14203
15211
  this.right_most_leaf = 0;
14204
15212
 
14205
15213
  this.phylotree.nodes.each(d => {
15214
+ // hidden nodes (and their descendants) are not laid out; do not
15215
+ // rescale their stale coordinates
15216
+ if (nodeOrAncestorNotshown(d)) return;
14206
15217
 
14207
15218
  d.x *= this.scales[0];
14208
15219
  d.y *= this.scales[1]*.8;
@@ -14414,9 +15425,9 @@
14414
15425
  return this.css(arg);
14415
15426
  }
14416
15427
 
14417
- for (var key in css_classes) {
14418
- if (key in opt && opt[key] != css_classes[key]) {
14419
- css_classes[key] = opt[key];
15428
+ for (var key in this.css_classes) {
15429
+ if (key in opt && opt[key] != this.css_classes[key]) {
15430
+ this.css_classes[key] = opt[key];
14420
15431
  }
14421
15432
  }
14422
15433
 
@@ -14448,7 +15459,7 @@
14448
15459
 
14449
15460
  let do_update = false;
14450
15461
 
14451
- for (var key in css_classes) {
15462
+ for (var key in this.css_classes) {
14452
15463
  if (key in opt && opt[key] != this.css_classes[key]) {
14453
15464
  do_update = true;
14454
15465
  this.css_classes[key] = opt[key];
@@ -14504,20 +15515,11 @@
14504
15515
  .attr("class", this.reclassEdge.bind(this));
14505
15516
 
14506
15517
  if (this.edge_styler) {
14507
- edges.each(d => {
14508
- this.edge_styler(select(this), d);
15518
+ let self = this;
15519
+ edges.each(function(d) {
15520
+ self.edge_styler(select(this), d);
14509
15521
  });
14510
15522
  }
14511
-
14512
- //let nodes = this.enclosure
14513
- // .selectAll(inspector.nodeCssSelectors(this.css_classes))
14514
- // .attr("class", this.phylotree.reclassNode);
14515
-
14516
- //if (this.node_styler) {
14517
- // nodes.each(function(d) {
14518
- // this.node_styler(d3.select(this), d);
14519
- // });
14520
- //}
14521
15523
  }
14522
15524
 
14523
15525
  return this;