From 9f151aca7c3990bab7afe2d82ac58088d3b01074 Mon Sep 17 00:00:00 2001 From: Arpad Borsos Date: Sun, 26 Jul 2026 16:34:10 +0200 Subject: [PATCH] update dependencies, rebuild --- dist/{cache-oK5XC6-w.js => cache-CxTjXol0.js} | 2209 +++++++- dist/{cache-COXGx-w3.js => cache-DhiwylR9.js} | 4952 +++++++++-------- ...leanup-BnmJoqJp.js => cleanup-BaSEYL-3.js} | 545 +- dist/restore.js | 2 +- dist/save.js | 2 +- ...-cjs-DNYNk0pO.js => state-cjs-CkvFUaNy.js} | 20 +- package-lock.json | 731 ++- package.json | 8 +- src/cleanup.ts | 6 +- src/config.ts | 4 +- src/restore.ts | 6 +- src/save.ts | 6 +- src/workspace.ts | 15 +- tsconfig.json | 3 - 14 files changed, 5617 insertions(+), 2892 deletions(-) rename dist/{cache-oK5XC6-w.js => cache-CxTjXol0.js} (95%) rename dist/{cache-COXGx-w3.js => cache-DhiwylR9.js} (97%) rename dist/{cleanup-BnmJoqJp.js => cleanup-BaSEYL-3.js} (98%) rename dist/{state-cjs-DNYNk0pO.js => state-cjs-CkvFUaNy.js} (99%) diff --git a/dist/cache-oK5XC6-w.js b/dist/cache-CxTjXol0.js similarity index 95% rename from dist/cache-oK5XC6-w.js rename to dist/cache-CxTjXol0.js index 836963a..e9a4ccf 100644 --- a/dist/cache-oK5XC6-w.js +++ b/dist/cache-CxTjXol0.js @@ -1,6 +1,6 @@ -import { f as debug, m as mkdirP, n as create, l as exec, w as which, o as warning, i as info, H as HttpCodes, p as HttpClientError, q as HttpClient, t as isDebug, u as setSecret, B as BearerCredentialHandler, e as error } from './cleanup-BnmJoqJp.js'; +import { f as debug, m as mkdirP, n as create, l as exec, w as which, o as warning, i as info, H as HttpCodes, p as HttpClientError, q as HttpClient, t as isDebug, u as setSecret, B as BearerCredentialHandler, e as error } from './cleanup-BaSEYL-3.js'; import * as path from 'path'; -import * as crypto$1 from 'crypto'; +import * as crypto from 'crypto'; import * as fs from 'fs'; import { writeFileSync, existsSync } from 'fs'; import * as require$$0$1 from 'util'; @@ -20,7 +20,7 @@ import zlib from 'node:zlib'; import { EventEmitter } from 'events'; import require$$0$4 from 'node:buffer'; import { createHmac } from 'node:crypto'; -import { r as requireDist, a as requireDist$1, b as requireState, c as requireStateCjs } from './state-cjs-DNYNk0pO.js'; +import { r as requireDist, a as requireDist$1, b as requireStateCjs, c as requireStateCjs$1 } from './state-cjs-CkvFUaNy.js'; import * as require$$0$2 from 'stream'; import { Readable } from 'stream'; import fs$1 from 'node:fs'; @@ -1660,6 +1660,11 @@ function requireRange () { const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + const invalidXRangeOrder = (M, m, p) => ( + (isX(M) && !isX(m)) || + (isX(m) && p && !isX(p)) + ); + // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 @@ -1677,6 +1682,10 @@ function requireRange () { const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + // if we're including prereleases in the match, then the lower bound is + // -0, the lowest possible prerelease value, just like x-ranges and carets. + // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as. + const z = options.includePrerelease ? '-0' : ''; return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr); let ret; @@ -1684,10 +1693,10 @@ function requireRange () { if (isX(M)) { ret = ''; } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; } else if (pr) { debug('replaceTilde pr', pr); ret = `>=${M}.${m}.${p}-${pr @@ -1756,10 +1765,10 @@ function requireRange () { if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0`; + } <${M}.${m}.${+p + 1}-0`; } else { ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0`; + } <${M}.${+m + 1}.0-0`; } } else { ret = `>=${M}.${m}.${p @@ -1785,6 +1794,10 @@ function requireRange () { const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr); + if (invalidXRangeOrder(M, m, p)) { + return comp + } + const xM = isX(M); const xm = xM || isX(m); const xp = xm || isX(p); @@ -2882,6 +2895,10 @@ const GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar. const SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`; const TarFilename = 'cache.tar'; const ManifestFilename = 'manifest.txt'; +// Prefix the cache backend embeds in a read-denial message (v2 twirp +// GetCacheEntryDownloadURL error or the GHES v1 `_apis/artifactcache` 403 body). +// Shared so cache.ts and cacheHttpClient.ts match the same contract value. +const CacheReadDeniedMessagePrefix = 'cache read denied:'; var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -2921,7 +2938,7 @@ function createTempDirectory() { } tempDirectory = path.join(baseLocation, 'actions', 'temp'); } - const dest = path.join(tempDirectory, crypto$1.randomUUID()); + const dest = path.join(tempDirectory, crypto.randomUUID()); yield mkdirP(dest); return dest; }); @@ -3043,7 +3060,7 @@ function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) } // Add salt to cache version to support breaking changes in cache entry components.push(versionSalt); - return crypto$1.createHash('sha256').update(components.join('|')).digest('hex'); + return crypto.createHash('sha256').update(components.join('|')).digest('hex'); } function getRuntimeToken() { const token = process.env['ACTIONS_RUNTIME_TOKEN']; @@ -3506,7 +3523,7 @@ function createHttpHeaders$1(rawHeaders) { * @returns RFC4122 v4 UUID. */ function randomUUID$1() { - return crypto.randomUUID(); + return globalThis.crypto.randomUUID(); } // Copyright (c) Microsoft Corporation. @@ -4496,7 +4513,7 @@ function logPolicy$1(options = {}) { logger(`Request: ${sanitizer.sanitize(request)}`); const response = await next(request); logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + logger(`Headers: ${sanitizer.sanitize({ headers: response.headers })}`); return response; }, }; @@ -5557,7 +5574,7 @@ async function setPlatformSpecificData(map) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -const SDK_VERSION$1 = "1.24.0"; +const SDK_VERSION$1 = "1.25.0"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -5713,20 +5730,30 @@ function formDataPolicy() { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This error is thrown when an asynchronous operation has been aborted. * Check for this error by testing the `name` that the name property of the * error matches `"AbortError"`. * * @example - * ```ts + * ```ts snippet:AbortErrorSample + * import { AbortError } from "@azure/abort-controller"; + * + * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise { + * if (options.abortSignal.aborted) { + * throw new AbortError(); + * } + * + * // do async work + * } + * * const controller = new AbortController(); * controller.abort(); * try { - * doAsyncWork(controller.signal) + * doAsyncWork({ abortSignal: controller.signal }); * } catch (e) { - * if (e.name === 'AbortError') { + * if (e instanceof Error && e.name === "AbortError") { * // handle abort error here. * } * } @@ -5980,7 +6007,7 @@ class TracingContextImpl { } } -var stateExports = requireState(); +var stateCjsExports$1 = requireStateCjs(); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -5989,7 +6016,7 @@ var stateExports = requireState(); /** * Defines the shared state between CJS and ESM by re-exporting the CJS state. */ -const state$1 = stateExports.state; +const state$1 = stateCjsExports$1.state; // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -6057,8 +6084,8 @@ function createTracingClient(options) { function startSpan(name, operationOptions, spanOptions) { const startSpanResult = getInstrumenter().startSpan(name, { ...spanOptions, - packageName: packageName, - packageVersion: packageVersion, + packageName, + packageVersion, tracingContext: operationOptions?.tracingOptions?.tracingContext, }); let tracingContext = startSpanResult.tracingContext; @@ -6078,7 +6105,7 @@ function createTracingClient(options) { async function withSpan(name, operationOptions, callback, spanOptions) { const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => callback(updatedOptions, span)); span.setStatus({ status: "success" }); return result; } @@ -6807,11 +6834,6 @@ function getCaeChallengeClaims(challenges) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -/** - * @internal - * @param accessToken - Access token - * @returns Whether a token is bearer type or not - */ /** * Tests an object to determine whether it implements TokenCredential. * @@ -6835,7 +6857,7 @@ const disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; function createDisableKeepAlivePolicy() { return { name: disableKeepAlivePolicyName, - async sendRequest(request, next) { + sendRequest(request, next) { request.disableKeepAlive = true; return next(request); }, @@ -7945,7 +7967,7 @@ const MapperTypeNames = { UnixTime: "UnixTime", }; -var stateCjsExports = requireStateCjs(); +var stateCjsExports = requireStateCjs$1(); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -9021,6 +9043,22 @@ const originalRequestSymbol = Symbol("Original PipelineRequest"); // cloned but we need to retrieve the OperationSpec and OperationArguments from the // original request. const originalClientRequestSymbol = Symbol.for("@azure/core-client original request"); +const passThroughProps = new Set([ + "url", + "method", + "withCredentials", + "timeout", + "requestId", + "abortSignal", + "body", + "formData", + "onDownloadProgress", + "onUploadProgress", + "proxySettings", + "streamResponseStatusCodes", + "agent", + "requestOverrides", +]); function toPipelineRequest(webResource, options = {}) { const compatWebResource = webResource; const request = compatWebResource[originalRequestSymbol]; @@ -9104,23 +9142,7 @@ function toWebResourceLike(request, options) { if (prop === "keepAlive") { request.disableKeepAlive = !value; } - const passThroughProps = [ - "url", - "method", - "withCredentials", - "timeout", - "requestId", - "abortSignal", - "body", - "formData", - "onDownloadProgress", - "onUploadProgress", - "proxySettings", - "streamResponseStatusCodes", - "agent", - "requestOverrides", - ]; - if (typeof prop === "string" && passThroughProps.includes(prop)) { + if (typeof prop === "string" && passThroughProps.has(prop)) { request[prop] = value; } return Reflect.set(target, prop, value, receiver); @@ -9983,6 +10005,30 @@ const COMMON_HTML = { // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// Entity hook action constants +// --------------------------------------------------------------------------- + +/** + * Action constants for `onExternalEntity` and `onInputEntity` hooks. + * + * Use these instead of raw strings to avoid typos: + * + * @example + * import EntityDecoder, { ENTITY_ACTION } from './EntityDecoder.js'; + * const dec = new EntityDecoder({ + * onInputEntity: (name, value) => ENTITY_ACTION.BLOCK, + * }); + */ +const ENTITY_ACTION = Object.freeze({ + /** Resolve and expand the entity normally. */ + ALLOW: 'allow', + /** Silently skip this entity — it will not be registered. */ + BLOCK: 'block', + /** Throw an error, aborting entity registration entirely. */ + THROW: 'throw', +}); + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- @@ -10147,6 +10193,14 @@ class EntityDecoder { * the effective action is max(onNCR, rangeMinimum). * @param {'remove'|'throw'} [options.ncr.nullNCR='remove'] * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onExternalEntity=null] + * Hook called when an external entity is registered via `setExternalEntities()` or + * `addExternalEntity()`. Return `ENTITY_ACTION.ALLOW` to accept the entity, + * `ENTITY_ACTION.BLOCK` to silently skip it, or `ENTITY_ACTION.THROW` to abort with an error. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onInputEntity=null] + * Hook called when an input entity is registered via `addInputEntities()`. Return + * `ENTITY_ACTION.ALLOW` to accept, `ENTITY_ACTION.BLOCK` to silently skip, or + * `ENTITY_ACTION.THROW` to abort with an error. */ constructor(options = {}) { this._limit = options.limit || {}; @@ -10182,6 +10236,43 @@ class EntityDecoder { this._ncrXmlVersion = ncrCfg.xmlVersion; this._ncrOnLevel = ncrCfg.onLevel; this._ncrNullLevel = ncrCfg.nullLevel; + + // --- Registration hooks --- + /** @type {((name: string, value: string) => 'allow'|'block'|'throw')|null} */ + this._onExternalEntity = typeof options.onExternalEntity === 'function' + ? options.onExternalEntity + : null; + /** @type {((name: string, value: string) => 'allow'|'block'|'throw')|null} */ + this._onInputEntity = typeof options.onInputEntity === 'function' + ? options.onInputEntity + : null; + } + + // ------------------------------------------------------------------------- + // Private: registration hook dispatch + // ------------------------------------------------------------------------- + + /** + * Invoke a registration hook for a single entity name/value pair. + * Returns true when the entity should be accepted, false when it should be + * silently skipped (BLOCK), and throws when the hook returns THROW. + * + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} hook + * @param {string} name + * @param {string} value + * @param {string} context — used in error messages ('external' | 'input') + * @returns {boolean} true = accept, false = skip + */ + _applyRegistrationHook(hook, name, value, context) { + if (!hook) return true; // no hook → always accept + const action = hook(name, value); + if (action === ENTITY_ACTION.BLOCK) return false; + if (action === ENTITY_ACTION.THROW) { + throw new Error( + `[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook` + ); + } + return true; // ALLOW or any unknown return value → accept } // ------------------------------------------------------------------------- @@ -10191,6 +10282,9 @@ class EntityDecoder { /** * Replace the full set of persistent external entities. * All keys are validated — throws on invalid characters. + * If `onExternalEntity` is set, it is called once per entry; entries that + * return `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` + * aborts the whole call. * @param {Record} map */ setExternalEntities(map) { @@ -10199,18 +10293,34 @@ class EntityDecoder { validateEntityName$1(key); } } - this._externalMap = mergeEntityMaps(map); + if (!this._onExternalEntity) { + this._externalMap = mergeEntityMaps(map); + return; + } + // Hook present — resolve values first, then filter + const flat = mergeEntityMaps(map); + const filtered = Object.create(null); + for (const [name, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onExternalEntity, name, value, 'external')) { + filtered[name] = value; + } + } + this._externalMap = filtered; } /** * Add a single persistent external entity. + * If `onExternalEntity` is set it is called before the entity is stored; + * `ENTITY_ACTION.BLOCK` silently skips storage, `ENTITY_ACTION.THROW` raises. * @param {string} key * @param {string} value */ addExternalEntity(key, value) { validateEntityName$1(key); if (typeof value === 'string' && value.indexOf('&') === -1) { - this._externalMap[key] = value; + if (this._applyRegistrationHook(this._onExternalEntity, key, value, 'external')) { + this._externalMap[key] = value; + } } } @@ -10221,12 +10331,25 @@ class EntityDecoder { /** * Inject DOCTYPE entities for the current document. * Also resets per-document expansion counters. + * If `onInputEntity` is set it is called once per entry; entries returning + * `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` aborts. * @param {Record} map */ addInputEntities(map) { this._totalExpansions = 0; this._expandedLength = 0; - this._inputMap = mergeEntityMaps(map); + if (!this._onInputEntity) { + this._inputMap = mergeEntityMaps(map); + return; + } + const flat = mergeEntityMaps(map); + const filtered = Object.create(null); + for (const [name, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onInputEntity, name, value, 'input')) { + filtered[name] = value; + } + } + this._inputMap = filtered; } // ------------------------------------------------------------------------- @@ -10544,7 +10667,8 @@ const defaultOptions$1 = { numberParseOptions: { hex: true, leadingZeros: true, - eNotation: true + eNotation: true, + unicode: false }, tagValueProcessor: function (tagName, val) { return val; @@ -10832,16 +10956,108 @@ const buildRegexes = (startChar, char, flags = '') => { const regexes10 = buildRegexes(nameStartChar10, nameChar10); // no /u — BMP only const regexes11 = buildRegexes(nameStartChar11, nameChar11, 'u'); // /u — enables \u{10000}-\u{EFFFF} -const getRegexes = (xmlVersion = '1.0') => - xmlVersion === '1.1' ? regexes11 : regexes10; +// --------------------------------------------------------------------------- +// ASCII-only fast path (opt-in, off by default) +// +// The XML 1.0 vs 1.1 NameStartChar/NameChar productions differ *only* in +// their non-ASCII ranges (merged vs split Latin-1 ranges, \u0487, and +// supplementary planes). Restricted to ASCII, both versions collapse to the +// same character classes, so a single regex pair covers both xmlVersion +// values — no /u flag needed. +// +// Rationale: unicode-aware regexes (the /u flag, required for XML 1.1's +// supplementary-plane range) are measurably slower in V8 than plain +// non-unicode regexes on the same input, even when the input is pure ASCII. +// For the common case — HTML/SVG ids, XML tags — names are ASCII, so callers +// who know this can opt in to skip the unicode-aware matching path entirely. +// This is a real but *conditional* win: mainly for XML 1.1 input (avoids /u), +// or at scale where the larger unicode character classes add engine +// overhead. It also changes behaviour (rejects legitimate non-ASCII XML +// 1.0/1.1 names), so it must never be silently enabled — hence off by +// default. +// --------------------------------------------------------------------------- + +const nameStartCharAscii = ':A-Za-z_'; +const nameCharAscii = nameStartCharAscii + '\\-\\.\\d'; + +const regexesAscii = buildRegexes(nameStartCharAscii, nameCharAscii); // no /u — ASCII only + +const getRegexes = (xmlVersion = '1.0', asciiOnly = false) => { + if (asciiOnly) return regexesAscii; + return xmlVersion === '1.1' ? regexes11 : regexes10; +}; /** * Returns true if the string is a valid QName (Qualified Name). * Allows exactly one colon as a prefix separator: prefix:localName. * Used for: element and attribute names in namespace-aware XML/SVG. + * + * @param {{ xmlVersion?: '1.0'|'1.1', asciiOnly?: boolean }} [opts] + * asciiOnly: skip unicode-aware matching, ASCII names only (default false). */ -const qName = (str, { xmlVersion = '1.0' } = {}) => - getRegexes(xmlVersion).qName.test(str); +const qName = (str, { xmlVersion = '1.0', asciiOnly = false } = {}) => + getRegexes(xmlVersion, asciiOnly).qName.test(str); + +// --------------------------------------------------------------------------- +// Memoized validator factory +// +// Real documents reuse a small vocabulary of tag/attribute names across many +// siblings (e.g. `id`, `class`, `href` repeated across hundreds of elements). +// The plain boolean validators above re-run the regex on every call +// regardless of repeats. `createValidator` returns a closure with a private +// string -> boolean cache, so repeated names after the first become O(1) +// lookups instead of regex tests. +// +// - opts (xmlVersion, asciiOnly) are fixed at creation time, so the regex is +// resolved once, not on every call. +// - The cache is private to the returned closure — no shared/global state, +// no cross-caller pollution. +// - `maxCacheSize` bounds memory: once the cache reaches this many entries, +// it stops accepting new ones (existing entries keep serving hits; new +// misses just fall through to the regex, uncached). This avoids unbounded +// growth against adversarial/high-cardinality input (e.g. validating +// attacker-supplied names with no repeats) without the cost/complexity of +// a full LRU, and without the perf cliff of reset-and-refill thrashing. +// - Call `.reset()` on the returned function to clear the cache manually +// (e.g. between unrelated parse calls). +// --------------------------------------------------------------------------- + +const PRODUCTIONS = ['name', 'ncName', 'qName', 'nmToken', 'nmTokens']; + +/** + * Returns a memoized boolean validator function for a single production, + * with opts fixed at creation time. + * + * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production + * @param {{ xmlVersion?: '1.0'|'1.1', asciiOnly?: boolean, maxCacheSize?: number }} [opts] + * maxCacheSize: max number of distinct strings to cache (default 2048). + * Once reached, new strings are validated but not cached; existing cached + * entries keep being served. + * @returns {((str: string) => boolean) & { reset: () => void }} + */ +const createValidator = (production, { xmlVersion = '1.0', asciiOnly = false, maxCacheSize = 2048 } = {}) => { + if (!PRODUCTIONS.includes(production)) { + throw new TypeError( + `Unknown production "${production}". Must be one of: ${PRODUCTIONS.join(', ')}` + ); + } + + const regex = getRegexes(xmlVersion, asciiOnly)[production]; + let cache = new Map(); + + const validator = (str) => { + const cached = cache.get(str); + if (cached !== undefined) return cached; + + const result = regex.test(str); + if (cache.size < maxCacheSize) cache.set(str, result); + return result; + }; + + validator.reset = () => { cache = new Map(); }; + + return validator; +}; class DocTypeReader { constructor(options, xmlVersion) { @@ -11253,6 +11469,250 @@ function validateEntityName(name, xmlVersion) { throw new Error(`Invalid entity name ${name}`); } +/** + * Flat lookup table: maps Unicode code point → ASCII digit (0-9). + * Only decimal digit characters (Unicode category Nd) are included. + * + * Strategy: Int32Array of size (maxCodePoint - minCodePoint + 1). + * Value 0xFF means "not a digit". Value 0-9 is the ASCII digit value. + * This gives O(1) lookup with no branching, no bisect, no loop. + * + * Memory: range is 0x0660 to 0x1FBF0 → ~129,936 entries × 1 byte = ~127 KB. + * Acceptable for a one-time init; lookup is a single array index. + */ + +// All known Unicode Nd (decimal digit) script zero code points. +// Each script has exactly 10 consecutive digits: zero+0 .. zero+9. +const SCRIPT_ZEROS = [ + // Basic Latin (ASCII) — included for completeness / pass-through + 0x0030, // 0-9 + + // Arabic scripts + 0x0660, // Arabic-Indic ٠١٢٣٤٥٦٧٨٩ + 0x06F0, // Extended Arabic-Indic (Urdu/Persian/Sindhi) ۰۱۲۳ + + // Indic scripts + 0x0966, // Devanagari ०१२३४५६७८९ + 0x09E6, // Bengali ০১২৩৪৫৬৭৮৯ + 0x0A66, // Gurmukhi ੦੧੨੩੪੫੬੭੮੯ + 0x0AE6, // Gujarati ૦૧૨૩૪૫૬૭૮૯ + 0x0B66, // Odia ୦୧୨୩୪୫୬୭୮୯ + 0x0BE6, // Tamil ௦௧௨௩௪௫௬௭௮௯ + 0x0C66, // Telugu ౦౧౨౩౪౫౬౭౮౯ + 0x0CE6, // Kannada ೦೧೨೩೪೫೬೭೮೯ + 0x0D66, // Malayalam ൦൧൨൩൪൫൬൭൮൯ + 0x0DE6, // Sinhala Archaic ෦෧෨෩෪෫෬෭෮෯ + + // Southeast Asian scripts + 0x0E50, // Thai ๐๑๒๓๔๕๖๗๘๙ + 0x0ED0, // Lao ໐໑໒໓໔໕໖໗໘໙ + 0x0F20, // Tibetan ༠༡༢༣༤༥༦༧༨༩ + 0x1040, // Myanmar ၀၁၂၃၄၅၆၇၈၉ + 0x1090, // Myanmar Shan ႐႑႒႓႔႕႖႗႘႙ + 0x17E0, // Khmer ០១២៣៤៥៦៧៨៩ + 0x1810, // Mongolian ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ + 0x1946, // Limbu ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ + 0x19D0, // New Tai Lue ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ + 0x1A80, // Tai Tham Hora ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉ + 0x1A90, // Tai Tham Tham ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ + 0x1B50, // Balinese ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ + 0x1BB0, // Sundanese ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ + 0x1C40, // Lepcha ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ + 0x1C50, // Ol Chiki ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ + + // Fullwidth (CJK context) + 0xFF10, // Fullwidth 0123456789 + + // Mathematical digit variants (Unicode math block) + 0x1D7CE, // Mathematical Bold + 0x1D7D8, // Mathematical Double-Struck + 0x1D7E2, // Mathematical Sans-Serif + 0x1D7EC, // Mathematical Sans-Serif Bold + 0x1D7F6, // Mathematical Monospace + + // Other scripts + 0x104A0, // Osmanya 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩 + 0x10D30, // Hanifi Rohingya 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹 + 0x11066, // Brahmi 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯 + 0x110F0, // Sora Sompeng 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹 + 0x11136, // Chakma 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿 + 0x111D0, // Sharada 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙 + 0x112F0, // Khudawadi 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹 + 0x11450, // Newa 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙 + 0x114D0, // Tirhuta 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙 + 0x11650, // Modi 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙 + 0x116C0, // Takri 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉 + 0x11730, // Ahom 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹 + 0x118E0, // Warang Citi 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩 + 0x11950, // Dives Akuru 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙 + 0x11BF0, // Khitan Small Script 𑯰𑯱𑯲𑯳𑯴𑯵𑯶𑯷𑯸𑯹 + 0x11C50, // Bhaiksuki 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙 + 0x11D50, // Masaram Gondi 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙 + 0x11DA0, // Gunjala Gondi 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩 + 0x11F50, // Kawi 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙 + 0x16A60, // Mro 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩 + 0x16AC0, // Tangsa 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉 + 0x16B50, // Pahawh Hmong 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙 + 0x1E140, // Nyiakeng Puachue Hmong 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉 + 0x1E2F0, // Wancho 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹 + 0x1E4F0, // Nag Mundari 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹 + 0x1E950, // Adlam 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙 + 0x1FBF0, // Segmented digit symbols 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹 +]; + +// Build a sparse Map for scripts above 0xFFFF (surrogate-pair range). +// These can't go into a flat Uint8Array indexed by code point efficiently. +const NOT_DIGIT = 0xFF; +const HIGH_MAP = new Map(); // codePoint → digit value (0-9) + +const LOW_MAX = 0xFFFF; +const LOW_MIN = 0x0660; // first non-ASCII digit script + +// Flat Uint8Array covering 0x0660 .. 0xFFFF +const TABLE_OFFSET = LOW_MIN; +const TABLE_SIZE = LOW_MAX - LOW_MIN + 1; +const TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT); + +for (const zero of SCRIPT_ZEROS) { + for (let d = 0; d < 10; d++) { + const cp = zero + d; + if (cp <= LOW_MAX) { + TABLE[cp - TABLE_OFFSET] = d; + } else { + HIGH_MAP.set(cp, d); + } + } +} + +const CHAR_0 = 48; // '0'.charCodeAt(0) +const CHAR_9 = 57; // '9'.charCodeAt(0) +const CHAR_MINUS = 45; // '-'.charCodeAt(0) + +// Unicode minus/hyphen variants worth normalizing to ASCII '-' in numeric context: +// U+2212 MINUS SIGN − (mathematically correct minus) +// U+FF0D FULLWIDTH HYPHEN-MINUS - (Japanese fullwidth context) +// U+FE63 SMALL HYPHEN-MINUS ﹣ (small form variant) +// +// NOT normalized (deliberate): +// U+2013 EN DASH – (punctuation, not a numeric sign) +// U+2014 EM DASH — (punctuation) +// U+2010 HYPHEN ‐ (typographic hyphen) +// +// Rationale: only characters a human or locale formatter would plausibly use +// as a numeric minus sign are normalized. Dashes used for punctuation are left +// alone to avoid mangling non-numeric strings. +const MINUS_SET = new Set([0x2212, 0xFF0D, 0xFE63]); + +/** + * Normalize all Unicode decimal digit characters in a string to ASCII (0-9), + * and normalize Unicode minus variants to ASCII '-' (U+002D). + * + * Non-digit, non-minus characters are passed through unchanged. + * + * Performance design: + * - Fast path: if the string has no convertible characters, return it unchanged + * (zero allocation). + * - BMP digits (0x0660..0xFFFF excl. surrogates): flat Uint8Array lookup (O(1)). + * - Supplementary plane digits (> 0xFFFF, encoded as surrogate pairs): Map lookup. + * - Minus variants: checked inline with a small fixed Set. + * + * @param {string} str + * @returns {string} + */ +function anynum(str) { + if (typeof str !== 'string') return str; + + const len = str.length; + if (len === 0) return str; + + // Scan for first character needing conversion. + // If none found, return original string (zero allocation). + let firstHit = -1; + + for (let i = 0; i < len; i++) { + const cc = str.charCodeAt(i); + + // ASCII digit or ASCII minus — already normalized, skip fast + if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) continue; + + // Below first unicode digit script — check minus variants only + if (cc < TABLE_OFFSET) { + if (MINUS_SET.has(cc)) { firstHit = i; break; } + continue; + } + + // Surrogate pairs live in BMP range 0xD800-0xDFFF — check before TABLE + if (cc >= 0xD800 && cc <= 0xDBFF) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 0xDC00 && low <= 0xDFFF) { + const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00); + if (HIGH_MAP.has(cp)) { firstHit = i; break; } + } + } + continue; + } + + // BMP non-surrogate: flat table lookup; also check minus variants in this range + if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) { + firstHit = i; + break; + } + } + + // Nothing to replace — return original, zero allocation + if (firstHit === -1) return str; + + // Build result: copy unchanged prefix, then convert from firstHit onward + const chars = []; + + if (firstHit > 0) chars.push(str.slice(0, firstHit)); + + for (let i = firstHit; i < len; i++) { + const cc = str.charCodeAt(i); + + // ASCII digit or ASCII minus — pass through + if ((cc >= CHAR_0 && cc <= CHAR_9) || cc === CHAR_MINUS) { + chars.push(str[i]); + continue; + } + + // Below TABLE_OFFSET — check minus variants, else pass through + if (cc < TABLE_OFFSET) { + chars.push(MINUS_SET.has(cc) ? '-' : str[i]); + continue; + } + + // Surrogate pairs + if (cc >= 0xD800 && cc <= 0xDBFF) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 0xDC00 && low <= 0xDFFF) { + const cp = 0x10000 + ((cc - 0xD800) << 10) + (low - 0xDC00); + const d = HIGH_MAP.get(cp); + if (d !== undefined) { + chars.push(String.fromCharCode(d + 48)); + i++; // consume low surrogate + continue; + } + } + } + chars.push(str[i]); + continue; + } + + // BMP non-surrogate: flat table lookup + minus variants + if (MINUS_SET.has(cc)) { + chars.push('-'); + continue; + } + const d = TABLE[cc - TABLE_OFFSET]; + chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]); + } + + return chars.join(''); +} + const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; const binRegex = /^0b[01]+$/; const octRegex = /^0o[0-7]+$/; @@ -11267,6 +11727,7 @@ const consider = { eNotation: true, //skipLike: /regex/, infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) + unicode: false, }; function toNumber(str, options = {}) { @@ -11278,7 +11739,12 @@ function toNumber(str, options = {}) { if (trimmedStr.length === 0) return str; else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; else if (trimmedStr === "0") return 0; - else if (options.hex && hexRegex.test(trimmedStr)) { + + if (options.unicode) { + trimmedStr = anynum(trimmedStr); + if (trimmedStr === "0") return 0; // re-check after normalization + } + if (options.hex && hexRegex.test(trimmedStr)) { return parse_int(trimmedStr, 16); } else if (options.binary && binRegex.test(trimmedStr)) { return parse_int(trimmedStr, 2); @@ -11705,6 +12171,9 @@ class ExpressionSet { /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */ this._deepWildcards = []; + /** @type {Map} terminalTag → deep wildcard expressions */ + this._deepByTerminalTag = new Map(); + /** @type {Set} pattern strings already added — used for deduplication */ this._patterns = new Set(); @@ -11736,7 +12205,14 @@ class ExpressionSet { this._patterns.add(expression.pattern); if (expression.hasDeepWildcard()) { - this._deepWildcards.push(expression); + const lastSeg = expression.segments[expression.segments.length - 1]; + if (lastSeg && lastSeg.type !== 'deep-wildcard' && lastSeg.tag !== '*') { + const tag = lastSeg.tag; + if (!this._deepByTerminalTag.has(tag)) this._deepByTerminalTag.set(tag, []); + this._deepByTerminalTag.get(tag).push(expression); + } else { + this._deepWildcards.push(expression); + } return this; } @@ -11870,7 +12346,13 @@ class ExpressionSet { } } - // 3. Deep wildcards — cannot be pre-filtered by depth or tag + // 3. Deep wildcards — indexed by terminal tag, then unindexed fallback + const deepBucket = this._deepByTerminalTag.get(tag); + if (deepBucket) { + for (let i = 0; i < deepBucket.length; i++) { + if (matcher.matches(deepBucket[i])) return deepBucket[i]; + } + } for (let i = 0; i < this._deepWildcards.length; i++) { if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i]; } @@ -11955,6 +12437,26 @@ class MatcherView { return current.values !== undefined && attrName in current.values; } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {*} + */ + getAnyParentAttr(attrName) { + return this._matcher.getAnyParentAttr(attrName); + } + + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + return this._matcher.hasAnyParentAttr(attrName); + } + /** * Get current node's sibling position (child index in parent). * @returns {number} @@ -12063,6 +12565,9 @@ class Matcher { // Each siblingStacks entry: Map tracking occurrences at each level this._pathStringCache = null; this._view = new MatcherView(this); + + // Kept-attribute stack: only populated when push() is called with options.keep. + this._keptAttrs = []; } /** @@ -12070,8 +12575,10 @@ class Matcher { * @param {string} tagName * @param {Object|null} [attrValues=null] * @param {string|null} [namespace=null] + * @param {Object|null} [options=null] + * @param {string[]} [options.keep] - Names of attributes (from attrValues) */ - push(tagName, attrValues = null, namespace = null) { + push(tagName, attrValues = null, namespace = null, options = null) { this._pathStringCache = null; // Remove values from previous current node (now becoming ancestor) @@ -12081,26 +12588,29 @@ class Matcher { // Get or create sibling tracking for current level const currentLevel = this.path.length; - if (!this.siblingStacks[currentLevel]) { - this.siblingStacks[currentLevel] = new Map(); + let level = this.siblingStacks[currentLevel]; + if (!level) { + // `counts` tells same-name siblings apart (the "counter" — nth + // among other s). `total` is every child seen at this level so + // far, kept as a running number instead of re-added from `counts` on + // every push — a parent with many differently-named children would + // otherwise cost more per child the more distinct names it has. + level = { counts: new Map(), total: 0 }; + this.siblingStacks[currentLevel] = level; } - const siblings = this.siblingStacks[currentLevel]; - // Create a unique key for sibling tracking that includes namespace const siblingKey = namespace ? `${namespace}:${tagName}` : tagName; // Calculate counter (how many times this tag appeared at this level) - const counter = siblings.get(siblingKey) || 0; + const counter = level.counts.get(siblingKey) || 0; - // Calculate position (total children at this level so far) - let position = 0; - for (const count of siblings.values()) { - position += count; - } + // Position = total children at this level seen before this one. + const position = level.total; - // Update sibling count for this tag - siblings.set(siblingKey, counter + 1); + // Update sibling count for this tag, and the level's running total. + level.counts.set(siblingKey, counter + 1); + level.total++; // Create new node const node = { @@ -12118,6 +12628,24 @@ class Matcher { } this.path.push(node); + + // Depth of the node we just pushed (1-based, matches this.path.length) + const depth = this.path.length; + + // Copy only the requested attributes into the kept-attrs stack. This is + // the one part of push() whose cost scales with input (O(keep.length)) + // rather than being O(1) — by design, since the caller is explicitly + // opting in for specific attribute names. No options/keep => zero added + // cost beyond the two property reads below. + const keep = options !== null ? options.keep : null; + if (keep !== null && keep !== undefined && keep.length > 0 && attrValues) { + for (let i = 0; i < keep.length; i++) { + const name = keep[i]; + if (attrValues[name] !== undefined) { + this._keptAttrs.push({ depth, name, value: attrValues[name] }); + } + } + } } /** @@ -12134,6 +12662,18 @@ class Matcher { this.siblingStacks.length = this.path.length + 1; } + // Drop any kept attributes that belonged to the popped node (or deeper). + // _keptAttrs is depth-ordered (push only ever appends increasing depths), + // so this is a backward scan that stops at the first surviving entry — + // typically O(1) since kept attrs are rare by design. + const poppedDepth = this.path.length + 1; + while ( + this._keptAttrs.length > 0 && + this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth + ) { + this._keptAttrs.pop(); + } + return node; } @@ -12188,6 +12728,38 @@ class Matcher { return current.values !== undefined && attrName in current.values; } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * Unlike getAttrValue(), this works regardless of how deep the path has + * gone since the attribute was pushed — but only for attribute names that + * were explicitly marked with `keep` at push time. Cost is proportional to + * the number of currently-kept attributes (typically 0-3), not path depth. + * @param {string} attrName + * @returns {*} the value, or undefined if no ancestor kept this attribute + */ + getAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return kept[i].value; + } + return undefined; + } + + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return true; + } + return false; + } + /** * Get current node's sibling position (child index in parent). * @returns {number} @@ -12264,6 +12836,7 @@ class Matcher { this._pathStringCache = null; this.path = []; this.siblingStacks = []; + this._keptAttrs = []; } /** @@ -12413,7 +12986,8 @@ class Matcher { snapshot() { return { path: this.path.map(node => ({ ...node })), - siblingStacks: this.siblingStacks.map(map => new Map(map)) + siblingStacks: this.siblingStacks.map(level => level ? { counts: new Map(level.counts), total: level.total } : level), + keptAttrs: this._keptAttrs.map(entry => ({ ...entry })) }; } @@ -12424,7 +12998,8 @@ class Matcher { restore(snapshot) { this._pathStringCache = null; this.path = snapshot.path.map(node => ({ ...node })); - this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map)); + this.siblingStacks = snapshot.siblingStacks.map(level => level ? { counts: new Map(level.counts), total: level.total } : level); + this._keptAttrs = (snapshot.keptAttrs || []).map(entry => ({ ...entry })); } /** @@ -12448,6 +13023,928 @@ class Matcher { } } +/** + * HTML context patterns. + * + * Detects XSS vectors that are dangerous when a string ends up rendered as HTML. + * All patterns use bounded quantifiers to ensure linear-time matching (ReDoS-safe). + * + * Each entry is { pattern: RegExp, id: string, description: string } + * so callers can inspect which rule fired if they need to. + */ + +const HTML_PATTERNS = [ + { + id: 'html-script-open', + description: ']/i, + }, + { + id: 'html-javascript-protocol', + description: 'javascript: URI scheme (with optional whitespace/encoding)', + // Handles javascript:, j\u0061vascript:, and whitespace variants + pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i, + }, + { + id: 'html-vbscript-protocol', + description: 'vbscript: URI scheme', + pattern: /vbscript[\t\n\r ]*:/i, + }, + { + id: 'html-data-html', + description: 'data:text/html URI — can execute scripts in browsers', + pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i, + }, + { + id: 'html-data-xhtml', + description: 'data:application/xhtml+xml URI', + pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i, + }, + { + id: 'html-data-svg', + description: 'data:image/svg+xml URI — can execute scripts', + pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i, + }, + { + id: 'html-inline-event-handler', + description: 'Inline event handler attributes: onclick=, onerror=, onload=, etc.', + // \bon ensures we match a word boundary so "phonetic=" is not caught + pattern: /\bon\w{1,30}\s*=/i, + }, + { + id: 'html-entity-obfuscated-script', + description: 'HTML-entity-encoded ', HTML) // true + * isUnsafe('hello world', HTML) // false + * isUnsafe('value', [HTML, SQL]) // false + * isUnsafe('value', /my-pattern/i) // false + */ +function isUnsafe(value, context) { + assertString(value); + assertContext(context); + + const { lists, regex } = normalise(context); + + if (regex) return regex.test(value); + + for (const list of lists) { + if (matchList(value, list) !== null) return true; + } + return false; +} + // const regx = // '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' // .replace(/NAME/g, util.nameRegexp); @@ -12523,6 +14020,7 @@ class OrderedObjParser { this.ignoreAttributesFn = getIgnoreAttributesFn$1(this.options.ignoreAttributes); this.entityExpansionCount = 0; this.currentExpandedLength = 0; + this.doctypefound = false; let namedEntities = { ...XML }; if (this.options.entityDecoder) { this.entityDecoder = this.options.entityDecoder; @@ -12536,7 +14034,12 @@ class OrderedObjParser { maxTotalExpansions: this.options.processEntities.maxTotalExpansions, maxExpandedLength: this.options.processEntities.maxExpandedLength, applyLimitsTo: this.options.processEntities.appliesTo, - } + }, + // onExternalEntity: (name, value) => isUnsafe(value) ? 'block' : 'allow', + onInputEntity: (name, value) => + //TODO: VALID_CONTEXTS.HTML should be set only if this.options.htmlEntities + isUnsafe(value, [HTML_PATTERNS, XML_PATTERNS]) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW, + //postCheck: resolved => resolved }); } @@ -12725,6 +14228,7 @@ const parseXml = function (xmlData) { // Reset entity expansion counters for this document this.entityExpansionCount = 0; this.currentExpandedLength = 0; + this.doctypefound = false; const options = this.options; const docTypeReader = new DocTypeReader(options.processEntities); const xmlLen = xmlData.length; @@ -12807,6 +14311,8 @@ const parseXml = function (xmlData) { i = endIndex; } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 68) { //'!D' + if (this.doctypefound) throw new Error("Multiple DOCTYPE declarations found."); + this.doctypefound = true; const result = docTypeReader.readDocType(xmlData, i); this.entityDecoder.addInputEntities(result.entities); i = result.i; @@ -13548,11 +15054,11 @@ function detectXmlVersionFromArray(jArray, options) { * @param {boolean} isAttribute - true when resolving an attribute name * @param {object} options * @param {Matcher} matcher - current matcher state (readonly from callback perspective) - * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming + * @param {function} qNameValidator - function to validate tag names */ -function resolveTagName$1(name, isAttribute, options, matcher, xmlVersion) { +function resolveTagName$1(name, isAttribute, options, matcher, qNameValidator) { if (!options.sanitizeName) return name; - if (qName(name, { xmlVersion })) return name; + if (qNameValidator(name)) return name; return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() }); } @@ -13582,14 +15088,14 @@ function toXml(jArray, options) { // Detect XML version for use in name validation const xmlVersion = detectXmlVersionFromArray(jArray, options); - + const qNameValidator = createValidator('qName', { xmlVersion }); // Initialize matcher for path tracking const matcher = new Matcher(); - return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions, xmlVersion); + return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions, qNameValidator); } -function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVersion) { +function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, qNameValidator) { let xmlStr = ""; let isPreviousElementTag = false; @@ -13622,7 +15128,7 @@ function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVe // Resolve tag name (may transform it; may throw for invalid names) const tagName = isSpecialName ? rawTagName - : resolveTagName$1(rawTagName, false, options, matcher, xmlVersion); + : resolveTagName$1(rawTagName, false, options, matcher, qNameValidator); // Extract attributes from ":@" property const attrValues = extractAttributeValues(tagObj[":@"], options); @@ -13664,7 +15170,7 @@ function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVe matcher.pop(); continue; } else if (tagName[0] === "?") { - const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, xmlVersion); + const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, qNameValidator); const tempInd = tagName === "?xml" ? "" : indentation; // Text node content on PI/XML declaration tags is intentionally ignored. // Only attributes are valid on these tags per the XML spec. @@ -13680,7 +15186,7 @@ function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVe } // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes - const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, xmlVersion); + const attStr = attr_to_str(tagObj[":@"], options, isStopNode, matcher, qNameValidator); const tagStart = indentation + `<${tagName}${attStr}`; // If this is a stopNode, get raw content without processing @@ -13688,7 +15194,7 @@ function arrToStr(arr, options, indentation, matcher, stopNodeExpressions, xmlVe if (isStopNode) { tagValue = getRawContent(tagObj[rawTagName], options); } else { - tagValue = arrToStr(tagObj[rawTagName], options, newIdentation, matcher, stopNodeExpressions, xmlVersion); + tagValue = arrToStr(tagObj[rawTagName], options, newIdentation, matcher, stopNodeExpressions, qNameValidator); } if (options.unpairedTags.indexOf(tagName) !== -1) { @@ -13817,7 +15323,7 @@ function propName(obj) { * Build attribute string, resolving attribute names through sanitizeName when configured. * Accepts matcher so the callback has path context. */ -function attr_to_str(attrMap, options, isStopNode, matcher, xmlVersion) { +function attr_to_str(attrMap, options, isStopNode, matcher, qNameValidator) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { @@ -13827,7 +15333,7 @@ function attr_to_str(attrMap, options, isStopNode, matcher, xmlVersion) { const cleanAttrName = attr.substr(options.attributeNamePrefix.length); const resolvedAttrName = isStopNode ? cleanAttrName // stopNodes are raw — skip sanitizeName for attr names too - : resolveTagName$1(cleanAttrName, true, options, matcher, xmlVersion); + : resolveTagName$1(cleanAttrName, true, options, matcher, qNameValidator); let attrVal; if (isStopNode) { @@ -14013,11 +15519,11 @@ function detectXmlVersionFromObj(jObj, options) { * @param {boolean} isAttribute - true when resolving an attribute name * @param {object} options * @param {Matcher} matcher - current matcher state (readonly from callback perspective) - * @param {string} xmlVersion - '1.0' or '1.1', forwarded to xml-naming + * @param {function} qNameValidator - function to validate tag names */ -function resolveTagName(name, isAttribute, options, matcher, xmlVersion) { +function resolveTagName(name, isAttribute, options, matcher, qNameValidator) { if (!options.sanitizeName) return name; - if (qName(name, { xmlVersion })) return name; + if (qNameValidator(name)) return name; return options.sanitizeName(name, { isAttribute, matcher: matcher.readOnly() }); } @@ -14033,11 +15539,12 @@ Builder.prototype.build = function (jObj) { // Initialize matcher for path tracking const matcher = new Matcher(); const xmlVersion = detectXmlVersionFromObj(jObj, this.options); - return this.j2x(jObj, 0, matcher, xmlVersion).val; + const qNameValidator = createValidator('qName', { xmlVersion }); + return this.j2x(jObj, 0, matcher, qNameValidator).val; } }; -Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { +Builder.prototype.j2x = function (jObj, level, matcher, qNameValidator) { let attrStr = ''; let val = ''; if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) { @@ -14065,7 +15572,7 @@ Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { const resolvedKey = isSpecialKey ? key - : resolveTagName(key, false, this.options, matcher, xmlVersion); + : resolveTagName(key, false, this.options, matcher, qNameValidator); if (typeof jObj[key] === 'undefined') { // supress undefined node only if it is not an attribute @@ -14090,7 +15597,7 @@ Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { const attr = this.isAttribute(key); if (attr && !this.ignoreAttributesFn(attr, jPath)) { // Resolve the attribute name through sanitizeName - const resolvedAttr = resolveTagName(attr, true, this.options, matcher, xmlVersion); + const resolvedAttr = resolveTagName(attr, true, this.options, matcher, qNameValidator); attrStr += this.buildAttrPairStr(resolvedAttr, '' + jObj[key], isCurrentStopNode); } else if (!attr) { //tag value @@ -14130,7 +15637,7 @@ Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { if (this.options.oneListGroup) { // Push tag to matcher before recursive call matcher.push(resolvedKey); - const result = this.j2x(item, level + 1, matcher, xmlVersion); + const result = this.j2x(item, level + 1, matcher, qNameValidator); // Pop tag from matcher after recursive call matcher.pop(); @@ -14139,7 +15646,7 @@ Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { listTagAttr += result.attrStr; } } else { - listTagVal += this.processTextOrObjNode(item, resolvedKey, level, matcher, xmlVersion); + listTagVal += this.processTextOrObjNode(item, resolvedKey, level, matcher, qNameValidator); } } else { if (this.options.oneListGroup) { @@ -14177,11 +15684,11 @@ Builder.prototype.j2x = function (jObj, level, matcher, xmlVersion) { const L = Ks.length; for (let j = 0; j < L; j++) { // Resolve attribute names inside attributesGroupName - const resolvedAttr = resolveTagName(Ks[j], true, this.options, matcher, xmlVersion); + const resolvedAttr = resolveTagName(Ks[j], true, this.options, matcher, qNameValidator); attrStr += this.buildAttrPairStr(resolvedAttr, '' + jObj[key][Ks[j]], isCurrentStopNode); } } else { - val += this.processTextOrObjNode(jObj[key], resolvedKey, level, matcher, xmlVersion); + val += this.processTextOrObjNode(jObj[key], resolvedKey, level, matcher, qNameValidator); } } } @@ -14198,7 +15705,7 @@ Builder.prototype.buildAttrPairStr = function (attrName, val, isStopNode) { } else return ' ' + attrName + '="' + escapeAttribute(val) + '"'; }; -function processTextOrObjNode(object, key, level, matcher, xmlVersion) { +function processTextOrObjNode(object, key, level, matcher, qNameValidator) { // Extract attributes to pass to matcher const attrValues = this.extractAttributes(object); @@ -14216,7 +15723,7 @@ function processTextOrObjNode(object, key, level, matcher, xmlVersion) { return this.buildObjectNode(rawContent, key, attrStr, level); } - const result = this.j2x(object, level + 1, matcher, xmlVersion); + const result = this.j2x(object, level + 1, matcher, qNameValidator); // Pop tag from matcher after recursion matcher.pop(); @@ -14345,7 +15852,9 @@ Builder.prototype.buildAttributesForStopNode = function (obj) { if (val === true && this.options.suppressBooleanAttributes) { attrStr += ' ' + cleanKey; } else { - attrStr += ' ' + cleanKey + '="' + val + '"'; // No encoding for stopNode + // stopNode content is raw, but the quote delimiter is always escaped + // so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str) + attrStr += ' ' + cleanKey + '="' + escapeAttribute(val) + '"'; } } } else { @@ -14358,7 +15867,9 @@ Builder.prototype.buildAttributesForStopNode = function (obj) { if (val === true && this.options.suppressBooleanAttributes) { attrStr += ' ' + attr; } else { - attrStr += ' ' + attr + '="' + val + '"'; // No encoding for stopNode + // stopNode content is raw, but the quote delimiter is always escaped + // so a quote in the value cannot break out of the attribute (see orderedJs2Xml attr_to_str) + attrStr += ' ' + attr + '="' + escapeAttribute(val) + '"'; } } } @@ -14389,7 +15900,7 @@ Builder.prototype.buildObjectNode = function (val, key, attrStr, level) { if ((attrStr || attrStr === '') && val.indexOf('<') === -1) { return (this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp); } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { - return this.indentate(level) + `` + this.newLine; + return this.indentate(level) + `` + this.newLine; } else { return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + @@ -14550,7 +16061,8 @@ async function parseXML(str, opts = {}) { delete parsedXml["?xml"]; } if (!opts.includeRoot) { - for (const key of Object.keys(parsedXml)) { + const key = Object.keys(parsedXml)[0]; + if (key !== undefined) { const value = parsedXml[key]; return typeof value === "object" ? { ...value } : value; } @@ -15031,20 +16543,30 @@ class BufferScheduler { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This error is thrown when an asynchronous operation has been aborted. * Check for this error by testing the `name` that the name property of the * error matches `"AbortError"`. * * @example - * ```ts + * ```ts snippet:AbortErrorSample + * import { AbortError } from "@azure/abort-controller"; + * + * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise { + * if (options.abortSignal.aborted) { + * throw new AbortError(); + * } + * + * // do async work + * } + * * const controller = new AbortController(); * controller.abort(); * try { - * doAsyncWork(controller.signal) + * doAsyncWork({ abortSignal: controller.signal }); * } catch (e) { - * if (e.name === 'AbortError') { + * if (e instanceof Error && e.name === "AbortError") { * // handle abort error here. * } * } @@ -15154,6 +16676,7 @@ function locateFile(path) { if (ENVIRONMENT_IS_NODE) { if (typeof process == 'undefined' || !process.release || process.release.name !== 'node') throw new Error('not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)'); +// NODE-READ-START (this block is replaced with a no-op in dist/browser and dist/react-native by copyJSFiles.cjs) // `require()` is no-op in an ESM module, use `createRequire()` to construct // the require()` function. This is only necessary for multi-environment // builds, `-sENVIRONMENT=node` emits a static import declaration instead. @@ -15170,6 +16693,7 @@ if (ENVIRONMENT_IS_NODE) { } // end include: node_shell_read.js +// NODE-READ-END if (process['argv'].length > 1) { process['argv'][1].replace(/\\/g, '/'); } @@ -19280,8 +20804,8 @@ class UserDelegationKeyCredential { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -const SDK_VERSION = "12.32.0"; -const SERVICE_VERSION = "2026-04-06"; +const SDK_VERSION = "12.33.0"; +const SERVICE_VERSION = "2026-06-06"; const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB const BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -21308,6 +22832,7 @@ const BlobPropertiesInternal = { "Cool", "Archive", "Cold", + "Smart", ], }, }, @@ -21327,6 +22852,32 @@ const BlobPropertiesInternal = { "rehydrate-pending-to-hot", "rehydrate-pending-to-cool", "rehydrate-pending-to-cold", + "rehydrate-pending-to-smart", + ], + }, + }, + smartAccessTier: { + serializedName: "SmartAccessTier", + xmlName: "SmartAccessTier", + type: { + name: "Enum", + allowedValues: [ + "P4", + "P6", + "P10", + "P15", + "P20", + "P30", + "P40", + "P50", + "P60", + "P70", + "P80", + "Hot", + "Cool", + "Archive", + "Cold", + "Smart", ], }, }, @@ -24472,6 +26023,13 @@ const BlobGetPropertiesHeaders = { name: "DateTimeRfc1123", }, }, + smartAccessTier: { + serializedName: "x-ms-smart-access-tier", + xmlName: "x-ms-smart-access-tier", + type: { + name: "String", + }, + }, versionId: { serializedName: "x-ms-version-id", xmlName: "x-ms-version-id", @@ -28647,7 +30205,7 @@ const timeoutInSeconds = { const version$1 = { parameterPath: "version", mapper: { - defaultValue: "2026-04-06", + defaultValue: "2026-06-06", isConstant: true, serializedName: "x-ms-version", type: { @@ -29554,6 +31112,7 @@ const tier = { "Cool", "Archive", "Cold", + "Smart", ], }, }, @@ -29792,6 +31351,7 @@ const tier1 = { "Cool", "Archive", "Cold", + "Smart", ], }, }, @@ -33458,7 +35018,7 @@ let StorageClient$1 = class StorageClient extends ExtendedServiceClient { const defaults = { requestContentType: "application/json; charset=utf-8", }; - const packageDetails = `azsdk-js-azure-storage-blob/12.32.0`; + const packageDetails = `azsdk-js-azure-storage-blob/12.33.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; @@ -33474,7 +35034,7 @@ let StorageClient$1 = class StorageClient extends ExtendedServiceClient { // Parameter assignments this.url = url; // Assigning values to Constant parameters - this.version = options.version || "2026-04-06"; + this.version = options.version || "2026-06-06"; this.service = new ServiceImpl(this); this.container = new ContainerImpl(this); this.blob = new BlobImpl(this); @@ -33508,6 +35068,13 @@ class StorageContextClient extends StorageClient$1 { // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +const accountNameSuffixes = [ + "-secondary-ipv6", + "-secondary-dualstack", + "-ipv6", + "-dualstack", + "-secondary", +]; /** * Reserved URL characters must be properly escaped for Storage services like Blob or File. * @@ -33854,7 +35421,15 @@ function getAccountNameFromUrl(url) { try { if (parsedUrl.hostname.split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + // `${defaultEndpointsProtocol}://${accountName}-suffix.blob.${endpointSuffix}`; accountName = parsedUrl.hostname.split(".")[0]; + for (let i = 0; i < accountNameSuffixes.length; ++i) { + const suffix = accountNameSuffixes[i]; + if (accountName.endsWith(suffix)) { + accountName = accountName.substring(0, accountName.length - suffix.length); + break; + } + } } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ @@ -34752,6 +36327,10 @@ class SASQueryParameters { * Keys for request query parameters required in the SAS token */ requestQueryParameterKeys; + /** To indicate the depth of the virtual blob directory specified + * in the canonicalizedresource field of the string-to-sign. + */ + directoryDepth; /** * Optional. IP range allowed for this SAS. * @@ -34766,7 +36345,7 @@ class SASQueryParameters { } return undefined; } - constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope, delegatedUserObjectId, requestHeaderKeys, requestQueryParameterKeys) { + constructor(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId, encryptionScope, delegatedUserObjectId, requestHeaderKeys, requestQueryParameterKeys, directoryDepth) { this.version = version; this.signature = signature; if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { @@ -34789,6 +36368,7 @@ class SASQueryParameters { this.contentType = permissionsOrOptions.contentType; this.requestHeaderKeys = permissionsOrOptions.requestHeaderKeys; this.requestQueryParameterKeys = permissionsOrOptions.requestQueryParameterKeys; + this.directoryDepth = permissionsOrOptions.directoryDepth; if (permissionsOrOptions.userDelegationKey) { this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; @@ -34821,6 +36401,7 @@ class SASQueryParameters { this.contentType = contentType; this.requestHeaderKeys = requestHeaderKeys; this.requestQueryParameterKeys = requestQueryParameterKeys; + this.directoryDepth = directoryDepth; if (userDelegationKey) { this.signedOid = userDelegationKey.signedObjectId; this.signedTenantId = userDelegationKey.signedTenantId; @@ -34864,6 +36445,7 @@ class SASQueryParameters { "rsct", "saoid", "scid", + "sdd", "sduoid", // Signed key user delegation object ID "skdutid", // Signed key user delegation tenant ID "srh", // Request Headers @@ -34960,6 +36542,9 @@ class SASQueryParameters { case "srq": // Request headers this.tryAppendQueryParameter(queries, param, this.requestQueryParameterKeys); break; + case "sdd": // Directory depth + this.tryAppendQueryParameter(queries, param, this.directoryDepth !== undefined ? this.directoryDepth.toString() : ""); + break; } } return queries.join("&"); @@ -35022,7 +36607,13 @@ function generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKe // https://learn.microsoft.com/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string if (version >= "2018-11-09") { if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + // Version 2020-02-10 delegation SAS signature construction supports blob name as a virtual directory. + if (version >= "2020-02-10") { + return generateBlobSASQueryParameters20200210(blobSASSignatureValues, sharedKeyCredential); + } + else { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } } else { // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. @@ -35178,6 +36769,85 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe stringToSign: stringToSign, }; } +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param blobSASSignatureValues - + * @param sharedKeyCredential - + */ +function generateBlobSASQueryParameters20200210(blobSASSignatureValues, sharedKeyCredential) { + blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); + if (!blobSASSignatureValues.identifier && + !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; + if (blobSASSignatureValues.blobName) { + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; + } + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + let verifiedPermissions; + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + const stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + blobSASSignatureValues.version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", + ].join("\n"); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, undefined, undefined, undefined, undefined, directoryDepth), + stringToSign: stringToSign, + }; +} /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-12-06. @@ -35202,14 +36872,21 @@ function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKe } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. @@ -35247,7 +36924,7 @@ function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKe ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope), + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope, undefined, undefined, undefined, directoryDepth), stringToSign: stringToSign, }; } @@ -35352,14 +37029,21 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. @@ -35408,7 +37092,7 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId), + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, undefined, undefined, undefined, undefined, directoryDepth), stringToSign: stringToSign, }; } @@ -35434,14 +37118,21 @@ function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userD } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. @@ -35491,7 +37182,7 @@ function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userD ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope), + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope, undefined, undefined, undefined, directoryDepth), stringToSign: stringToSign, }; } @@ -35517,14 +37208,21 @@ function generateBlobSASQueryParametersUDK20250705(blobSASSignatureValues, userD } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. @@ -35576,7 +37274,7 @@ function generateBlobSASQueryParametersUDK20250705(blobSASSignatureValues, userD ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.delegatedUserObjectId), + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.delegatedUserObjectId, undefined, undefined, directoryDepth), stringToSign: stringToSign, }; } @@ -35602,14 +37300,21 @@ function generateBlobSASQueryParametersUDK20260406(blobSASSignatureValues, userD } let resource = "c"; let timestamp = blobSASSignatureValues.snapshotTime; + let directoryDepth = undefined; if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; + if (blobSASSignatureValues.isDirectory === true) { + resource = "d"; + directoryDepth = trimBlobName(blobSASSignatureValues.blobName).split("/").length; } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; + else { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. @@ -35663,7 +37368,7 @@ function generateBlobSASQueryParametersUDK20260406(blobSASSignatureValues, userD ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return { - sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.delegatedUserObjectId, getKeysOfRequestHeaders(blobSASSignatureValues.requestHeaders), getKeysOfRequestHeaders(blobSASSignatureValues.requestQueryParameters)), + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope, blobSASSignatureValues.delegatedUserObjectId, getKeysOfRequestHeaders(blobSASSignatureValues.requestHeaders), getKeysOfRequestHeaders(blobSASSignatureValues.requestQueryParameters), directoryDepth), stringToSign: stringToSign, }; } @@ -35771,6 +37476,16 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { blobSASSignatureValues.version = version; return blobSASSignatureValues; } +function trimBlobName(blobName) { + let internalName = blobName; + while (internalName.startsWith("/")) { + internalName = internalName.substring(1); + } + while (internalName.endsWith("/")) { + internalName = internalName.substring(0, internalName.length - 1); + } + return internalName; +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. @@ -35970,20 +37685,30 @@ class BlobLeaseClient { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This error is thrown when an asynchronous operation has been aborted. * Check for this error by testing the `name` that the name property of the * error matches `"AbortError"`. * * @example - * ```ts + * ```ts snippet:AbortErrorSample + * import { AbortError } from "@azure/abort-controller"; + * + * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise { + * if (options.abortSignal.aborted) { + * throw new AbortError(); + * } + * + * // do async work + * } + * * const controller = new AbortController(); * controller.abort(); * try { - * doAsyncWork(controller.signal) + * doAsyncWork({ abortSignal: controller.signal }); * } catch (e) { - * if (e.name === 'AbortError') { + * if (e instanceof Error && e.name === "AbortError") { * // handle abort error here. * } * } @@ -38682,6 +40407,7 @@ class BlobClient extends StorageClient { * ```ts snippet:ReadmeSampleDownloadBlob_Node * import { BlobServiceClient } from "@azure/storage-blob"; * import { DefaultAzureCredential } from "@azure/identity"; + * import { buffer } from "node:stream/consumers"; * * const account = ""; * const blobServiceClient = new BlobServiceClient( @@ -38698,22 +40424,10 @@ class BlobClient extends StorageClient { * // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody * const downloadBlockBlobResponse = await blobClient.download(); * if (downloadBlockBlobResponse.readableStreamBody) { - * const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody); - * console.log(`Downloaded blob content: ${downloaded}`); - * } - * - * async function streamToString(stream: NodeJS.ReadableStream): Promise { - * const result = await new Promise>((resolve, reject) => { - * const chunks: Buffer[] = []; - * stream.on("data", (data) => { - * chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data)); - * }); - * stream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * stream.on("error", reject); - * }); - * return result.toString(); + * // Download the raw bytes of the blob. Use `text` from "node:stream/consumers" + * // instead if you want to read the content as a string directly. + * const downloaded = await buffer(downloadBlockBlobResponse.readableStreamBody); + * console.log(`Downloaded blob content: ${downloaded.toString()}`); * } * ``` * @@ -40072,6 +41786,7 @@ class BlockBlobClient extends BlobClient { * ```ts snippet:ClientsQuery * import { BlobServiceClient } from "@azure/storage-blob"; * import { DefaultAzureCredential } from "@azure/identity"; + * import { buffer } from "node:stream/consumers"; * * const account = ""; * const blobServiceClient = new BlobServiceClient( @@ -40087,22 +41802,10 @@ class BlockBlobClient extends BlobClient { * // Query and convert a blob to a string * const queryBlockBlobResponse = await blockBlobClient.query("select from BlobStorage"); * if (queryBlockBlobResponse.readableStreamBody) { - * const downloadedBuffer = await streamToBuffer(queryBlockBlobResponse.readableStreamBody); - * const downloaded = downloadedBuffer.toString(); - * console.log(`Query blob content: ${downloaded}`); - * } - * - * async function streamToBuffer(readableStream: NodeJS.ReadableStream): Promise { - * return new Promise((resolve, reject) => { - * const chunks: Buffer[] = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); + * // Read the response bytes. Use `text` from "node:stream/consumers" instead + * // if you want the response as a string directly. + * const downloadedBuffer = await buffer(queryBlockBlobResponse.readableStreamBody); + * console.log(`Query blob content: ${downloadedBuffer.toString()}`); * } * ``` * @@ -42109,6 +43812,24 @@ function getCacheServiceVersion() { return 'v1'; return process.env['ACTIONS_CACHE_SERVICE_V2'] ? 'v2' : 'v1'; } +// The cache-mode lattice: readable = {read, write}, writable = {write, +// write-only}, none = neither. +const KNOWN_CACHE_MODES = ['none', 'read', 'write', 'write-only']; +// The effective cache-mode exported by the runner, or '' when not set. +function getCacheMode() { + return (process.env['ACTIONS_CACHE_MODE'] || '').trim().toLowerCase(); +} +// Unset or unrecognized modes are permissive so behavior matches today. +function isCacheReadable(mode) { + if (!KNOWN_CACHE_MODES.includes(mode)) + return true; + return mode === 'read' || mode === 'write'; +} +function isCacheWritable(mode) { + if (!KNOWN_CACHE_MODES.includes(mode)) + return true; + return mode === 'write' || mode === 'write-only'; +} function getCacheServiceURL() { const version = getCacheServiceVersion(); // Based on the version of the cache service, we will determine which @@ -42125,7 +43846,7 @@ function getCacheServiceURL() { } } -var version = "6.1.0"; +var version = "6.2.0"; var require$$0 = { version: version}; @@ -42190,6 +43911,7 @@ function createHttpClient() { } function getCacheEntry(keys, paths, options) { return __awaiter$3(this, void 0, void 0, function* () { + var _a; const httpClient = createHttpClient(); const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive); const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`; @@ -42203,6 +43925,12 @@ function getCacheEntry(keys, paths, options) { return null; } if (!isSuccessStatusCode(response.statusCode)) { + // Only surface the receiver's body for a `cache read denied:` policy denial + // so callers can dispatch on it; keep the generic message otherwise. + const errorMessage = (_a = response.error) === null || _a === void 0 ? void 0 : _a.message; + if (errorMessage === null || errorMessage === void 0 ? void 0 : errorMessage.includes(CacheReadDeniedMessagePrefix)) { + throw new Error(errorMessage); + } throw new Error(`Cache service responded with ${response.statusCode}`); } const cacheResult = response.result; @@ -46376,19 +48104,20 @@ class ReserveCacheError extends Error { } } /** - * Stable prefix the receiver writes into the cache reservation response when - * the issuer downgraded the cache token to read-only (for example, because + * Stable prefix the cache service writes into the cache reservation response + * when the issuer downgraded the cache token to read-only (for example, because * the run was triggered by an untrusted event). saveCacheV1 / saveCacheV2 - * dispatch on this prefix to re-classify the failure as a - * CacheWriteDeniedError so consumers (and the outer catch arm) can - * distinguish a policy denial from other reservation failures. + * dispatch on this prefix to re-classify the failure as a CacheWriteDeniedError + * so consumers and tests can distinguish a policy denial from other reservation + * failures. Internally it is logged as a non-fatal warning like other + * best-effort save failures. */ const CACHE_WRITE_DENIED_PREFIX = 'cache write denied:'; /** * Raised when the cache backend refuses to reserve a writable cache entry * because the JWT issued for this run was scoped read-only (for example, the * run was triggered by an event the repository administrator classified as - * untrusted). The receiver-supplied detail message always begins with + * untrusted). The service-supplied detail message always begins with * `cache write denied:` (the full error message includes additional context * like the cache key). * @@ -46404,6 +48133,19 @@ class CacheWriteDeniedError extends ReserveCacheError { Object.setPrototypeOf(this, CacheWriteDeniedError.prototype); } } +// Re-exported from constants so consumers keep referencing it here; the shared +// value also drives detection in cacheHttpClient without duplicating the string. +const CACHE_READ_DENIED_PREFIX = CacheReadDeniedMessagePrefix; +// Raised when the cache backend denies a download URL because the run's token +// has no readable cache scopes. Caching is best-effort, so restoreCache logs a +// warning and reports a cache miss rather than rethrowing this. +class CacheReadDeniedError extends Error { + constructor(message) { + super(message); + this.name = 'CacheReadDeniedError'; + Object.setPrototypeOf(this, CacheReadDeniedError.prototype); + } +} class FinalizeCacheError extends Error { constructor(message) { super(message); @@ -46458,6 +48200,12 @@ function restoreCache(paths_1, primaryKey_1, restoreKeys_1, options_1) { const cacheServiceVersion = getCacheServiceVersion(); debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); + const cacheMode = getCacheMode(); + if (!isCacheReadable(cacheMode)) { + info(`Cache restore skipped: the effective cache-mode '${cacheMode}' does not permit reads.`); + debug(`Skipped restore for paths [${paths.join(', ')}] with primary key '${primaryKey}'.`); + return undefined; + } switch (cacheServiceVersion) { case 'v2': return yield restoreCacheV2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive); @@ -46479,6 +48227,7 @@ function restoreCache(paths_1, primaryKey_1, restoreKeys_1, options_1) { */ function restoreCacheV1(paths_1, primaryKey_1, restoreKeys_1, options_1) { return __awaiter(this, arguments, void 0, function* (paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + var _a; restoreKeys = restoreKeys || []; const keys = [primaryKey, ...restoreKeys]; debug('Resolved Keys:'); @@ -46493,10 +48242,26 @@ function restoreCacheV1(paths_1, primaryKey_1, restoreKeys_1, options_1) { let archivePath = ''; try { // path are needed to compute version - const cacheEntry = yield getCacheEntry(keys, paths, { - compressionMethod, - enableCrossOsArchive - }); + let cacheEntry; + try { + cacheEntry = yield getCacheEntry(keys, paths, { + compressionMethod, + enableCrossOsArchive + }); + } + catch (error) { + // The v1 artifact cache service returns HTTP 403 with a + // `cache read denied:` body when the run's token has no readable cache + // scopes. getCacheEntry lives in a dependency-free internal module and + // cannot import CacheReadDeniedError without a circular dependency, so it + // only surfaces the raw denial message; we classify it into the typed + // error here so the outer catch and consumers can dispatch on it. + const errorMessage = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : ''; + if (errorMessage.includes(CACHE_READ_DENIED_PREFIX)) { + throw new CacheReadDeniedError(errorMessage); + } + throw error; + } if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) { // Cache not found return undefined; @@ -46525,7 +48290,9 @@ function restoreCacheV1(paths_1, primaryKey_1, restoreKeys_1, options_1) { } else { // warn on cache restore failure and continue build - // Log server errors (5xx) as errors, all other errors as warnings + // Log server errors (5xx) as errors, all other errors as warnings. + // A read denied by policy (CacheReadDeniedError) is not an HttpClientError + // so it falls here and is warned, treated as a cache miss. if (typedError instanceof HttpClientError && typeof typedError.statusCode === 'number' && typedError.statusCode >= 500) { @@ -46560,6 +48327,7 @@ function restoreCacheV1(paths_1, primaryKey_1, restoreKeys_1, options_1) { */ function restoreCacheV2(paths_1, primaryKey_1, restoreKeys_1, options_1) { return __awaiter(this, arguments, void 0, function* (paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) { + var _a; // Override UploadOptions to force the use of Azure options = Object.assign(Object.assign({}, options), { useAzureSdk: true }); restoreKeys = restoreKeys || []; @@ -46581,7 +48349,20 @@ function restoreCacheV2(paths_1, primaryKey_1, restoreKeys_1, options_1) { restoreKeys, version: getCacheVersion(paths, compressionMethod, enableCrossOsArchive) }; - const response = yield twirpClient.GetCacheEntryDownloadURL(request); + let response; + try { + response = yield twirpClient.GetCacheEntryDownloadURL(request); + } + catch (error) { + // The receiver returns twirp PermissionDenied (403) when the run's token + // has no readable cache scopes. The client wraps that 403, so the stable + // prefix is embedded in the message rather than leading it. + const errorMessage = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : ''; + if (errorMessage.includes(CACHE_READ_DENIED_PREFIX)) { + throw new CacheReadDeniedError(errorMessage); + } + throw error; + } if (!response.ok) { debug(`Cache not found for version ${request.version} of keys: ${keys.join(', ')}`); return undefined; @@ -46616,8 +48397,10 @@ function restoreCacheV2(paths_1, primaryKey_1, restoreKeys_1, options_1) { throw error$1; } else { - // Supress all non-validation cache related errors because caching should be optional - // Log server errors (5xx) as errors, all other errors as warnings + // Suppress all non-validation cache related errors because caching should be optional + // Log server errors (5xx) as errors, all other errors as warnings. + // A read denied by policy (CacheReadDeniedError) is not an HttpClientError + // so it falls here and is warned, treated as a cache miss. if (typedError instanceof HttpClientError && typeof typedError.statusCode === 'number' && typedError.statusCode >= 500) { @@ -46656,6 +48439,12 @@ function saveCache(paths_1, key_1, options_1) { debug(`Cache service version: ${cacheServiceVersion}`); checkPaths(paths); checkKey(key); + const cacheMode = getCacheMode(); + if (!isCacheWritable(cacheMode)) { + info(`Cache save skipped: the effective cache-mode '${cacheMode}' does not permit writes.`); + debug(`Skipped save for paths [${paths.join(', ')}] with key '${key}'.`); + return -1; + } switch (cacheServiceVersion) { case 'v2': return yield saveCacheV2(paths, key, options, enableCrossOsArchive); @@ -46733,17 +48522,14 @@ function saveCacheV1(paths_1, key_1, options_1) { if (typedError.name === ValidationError.name) { throw error$1; } - else if (typedError.name === CacheWriteDeniedError.name) { - // Cache write was denied by policy (read-only token). Surface to the - // customer at warning level so it is visible in the workflow log - // without failing the run. - warning(`Failed to save: ${typedError.message}`); - } else if (typedError.name === ReserveCacheError.name) { info(`Failed to save: ${typedError.message}`); } else { - // Log server errors (5xx) as errors, all other errors as warnings + // Log server errors (5xx) as errors, all other errors as warnings. + // A write denied by policy (CacheWriteDeniedError) is not an + // HttpClientError and its name does not match the ReserveCacheError arm, + // so it falls here and is warned without failing the run. if (typedError instanceof HttpClientError && typeof typedError.statusCode === 'number' && typedError.statusCode >= 500) { @@ -46854,12 +48640,6 @@ function saveCacheV2(paths_1, key_1, options_1) { if (typedError.name === ValidationError.name) { throw error$1; } - else if (typedError.name === CacheWriteDeniedError.name) { - // Cache write was denied by policy (read-only token). Surface to the - // customer at warning level so it is visible in the workflow log - // without failing the run. - warning(`Failed to save: ${typedError.message}`); - } else if (typedError.name === ReserveCacheError.name) { info(`Failed to save: ${typedError.message}`); } @@ -46867,7 +48647,10 @@ function saveCacheV2(paths_1, key_1, options_1) { warning(typedError.message); } else { - // Log server errors (5xx) as errors, all other errors as warnings + // Log server errors (5xx) as errors, all other errors as warnings. + // A write denied by policy (CacheWriteDeniedError) is not an + // HttpClientError and its name does not match the ReserveCacheError arm, + // so it falls here and is warned without failing the run. if (typedError instanceof HttpClientError && typeof typedError.statusCode === 'number' && typedError.statusCode >= 500) { @@ -46891,4 +48674,4 @@ function saveCacheV2(paths_1, key_1, options_1) { }); } -export { CACHE_WRITE_DENIED_PREFIX, CacheWriteDeniedError, FinalizeCacheError, ReserveCacheError, ValidationError, isFeatureAvailable, restoreCache, saveCache }; +export { CACHE_READ_DENIED_PREFIX, CACHE_WRITE_DENIED_PREFIX, CacheReadDeniedError, CacheWriteDeniedError, FinalizeCacheError, ReserveCacheError, ValidationError, isFeatureAvailable, restoreCache, saveCache }; diff --git a/dist/cache-COXGx-w3.js b/dist/cache-DhiwylR9.js similarity index 97% rename from dist/cache-COXGx-w3.js rename to dist/cache-DhiwylR9.js index c45f1a1..71d8777 100644 --- a/dist/cache-COXGx-w3.js +++ b/dist/cache-DhiwylR9.js @@ -1,4 +1,4 @@ -import { v as commonjsGlobal, x as requireTunnel, y as getDefaultExportFromCjs, z as getAugmentedNamespace } from './cleanup-BnmJoqJp.js'; +import { v as commonjsGlobal, x as requireTunnel, y as getDefaultExportFromCjs, z as getAugmentedNamespace } from './cleanup-BaSEYL-3.js'; import os__default from 'os'; import crypto__default from 'crypto'; import fs__default from 'fs'; @@ -24,14 +24,14 @@ import require$$4$2 from 'async_hooks'; import require$$1$4 from 'console'; import require$$2$3 from 'url'; import zlib from 'zlib'; -import require$$6$1 from 'string_decoder'; +import require$$6 from 'string_decoder'; import require$$0$a from 'diagnostics_channel'; import require$$2__default$1 from 'child_process'; -import require$$6$2 from 'timers'; +import require$$6$1 from 'timers'; import require$$0$b from 'punycode'; -import { r as requireDist$4, d as requireSrc$d, a as requireDist$5, b as requireState$2, c as requireStateCjs } from './state-cjs-DNYNk0pO.js'; +import { r as requireDist$4, d as requireSrc$d, a as requireDist$5, b as requireStateCjs, c as requireStateCjs$1 } from './state-cjs-CkvFUaNy.js'; import process$1 from 'node:process'; -import require$$6$3 from 'http2'; +import require$$6$2 from 'http2'; import os from 'node:os'; import http from 'node:http'; import https from 'node:https'; @@ -19325,7 +19325,7 @@ function requireUtil$f () { const { DOMException } = requireConstants$e(); const { serializeAMimeType, parseMIMEType } = requireDataURL$1(); const { types } = require$$0__default$1; - const { StringDecoder } = require$$6$1; + const { StringDecoder } = require$$6; const { btoa } = require$$0__default; /** @type {PropertyDescriptor} */ @@ -21428,11 +21428,11 @@ function requireUtil$d () { return util$d; } -var parse$6; +var parse$5; var hasRequiredParse$2; function requireParse$2 () { - if (hasRequiredParse$2) return parse$6; + if (hasRequiredParse$2) return parse$5; hasRequiredParse$2 = 1; const { maxNameValuePairSize, maxAttributeValueSize } = requireConstants$c(); @@ -21746,11 +21746,11 @@ function requireParse$2 () { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } - parse$6 = { + parse$5 = { parseSetCookie, parseUnparsedAttributes }; - return parse$6; + return parse$5; } var cookies$1; @@ -25841,7 +25841,7 @@ function requireToolrunner () { const path = __importStar(path__default); const io = __importStar(requireIo()); const ioUtil = __importStar(requireIoUtil()); - const timers_1 = require$$6$2; + const timers_1 = require$$6$1; /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -26460,7 +26460,7 @@ function requireExec () { }; Object.defineProperty(exec, "__esModule", { value: true }); exec.getExecOutput = exec.exec = void 0; - const string_decoder_1 = require$$6$1; + const string_decoder_1 = require$$6; const tr = __importStar(requireToolrunner()); /** * Exec a command. @@ -27590,103 +27590,109 @@ function requireBraceExpansion () { function expand(str, max, isTop) { var expansions = []; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + // The `{a},b}` rewrite below restarts expansion on a rewritten string with + // the same `max` and `isTop = true`. Loop instead of recursing so a long run + // of non-expanding `{}` groups can't exhaust the call stack. + for (;;) { + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,(?!,).*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str, max, true); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], max, false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, max, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + isTop = true; + continue } + return [str]; } - } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, max, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length); - var incr = n.length == 3 - ? Math.max(Math.abs(numeric(n[2])), 1) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y) && N.length < max; i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], max, false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, max, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); } } - N.push(c); } - } else { - N = concatMap(n, function(el) { return expand(el, max, false) }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length && expansions.length < max; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, max, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 + ? Math.max(Math.abs(numeric(n[2])), 1) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y) && N.length < max; i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, max, false) }); } - } - return expansions; + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length && expansions.length < max; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; + } } return braceExpansion; } @@ -31039,21 +31045,21 @@ function requireSemver () { return semver.exports; } -var rng$3; +var rng$2; var hasRequiredRng; function requireRng () { - if (hasRequiredRng) return rng$3; + if (hasRequiredRng) return rng$2; hasRequiredRng = 1; // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = crypto__default; - rng$3 = function nodeRNG() { + rng$2 = function nodeRNG() { return crypto.randomBytes(16); }; - return rng$3; + return rng$2; } /** @@ -49022,7 +49028,7 @@ function requireUtil$8 () { const { DOMException } = requireConstants$8(); const { serializeAMimeType, parseMIMEType } = requireDataURL(); const { types } = require$$0__default$1; - const { StringDecoder } = require$$6$1; + const { StringDecoder } = require$$6; const { btoa } = require$$0__default; /** @type {PropertyDescriptor} */ @@ -51125,11 +51131,11 @@ function requireUtil$6 () { return util$6; } -var parse$5; +var parse$4; var hasRequiredParse$1; function requireParse$1 () { - if (hasRequiredParse$1) return parse$5; + if (hasRequiredParse$1) return parse$4; hasRequiredParse$1 = 1; const { maxNameValuePairSize, maxAttributeValueSize } = requireConstants$6(); @@ -51443,11 +51449,11 @@ function requireParse$1 () { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } - parse$5 = { + parse$4 = { parseSetCookie, parseUnparsedAttributes }; - return parse$5; + return parse$4; } var cookies; @@ -54979,7 +54985,7 @@ function expand(template, context) { } } -function parse$4(options) { +function parse$3(options) { let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); @@ -55044,7 +55050,7 @@ function parse$4(options) { } function endpointWithDefaults(defaults, route, options) { - return parse$4(merge(defaults, route, options)); + return parse$3(merge(defaults, route, options)); } function withDefaults$2(oldDefaults, newDefaults) { @@ -55054,7 +55060,7 @@ function withDefaults$2(oldDefaults, newDefaults) { DEFAULTS, defaults: withDefaults$2.bind(null, DEFAULTS), merge: merge.bind(null, DEFAULTS), - parse: parse$4 + parse: parse$3 }); } @@ -58631,7 +58637,7 @@ function requireExtend () { var publicApi = {}; -var URL$5 = {exports: {}}; +var URL$4 = {exports: {}}; var lib$2; var hasRequiredLib$1; @@ -138232,7 +138238,7 @@ function requireURLImpl () { var hasRequiredURL; function requireURL () { - if (hasRequiredURL) return URL$5.exports; + if (hasRequiredURL) return URL$4.exports; hasRequiredURL = 1; (function (module) { @@ -138429,8 +138435,8 @@ function requireURL () { Worker: { URL: URL } } }; - } (URL$5)); - return URL$5.exports; + } (URL$4)); + return URL$4.exports; } var hasRequiredPublicApi; @@ -139585,7 +139591,7 @@ Object.defineProperty(Response$1.prototype, Symbol.toStringTag, { }); const INTERNALS$2 = Symbol('Request internals'); -const URL$4 = require$$2$3.URL || whatwgUrl.URL; +const URL$3 = require$$2$3.URL || whatwgUrl.URL; // fix an issue where "format", "parse" aren't a named export for node <10 const parse_url = require$$2$3.parse; @@ -139604,7 +139610,7 @@ function parseURL(urlStr) { Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 */ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL$4(urlStr).toString(); + urlStr = new URL$3(urlStr).toString(); } // Fallback to old implementation for arbitrary URLs @@ -139830,7 +139836,7 @@ function getNodeRequestOptions(request) { * @param String message Error message for human * @return AbortError */ -function AbortError$3(message) { +function AbortError(message) { Error.call(this, message); this.type = 'aborted'; @@ -139840,9 +139846,9 @@ function AbortError$3(message) { Error.captureStackTrace(this, this.constructor); } -AbortError$3.prototype = Object.create(Error.prototype); -AbortError$3.prototype.constructor = AbortError$3; -AbortError$3.prototype.name = 'AbortError'; +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; const URL$1$1 = require$$2$3.URL || whatwgUrl.URL; @@ -139898,7 +139904,7 @@ function fetch$1(url, opts) { let response = null; const abort = function abort() { - let error = new AbortError$3('The user aborted a request.'); + let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof require$$0__default$2.Readable) { destroyStream(request.body, error); @@ -140222,7 +140228,7 @@ fetch$1.Promise = global.Promise; var lib$1 = /*#__PURE__*/Object.freeze({ __proto__: null, - AbortError: AbortError$3, + AbortError: AbortError, FetchError: FetchError, Headers: Headers, Request: Request, @@ -140273,7 +140279,7 @@ var common = {}; var util$4 = {}; var name$1 = "gaxios"; -var version$5 = "6.7.1"; +var version$4 = "6.7.1"; var description$1 = "A simple common HTTP client specifically for Google APIs and services."; var main$1 = "build/src/index.js"; var types$1 = "build/src/index.d.ts"; @@ -140368,7 +140374,7 @@ var dependencies$1 = { }; var require$$0$4 = { name: name$1, - version: version$5, + version: version$4, description: description$1, main: main$1, types: types$1, @@ -140782,26 +140788,26 @@ function requireRetry$2 () { // Unique ID creation requires a high quality random # generator. In the browser we therefore // require the crypto API and do not support built-in fallback to lower quality random number // generators (like Math.random()). -let getRandomValues$2; -const rnds8$2 = new Uint8Array(16); -function rng$2() { +let getRandomValues$1; +const rnds8$1 = new Uint8Array(16); +function rng$1() { // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues$2) { + if (!getRandomValues$1) { // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. - getRandomValues$2 = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + getRandomValues$1 = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); - if (!getRandomValues$2) { + if (!getRandomValues$1) { throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); } } - return getRandomValues$2(rnds8$2); + return getRandomValues$1(rnds8$1); } -var REGEX$2 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +var REGEX$1 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -function validate$2(uuid) { - return typeof uuid === 'string' && REGEX$2.test(uuid); +function validate$1(uuid) { + return typeof uuid === 'string' && REGEX$1.test(uuid); } /** @@ -140809,26 +140815,26 @@ function validate$2(uuid) { * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ -const byteToHex$2 = []; +const byteToHex$1 = []; for (let i = 0; i < 256; ++i) { - byteToHex$2.push((i + 0x100).toString(16).slice(1)); + byteToHex$1.push((i + 0x100).toString(16).slice(1)); } function unsafeStringify$1(arr, offset = 0) { // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - return byteToHex$2[arr[offset + 0]] + byteToHex$2[arr[offset + 1]] + byteToHex$2[arr[offset + 2]] + byteToHex$2[arr[offset + 3]] + '-' + byteToHex$2[arr[offset + 4]] + byteToHex$2[arr[offset + 5]] + '-' + byteToHex$2[arr[offset + 6]] + byteToHex$2[arr[offset + 7]] + '-' + byteToHex$2[arr[offset + 8]] + byteToHex$2[arr[offset + 9]] + '-' + byteToHex$2[arr[offset + 10]] + byteToHex$2[arr[offset + 11]] + byteToHex$2[arr[offset + 12]] + byteToHex$2[arr[offset + 13]] + byteToHex$2[arr[offset + 14]] + byteToHex$2[arr[offset + 15]]; + return byteToHex$1[arr[offset + 0]] + byteToHex$1[arr[offset + 1]] + byteToHex$1[arr[offset + 2]] + byteToHex$1[arr[offset + 3]] + '-' + byteToHex$1[arr[offset + 4]] + byteToHex$1[arr[offset + 5]] + '-' + byteToHex$1[arr[offset + 6]] + byteToHex$1[arr[offset + 7]] + '-' + byteToHex$1[arr[offset + 8]] + byteToHex$1[arr[offset + 9]] + '-' + byteToHex$1[arr[offset + 10]] + byteToHex$1[arr[offset + 11]] + byteToHex$1[arr[offset + 12]] + byteToHex$1[arr[offset + 13]] + byteToHex$1[arr[offset + 14]] + byteToHex$1[arr[offset + 15]]; } -function stringify$3(arr, offset = 0) { +function stringify$2(arr, offset = 0) { const uuid = unsafeStringify$1(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields - if (!validate$2(uuid)) { + if (!validate$1(uuid)) { throw TypeError('Stringified UUID is invalid'); } @@ -140839,34 +140845,34 @@ function stringify$3(arr, offset = 0) { // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html -let _nodeId$2; +let _nodeId$1; -let _clockseq$2; // Previous uuid creation time +let _clockseq$1; // Previous uuid creation time -let _lastMSecs$2 = 0; -let _lastNSecs$2 = 0; // See https://github.com/uuidjs/uuid for API details +let _lastMSecs$1 = 0; +let _lastNSecs$1 = 0; // See https://github.com/uuidjs/uuid for API details -function v1$2(options, buf, offset) { +function v1$1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; - let node = options.node || _nodeId$2; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq$2; // node and clockseq need to be initialized to random values if they're not + let node = options.node || _nodeId$1; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq$1; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || rng$2)(); + const seedBytes = options.random || (options.rng || rng$1)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId$2 = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + node = _nodeId$1 = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq$2 = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + clockseq = _clockseq$1 = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so @@ -140877,9 +140883,9 @@ function v1$2(options, buf, offset) { let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs$2 + 1; // Time since last uuid creation (in msecs) + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs$1 + 1; // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs$2 + (nsecs - _lastNSecs$2) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + const dt = msecs - _lastMSecs$1 + (nsecs - _lastNSecs$1) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; @@ -140887,7 +140893,7 @@ function v1$2(options, buf, offset) { // time interval - if ((dt < 0 || msecs > _lastMSecs$2) && options.nsecs === undefined) { + if ((dt < 0 || msecs > _lastMSecs$1) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested @@ -140896,9 +140902,9 @@ function v1$2(options, buf, offset) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } - _lastMSecs$2 = msecs; - _lastNSecs$2 = nsecs; - _clockseq$2 = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + _lastMSecs$1 = msecs; + _lastNSecs$1 = nsecs; + _clockseq$1 = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` @@ -140927,8 +140933,8 @@ function v1$2(options, buf, offset) { return buf || unsafeStringify$1(b); } -function parse$3(uuid) { - if (!validate$2(uuid)) { +function parse$2(uuid) { + if (!validate$1(uuid)) { throw TypeError('Invalid UUID'); } @@ -140959,7 +140965,7 @@ function parse$3(uuid) { return arr; } -function stringToBytes$2(str) { +function stringToBytes$1(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; @@ -140971,18 +140977,18 @@ function stringToBytes$2(str) { return bytes; } -const DNS$2 = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL$3 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35$2(name, version, hashfunc) { +const DNS$1 = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +const URL$2 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35$1(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === 'string') { - value = stringToBytes$2(value); + value = stringToBytes$1(value); } if (typeof namespace === 'string') { - namespace = parse$3(namespace); + namespace = parse$2(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { @@ -141018,8 +141024,8 @@ function v35$2(name, version, hashfunc) { } catch (err) {} // For CommonJS default export support - generateUUID.DNS = DNS$2; - generateUUID.URL = URL$3; + generateUUID.DNS = DNS$1; + generateUUID.URL = URL$2; return generateUUID; } @@ -141043,7 +141049,7 @@ function v35$2(name, version, hashfunc) { * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ -function md5$2(bytes) { +function md5$1(bytes) { if (typeof bytes === 'string') { const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape @@ -141054,14 +141060,14 @@ function md5$2(bytes) { } } - return md5ToHexEncodedArray$2(wordsToMd5$2(bytesToWords$2(bytes), bytes.length * 8)); + return md5ToHexEncodedArray$1(wordsToMd5$1(bytesToWords$1(bytes), bytes.length * 8)); } /* * Convert an array of little-endian words to an array of bytes */ -function md5ToHexEncodedArray$2(input) { +function md5ToHexEncodedArray$1(input) { const output = []; const length32 = input.length * 32; const hexTab = '0123456789abcdef'; @@ -141079,7 +141085,7 @@ function md5ToHexEncodedArray$2(input) { */ -function getOutputLength$2(inputLength8) { +function getOutputLength$1(inputLength8) { return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; } /* @@ -141087,10 +141093,10 @@ function getOutputLength$2(inputLength8) { */ -function wordsToMd5$2(x, len) { +function wordsToMd5$1(x, len) { /* append padding */ x[len >> 5] |= 0x80 << len % 32; - x[getOutputLength$2(len) - 1] = len; + x[getOutputLength$1(len) - 1] = len; let a = 1732584193; let b = -271733879; let c = -1732584194; @@ -141101,74 +141107,74 @@ function wordsToMd5$2(x, len) { const oldb = b; const oldc = c; const oldd = d; - a = md5ff$2(a, b, c, d, x[i], 7, -680876936); - d = md5ff$2(d, a, b, c, x[i + 1], 12, -389564586); - c = md5ff$2(c, d, a, b, x[i + 2], 17, 606105819); - b = md5ff$2(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5ff$2(a, b, c, d, x[i + 4], 7, -176418897); - d = md5ff$2(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5ff$2(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5ff$2(b, c, d, a, x[i + 7], 22, -45705983); - a = md5ff$2(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5ff$2(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5ff$2(c, d, a, b, x[i + 10], 17, -42063); - b = md5ff$2(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5ff$2(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5ff$2(d, a, b, c, x[i + 13], 12, -40341101); - c = md5ff$2(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5ff$2(b, c, d, a, x[i + 15], 22, 1236535329); - a = md5gg$2(a, b, c, d, x[i + 1], 5, -165796510); - d = md5gg$2(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5gg$2(c, d, a, b, x[i + 11], 14, 643717713); - b = md5gg$2(b, c, d, a, x[i], 20, -373897302); - a = md5gg$2(a, b, c, d, x[i + 5], 5, -701558691); - d = md5gg$2(d, a, b, c, x[i + 10], 9, 38016083); - c = md5gg$2(c, d, a, b, x[i + 15], 14, -660478335); - b = md5gg$2(b, c, d, a, x[i + 4], 20, -405537848); - a = md5gg$2(a, b, c, d, x[i + 9], 5, 568446438); - d = md5gg$2(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5gg$2(c, d, a, b, x[i + 3], 14, -187363961); - b = md5gg$2(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5gg$2(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5gg$2(d, a, b, c, x[i + 2], 9, -51403784); - c = md5gg$2(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5gg$2(b, c, d, a, x[i + 12], 20, -1926607734); - a = md5hh$2(a, b, c, d, x[i + 5], 4, -378558); - d = md5hh$2(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5hh$2(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5hh$2(b, c, d, a, x[i + 14], 23, -35309556); - a = md5hh$2(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5hh$2(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5hh$2(c, d, a, b, x[i + 7], 16, -155497632); - b = md5hh$2(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5hh$2(a, b, c, d, x[i + 13], 4, 681279174); - d = md5hh$2(d, a, b, c, x[i], 11, -358537222); - c = md5hh$2(c, d, a, b, x[i + 3], 16, -722521979); - b = md5hh$2(b, c, d, a, x[i + 6], 23, 76029189); - a = md5hh$2(a, b, c, d, x[i + 9], 4, -640364487); - d = md5hh$2(d, a, b, c, x[i + 12], 11, -421815835); - c = md5hh$2(c, d, a, b, x[i + 15], 16, 530742520); - b = md5hh$2(b, c, d, a, x[i + 2], 23, -995338651); - a = md5ii$2(a, b, c, d, x[i], 6, -198630844); - d = md5ii$2(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5ii$2(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5ii$2(b, c, d, a, x[i + 5], 21, -57434055); - a = md5ii$2(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5ii$2(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5ii$2(c, d, a, b, x[i + 10], 15, -1051523); - b = md5ii$2(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5ii$2(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5ii$2(d, a, b, c, x[i + 15], 10, -30611744); - c = md5ii$2(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5ii$2(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5ii$2(a, b, c, d, x[i + 4], 6, -145523070); - d = md5ii$2(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5ii$2(c, d, a, b, x[i + 2], 15, 718787259); - b = md5ii$2(b, c, d, a, x[i + 9], 21, -343485551); - a = safeAdd$2(a, olda); - b = safeAdd$2(b, oldb); - c = safeAdd$2(c, oldc); - d = safeAdd$2(d, oldd); + a = md5ff$1(a, b, c, d, x[i], 7, -680876936); + d = md5ff$1(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff$1(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff$1(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff$1(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff$1(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff$1(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff$1(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff$1(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff$1(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff$1(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff$1(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff$1(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff$1(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff$1(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff$1(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg$1(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg$1(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg$1(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg$1(b, c, d, a, x[i], 20, -373897302); + a = md5gg$1(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg$1(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg$1(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg$1(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg$1(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg$1(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg$1(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg$1(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg$1(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg$1(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg$1(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg$1(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh$1(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh$1(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh$1(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh$1(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh$1(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh$1(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh$1(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh$1(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh$1(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh$1(d, a, b, c, x[i], 11, -358537222); + c = md5hh$1(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh$1(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh$1(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh$1(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh$1(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh$1(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii$1(a, b, c, d, x[i], 6, -198630844); + d = md5ii$1(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii$1(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii$1(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii$1(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii$1(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii$1(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii$1(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii$1(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii$1(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii$1(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii$1(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii$1(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii$1(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii$1(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii$1(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd$1(a, olda); + b = safeAdd$1(b, oldb); + c = safeAdd$1(c, oldc); + d = safeAdd$1(d, oldd); } return [a, b, c, d]; @@ -141179,13 +141185,13 @@ function wordsToMd5$2(x, len) { */ -function bytesToWords$2(input) { +function bytesToWords$1(input) { if (input.length === 0) { return []; } const length8 = input.length * 8; - const output = new Uint32Array(getOutputLength$2(length8)); + const output = new Uint32Array(getOutputLength$1(length8)); for (let i = 0; i < length8; i += 8) { output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; @@ -141199,7 +141205,7 @@ function bytesToWords$2(input) { */ -function safeAdd$2(x, y) { +function safeAdd$1(x, y) { const lsw = (x & 0xffff) + (y & 0xffff); const msw = (x >> 16) + (y >> 16) + (lsw >> 16); return msw << 16 | lsw & 0xffff; @@ -141209,7 +141215,7 @@ function safeAdd$2(x, y) { */ -function bitRotateLeft$2(num, cnt) { +function bitRotateLeft$1(num, cnt) { return num << cnt | num >>> 32 - cnt; } /* @@ -141217,40 +141223,40 @@ function bitRotateLeft$2(num, cnt) { */ -function md5cmn$2(q, a, b, x, s, t) { - return safeAdd$2(bitRotateLeft$2(safeAdd$2(safeAdd$2(a, q), safeAdd$2(x, t)), s), b); +function md5cmn$1(q, a, b, x, s, t) { + return safeAdd$1(bitRotateLeft$1(safeAdd$1(safeAdd$1(a, q), safeAdd$1(x, t)), s), b); } -function md5ff$2(a, b, c, d, x, s, t) { - return md5cmn$2(b & c | ~b & d, a, b, x, s, t); +function md5ff$1(a, b, c, d, x, s, t) { + return md5cmn$1(b & c | ~b & d, a, b, x, s, t); } -function md5gg$2(a, b, c, d, x, s, t) { - return md5cmn$2(b & d | c & ~d, a, b, x, s, t); +function md5gg$1(a, b, c, d, x, s, t) { + return md5cmn$1(b & d | c & ~d, a, b, x, s, t); } -function md5hh$2(a, b, c, d, x, s, t) { - return md5cmn$2(b ^ c ^ d, a, b, x, s, t); +function md5hh$1(a, b, c, d, x, s, t) { + return md5cmn$1(b ^ c ^ d, a, b, x, s, t); } -function md5ii$2(a, b, c, d, x, s, t) { - return md5cmn$2(c ^ (b | ~d), a, b, x, s, t); +function md5ii$1(a, b, c, d, x, s, t) { + return md5cmn$1(c ^ (b | ~d), a, b, x, s, t); } -const v3$2 = v35$2('v3', 0x30, md5$2); +const v3$1 = v35$1('v3', 0x30, md5$1); const randomUUID$1 = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); var native$1 = { randomUUID: randomUUID$1 }; -function v4$2(options, buf, offset) { +function v4$1(options, buf, offset) { if (native$1.randomUUID && !buf && !options) { return native$1.randomUUID(); } options = options || {}; - const rnds = options.random || (options.rng || rng$2)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + const rnds = options.random || (options.rng || rng$1)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided @@ -141270,7 +141276,7 @@ function v4$2(options, buf, offset) { // Adapted from Chris Veness' SHA1 code at // http://www.movable-type.co.uk/scripts/sha1.html -function f$2(s, x, y, z) { +function f$1(s, x, y, z) { switch (s) { case 0: return x & y ^ ~x & z; @@ -141286,11 +141292,11 @@ function f$2(s, x, y, z) { } } -function ROTL$2(x, n) { +function ROTL$1(x, n) { return x << n | x >>> 32 - n; } -function sha1$2(bytes) { +function sha1$1(bytes) { const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; @@ -141334,7 +141340,7 @@ function sha1$2(bytes) { } for (let t = 16; t < 80; ++t) { - W[t] = ROTL$2(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + W[t] = ROTL$1(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); } let a = H[0]; @@ -141345,10 +141351,10 @@ function sha1$2(bytes) { for (let t = 0; t < 80; ++t) { const s = Math.floor(t / 20); - const T = ROTL$2(a, 5) + f$2(s, b, c, d) + e + K[s] + W[t] >>> 0; + const T = ROTL$1(a, 5) + f$1(s, b, c, d) + e + K[s] + W[t] >>> 0; e = d; d = c; - c = ROTL$2(b, 30) >>> 0; + c = ROTL$1(b, 30) >>> 0; b = a; a = T; } @@ -141363,32 +141369,32 @@ function sha1$2(bytes) { return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; } -const v5$2 = v35$2('v5', 0x50, sha1$2); +const v5$1 = v35$1('v5', 0x50, sha1$1); -var nil$2 = '00000000-0000-0000-0000-000000000000'; +var nil$1 = '00000000-0000-0000-0000-000000000000'; -function version$4(uuid) { - if (!validate$2(uuid)) { +function version$3(uuid) { + if (!validate$1(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.slice(14, 15), 16); } -var esmBrowser$2 = /*#__PURE__*/Object.freeze({ +var esmBrowser$1 = /*#__PURE__*/Object.freeze({ __proto__: null, - NIL: nil$2, - parse: parse$3, - stringify: stringify$3, - v1: v1$2, - v3: v3$2, - v4: v4$2, - v5: v5$2, - validate: validate$2, - version: version$4 + NIL: nil$1, + parse: parse$2, + stringify: stringify$2, + v1: v1$1, + v3: v3$1, + v4: v4$1, + v5: v5$1, + validate: validate$1, + version: version$3 }); -var require$$9 = /*@__PURE__*/getAugmentedNamespace(esmBrowser$2); +var require$$9 = /*@__PURE__*/getAugmentedNamespace(esmBrowser$1); var interceptor = {}; @@ -141965,7 +141971,7 @@ function requireSrc$c () { var jsonBigint = {exports: {}}; -var stringify$2 = {exports: {}}; +var stringify$1 = {exports: {}}; var bignumber$1 = {exports: {}}; @@ -144901,7 +144907,7 @@ function requireBignumber () { var hasRequiredStringify; function requireStringify () { - if (hasRequiredStringify) return stringify$2.exports; + if (hasRequiredStringify) return stringify$1.exports; hasRequiredStringify = 1; (function (module) { var BigNumber = requireBignumber(); @@ -145281,15 +145287,15 @@ function requireStringify () { }; } }()); - } (stringify$2)); - return stringify$2.exports; + } (stringify$1)); + return stringify$1.exports; } -var parse$2; +var parse$1; var hasRequiredParse; function requireParse () { - if (hasRequiredParse) return parse$2; + if (hasRequiredParse) return parse$1; hasRequiredParse = 1; var BigNumber = null; @@ -145731,8 +145737,8 @@ function requireParse () { }; }; - parse$2 = json_parse; - return parse$2; + parse$1 = json_parse; + return parse$1; } var hasRequiredJsonBigint; @@ -147330,9 +147336,9 @@ function requireOptions$1 () { return options$1; } -var version$3 = "9.15.1"; +var version$2 = "9.15.1"; var require$$4 = { - version: version$3}; + version: version$2}; var hasRequiredTransporters; @@ -154814,604 +154820,6 @@ function requireSrc$8 () { return src$b; } -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -var getRandomValues$1; -var rnds8$1 = new Uint8Array(16); -function rng$1() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues$1) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues$1 = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - - if (!getRandomValues$1) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues$1(rnds8$1); -} - -var REGEX$1 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; - -function validate$1(uuid) { - return typeof uuid === 'string' && REGEX$1.test(uuid); -} - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - -var byteToHex$1 = []; - -for (var i = 0; i < 256; ++i) { - byteToHex$1.push((i + 0x100).toString(16).substr(1)); -} - -function stringify$1(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex$1[arr[offset + 0]] + byteToHex$1[arr[offset + 1]] + byteToHex$1[arr[offset + 2]] + byteToHex$1[arr[offset + 3]] + '-' + byteToHex$1[arr[offset + 4]] + byteToHex$1[arr[offset + 5]] + '-' + byteToHex$1[arr[offset + 6]] + byteToHex$1[arr[offset + 7]] + '-' + byteToHex$1[arr[offset + 8]] + byteToHex$1[arr[offset + 9]] + '-' + byteToHex$1[arr[offset + 10]] + byteToHex$1[arr[offset + 11]] + byteToHex$1[arr[offset + 12]] + byteToHex$1[arr[offset + 13]] + byteToHex$1[arr[offset + 14]] + byteToHex$1[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!validate$1(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -var _nodeId$1; - -var _clockseq$1; // Previous uuid creation time - - -var _lastMSecs$1 = 0; -var _lastNSecs$1 = 0; // See https://github.com/uuidjs/uuid for API details - -function v1$1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || new Array(16); - options = options || {}; - var node = options.node || _nodeId$1; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq$1; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || rng$1)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId$1 = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq$1 = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs$1 + 1; // Time since last uuid creation (in msecs) - - var dt = msecs - _lastMSecs$1 + (nsecs - _lastNSecs$1) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs$1) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs$1 = msecs; - _lastNSecs$1 = nsecs; - _clockseq$1 = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf || stringify$1(b); -} - -function parse$1(uuid) { - if (!validate$1(uuid)) { - throw TypeError('Invalid UUID'); - } - - var v; - var arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -function stringToBytes$1(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - var bytes = []; - - for (var i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -var DNS$1 = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -var URL$2 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35$1 (name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes$1(value); - } - - if (typeof namespace === 'string') { - namespace = parse$1(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - var bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return stringify$1(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS$1; - generateUUID.URL = URL$2; - return generateUUID; -} - -/* - * Browser-compatible JavaScript MD5 - * - * Modification of JavaScript MD5 - * https://github.com/blueimp/JavaScript-MD5 - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * https://opensource.org/licenses/MIT - * - * Based on - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ -function md5$1(bytes) { - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = new Uint8Array(msg.length); - - for (var i = 0; i < msg.length; ++i) { - bytes[i] = msg.charCodeAt(i); - } - } - - return md5ToHexEncodedArray$1(wordsToMd5$1(bytesToWords$1(bytes), bytes.length * 8)); -} -/* - * Convert an array of little-endian words to an array of bytes - */ - - -function md5ToHexEncodedArray$1(input) { - var output = []; - var length32 = input.length * 32; - var hexTab = '0123456789abcdef'; - - for (var i = 0; i < length32; i += 8) { - var x = input[i >> 5] >>> i % 32 & 0xff; - var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); - output.push(hex); - } - - return output; -} -/** - * Calculate output length with padding and bit length - */ - - -function getOutputLength$1(inputLength8) { - return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; -} -/* - * Calculate the MD5 of an array of little-endian words, and a bit length. - */ - - -function wordsToMd5$1(x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << len % 32; - x[getOutputLength$1(len) - 1] = len; - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - a = md5ff$1(a, b, c, d, x[i], 7, -680876936); - d = md5ff$1(d, a, b, c, x[i + 1], 12, -389564586); - c = md5ff$1(c, d, a, b, x[i + 2], 17, 606105819); - b = md5ff$1(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5ff$1(a, b, c, d, x[i + 4], 7, -176418897); - d = md5ff$1(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5ff$1(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5ff$1(b, c, d, a, x[i + 7], 22, -45705983); - a = md5ff$1(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5ff$1(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5ff$1(c, d, a, b, x[i + 10], 17, -42063); - b = md5ff$1(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5ff$1(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5ff$1(d, a, b, c, x[i + 13], 12, -40341101); - c = md5ff$1(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5ff$1(b, c, d, a, x[i + 15], 22, 1236535329); - a = md5gg$1(a, b, c, d, x[i + 1], 5, -165796510); - d = md5gg$1(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5gg$1(c, d, a, b, x[i + 11], 14, 643717713); - b = md5gg$1(b, c, d, a, x[i], 20, -373897302); - a = md5gg$1(a, b, c, d, x[i + 5], 5, -701558691); - d = md5gg$1(d, a, b, c, x[i + 10], 9, 38016083); - c = md5gg$1(c, d, a, b, x[i + 15], 14, -660478335); - b = md5gg$1(b, c, d, a, x[i + 4], 20, -405537848); - a = md5gg$1(a, b, c, d, x[i + 9], 5, 568446438); - d = md5gg$1(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5gg$1(c, d, a, b, x[i + 3], 14, -187363961); - b = md5gg$1(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5gg$1(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5gg$1(d, a, b, c, x[i + 2], 9, -51403784); - c = md5gg$1(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5gg$1(b, c, d, a, x[i + 12], 20, -1926607734); - a = md5hh$1(a, b, c, d, x[i + 5], 4, -378558); - d = md5hh$1(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5hh$1(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5hh$1(b, c, d, a, x[i + 14], 23, -35309556); - a = md5hh$1(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5hh$1(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5hh$1(c, d, a, b, x[i + 7], 16, -155497632); - b = md5hh$1(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5hh$1(a, b, c, d, x[i + 13], 4, 681279174); - d = md5hh$1(d, a, b, c, x[i], 11, -358537222); - c = md5hh$1(c, d, a, b, x[i + 3], 16, -722521979); - b = md5hh$1(b, c, d, a, x[i + 6], 23, 76029189); - a = md5hh$1(a, b, c, d, x[i + 9], 4, -640364487); - d = md5hh$1(d, a, b, c, x[i + 12], 11, -421815835); - c = md5hh$1(c, d, a, b, x[i + 15], 16, 530742520); - b = md5hh$1(b, c, d, a, x[i + 2], 23, -995338651); - a = md5ii$1(a, b, c, d, x[i], 6, -198630844); - d = md5ii$1(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5ii$1(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5ii$1(b, c, d, a, x[i + 5], 21, -57434055); - a = md5ii$1(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5ii$1(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5ii$1(c, d, a, b, x[i + 10], 15, -1051523); - b = md5ii$1(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5ii$1(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5ii$1(d, a, b, c, x[i + 15], 10, -30611744); - c = md5ii$1(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5ii$1(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5ii$1(a, b, c, d, x[i + 4], 6, -145523070); - d = md5ii$1(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5ii$1(c, d, a, b, x[i + 2], 15, 718787259); - b = md5ii$1(b, c, d, a, x[i + 9], 21, -343485551); - a = safeAdd$1(a, olda); - b = safeAdd$1(b, oldb); - c = safeAdd$1(c, oldc); - d = safeAdd$1(d, oldd); - } - - return [a, b, c, d]; -} -/* - * Convert an array bytes to an array of little-endian words - * Characters >255 have their high-byte silently ignored. - */ - - -function bytesToWords$1(input) { - if (input.length === 0) { - return []; - } - - var length8 = input.length * 8; - var output = new Uint32Array(getOutputLength$1(length8)); - - for (var i = 0; i < length8; i += 8) { - output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; - } - - return output; -} -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - - -function safeAdd$1(x, y) { - var lsw = (x & 0xffff) + (y & 0xffff); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 0xffff; -} -/* - * Bitwise rotate a 32-bit number to the left. - */ - - -function bitRotateLeft$1(num, cnt) { - return num << cnt | num >>> 32 - cnt; -} -/* - * These functions implement the four basic operations the algorithm uses. - */ - - -function md5cmn$1(q, a, b, x, s, t) { - return safeAdd$1(bitRotateLeft$1(safeAdd$1(safeAdd$1(a, q), safeAdd$1(x, t)), s), b); -} - -function md5ff$1(a, b, c, d, x, s, t) { - return md5cmn$1(b & c | ~b & d, a, b, x, s, t); -} - -function md5gg$1(a, b, c, d, x, s, t) { - return md5cmn$1(b & d | c & ~d, a, b, x, s, t); -} - -function md5hh$1(a, b, c, d, x, s, t) { - return md5cmn$1(b ^ c ^ d, a, b, x, s, t); -} - -function md5ii$1(a, b, c, d, x, s, t) { - return md5cmn$1(c ^ (b | ~d), a, b, x, s, t); -} - -var v3$1 = v35$1('v3', 0x30, md5$1); - -function v4$1(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng$1)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return stringify$1(rnds); -} - -// Adapted from Chris Veness' SHA1 code at -// http://www.movable-type.co.uk/scripts/sha1.html -function f$1(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; - - case 1: - return x ^ y ^ z; - - case 2: - return x & y ^ x & z ^ y & z; - - case 3: - return x ^ y ^ z; - } -} - -function ROTL$1(x, n) { - return x << n | x >>> 32 - n; -} - -function sha1$1(bytes) { - var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - if (typeof bytes === 'string') { - var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = []; - - for (var i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); - } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } - - bytes.push(0x80); - var l = bytes.length / 4 + 2; - var N = Math.ceil(l / 16); - var M = new Array(N); - - for (var _i = 0; _i < N; ++_i) { - var arr = new Uint32Array(16); - - for (var j = 0; j < 16; ++j) { - arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; - } - - M[_i] = arr; - } - - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - - for (var _i2 = 0; _i2 < N; ++_i2) { - var W = new Uint32Array(80); - - for (var t = 0; t < 16; ++t) { - W[t] = M[_i2][t]; - } - - for (var _t = 16; _t < 80; ++_t) { - W[_t] = ROTL$1(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); - } - - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - for (var _t2 = 0; _t2 < 80; ++_t2) { - var s = Math.floor(_t2 / 20); - var T = ROTL$1(a, 5) + f$1(s, b, c, d) + e + K[s] + W[_t2] >>> 0; - e = d; - d = c; - c = ROTL$1(b, 30) >>> 0; - b = a; - a = T; - } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; -} - -var v5$1 = v35$1('v5', 0x50, sha1$1); - -var nil$1 = '00000000-0000-0000-0000-000000000000'; - -function version$2(uuid) { - if (!validate$1(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.substr(14, 1), 16); -} - -var esmBrowser$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - NIL: nil$1, - parse: parse$1, - stringify: stringify$1, - v1: v1$1, - v3: v3$1, - v4: v4$1, - v5: v5$1, - validate: validate$1, - version: version$2 -}); - -var require$$6 = /*@__PURE__*/getAugmentedNamespace(esmBrowser$1); - var util$2 = {}; var src$6 = {}; @@ -158025,13 +157433,17 @@ var packageJsonHelper = {}; var name = "@google-cloud/storage"; var description = "Cloud Storage Client Library for Node.js"; -var version = "7.19.0"; +var version = "7.21.0"; var license = "Apache-2.0"; var author = "Google Inc."; var engines = { node: ">=14" }; -var repository = "googleapis/nodejs-storage"; +var repository = { + type: "git", + directory: "handwritten/storage", + url: "https://github.com/googleapis/google-cloud-node.git" +}; var main = "./build/cjs/src/index.js"; var types = "./build/cjs/src/index.d.ts"; var type$1 = "module"; @@ -158075,7 +157487,6 @@ var scripts = { "compile:esm": "tsc -p .", compile: "npm run compile:cjs && npm run compile:esm", "conformance-test": "mocha --parallel build/cjs/conformance-test/ --require build/cjs/conformance-test/globalHooks.js", - "docs-test": "linkinator docs", docs: "jsdoc -c .jsdoc.json", fix: "gts fix", lint: "gts check", @@ -158083,7 +157494,6 @@ var scripts = { "postcompile:cjs": "babel --plugins gapic-tools/build/src/replaceImportMetaUrl,gapic-tools/build/src/toggleESMFlagVariable build/cjs/src/util.js -o build/cjs/src/util.js && cp internal-tooling/helpers/package.cjs.json build/cjs/package.json", precompile: "rm -rf build/", "preconformance-test": "npm run compile:cjs -- --sourceMap", - "predocs-test": "npm run docs", predocs: "npm run compile:cjs -- --sourceMap", prelint: "cd samples; npm link ../; npm install", prepare: "npm run compile", @@ -158093,7 +157503,7 @@ var scripts = { "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", "system-test:esm": "mocha build/esm/system-test --timeout 600000 --exit", "system-test": "mocha build/cjs/system-test --timeout 600000 --exit", - test: "c8 mocha build/cjs/test" + test: "cross-env NODE_OPTIONS='--no-deprecation' c8 mocha build/cjs/test" }; var dependencies = { "@google-cloud/paginator": "^5.0.0", @@ -158109,8 +157519,7 @@ var dependencies = { mime: "^3.0.0", "p-limit": "^3.0.1", "retry-request": "^7.0.0", - "teeny-request": "^9.0.0", - uuid: "^8.0.0" + "teeny-request": "^9.0.0" }; var devDependencies = { "@babel/cli": "^7.22.10", @@ -158129,7 +157538,6 @@ var devDependencies = { "@types/request": "^2.48.4", "@types/sinon": "^17.0.0", "@types/tmp": "0.2.6", - "@types/uuid": "^8.0.0", "@types/yargs": "^17.0.10", c8: "^9.0.0", "form-data": "^4.0.4", @@ -158138,7 +157546,6 @@ var devDependencies = { jsdoc: "^4.0.4", "jsdoc-fresh": "^5.0.0", "jsdoc-region-tag": "^4.0.0", - linkinator: "^3.0.0", mocha: "^9.2.2", mockery: "^2.1.0", nock: "~13.5.0", @@ -158150,8 +157557,10 @@ var devDependencies = { "path-to-regexp": "6.3.0", tmp: "^0.2.0", typescript: "^5.1.6", - yargs: "^17.3.1" + yargs: "^17.3.1", + "cross-env": "^7.0.3" }; +var homepage = "https://github.com/googleapis/google-cloud-node/tree/main/handwritten/storage"; var require$$0$3 = { name: name, description: description, @@ -158168,7 +157577,8 @@ var require$$0$3 = { keywords: keywords, scripts: scripts, dependencies: dependencies, - devDependencies: devDependencies + devDependencies: devDependencies, + homepage: homepage }; var hasRequiredPackageJsonHelper; @@ -158277,6 +157687,8 @@ function requireUtil$2 () { util$1.getUserAgentString = getUserAgentString; util$1.getDirName = getDirName; util$1.getModuleFormat = getModuleFormat; + util$1.validateContexts = validateContexts; + util$1.handleContextValidation = handleContextValidation; __importStar(path__default); const querystring = __importStar(require$$1$1); const stream_1 = require$$0__default$2; @@ -158483,6 +157895,41 @@ function requireUtil$2 () { } } util$1.PassThroughShim = PassThroughShim; + /** + * Validates Object Contexts for forbidden characters. + * Double quotes (") are forbidden in context keys and values as they + * interfere with GCS filter string syntax. + * + * @param {FileMetadata['contexts']} contexts The contexts object to validate. + * @returns {void} Throws an error if validation fails. + */ + function validateContexts(contexts) { + const custom = contexts === null || contexts === void 0 ? void 0 : contexts.custom; + if (!custom) return; + for (const [key, context] of Object.entries(custom)) { + if (key.includes('"')) { + throw new Error(`Invalid context key "${key}": Forbidden character (") detected.`); + } + if ((context === null || context === void 0 ? void 0 : context.value) && context.value.includes('"')) { + throw new Error(`Invalid context value for key "${key}": Forbidden character (") detected.`); + } + } + } + /** + * Helper to validate contexts and route errors to either a callback or a Promise. + * @param contexts The contexts to validate. + * @param callback The optional user-provided callback. + */ + function handleContextValidation(contexts, callback) { + try { + validateContexts(contexts); + } catch (err) { + if (callback) { + return callback(err); + } + return Promise.reject(err); + } + } return util$1; } @@ -162100,7 +161547,7 @@ function requireUtil$1 () { const retry_request_1 = __importDefault(requireRetryRequest()); const stream_1 = require$$0__default$2; const teeny_request_1 = requireSrc$5(); - const uuid = __importStar(require$$6); + const crypto = __importStar(crypto__default); const service_js_1 = requireService$2(); const util_js_1 = requireUtil$2(); const duplexify_1 = __importDefault(requireDuplexify()); @@ -162720,7 +162167,7 @@ function requireUtil$1 () { _getDefaultHeaders(gcclGcsCmd) { const headers = { 'User-Agent': (0, util_js_1.getUserAgentString)(), - 'x-goog-api-client': `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${uuid.v4()}`, + 'x-goog-api-client': `${(0, util_js_1.getRuntimeTrackingString)()} gccl/${packageJson.version}-${(0, util_js_1.getModuleFormat)()} gccl-invocation-id/${crypto.randomUUID()}`, }; if (gcclGcsCmd) { headers['x-goog-api-client'] += ` gccl-gcs-cmd/${gcclGcsCmd}`; @@ -162809,7 +162256,7 @@ function requireService$2 () { * limitations under the License. */ const google_auth_library_1 = requireSrc$8(); - const uuid = __importStar(require$$6); + const crypto = __importStar(crypto__default); const util_js_1 = requireUtil$1(); const util_js_2 = requireUtil$2(); exports.DEFAULT_PROJECT_ID_TOKEN = '{{projectId}}'; @@ -162941,7 +162388,7 @@ function requireService$2 () { reqOpts.headers = { ...reqOpts.headers, 'User-Agent': userAgent, - 'x-goog-api-client': `${(0, util_js_2.getRuntimeTrackingString)()} gccl/${pkg.version}-${(0, util_js_2.getModuleFormat)()} gccl-invocation-id/${uuid.v4()}`, + 'x-goog-api-client': `${(0, util_js_2.getRuntimeTrackingString)()} gccl/${pkg.version}-${(0, util_js_2.getModuleFormat)()} gccl-invocation-id/${crypto.randomUUID()}`, }; if (reqOpts[util_js_1.GCCL_GCS_CMD_KEY]) { reqOpts.headers['x-goog-api-client'] += @@ -166659,7 +166106,7 @@ function requireResumableUpload () { const google_auth_library_1 = requireSrc$8(); const stream_1 = require$$0__default$2; const async_retry_1 = __importDefault(requireLib()); - const uuid = __importStar(require$$6); + const crypto = __importStar(crypto__default); const util_js_1 = requireUtil$2(); const util_js_2 = requireUtil$1(); const file_js_1 = requireFile$1(); @@ -166679,9 +166126,9 @@ function requireResumableUpload () { this.numBytesWritten = 0; this.numRetries = 0; this.currentInvocationId = { - checkUploadStatus: uuid.v4(), - chunk: uuid.v4(), - uri: uuid.v4(), + checkUploadStatus: crypto.randomUUID(), + chunk: crypto.randomUUID(), + uri: crypto.randomUUID(), }; /** * A cache of buffers written to this instance, ready for consuming @@ -167048,7 +166495,7 @@ function requireResumableUpload () { try { const res = await this.makeRequest(reqOpts); // We have successfully got a URI we can now create a new invocation id - this.currentInvocationId.uri = uuid.v4(); + this.currentInvocationId.uri = crypto.randomUUID(); return res.headers.location; } catch (err) { @@ -167243,7 +166690,7 @@ function requireResumableUpload () { return; } // At this point we can safely create a new id for the chunk - this.currentInvocationId.chunk = uuid.v4(); + this.currentInvocationId.chunk = crypto.randomUUID(); const moreDataToUpload = await this.waitForNextChunk(); const shouldContinueWithNextMultiChunkRequest = this.chunkSize && resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && @@ -167342,7 +166789,7 @@ function requireResumableUpload () { try { const resp = await this.makeRequest(opts); // Successfully got the offset we can now create a new offset invocation id - this.currentInvocationId.checkUploadStatus = uuid.v4(); + this.currentInvocationId.checkUploadStatus = crypto.randomUUID(); return resp; } catch (e) { @@ -167992,7 +167439,7 @@ function requireFile$1 () { }; var _File_instances, _File_validateIntegrity; Object.defineProperty(file$1, "__esModule", { value: true }); - file$1.File = file$1.FileExceptionMessages = file$1.RequestError = file$1.STORAGE_POST_POLICY_BASE_URL = file$1.ActionToHTTPMethod = void 0; + file$1.File = file$1.FileExceptionMessages = file$1.RequestError = file$1.SkipReason = file$1.STORAGE_POST_POLICY_BASE_URL = file$1.ActionToHTTPMethod = void 0; const index_js_1 = requireNodejsCommon(); const promisify_1 = requireSrc$4(); const crypto = __importStar(crypto__default); @@ -168043,6 +167490,13 @@ function requireFile$1 () { ] .map(r => r.source) .join(''), 'i'); + var SkipReason; + (function (SkipReason) { + SkipReason["PATH_TRAVERSAL"] = "PATH_TRAVERSAL"; + SkipReason["ILLEGAL_CHARACTER"] = "ILLEGAL_CHARACTER"; + SkipReason["ALREADY_EXISTS"] = "ALREADY_EXISTS"; + SkipReason["DOWNLOAD_ERROR"] = "DOWNLOAD_ERROR"; + })(SkipReason || (file$1.SkipReason = SkipReason = {})); class RequestError extends Error { } file$1.RequestError = RequestError; @@ -168749,6 +168203,11 @@ function requireFile$1 () { else if (optionsOrCallback) { options = { ...optionsOrCallback }; } + if (options.contexts) { + const validationError = (0, util_js_2.handleContextValidation)(options.contexts, callback); + if (validationError) + return validationError; + } callback = callback || index_js_1.util.noop; let destBucket; let destName; @@ -170120,7 +169579,11 @@ function requireFile$1 () { fields['policy'] = policyBase64; fields['x-goog-signature'] = signatureHex; let url; - if (this.storage.customEndpoint) { + const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST; + if (this.storage.customEndpoint && typeof EMULATOR_HOST === 'string') { + url = `${this.storage.apiEndpoint}/${this.bucket.name}`; + } + else if (this.storage.customEndpoint) { url = this.storage.apiEndpoint; } else if (options.virtualHostedStyle) { @@ -171141,10 +170604,13 @@ function requireFile$1 () { * ``` */ save(data, optionsOrCallback, callback) { - // tslint:enable:no-any + var _a; callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const validationError = (0, util_js_2.handleContextValidation)((_a = options.metadata) === null || _a === void 0 ? void 0 : _a.contexts, callback); + if (validationError) + return validationError; let maxRetries = this.storage.retryOptions.maxRetries; if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) { maxRetries = 0; @@ -171215,6 +170681,9 @@ function requireFile$1 () { typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + const validationError = (0, util_js_2.handleContextValidation)(metadata.contexts, cb); + if (validationError) + return validationError; this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, bucket_js_1.AvailableServiceObjectMethods.setMetadata, options); super .setMetadata(metadata, options) @@ -172843,6 +172312,25 @@ function requireBucket () { * }, function(err, apiResponse) {}); * * //- + * // Enforce CMEK-only encryption for new objects. + * // This blocks Google-Managed and Customer-Supplied keys. + * //- + * bucket.setMetadata({ + * encryption: { + * defaultKmsKeyName: 'projects/grape-spaceship-123/...', + * googleManagedEncryptionEnforcementConfig: { + * restrictionMode: 'FullyRestricted' + * }, + * customerSuppliedEncryptionEnforcementConfig: { + * restrictionMode: 'FullyRestricted' + * }, + * customerManagedEncryptionEnforcementConfig: { + * restrictionMode: 'NotRestricted' + * } + * } + * }, function(err, apiResponse) {}); + * + * //- * // Set the default event-based hold value for new objects in this * // bucket. * //- @@ -173221,6 +172709,11 @@ function requireBucket () { else if (optionsOrCallback) { options = optionsOrCallback; } + if (options.contexts) { + const validationError = (0, util_js_1.handleContextValidation)(options.contexts, callback); + if (validationError) + return validationError; + } this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, // Not relevant but param is required AvailableServiceObjectMethods.setMetadata, // Same as above options); @@ -173262,6 +172755,7 @@ function requireBucket () { destination: { contentType: destinationFile.metadata.contentType, contentEncoding: destinationFile.metadata.contentEncoding, + contexts: options.contexts || destinationFile.metadata.contexts, }, sourceObjects: sources.map(source => { const sourceObject = { @@ -174064,6 +173558,10 @@ function requireBucket () { * in addition to the relevant part of the object name appearing in prefixes[]. * @property {string} [prefix] Filter results to objects whose names begin * with this prefix. + * @property {string} [filter] Filter results using a server-side filter + * expression. This is primarily used for filtering by Object Contexts. + * Syntax: `contexts.""=""` or `contexts."":*`. + * Prepend `-` for negation (e.g., `-contexts."key":*`). * @property {string} [matchGlob] A glob pattern used to filter results, * for example foo*bar * @property {number} [maxApiCalls] Maximum number of API calls to make. @@ -174111,6 +173609,9 @@ function requireBucket () { * in addition to the relevant part of the object name appearing in prefixes[]. * @param {string} [query.prefix] Filter results to objects whose names begin * with this prefix. + * @param {string} [query.filter] Filter results using a server-side filter + * expression. Supports Object Contexts with operators like `=`, `:`, + * and `-` for negation. * @param {number} [query.maxApiCalls] Maximum number of API calls to make. * @param {number} [query.maxResults] Maximum number of items plus prefixes to * return per call. @@ -174130,6 +173631,7 @@ function requireBucket () { * billed for the request. * @param {boolean} [query.versions] If true, returns File objects scoped to * their versions. + * * @param {GetFilesCallback} [callback] Callback function. * @returns {Promise} * @@ -174223,6 +173725,31 @@ function requireBucket () { * }); * ``` * + * @example + * //- + * // Filter files using Object Contexts. + * //- + * ``` + * const query = { + * filter: 'contexts."status"="active"' + * }; + * bucket.getFiles(query, function(err, files) { + * if (!err) { + * // files only contains objects with the 'status' context set to 'active'. + * } + * }); + * + * //- + * // You can also filter by the absence of a context key. + * //- + * + * bucket.getFiles({ + * filter: '-contexts."priority":*' + * }, function(err, files) { + * // files contains objects that DO NOT have the 'priority' context key. + * }); + * ``` + * * @example include:samples/files.js * region_tag:storage_list_files * Another example: @@ -177354,7 +176881,7 @@ var hasRequiredFxp; function requireFxp () { if (hasRequiredFxp) return fxp.exports; hasRequiredFxp = 1; - (()=>{var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:true,get:n[i]});},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:true});}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ie,XMLParser:()=>Lt,XMLValidator:()=>se});const n=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)h+=t[r];if(h=h.trim(),"/"===h[h.length-1]&&(h=h.substring(0,h.length-1),r--),!E(h)){let e;return e=0===h.trim().length?"Invalid space after '<'.":"Tag '"+h+"' is an invalid name.",b("InvalidTag",e,w(t,r))}const l=g(t,r);if(false===l)return b("InvalidAttr","Attributes for '"+h+"' have open quote.",w(t,r));let d=l.value;if(r=l.index,"/"===d[d.length-1]){const n=r-d.length;d=d.substring(0,d.length-1);const s=x(d,e);if(true!==s)return b(s.err.code,s.err.msg,w(t,n+s.err.line));i=true;}else if(a){if(!l.tagClosed)return b("InvalidTag","Closing tag '"+h+"' doesn't have proper closing.",w(t,r));if(d.trim().length>0)return b("InvalidTag","Closing tag '"+h+"' can't have attributes or invalid starting.",w(t,o));if(0===n.length)return b("InvalidTag","Closing tag '"+h+"' has not been opened.",w(t,o));{const e=n.pop();if(h!==e.tagName){let n=w(t,e.tagStartPos);return b("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+h+"'.",w(t,o))}0==n.length&&(s=true);}}else {const a=x(d,e);if(true!==a)return b(a.err.code,a.err.msg,w(t,r-d.length+a.err.line));if(true===s)return b("InvalidXml","Multiple possible root nodes found.",w(t,r));-1!==e.unpairedTags.indexOf(h)||n.push({tagName:h,tagStartPos:o}),i=true;}for(r++;r0)||b("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):b("InvalidXml","Start tag expected.",1)}function u(t){return " "===t||"\t"===t||"\n"===t||"\r"===t}function p(t,e){const n=e;for(;e5&&"xml"===i)return b("InvalidXml","XML declaration allowed only at the start of the document.",w(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function c(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function g(t,e){let n="",i="",s=false;for(;e"===t[e]&&""===i){s=true;break}n+=t[e];}return ""===i&&{value:n,index:e,tagClosed:s}}const m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function x(t,e){const n=s(t,m),i={};for(let t=0;to.includes(t)?"__"+t:t,_={preserveOrder:false,attributeNamePrefix:"@_",attributesGroupName:false,textNodeName:"#text",ignoreAttributes:true,removeNSPrefix:false,allowBooleanAttributes:false,parseTagValue:true,parseAttributeValue:false,trimValues:true,cdataPropName:false,numberParseOptions:{hex:true,leadingZeros:true,eNotation:true},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:false,isArray:()=>false,commentPropName:false,unpairedTags:[],processEntities:true,htmlEntities:false,entityDecoder:null,ignoreDeclaration:false,ignorePiTags:false,transformTagName:false,transformAttributeName:false,updateTag:function(t,e,n){return t},captureMetaData:false,maxNestedTags:100,strictReservedNames:true,jPath:true,onDangerousProperty:S};function A(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(o.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(a.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function T(t,e){return "boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:false!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:T(true)}const C=function(t){const e=Object.assign({},_,t),n=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of n)t&&A(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=S),e.processEntities=T(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let P;P="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class ${constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null);}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e});}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][P]={startIndex:e});}static getMetaDataSymbol(){return P}}const O=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",I=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",V=I+"\\-\\.\\d·̀-ͯ҇‿-⁀",D=(t,e,n="")=>{const i=`[${t.replace(":","")}][${e.replace(":","")}]*`;return {name:new RegExp(`^[${t}][${e}]*$`,n),ncName:new RegExp(`^${i}$`,n),qName:new RegExp(`^${i}(?::${i})?$`,n),nmToken:new RegExp(`^[${e}]+$`,n),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,n)}},M=D(O,O+"\\-\\.\\d·̀-ͯ‿-⁀"),j=D(I,V,"u"),L=(t,{xmlVersion:e="1.0"}={})=>((t="1.0")=>"1.1"===t?j:M)(e).qName.test(t);class k{constructor(t,e){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=e||1;}setXmlVersion(t=1){this.xmlVersion=t;}readDocType(t,e){const n=Object.create(null);let i=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,r=false,o=false,a="";for(;e"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=false,s--):s--,0===s)break}else "["===t[e]?r=true:a+=t[e];else {if(r&&F(t,"!ENTITY",e)){let s,r;if(e+=7,[s,r,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===r.indexOf("&")){if(false!==this.options.enabled&&null!=this.options.maxEntityCount&&i>=this.options.maxEntityCount)throw new Error(`Entity count (${i+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);n[s]=r,i++;}}else if(r&&F(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n;}else if(r&&F(t,"!ATTLIST",e))e+=8;else if(r&&F(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n;}else {if(!F(t,"!--",e))throw new Error("Invalid DOCTYPE");o=true;}s++,a="";}if(0!==s)throw new Error("Unclosed DOCTYPE")}return {entities:n,i:e}}readEntityExp(t,e){const n=e=R(t,e);for(;ethis.options.maxEntitySize)throw new Error(`Entity "${i}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return [i,s,--e]}readNotationExp(t,e){const n=e=R(t,e);for(;e{for(;e0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return false;const n=e[e.length-1];return void 0!==n.values&&t in n.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=true){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class J{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new Z(this);}push(t,e=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const i=this.path.length;this.siblingStacks[i]||(this.siblingStacks[i]=new Map);const s=this.siblingStacks[i],r=n?`${n}:${t}`:t,o=s.get(r)||0;let a=0;for(const t of s.values())a+=t;s.set(r,o+1);const h={tag:t,position:a,counter:o};null!=n&&(h.namespace=n),null!=e&&(h.values=e),this.path.push(h);}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t);}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return false;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=true){const n=t||this.separator;if(n===this.separator&&true===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[];}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return false;for(let e=0;e=0&&e>=0;){const i=t[n];if("deep-wildcard"===i.type){if(n--,n<0)return true;const i=t[n];let s=false;for(let t=e;t>=0;t--)if(this._matchSegment(i,this.path[t],t===this.path.length-1)){e=t-1,n--,s=true;break}if(!s)return false}else {if(!this._matchSegment(i,this.path[e],e===this.path.length-1))return false;e--,n--;}}return n<0}_matchSegment(t,e,n){if("*"!==t.tag&&t.tag!==e.tag)return false;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return false;if(void 0!==t.attrName){if(!n)return false;if(!e.values||!(t.attrName in e.values))return false;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return false}if(void 0!==t.position){if(!n)return false;const i=e.counter??0;if("first"===t.position&&0!==i)return false;if("odd"===t.position&&i%2!=1)return false;if("even"===t.position&&i%2!=0)return false;if("nth"===t.position&&i!==t.positionValue)return false}return true}matchesAny(t){return t.matchesAny(this)}snapshot(){return {path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t));}readOnly(){return this._view}}class K{constructor(t,e={},n){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=n,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position);}_parse(t){const e=[];let n=0,i="";for(;n",lt:"<",quot:'"'},et={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},nt=new Set("!?\\\\/[]$%{}^&*()<>|+");function it(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(nt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function st(...t){const e=Object.create(null);for(const n of t)if(n)for(const t of Object.keys(n)){const i=n[t];if("string"==typeof i)e[t]=i;else if(i&&"object"==typeof i&&void 0!==i.val){const n=i.val;"string"==typeof n&&(e[t]=n);}}return e}const rt="external",ot="base",at="all",ht=Object.freeze({allow:0,leave:1,remove:2,throw:3}),lt=new Set([9,10,13]);class ut{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??rt)&&e!==rt?e===at?new Set([at]):e===ot?new Set([ot]):Array.isArray(e)?new Set(e):new Set([rt]):new Set([rt]),this._numericAllowed=t.numericAllowed??true,this._baseMap=st(tt,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const n=function(t){if(!t)return {xmlVersion:1,onLevel:ht.allow,nullLevel:ht.remove};const e=1.1===t.xmlVersion?1.1:1,n=ht[t.onNCR]??ht.allow,i=ht[t.nullNCR]??ht.remove;return {xmlVersion:e,onLevel:n,nullLevel:Math.max(i,ht.remove)}}(t.ncr);this._ncrXmlVersion=n.xmlVersion,this._ncrOnLevel=n.onLevel,this._ncrNullLevel=n.nullLevel;}setExternalEntities(t){if(t)for(const e of Object.keys(t))it(e);this._externalMap=st(t);}addExternalEntity(t,e){it(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e);}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=st(t);}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1;}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,n=[],i=t.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,h=o||a;for(;r=i||59!==t.charCodeAt(e)){r++;continue}const l=t.slice(r+1,e);if(0===l.length){r++;continue}let u,p;if(this._removeSet.has(l))u="",void 0===p&&(p=rt);else {if(this._leaveSet.has(l)){r++;continue}if(35===l.charCodeAt(0)){const t=this._resolveNCR(l);if(void 0===t){r++;continue}u=t,p=ot;}else {const t=this._resolveName(l);u=t?.value,p=t?.tier;}}if(void 0!==u){if(r>s&&n.push(t.slice(s,r)),n.push(u),s=e+1,r=s,h&&this._tierCounts(p)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=u.length-(l.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++;}s=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!lt.has(t)?ht.remove:-1}_applyNCRAction(t,e,n){switch(t){case ht.allow:return String.fromCodePoint(n);case ht.remove:return "";case ht.leave:return;case ht.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${n.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(n)}}_resolveNCR(t){const e=t.charCodeAt(1);let n;if(n=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(n)||n<0||n>1114111)return;const i=this._classifyNCR(n);if(!this._numericAllowed&&i0){const n=t.substring(0,e);if("xmlns"!==n)return n}}class dt{constructor(t,e){var n;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Nt,this.parseTextData=ft,this.resolveNameSpace=gt,this.buildAttributesMap=xt,this.isItStopNode=wt,this.replaceEntitiesValue=yt,this.readStopNodeData=At,this.saveTextToParentTag=Et,this.addChild=bt,this.ignoreAttributesFn="function"==typeof(n=this.options.ignoreAttributes)?n:Array.isArray(n)?t=>{for(const e of n){if("string"==typeof e&&t===e)return true;if(e instanceof RegExp&&e.test(t))return true}}:()=>false,this.entityExpansionCount=0,this.currentExpandedLength=0;let i={...tt};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?i=this.options.htmlEntities:true===this.options.htmlEntities&&(i={...et,...H}),this.entityDecoder=new ut({namedEntities:{...i,...e},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new J,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=false,this.stopNodeExpressionsSet=new Q;const s=this.options.stopNodes;if(s&&s.length>0){for(let t=0;t0)){o||(t=this.replaceEntitiesValue(t,e,n));const i=a.jPath?n.toString():n,h=a.tagValueProcessor(e,t,i,s,r);return null==h?t:typeof h!=typeof t||h!==t?h:a.trimValues||t.trim()===t?Tt(t,a.parseTagValue,a.numberParseOptions):t}}function gt(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return "";2===e.length&&(t=n+e[1]);}return t}const mt=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function xt(t,e,n,i=false){const r=this.options;if(true===i||true!==r.ignoreAttributes&&"string"==typeof t){const i=s(t,mt),o=i.length,a={},h=new Array(o);let l=false;const u={};for(let t=0;t",a,"Closing Tag is not closed.");let r=t.substring(a+2,e).trim();if(s.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1));}r=Ct(s.transformTagName,r,"",s).tagName,n&&(i=this.saveTextToParentTag(i,n,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(r&&s.unpairedTagsSet.has(r))throw new Error(`Unpaired tag can not be used as closing tag: `);o&&s.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=false,n=this.tagsNodeStack.pop(),i="",a=e;}else if(63===h){let e=_t(t,a,false,"?>");if(!e)throw new Error("Pi Tag is not closed.");i=this.saveTextToParentTag(i,n,this.readonlyMatcher);const o=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName,true);if(o){const t=o[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(t)||1),r.setXmlVersion(Number(t)||1);}if(s.ignoreDeclaration&&"?xml"===e.tagName||s.ignorePiTags);else {const t=new $(e.tagName);t.add(s.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&true!==s.ignoreAttributes&&(t[":@"]=o),this.addChild(n,t,this.readonlyMatcher,a);}a=e.closeIndex+1;}else if(33===h&&45===t.charCodeAt(a+2)&&45===t.charCodeAt(a+3)){const e=vt(t,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=t.substring(a+4,e-2);i=this.saveTextToParentTag(i,n,this.readonlyMatcher),n.add(s.commentPropName,[{[s.textNodeName]:r}]);}a=e;}else if(33===h&&68===t.charCodeAt(a+2)){const e=r.readDocType(t,a);this.entityDecoder.addInputEntities(e.entities),a=e.i;}else if(33===h&&91===t.charCodeAt(a+2)){const e=vt(t,"]]>",a,"CDATA is not closed.")-2,r=t.substring(a+9,e);i=this.saveTextToParentTag(i,n,this.readonlyMatcher);let o=this.parseTextData(r,n.tagname,this.readonlyMatcher,true,false,true,true);null==o&&(o=""),s.cdataPropName?n.add(s.cdataPropName,[{[s.textNodeName]:r}]):n.add(s.textNodeName,o),a=e+2;}else {let r=_t(t,a,s.removeNSPrefix);if(!r){const e=t.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${e}"`)}let h=r.tagName;const l=r.rawTagName;let u=r.tagExp,p=r.attrExpPresent,c=r.closeIndex;if(({tagName:h,tagExp:u}=Ct(s.transformTagName,h,u,s)),s.strictReservedNames&&(h===s.commentPropName||h===s.cdataPropName||h===s.textNodeName||h===s.attributesGroupName))throw new Error(`Invalid tag name: ${h}`);n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,this.readonlyMatcher,false));const d=n;d&&s.unpairedTagsSet.has(d.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let f=false;u.length>0&&u.lastIndexOf("/")===u.length-1&&(f=true,"/"===h[h.length-1]?(h=h.substr(0,h.length-1),u=h):u=u.substr(0,u.length-1),p=h!==u);let g,m=null;g=ct(l),h!==e.tagname&&this.matcher.push(h,{},g),h!==u&&p&&(m=this.buildAttributesMap(u,this.matcher,h),m&&(pt(m,s))),h!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const N=a;if(this.isCurrentNodeStopNode){let e="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(h))a=r.closeIndex;else {const n=this.readStopNodeData(t,l,c+1);if(!n)throw new Error(`Unexpected end of ${l}`);a=n.i,e=n.tagContent;}const i=new $(h);m&&(i[":@"]=m),i.add(s.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=false,this.addChild(n,i,this.readonlyMatcher,N);}else {if(f){({tagName:h,tagExp:u}=Ct(s.transformTagName,h,u,s));const t=new $(h);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),this.matcher.pop(),this.isCurrentNodeStopNode=false;}else {if(s.unpairedTagsSet.has(h)){const t=new $(h);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),this.matcher.pop(),this.isCurrentNodeStopNode=false,a=r.closeIndex;continue}{const t=new $(h);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,N),n=t;}}i="",a=c;}}}else i+=t[a];return e.child};function bt(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.jPath?n.toString():n,r=this.options.updateTag(e.tagname,s,e[":@"]);false===r||("string"==typeof r?(e.tagname=r,t.addChild(e,i)):t.addChild(e,i));}function yt(t,e,n){const i=this.options.processEntities;if(!i||!i.enabled)return t;if(i.allowedTags){const s=this.options.jPath?n.toString():n;if(!(Array.isArray(i.allowedTags)?i.allowedTags.includes(e):i.allowedTags(e,s)))return t}if(i.tagFilter){const s=this.options.jPath?n.toString():n;if(!i.tagFilter(e,s))return t}return this.entityDecoder.decode(t)}function Et(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,false,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function wt(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function vt(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function St(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s}function _t(t,e,n,i=">"){const s=function(t,e,n=">"){let i=0;const s=t.length,r=n.charCodeAt(0),o=n.length>1?n.charCodeAt(1):-1;let a="",h=e;for(let n=e;n",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return {tagContent:t.substring(i,n),i:r};n=r;}else if(63===r)n=vt(t,"?>",n+1,"StopNode is not closed.");else if(33===r&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=vt(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===r&&91===t.charCodeAt(n+2))n=vt(t,"]]>",n,"StopNode is not closed.")-2;else {const i=_t(t,n,false);i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex);}}}function Tt(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return "true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},X,e),!t||"string"!=typeof t)return t;let n=t.trim();if(0===n.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===n)return 0;if(e.hex&&U.test(n))return q(n,16);if(e.binary&&B.test(n))return q(n,2);if(e.octal&&W.test(n))return q(n,8);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(Y);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:(1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r)&&o.length>0?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=z.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const h=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!h))return t;{const i=Number(n),s=String(i);if(0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return "0"===s||s===a||s===`${r}${a}`?i:t;let h=o?a:n;return o?h===s||r+h===s?i:t:h===s||h===r+s?i:t}}return t}}var i;return function(t,e,n){const i=e===1/0;switch(n.infinity.toLowerCase()){case "null":return null;case "infinity":return e;case "string":return i?"Infinity":"-Infinity";default:return t}}(t,Number(n),e)}(t,n)}return void 0!==t?t:""}function Ct(t,e,n,i){if(t){const i=t(e);n===e&&(n=i),e=i;}return {tagName:e=Pt(e,i),tagExp:n}}function Pt(t,e){if(a.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return o.includes(t)?e.onDangerousProperty(t):t}const $t=$.getMetaDataSymbol();function Ot(t,e){if(!t||"object"!=typeof t)return {};if(!e)return t;const n={};for(const i in t)i.startsWith(e)?n[i.substring(e.length)]=t[i]:n[i]=t[i];return n}function It(t,e,n,i){return Vt(t,e,n,i)}function Vt(t,e,n,i){let s;const r={};for(let o=0;o0&&(r[e.textNodeName]=s):void 0!==s&&(r[e.textNodeName]=s),r}function Dt(t){const e=Object.keys(t);for(let t=0;t/g,"]]]]>")}function Ft(t){return String(t).replace(/"/g,""").replace(/'/g,"'")}function Gt(t,e,n,i,s){return n.sanitizeName?L(t,{xmlVersion:s})?t:n.sanitizeName(t,{isAttribute:e,matcher:i.readOnly()}):t}function Ut(t,e){let n="";e.format&&(n="\n");const i=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;te.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let n=t.toString();return n=Jt(n,e),n}return ""}for(let h=0;h`,a=false,i.pop();continue}if(p===e.commentPropName){o+=n+`\x3c!--${kt(l[u][0][e.textNodeName])}--\x3e`,a=true,i.pop();continue}if("?"===p[0]){o+=("?xml"===p?"":n)+`<${p}${qt(l[":@"],e,d,i,r)}?>`,a=true,i.pop();continue}let f=n;""!==f&&(f+=e.indentBy);const g=n+`<${p}${qt(l[":@"],e,d,i,r)}`;let m;m=d?zt(l[u],e):Bt(l[u],e,f,i,s,r),-1!==e.unpairedTags.indexOf(p)?e.suppressUnpairedNode?o+=g+">":o+=g+"/>":m&&0!==m.length||!e.suppressEmptyNode?m&&m.endsWith(">")?o+=g+`>${m}${n}`:(o+=g+">",m&&""!==n&&(m.includes("/>")||m.includes("`):o+=g+"/>",a=true,i.pop();}return o}function Wt(t,e){if(!t||e.ignoreAttributes)return null;const n={};let i=false;for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s.startsWith(e.attributeNamePrefix)?s.substr(e.attributeNamePrefix.length):s]=Ft(t[s]),i=true);return i?n:null}function zt(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let n="";for(let i=0;i${i}`:n+=`<${r}${t}/>`;}}}return n}function Xt(t,e){let n="";if(t&&!e.ignoreAttributes)for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i];true===s&&e.suppressBooleanAttributes?n+=` ${i.substr(e.attributeNamePrefix.length)}`:n+=` ${i.substr(e.attributeNamePrefix.length)}="${Ft(s)}"`;}return n}function Yt(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:true,stopNodes:[],oneListGroup:false,maxNestedTags:100,jPath:true,sanitizeName:false};function Qt(t){if(this.options=Object.assign({},Kt,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t{for(const n of e){if("string"==typeof n&&t===n)return true;if(n instanceof RegExp&&n.test(t))return true}}:()=>false,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ne),this.processTextOrObjNode=te,this.options.format?(this.indentate=ee,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return ""},this.tagEndChar=">",this.newLine="");}function Ht(t,e,n,i,s){return n.sanitizeName?L(t,{xmlVersion:s})?t:n.sanitizeName(t,{isAttribute:e,matcher:i.readOnly()}):t}function te(t,e,n,i,s){const r=this.extractAttributes(t);if(i.push(e,r),this.checkStopNode(i)){const s=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return i.pop(),this.buildObjectNode(s,e,r,n)}const o=this.j2x(t,n+1,i,s);return i.pop(),"?"===e[0]?this.buildTextValNode("",e,o.attrStr,n,i):void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,o.attrStr,n,i):this.buildObjectNode(o.val,e,o.attrStr,n)}function ee(t){return this.options.indentBy.repeat(t)}function ne(t){return !(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}Qt.prototype.build=function(t){if(this.options.preserveOrder)return Ut(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new J,n=function(t,e){const n=t["?xml"];if(n&&"object"==typeof n){if(e.attributesGroupName&&n[e.attributesGroupName]){const t=n[e.attributesGroupName][e.attributeNamePrefix+"version"];if(t)return t}const t=n[e.attributeNamePrefix+"version"];if(t)return t}return "1.0"}(t,this.options);return this.j2x(t,0,e,n).val}},Qt.prototype.j2x=function(t,e,n,i){let s="",r="";if(this.options.maxNestedTags&&n.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const o=this.options.jPath?n.toString():n,a=this.checkStopNode(n);for(let h in t){if(!Object.prototype.hasOwnProperty.call(t,h))continue;const l=h===this.options.textNodeName||h===this.options.cdataPropName||h===this.options.commentPropName||this.options.attributesGroupName&&h===this.options.attributesGroupName||this.isAttribute(h)||"?"===h[0]?h:Ht(h,false,this.options,n,i);if(void 0===t[h])this.isAttribute(h)&&(r+="");else if(null===t[h])this.isAttribute(h)||l===this.options.cdataPropName||l===this.options.commentPropName?r+="":"?"===l[0]?r+=this.indentate(e)+"<"+l+"?"+this.tagEndChar:r+=this.indentate(e)+"<"+l+"/"+this.tagEndChar;else if(t[h]instanceof Date)r+=this.buildTextValNode(t[h],l,"",e,n);else if("object"!=typeof t[h]){const u=this.isAttribute(h);if(u&&!this.ignoreAttributesFn(u,o)){const e=Ht(u,true,this.options,n,i);s+=this.buildAttrPairStr(e,""+t[h],a);}else if(!u)if(h===this.options.textNodeName){let e=this.options.tagValueProcessor(h,""+t[h]);r+=this.replaceEntitiesValue(e);}else {n.push(l);const i=this.checkStopNode(n);if(n.pop(),i){const n=""+t[h];r+=""===n?this.indentate(e)+"<"+l+this.closeTag(l)+this.tagEndChar:this.indentate(e)+"<"+l+">"+n+""+t+"${t}`;else if("object"==typeof t&&null!==t){const i=this.buildRawContent(t),s=this.buildAttributesForStopNode(t);e+=""===i?`<${n}${s}/>`:`<${n}${s}>${i}`;}}else if("object"==typeof i&&null!==i){const t=this.buildRawContent(i),s=this.buildAttributesForStopNode(i);e+=""===t?`<${n}${s}/>`:`<${n}${s}>${t}`;}else e+=`<${n}>${i}`;}return e},Qt.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return "";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const n=t[this.options.attributesGroupName];for(let t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;const i=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,s=n[t];true===s&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+s+'"';}}else for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const i=this.isAttribute(n);if(i){const s=t[n];true===s&&this.options.suppressBooleanAttributes?e+=" "+i:e+=" "+i+'="'+s+'"';}}return e},Qt.prototype.buildObjectNode=function(t,e,n,i){if(""===t)return "?"===e[0]?this.indentate(i)+"<"+e+n+"?"+this.tagEndChar:this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=""+t+s}},Qt.prototype.closeTag=function(t){let e="";return -1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine}if(false!==this.options.commentPropName&&e===this.options.commentPropName){const e=kt(t);return this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e{var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:true,get:i[n]});},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:true});}},e={};t.r(e),t.d(e,{XMLBuilder:()=>Oe,XMLParser:()=>re,XMLValidator:()=>je});const i=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=new RegExp("^["+i+"]["+i+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function r(t,e){const i=[];let n=e.exec(t);for(;n;){const r=[];r.startIndex=e.lastIndex-n[0].length;const s=n.length;for(let t=0;t"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)l+=t[s];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),s--),!E(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",y("InvalidTag",e,w(t,s))}const p=g(t,s);if(false===p)return y("InvalidAttr","Attributes for '"+l+"' have open quote.",w(t,s));let u=p.value;if(s=p.index,"/"===u[u.length-1]){const i=s-u.length;u=u.substring(0,u.length-1);const r=x(u,e);if(true!==r)return y(r.err.code,r.err.msg,w(t,i+r.err.line));n=true;}else if(a){if(!p.tagClosed)return y("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",w(t,s));if(u.trim().length>0)return y("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",w(t,o));if(0===i.length)return y("InvalidTag","Closing tag '"+l+"' has not been opened.",w(t,o));{const e=i.pop();if(l!==e.tagName){let i=w(t,e.tagStartPos);return y("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",w(t,o))}0==i.length&&(r=true);}}else {const a=x(u,e);if(true!==a)return y(a.err.code,a.err.msg,w(t,s-u.length+a.err.line));if(true===r)return y("InvalidXml","Multiple possible root nodes found.",w(t,s));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=true;}for(s++;s0)||y("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):y("InvalidXml","Start tag expected.",1)}function c(t){return " "===t||"\t"===t||"\n"===t||"\r"===t}function h(t,e){const i=e;for(;e5&&"xml"===n)return y("InvalidXml","XML declaration allowed only at the start of the document.",w(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function d(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const u='"',f="'";function g(t,e){let i="",n="",r=false;for(;e"===t[e]&&""===n){r=true;break}i+=t[e];}return ""===n&&{value:i,index:e,tagClosed:r}}const m=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function x(t,e){const i=r(t,m),n={};for(let t=0;to.includes(t)?"__"+t:t,A={preserveOrder:false,attributeNamePrefix:"@_",attributesGroupName:false,textNodeName:"#text",ignoreAttributes:true,removeNSPrefix:false,allowBooleanAttributes:false,parseTagValue:true,parseAttributeValue:false,trimValues:true,cdataPropName:false,numberParseOptions:{hex:true,leadingZeros:true,eNotation:true,unicode:false},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:false,isArray:()=>false,commentPropName:false,unpairedTags:[],processEntities:true,htmlEntities:false,entityDecoder:null,ignoreDeclaration:false,ignorePiTags:false,transformTagName:false,transformAttributeName:false,updateTag:function(t,e,i){return t},captureMetaData:false,maxNestedTags:100,strictReservedNames:true,jPath:true,onDangerousProperty:S};function T(t,e){if("string"!=typeof t)return;const i=t.toLowerCase();if(o.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(a.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function _(t,e){return "boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:false!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:_(true)}const C=function(t){const e=Object.assign({},A,t),i=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of i)t&&T(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=S),e.processEntities=_(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let $;$="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class P{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null);}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e});}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][$]={startIndex:e});}static getMetaDataSymbol(){return $}}const O=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�",j=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿",I=j+"\\-\\.\\d·̀-ͯ҇‿-⁀",k=(t,e,i="")=>{const n=`[${t.replace(":","")}][${e.replace(":","")}]*`;return {name:new RegExp(`^[${t}][${e}]*$`,i),ncName:new RegExp(`^${n}$`,i),qName:new RegExp(`^${n}(?::${n})?$`,i),nmToken:new RegExp(`^[${e}]+$`,i),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,i)}},L=k(O,O+"\\-\\.\\d·̀-ͯ‿-⁀"),D=k(j,I,"u"),R=":A-Za-z_",M=k(R,R+"\\-\\.\\d"),V=(t,{xmlVersion:e="1.0",asciiOnly:i=false}={})=>((t="1.0",e=false)=>e?M:"1.1"===t?D:L)(e,i).qName.test(t);class q{constructor(t,e){this.suppressValidationErr=!t,this.options=t,this.xmlVersion=e||1;}setXmlVersion(t=1){this.xmlVersion=t;}readDocType(t,e){const i=Object.create(null);let n=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let r=1,s=false,o=false,a="";for(;e"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=false,r--):r--,0===r)break}else "["===t[e]?s=true:a+=t[e];else {if(s&&U(t,"!ENTITY",e)){let r,s;if(e+=7,[r,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){if(false!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);i[r]=s,n++;}}else if(s&&U(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i;}else if(s&&U(t,"!ATTLIST",e))e+=8;else if(s&&U(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i;}else {if(!U(t,"!--",e))throw new Error("Invalid DOCTYPE");o=true;}r++,a="";}if(0!==r)throw new Error("Unclosed DOCTYPE")}return {entities:i,i:e}}readEntityExp(t,e){const i=e=F(t,e);for(;ethis.options.maxEntitySize)throw new Error(`Entity "${n}" size (${r.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return [n,r,--e]}readNotationExp(t,e){const i=e=F(t,e);for(;e{for(;e=48&&r<=57||45===r))if(r=55296&&r<=56319){if(n+1=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320);if(X.has(t)){i=n;break}}}}else if(255!==z[r-W]||Y.has(r)){i=n;break}}if(-1===i)return t;const n=[];i>0&&n.push(t.slice(0,i));for(let r=i;r=48&&i<=57||45===i){n.push(t[r]);continue}if(i=55296&&i<=56319){if(r+1=56320&&e<=57343){const t=65536+(i-55296<<10)+(e-56320),s=X.get(t);if(void 0!==s){n.push(String.fromCharCode(s+48)),r++;continue}}}n.push(t[r]);continue}if(Y.has(i)){n.push("-");continue}const s=z[i-W];n.push(255!==s?String.fromCharCode(s+48):t[r]);}return n.join("")}(i),"0"===i))return 0;if(e.hex&&H.test(i))return it(i,16);if(e.binary&&Q.test(i))return it(i,2);if(e.octal&&J.test(i))return it(i,8);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(et);if(n){let r=n[1]||"";const s=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=r?t[o.length+1]===s:t[o.length]===s;return o.length>1&&a?t:(1!==o.length||!n[3].startsWith(`.${s}`)&&n[3][0]!==s)&&o.length>0?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const r=Z.exec(i);if(r){const s=r[1]||"",o=r[2];let a=(n=r[3])&&-1!==n.indexOf(".")?("."===(n=n.replace(/0+$/,""))?n="0":"."===n[0]?n="0"+n:"."===n[n.length-1]&&(n=n.substring(0,n.length-1)),n):n;const l=s?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const n=Number(i),r=String(n);if(0===n)return n;if(-1!==r.search(/[eE]/))return e.eNotation?n:t;if(-1!==i.indexOf("."))return "0"===r||r===a||r===`${s}${a}`?n:t;let l=o?a:i;return o?l===r||s+l===r?n:t:l===r||l===s+r?n:t}}return t}}var n;return function(t,e,i){const n=e===1/0;switch(i.infinity.toLowerCase()){case "null":return null;case "infinity":return e;case "string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(i),e)}const et=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function it(t,e){const i=t.trim();if(2!==e&&8!==e||(t=i.substring(2)),parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}class nt{constructor(t){this._matcher=t;}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return false;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=true){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class rt{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new nt(this),this._keptAttrs=[];}push(t,e=null,i=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;let s=this.siblingStacks[r];s||(s={counts:new Map,total:0},this.siblingStacks[r]=s);const o=i?`${i}:${t}`:t,a=s.counts.get(o)||0,l=s.total;s.counts.set(o,a+1),s.total++;const p={tag:t,position:l,counter:a};null!=i&&(p.namespace=i),null!=e&&(p.values=e),this.path.push(p);const c=this.path.length,h=null!==n?n.keep:null;if(null!=h&&h.length>0&&e)for(let t=0;tthis.path.length+1&&(this.siblingStacks.length=this.path.length+1);const e=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=e;)this._keptAttrs.pop();return t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t);}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return false;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getAnyParentAttr(t){const e=this._keptAttrs;for(let i=e.length-1;i>=0;i--)if(e[i].name===t)return e[i].value}hasAnyParentAttr(t){const e=this._keptAttrs;for(let i=e.length-1;i>=0;i--)if(e[i].name===t)return true;return false}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=true){const i=t||this.separator;if(i===this.separator&&true===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(i)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[];}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return false;for(let e=0;e=0&&e>=0;){const n=t[i];if("deep-wildcard"===n.type){if(i--,i<0)return true;const n=t[i];let r=false;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,i--,r=true;break}if(!r)return false}else {if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return false;e--,i--;}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return false;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return false;if(void 0!==t.attrName){if(!i)return false;if(!e.values||!(t.attrName in e.values))return false;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return false}if(void 0!==t.position){if(!i)return false;const n=e.counter??0;if("first"===t.position&&0!==n)return false;if("odd"===t.position&&n%2!=1)return false;if("even"===t.position&&n%2!=0)return false;if("nth"===t.position&&n!==t.positionValue)return false}return true}matchesAny(t){return t.matchesAny(this)}snapshot(){return {path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),this._keptAttrs=(t.keptAttrs||[]).map(t=>({...t}));}readOnly(){return this._view}}class st{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position);}_parse(t){const e=[];let i=0,n="";for(;i",lt:"<",quot:'"'},pt={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},ct=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),ht=new Set("!?\\\\/[]$%{}^&*()<>|+");function dt(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(ht.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function ut(...t){const e=Object.create(null);for(const i of t)if(i)for(const t of Object.keys(i)){const n=i[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(e[t]=i);}}return e}const ft="external",gt="base",mt="all",xt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),bt=new Set([9,10,13]);class yt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??ft)&&e!==ft?e===mt?new Set([mt]):e===gt?new Set([gt]):Array.isArray(e)?new Set(e):new Set([ft]):new Set([ft]),this._numericAllowed=t.numericAllowed??true,this._baseMap=ut(lt,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const i=function(t){if(!t)return {xmlVersion:1,onLevel:xt.allow,nullLevel:xt.remove};const e=1.1===t.xmlVersion?1.1:1,i=xt[t.onNCR]??xt.allow,n=xt[t.nullNCR]??xt.remove;return {xmlVersion:e,onLevel:i,nullLevel:Math.max(n,xt.remove)}}(t.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null;}_applyRegistrationHook(t,e,i,n){if(!t)return true;const r=t(e,i);if(r===ct.BLOCK)return false;if(r===ct.THROW)throw new Error(`[EntityDecoder] Registration of ${n} entity "&${e};" was rejected by hook`);return true}setExternalEntities(t){if(t)for(const e of Object.keys(t))dt(e);if(!this._onExternalEntity)return void(this._externalMap=ut(t));const e=ut(t),i=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,n,"external")&&(i[t]=n);this._externalMap=i;}addExternalEntity(t,e){dt(t),"string"==typeof e&&-1===e.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,t,e,"external")&&(this._externalMap[t]=e);}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=ut(t));const e=ut(t),i=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,n,"input")&&(i[t]=n);this._inputMap=i;}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1;}decode(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t,i=[],n=t.length;let r=0,s=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;s=n||59!==t.charCodeAt(e)){s++;continue}const p=t.slice(s+1,e);if(0===p.length){s++;continue}let c,h;if(this._removeSet.has(p))c="",void 0===h&&(h=ft);else {if(this._leaveSet.has(p)){s++;continue}if(35===p.charCodeAt(0)){const t=this._resolveNCR(p);if(void 0===t){s++;continue}c=t,h=gt;}else {const t=this._resolveName(p);c=t?.value,h=t?.tier;}}if(void 0!==c){if(s>r&&i.push(t.slice(r,s)),i.push(c),r=e+1,s=r,l&&this._tierCounts(h)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=c.length-(p.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++;}r=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!bt.has(t)?xt.remove:-1}_applyNCRAction(t,e,i){switch(t){case xt.allow:return String.fromCodePoint(i);case xt.remove:return "";case xt.leave:return;case xt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(t){const e=t.charCodeAt(1);let i;if(i=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded