diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index b1c086d..a97b8ae 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,5 +1,3 @@ -# Release 0.6.1 +# Release 0.6.2 -Includes the reviewed September 2026 integrity, replay, persistence, async-lifecycle and compatibility repairs applicable to this repository. Wire/profile versions are unchanged unless explicitly described in the repository hardening notes. - -See HARDENING.md for supported verification scopes and migration boundaries. Registry publication and service deployment are reported by their workflows; a source merge alone is not a published package. +Adds `jep_api_token` for authenticated API signing. Pass `${{ secrets.JEP_API_TOKEN }}`; the action masks the value in workflow logs. The committed Node 24 bundle is rebuilt and checked in CI. diff --git a/VERSION b/VERSION index ee6cdce..b616048 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.6.1 +0.6.2 diff --git a/action.yml b/action.yml index b27c36e..2a0ac6a 100644 --- a/action.yml +++ b/action.yml @@ -39,6 +39,10 @@ inputs: description: "Optional JEP API URL for api mode" required: false default: "" + jep_api_token: + description: "Bearer token for authenticated API signing; pass a GitHub secret" + required: false + default: "" upload_artifact: description: "Upload the generated event artifact" required: false diff --git a/dist/index.mjs b/dist/index.mjs index 8cec7ad..7982fa2 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -91,4 +91,4 @@ const SP=32;const HTAB=9;const SEMI=59;const EQ=61;const DQUOTE=34;const BSLASH= ()=>new ArrayBuffer(0)))}}function isJSONResponse(e){return e.type==="application/json"||e.type==="application/scim+json"}function toErrorMessage(e){if(typeof e==="string"){return e}if(e instanceof ArrayBuffer){return"Unknown error"}if(typeof e==="object"&&e!==null&&"message"in e){const t=e;const r="documentation_url"in t?` - ${t.documentation_url}`:"";return Array.isArray(t.errors)?`${t.message}: ${t.errors.map((e=>JSON.stringify(e))).join(", ")}${r}`:`${t.message}${r}`}return`Unknown error: ${JSON.stringify(e)}`}function dist_bundle_withDefaults(e,t){const r=e.defaults(t);const newApi=function(e,t){const n=r.merge(e,t);if(!n.request||!n.request.hook){return fetchWrapper(r.parse(n))}const request2=(e,t)=>fetchWrapper(r.parse(r.merge(e,t)));Object.assign(request2,{endpoint:r,defaults:dist_bundle_withDefaults.bind(null,r)});return n.request.hook(request2,n)};return Object.assign(newApi,{endpoint:r,defaults:dist_bundle_withDefaults.bind(null,r)})}var request=dist_bundle_withDefaults(endpoint,defaults_default); /* v8 ignore next -- @preserve */ /* v8 ignore else -- @preserve */var graphql_dist_bundle_VERSION="0.0.0-development";function _buildMessageForResponseErrors(e){return`Request failed due to following response errors:\n`+e.errors.map((e=>` - ${e.message}`)).join("\n")}var GraphqlResponseError=class extends Error{constructor(e,t,r){super(_buildMessageForResponseErrors(r));this.request=e;this.headers=t;this.response=r;this.errors=r.errors;this.data=r.data;if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}}request;headers;response;name="GraphqlResponseError";errors;data};var NON_VARIABLE_OPTIONS=["method","baseUrl","url","headers","request","query","mediaType","operationName"];var FORBIDDEN_VARIABLE_OPTIONS=["query","method","url"];var GHES_V3_SUFFIX_REGEX=/\/api\/v3\/?$/;function graphql(e,t,r){if(r){if(typeof t==="string"&&"query"in r){return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`))}for(const e in r){if(!FORBIDDEN_VARIABLE_OPTIONS.includes(e))continue;return Promise.reject(new Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}}const n=typeof t==="string"?Object.assign({query:t},r):t;const s=Object.keys(n).reduce(((e,t)=>{if(NON_VARIABLE_OPTIONS.includes(t)){e[t]=n[t];return e}if(!e.variables){e.variables={}}e.variables[t]=n[t];return e}),{});const i=n.baseUrl||e.endpoint.DEFAULTS.baseUrl;if(GHES_V3_SUFFIX_REGEX.test(i)){s.url=i.replace(GHES_V3_SUFFIX_REGEX,"/api/graphql")}return e(s).then((e=>{if(e.data.errors){const t={};for(const r of Object.keys(e.headers)){t[r]=e.headers[r]}throw new GraphqlResponseError(s,t,e.data)}return e.data.data}))}function graphql_dist_bundle_withDefaults(e,t){const r=e.defaults(t);const newApi=(e,t)=>graphql(r,e,t);return Object.assign(newApi,{defaults:graphql_dist_bundle_withDefaults.bind(null,r),endpoint:r.endpoint})}var graphql2=graphql_dist_bundle_withDefaults(request,{headers:{"user-agent":`octokit-graphql.js/${graphql_dist_bundle_VERSION} ${getUserAgent()}`},method:"POST",url:"/graphql"});function withCustomRequest(e){return graphql_dist_bundle_withDefaults(e,{method:"POST",url:"/graphql"})} -/* v8 ignore if -- @preserve */var b64url="(?:[a-zA-Z0-9_-]+)";var sep="\\.";var jwtRE=new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);var isJWT=jwtRE.test.bind(jwtRE);async function auth(e){const t=isJWT(e);const r=e.startsWith("v1.")||e.startsWith("ghs_");const n=e.startsWith("ghu_");const s=t?"app":r?"installation":n?"user-to-server":"oauth";return{type:"token",token:e,tokenType:s}}function withAuthorizationPrefix(e){if(e.split(/\./).length===3){return`bearer ${e}`}return`token ${e}`}async function hook(e,t,r,n){const s=t.endpoint.merge(r,n);s.headers.authorization=withAuthorizationPrefix(e);return t(s)}var createTokenAuth=function createTokenAuth2(e){if(!e){throw new Error("[@octokit/auth-token] No token passed to createTokenAuth")}if(typeof e!=="string"){throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string")}e=e.replace(/^(token|bearer) +/i,"");return Object.assign(auth.bind(null,e),{hook:hook.bind(null,e)})};const version_VERSION="7.0.8";const dist_src_noop=()=>{};const consoleWarn=console.warn.bind(console);const consoleError=console.error.bind(console);function createLogger(e={}){if(typeof e.debug!=="function"){e.debug=dist_src_noop}if(typeof e.info!=="function"){e.info=dist_src_noop}if(typeof e.warn!=="function"){e.warn=consoleWarn}if(typeof e.error!=="function"){e.error=consoleError}return e}const userAgentTrail=`octokit-core.js/${version_VERSION} ${getUserAgent()}`;class Octokit{static VERSION=version_VERSION;static defaults(e){const t=class extends(this){constructor(...t){const r=t[0]||{};if(typeof e==="function"){super(e(r));return}super(Object.assign({},e,r,r.userAgent&&e.userAgent?{userAgent:`${r.userAgent} ${e.userAgent}`}:null))}};return t}static plugins=[];static plugin(...e){const t=this.plugins;const r=class extends(this){static plugins=t.concat(e.filter((e=>!t.includes(e))))};return r}constructor(e={}){const t=new before_after_hook.Collection;const r={baseUrl:request.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${userAgentTrail}`:userAgentTrail;if(e.baseUrl){r.baseUrl=e.baseUrl}if(e.previews){r.mediaType.previews=e.previews}if(e.timeZone){r.headers["time-zone"]=e.timeZone}this.request=request.defaults(r);this.graphql=withCustomRequest(this.request).defaults(r);this.log=createLogger(e.log);this.hook=t;if(!e.authStrategy){if(!e.auth){this.auth=async()=>({type:"unauthenticated"})}else{const r=createTokenAuth(e.auth);t.wrap("request",r.hook);this.auth=r}}else{const{authStrategy:r,...n}=e;const s=r(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:n},e.auth));t.wrap("request",s.hook);this.auth=s}const n=this.constructor;for(let t=0;t({async next(){if(!a)return{done:true};try{const e=await s({method:i,url:a,headers:o});const t=normalizePaginatedListResponse(e);a=((t.headers.link||"").match(/<([^<>]+)>;\s*rel="next"/)||[])[1];if(!a&&"total_commits"in t.data){const e=new URL(t.url);const r=e.searchParams;const n=parseInt(r.get("page")||"1",10);const s=parseInt(r.get("per_page")||"250",10);if(n*s{if(s.done){return t}let i=false;function done(){i=true}t=t.concat(n?n(s.value,done):s.value.data);if(i){return t}return gather(e,t,r,n)}))}var composePaginateRest=Object.assign(paginate,{iterator:iterator});var paginatingEndpoints=null&&["GET /advisories","GET /app/hook/deliveries","GET /app/installation-requests","GET /app/installations","GET /assignments/{assignment_id}/accepted_assignments","GET /classrooms","GET /classrooms/{classroom_id}/assignments","GET /enterprises/{enterprise}/code-security/configurations","GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories","GET /enterprises/{enterprise}/dependabot/alerts","GET /enterprises/{enterprise}/teams","GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships","GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations","GET /events","GET /gists","GET /gists/public","GET /gists/starred","GET /gists/{gist_id}/comments","GET /gists/{gist_id}/commits","GET /gists/{gist_id}/forks","GET /installation/repositories","GET /issues","GET /licenses","GET /marketplace_listing/plans","GET /marketplace_listing/plans/{plan_id}/accounts","GET /marketplace_listing/stubbed/plans","GET /marketplace_listing/stubbed/plans/{plan_id}/accounts","GET /networks/{owner}/{repo}/events","GET /notifications","GET /organizations","GET /organizations/{org}/dependabot/repository-access","GET /orgs/{org}/actions/cache/usage-by-repository","GET /orgs/{org}/actions/hosted-runners","GET /orgs/{org}/actions/permissions/repositories","GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories","GET /orgs/{org}/actions/runner-groups","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories","GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners","GET /orgs/{org}/actions/runners","GET /orgs/{org}/actions/secrets","GET /orgs/{org}/actions/secrets/{secret_name}/repositories","GET /orgs/{org}/actions/variables","GET /orgs/{org}/actions/variables/{name}/repositories","GET /orgs/{org}/attestations/repositories","GET /orgs/{org}/attestations/{subject_digest}","GET /orgs/{org}/blocks","GET /orgs/{org}/campaigns","GET /orgs/{org}/code-scanning/alerts","GET /orgs/{org}/code-security/configurations","GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories","GET /orgs/{org}/codespaces","GET /orgs/{org}/codespaces/secrets","GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories","GET /orgs/{org}/copilot/billing/seats","GET /orgs/{org}/copilot/metrics","GET /orgs/{org}/dependabot/alerts","GET /orgs/{org}/dependabot/secrets","GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories","GET /orgs/{org}/events","GET /orgs/{org}/failed_invitations","GET /orgs/{org}/hooks","GET /orgs/{org}/hooks/{hook_id}/deliveries","GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}","GET /orgs/{org}/insights/api/subject-stats","GET /orgs/{org}/insights/api/user-stats/{user_id}","GET /orgs/{org}/installations","GET /orgs/{org}/invitations","GET /orgs/{org}/invitations/{invitation_id}/teams","GET /orgs/{org}/issues","GET /orgs/{org}/members","GET /orgs/{org}/members/{username}/codespaces","GET /orgs/{org}/migrations","GET /orgs/{org}/migrations/{migration_id}/repositories","GET /orgs/{org}/organization-roles/{role_id}/teams","GET /orgs/{org}/organization-roles/{role_id}/users","GET /orgs/{org}/outside_collaborators","GET /orgs/{org}/packages","GET /orgs/{org}/packages/{package_type}/{package_name}/versions","GET /orgs/{org}/personal-access-token-requests","GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories","GET /orgs/{org}/personal-access-tokens","GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories","GET /orgs/{org}/private-registries","GET /orgs/{org}/projects","GET /orgs/{org}/projectsV2","GET /orgs/{org}/projectsV2/{project_number}/fields","GET /orgs/{org}/projectsV2/{project_number}/items","GET /orgs/{org}/properties/values","GET /orgs/{org}/public_members","GET /orgs/{org}/repos","GET /orgs/{org}/rulesets","GET /orgs/{org}/rulesets/rule-suites","GET /orgs/{org}/rulesets/{ruleset_id}/history","GET /orgs/{org}/secret-scanning/alerts","GET /orgs/{org}/security-advisories","GET /orgs/{org}/settings/immutable-releases/repositories","GET /orgs/{org}/settings/network-configurations","GET /orgs/{org}/team/{team_slug}/copilot/metrics","GET /orgs/{org}/teams","GET /orgs/{org}/teams/{team_slug}/discussions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions","GET /orgs/{org}/teams/{team_slug}/invitations","GET /orgs/{org}/teams/{team_slug}/members","GET /orgs/{org}/teams/{team_slug}/projects","GET /orgs/{org}/teams/{team_slug}/repos","GET /orgs/{org}/teams/{team_slug}/teams","GET /projects/{project_id}/collaborators","GET /repos/{owner}/{repo}/actions/artifacts","GET /repos/{owner}/{repo}/actions/caches","GET /repos/{owner}/{repo}/actions/organization-secrets","GET /repos/{owner}/{repo}/actions/organization-variables","GET /repos/{owner}/{repo}/actions/runners","GET /repos/{owner}/{repo}/actions/runs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts","GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs","GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs","GET /repos/{owner}/{repo}/actions/secrets","GET /repos/{owner}/{repo}/actions/variables","GET /repos/{owner}/{repo}/actions/workflows","GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs","GET /repos/{owner}/{repo}/activity","GET /repos/{owner}/{repo}/assignees","GET /repos/{owner}/{repo}/attestations/{subject_digest}","GET /repos/{owner}/{repo}/branches","GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations","GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs","GET /repos/{owner}/{repo}/code-scanning/alerts","GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances","GET /repos/{owner}/{repo}/code-scanning/analyses","GET /repos/{owner}/{repo}/codespaces","GET /repos/{owner}/{repo}/codespaces/devcontainers","GET /repos/{owner}/{repo}/codespaces/secrets","GET /repos/{owner}/{repo}/collaborators","GET /repos/{owner}/{repo}/comments","GET /repos/{owner}/{repo}/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/commits","GET /repos/{owner}/{repo}/commits/{commit_sha}/comments","GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls","GET /repos/{owner}/{repo}/commits/{ref}/check-runs","GET /repos/{owner}/{repo}/commits/{ref}/check-suites","GET /repos/{owner}/{repo}/commits/{ref}/status","GET /repos/{owner}/{repo}/commits/{ref}/statuses","GET /repos/{owner}/{repo}/compare/{basehead}","GET /repos/{owner}/{repo}/compare/{base}...{head}","GET /repos/{owner}/{repo}/contributors","GET /repos/{owner}/{repo}/dependabot/alerts","GET /repos/{owner}/{repo}/dependabot/secrets","GET /repos/{owner}/{repo}/deployments","GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses","GET /repos/{owner}/{repo}/environments","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies","GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps","GET /repos/{owner}/{repo}/environments/{environment_name}/secrets","GET /repos/{owner}/{repo}/environments/{environment_name}/variables","GET /repos/{owner}/{repo}/events","GET /repos/{owner}/{repo}/forks","GET /repos/{owner}/{repo}/hooks","GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries","GET /repos/{owner}/{repo}/invitations","GET /repos/{owner}/{repo}/issues","GET /repos/{owner}/{repo}/issues/comments","GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/issues/events","GET /repos/{owner}/{repo}/issues/{issue_number}/comments","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by","GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking","GET /repos/{owner}/{repo}/issues/{issue_number}/events","GET /repos/{owner}/{repo}/issues/{issue_number}/labels","GET /repos/{owner}/{repo}/issues/{issue_number}/reactions","GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues","GET /repos/{owner}/{repo}/issues/{issue_number}/timeline","GET /repos/{owner}/{repo}/keys","GET /repos/{owner}/{repo}/labels","GET /repos/{owner}/{repo}/milestones","GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels","GET /repos/{owner}/{repo}/notifications","GET /repos/{owner}/{repo}/pages/builds","GET /repos/{owner}/{repo}/projects","GET /repos/{owner}/{repo}/pulls","GET /repos/{owner}/{repo}/pulls/comments","GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions","GET /repos/{owner}/{repo}/pulls/{pull_number}/comments","GET /repos/{owner}/{repo}/pulls/{pull_number}/commits","GET /repos/{owner}/{repo}/pulls/{pull_number}/files","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews","GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments","GET /repos/{owner}/{repo}/releases","GET /repos/{owner}/{repo}/releases/{release_id}/assets","GET /repos/{owner}/{repo}/releases/{release_id}/reactions","GET /repos/{owner}/{repo}/rules/branches/{branch}","GET /repos/{owner}/{repo}/rulesets","GET /repos/{owner}/{repo}/rulesets/rule-suites","GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history","GET /repos/{owner}/{repo}/secret-scanning/alerts","GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations","GET /repos/{owner}/{repo}/security-advisories","GET /repos/{owner}/{repo}/stargazers","GET /repos/{owner}/{repo}/subscribers","GET /repos/{owner}/{repo}/tags","GET /repos/{owner}/{repo}/teams","GET /repos/{owner}/{repo}/topics","GET /repositories","GET /search/code","GET /search/commits","GET /search/issues","GET /search/labels","GET /search/repositories","GET /search/topics","GET /search/users","GET /teams/{team_id}/discussions","GET /teams/{team_id}/discussions/{discussion_number}/comments","GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions","GET /teams/{team_id}/discussions/{discussion_number}/reactions","GET /teams/{team_id}/invitations","GET /teams/{team_id}/members","GET /teams/{team_id}/projects","GET /teams/{team_id}/repos","GET /teams/{team_id}/teams","GET /user/blocks","GET /user/codespaces","GET /user/codespaces/secrets","GET /user/emails","GET /user/followers","GET /user/following","GET /user/gpg_keys","GET /user/installations","GET /user/installations/{installation_id}/repositories","GET /user/issues","GET /user/keys","GET /user/marketplace_purchases","GET /user/marketplace_purchases/stubbed","GET /user/memberships/orgs","GET /user/migrations","GET /user/migrations/{migration_id}/repositories","GET /user/orgs","GET /user/packages","GET /user/packages/{package_type}/{package_name}/versions","GET /user/public_emails","GET /user/repos","GET /user/repository_invitations","GET /user/social_accounts","GET /user/ssh_signing_keys","GET /user/starred","GET /user/subscriptions","GET /user/teams","GET /users","GET /users/{username}/attestations/{subject_digest}","GET /users/{username}/events","GET /users/{username}/events/orgs/{org}","GET /users/{username}/events/public","GET /users/{username}/followers","GET /users/{username}/following","GET /users/{username}/gists","GET /users/{username}/gpg_keys","GET /users/{username}/keys","GET /users/{username}/orgs","GET /users/{username}/packages","GET /users/{username}/projects","GET /users/{username}/projectsV2","GET /users/{username}/projectsV2/{project_number}/fields","GET /users/{username}/projectsV2/{project_number}/items","GET /users/{username}/received_events","GET /users/{username}/received_events/public","GET /users/{username}/repos","GET /users/{username}/social_accounts","GET /users/{username}/ssh_signing_keys","GET /users/{username}/starred","GET /users/{username}/subscriptions"];function isPaginatingEndpoint(e){if(typeof e==="string"){return paginatingEndpoints.includes(e)}else{return false}}function paginateRest(e){return{paginate:Object.assign(paginate.bind(null,e),{iterator:iterator.bind(null,e)})}}paginateRest.VERSION=plugin_paginate_rest_dist_bundle_VERSION;const context=new Context;const baseUrl=getApiBaseUrl();const defaults={baseUrl:baseUrl,request:{agent:getProxyAgent(baseUrl),fetch:getProxyFetch(baseUrl)}};const GitHub=Octokit.plugin(restEndpointMethods,paginateRest).defaults(defaults);function getOctokitOptions(e,t){const r=Object.assign({},t||{});const n=getAuthString(e,r);if(n){r.auth=n}const s=getUserAgentWithOrchestrationId(r.userAgent);if(s){r.userAgent=s}return r}const github_context=new Context;function getOctokit(e,t,...r){const n=GitHub.plugin(...r);return new n(getOctokitOptions(e,t))}function getUploadChunkSize(){return 8*1024*1024}function getRuntimeToken(){const e=process.env["ACTIONS_RUNTIME_TOKEN"];if(!e){throw new Error("Unable to get the ACTIONS_RUNTIME_TOKEN env variable")}return e}function getResultsServiceUrl(){const e=process.env["ACTIONS_RESULTS_URL"];if(!e){throw new Error("Unable to get the ACTIONS_RESULTS_URL env variable")}return new URL(e).origin}function isGhes(){const e=new URL(process.env["GITHUB_SERVER_URL"]||"https://github.com");const t=e.hostname.trimEnd().toUpperCase();const r=t==="GITHUB.COM";const n=t.endsWith(".GHE.COM");const s=t.endsWith(".LOCALHOST");return!r&&!n&&!s}function getGitHubWorkspaceDir(){const e=process.env["GITHUB_WORKSPACE"];if(!e){throw new Error("Unable to get the GITHUB_WORKSPACE env variable")}return e}function getConcurrency(){const e=external_os_namespaceObject.cpus().length;let t=32;if(e>4){const r=16*e;t=r>300?300:r}const r=process.env["ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY"];if(r){const e=parseInt(r);if(isNaN(e)||e<1){throw new Error("Invalid value set for ACTIONS_ARTIFACT_UPLOAD_CONCURRENCY env variable")}if(eDate.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let t=(e.nanos+1e9).toString().substring(1);if(t.substring(3)==="000000")n="."+t.substring(0,3)+"Z";else if(t.substring(6)==="000")n="."+t.substring(0,6)+"Z";else n="."+t+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if(typeof e!=="string")throw new Error("Unable to parse Timestamp from JSON "+(0,commonjs.typeofJsonValue)(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(sDate.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(!r)r=this.create();r.seconds=commonjs.PbLong.from(s/1e3).toString();r.nanos=0;if(n[7])r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9;return r}create(e){const t={seconds:"0",nanos:0};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posTimestamp},{no:5,name:"version",kind:"scalar",T:5},{no:6,name:"mime_type",kind:"message",T:()=>StringValue}])}create(e){const t={workflowRunBackendId:"",workflowJobRunBackendId:"",name:"",version:0};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posStringValue}])}create(e){const t={workflowRunBackendId:"",workflowJobRunBackendId:"",name:"",size:"0"};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posStringValue},{no:4,name:"id_filter",kind:"message",T:()=>Int64Value}])}create(e){const t={workflowRunBackendId:"",workflowJobRunBackendId:""};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posListArtifactsResponse_MonolithArtifact}])}create(e){const t={artifacts:[]};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posTimestamp},{no:7,name:"digest",kind:"message",T:()=>StringValue}])}create(e){const t={workflowRunBackendId:"",workflowJobRunBackendId:"",databaseId:"0",name:"",size:"0"};globalThis.Object.defineProperty(t,commonjs.MESSAGE_TYPE,{enumerable:false,value:this});if(e!==undefined)(0,commonjs.reflectionMergePartial)(this,t,e);return t}internalBinaryRead(e,t,r,n){let s=n!==null&&n!==void 0?n:this.create(),i=e.pos+t;while(e.posartifact_CreateArtifactResponse.fromJson(e,{ignoreUnknownFields:true})))}FinalizeArtifact(e){const t=artifact_FinalizeArtifactRequest.toJson(e,{useProtoFieldName:true,emitDefaultValues:false});const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","FinalizeArtifact","application/json",t);return r.then((e=>artifact_FinalizeArtifactResponse.fromJson(e,{ignoreUnknownFields:true})))}ListArtifacts(e){const t=artifact_ListArtifactsRequest.toJson(e,{useProtoFieldName:true,emitDefaultValues:false});const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","ListArtifacts","application/json",t);return r.then((e=>artifact_ListArtifactsResponse.fromJson(e,{ignoreUnknownFields:true})))}GetSignedArtifactURL(e){const t=artifact_GetSignedArtifactURLRequest.toJson(e,{useProtoFieldName:true,emitDefaultValues:false});const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","GetSignedArtifactURL","application/json",t);return r.then((e=>artifact_GetSignedArtifactURLResponse.fromJson(e,{ignoreUnknownFields:true})))}DeleteArtifact(e){const t=artifact_DeleteArtifactRequest.toJson(e,{useProtoFieldName:true,emitDefaultValues:false});const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","DeleteArtifact","application/json",t);return r.then((e=>artifact_DeleteArtifactResponse.fromJson(e,{ignoreUnknownFields:true})))}}class ArtifactServiceClientProtobuf{constructor(e){this.rpc=e;this.CreateArtifact.bind(this);this.FinalizeArtifact.bind(this);this.ListArtifacts.bind(this);this.GetSignedArtifactURL.bind(this);this.DeleteArtifact.bind(this)}CreateArtifact(e){const t=CreateArtifactRequest.toBinary(e);const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","CreateArtifact","application/protobuf",t);return r.then((e=>CreateArtifactResponse.fromBinary(e)))}FinalizeArtifact(e){const t=FinalizeArtifactRequest.toBinary(e);const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","FinalizeArtifact","application/protobuf",t);return r.then((e=>FinalizeArtifactResponse.fromBinary(e)))}ListArtifacts(e){const t=ListArtifactsRequest.toBinary(e);const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","ListArtifacts","application/protobuf",t);return r.then((e=>ListArtifactsResponse.fromBinary(e)))}GetSignedArtifactURL(e){const t=GetSignedArtifactURLRequest.toBinary(e);const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","GetSignedArtifactURL","application/protobuf",t);return r.then((e=>GetSignedArtifactURLResponse.fromBinary(e)))}DeleteArtifact(e){const t=DeleteArtifactRequest.toBinary(e);const r=this.rpc.request("github.actions.results.api.v1.ArtifactService","DeleteArtifact","application/protobuf",t);return r.then((e=>DeleteArtifactResponse.fromBinary(e)))}}function getExpiration(e){if(!e){return undefined}const t=getRetentionDays();if(t&&t"," Greater than >"],["|"," Vertical bar |"],["*"," Asterisk *"],["?"," Question mark ?"],["\r"," Carriage return \\r"],["\n"," Line feed \\n"]]);const invalidArtifactNameCharacters=new Map([...invalidArtifactFilePathCharacters,["\\"," Backslash \\"],["/"," Forward slash /"]]);function validateArtifactName(e){if(!e){throw new Error(`Provided artifact name input during validation is empty`)}for(const[t,r]of invalidArtifactNameCharacters){if(e.includes(t)){throw new Error(`The artifact name is not valid: ${e}. Contains the following character: ${r}\n \nInvalid characters include: ${Array.from(invalidArtifactNameCharacters.values()).toString()}\n \nThese characters are not allowed in the artifact name due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.`)}}info(`Artifact name is valid!`)}function validateFilePath(e){if(!e){throw new Error(`Provided file path input during validation is empty`)}for(const[t,r]of invalidArtifactFilePathCharacters){if(e.includes(t)){throw new Error(`The path for one of the files in artifact is not valid: ${e}. Contains the following character: ${r}\n \nInvalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()}\n \nThe following characters are not allowed in files that are uploaded due to limitations with certain file systems such as NTFS. To maintain file system agnostic behavior, these characters are intentionally not allowed to prevent potential problems with downloads on different file systems.\n `)}}}var package_version=__nccwpck_require__(9002);function getUserAgentString(){return`@actions/artifact-${package_version.version}`}class FilesNotFoundError extends Error{constructor(e=[]){let t="No files were found to upload";if(e.length>0){t+=`: ${e.join(", ")}`}super(t);this.files=e;this.name="FilesNotFoundError"}}class InvalidResponseError extends Error{constructor(e){super(e);this.name="InvalidResponseError"}}class ArtifactNotFoundError extends Error{constructor(e="Artifact not found"){super(e);this.name="ArtifactNotFoundError"}}class GHESNotSupportedError extends Error{constructor(e="@actions/artifact v2.0.0+, upload-artifact@v4+ and download-artifact@v4+ are not currently supported on GHES."){super(e);this.name="GHESNotSupportedError"}}class NetworkError extends Error{constructor(e){const t=`Unable to make request: ${e}\nIf you are using self-hosted runners, please make sure your runner has access to all GitHub endpoints: https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#communication-between-self-hosted-runners-and-github`;super(t);this.code=e;this.name="NetworkError"}}NetworkError.isNetworkErrorCode=e=>{if(!e)return false;return["ECONNRESET","ENOTFOUND","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH"].includes(e)};class UsageError extends Error{constructor(){const e=`Artifact storage quota has been hit. Unable to upload any new artifacts.\nMore info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`;super(e);this.name="UsageError"}}UsageError.isUsageErrorMessage=e=>{if(!e)return false;return e.includes("insufficient usage")};class InvalidTokenError extends Error{}InvalidTokenError.prototype.name="InvalidTokenError";function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();if(r.length<2){r="0"+r}return"%"+r})))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if(typeof e!=="string"){throw new InvalidTokenError("Invalid token specified: must be a string")}t||(t={});const r=t.header===true?0:1;const n=e.split(".")[r];if(typeof n!=="string"){throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`)}let s;try{s=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}const InvalidJwtError=new Error("Failed to get backend IDs: The provided JWT token is invalid and/or missing claims");function getBackendIdsFromToken(){const e=getRuntimeToken();const t=jwtDecode(e);if(!t.scp){throw InvalidJwtError}const r=t.scp.split(" ");if(r.length===0){throw InvalidJwtError}for(const e of r){const t=e.split(":");if((t===null||t===void 0?void 0:t[0])!=="Actions.Results"){continue}if(t.length!==3){throw InvalidJwtError}const r={workflowRunBackendId:t[1],workflowJobRunBackendId:t[2]};core_debug(`Workflow Run Backend ID: ${r.workflowRunBackendId}`);core_debug(`Workflow Job Run Backend ID: ${r.workflowJobRunBackendId}`);return r}throw InvalidJwtError}function maskSigUrl(e){if(!e)return;try{const t=new URL(e);const r=t.searchParams.get("sig");if(r){core_setSecret(r);core_setSecret(encodeURIComponent(r))}}catch(t){core_debug(`Failed to parse URL: ${e} ${t instanceof Error?t.message:String(t)}`)}}function maskSecretUrls(e){if(typeof e!=="object"||e===null){core_debug("body is not an object or is null");return}if("signed_upload_url"in e&&typeof e.signed_upload_url==="string"){maskSigUrl(e.signed_upload_url)}if("signed_url"in e&&typeof e.signed_url==="string"){maskSigUrl(e.signed_url)}}var artifact_twirp_client_awaiter=undefined&&undefined.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,s){function fulfilled(e){try{step(n.next(e))}catch(e){s(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){s(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())}))};class ArtifactHttpClient{constructor(e,t,r,n){this.maxAttempts=5;this.baseRetryIntervalMilliseconds=3e3;this.retryMultiplier=1.5;const s=getRuntimeToken();this.baseUrl=getResultsServiceUrl();if(t){this.maxAttempts=t}if(r){this.baseRetryIntervalMilliseconds=r}if(n){this.retryMultiplier=n}this.httpClient=new lib_HttpClient(e,[new auth_BearerCredentialHandler(s)])}request(e,t,r,n){return artifact_twirp_client_awaiter(this,void 0,void 0,(function*(){const s=new URL(`/twirp/${e}/${t}`,this.baseUrl).href;core_debug(`[Request] ${t} ${s}`);const i={"Content-Type":r};try{const{body:e}=yield this.retryableRequest((()=>artifact_twirp_client_awaiter(this,void 0,void 0,(function*(){return this.httpClient.post(s,JSON.stringify(n),i)}))));return e}catch(e){throw new Error(`Failed to ${t}: ${e.message}`)}}))}retryableRequest(e){return artifact_twirp_client_awaiter(this,void 0,void 0,(function*(){let t=0;let r="";let n="";while(t=200&&e<300}isRetryableHttpStatusCode(e){if(!e)return false;const t=[HttpCodes.BadGateway,HttpCodes.GatewayTimeout,HttpCodes.InternalServerError,HttpCodes.ServiceUnavailable,HttpCodes.TooManyRequests];return t.includes(e)}sleep(e){return artifact_twirp_client_awaiter(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}getExponentialRetryTimeMilliseconds(e){if(e<0){throw new Error("attempt should be a positive integer")}if(e===0){return this.baseRetryIntervalMilliseconds}const t=this.baseRetryIntervalMilliseconds*Math.pow(this.retryMultiplier,e);const r=t*this.retryMultiplier;return Math.trunc(Math.random()*(r-t)+t)}}function internalArtifactTwirpClient(e){const t=new ArtifactHttpClient(getUserAgentString(),e===null||e===void 0?void 0:e.maxAttempts,e===null||e===void 0?void 0:e.retryIntervalMs,e===null||e===void 0?void 0:e.retryMultiplier);return new ArtifactServiceClientJSON(t)}function validateRootDirectory(e){if(!external_fs_.existsSync(e)){throw new Error(`The provided rootDirectory ${e} does not exist`)}if(!external_fs_.statSync(e).isDirectory()){throw new Error(`The provided rootDirectory ${e} is not a valid directory`)}info(`Root directory input is valid!`)}function getUploadZipSpecification(e,t){const r=[];t=(0,external_path_.normalize)(t);t=(0,external_path_.resolve)(t);for(let n of e){const e=external_fs_.lstatSync(n,{throwIfNoEntry:false});if(!e){throw new Error(`File ${n} does not exist`)}if(!e.isDirectory()){n=(0,external_path_.normalize)(n);n=(0,external_path_.resolve)(n);if(!n.startsWith(t)){throw new Error(`The rootDirectory: ${t} is not a parent directory of the file: ${n}`)}const s=n.replace(t,"");validateFilePath(s);r.push({sourcePath:n,destinationPath:s,stats:e})}else{const s=n.replace(t,"");validateFilePath(s);r.push({sourcePath:null,destinationPath:s,stats:e})}}return r}class AbortError extends Error{constructor(e){super(e);this.name="AbortError"}}const external_node_os_namespaceObject=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");var external_node_util_=__nccwpck_require__(57975);const external_node_process_namespaceObject=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");function log(e,...t){external_node_process_namespaceObject.stderr.write(`${external_node_util_.format(e,...t)}${external_node_os_namespaceObject.EOL}`)}function getEnvironmentVariable(e){return external_node_process_namespaceObject.env[e]}function env_emitNodeWarning(e){process.emitWarning(e)}const isBrowser=false;const isWebWorker=false;const isDeno=typeof external_node_process_namespaceObject.versions.deno==="string"&&external_node_process_namespaceObject.versions.deno.length>0;const isBun=typeof external_node_process_namespaceObject.versions.bun==="string"&&external_node_process_namespaceObject.versions.bun.length>0;const env_isNodeLike=true;const isNodeRuntime=!isBun&&!isDeno;const isReactNative=false;const debugEnvVariable=getEnvironmentVariable("DEBUG");let enabledString;let enabledNamespaces=[];let skippedNamespaces=[];const debuggers=[];if(debugEnvVariable){enable(debugEnvVariable)}const debugObj=Object.assign((e=>createDebugger(e)),{enable:enable,enabled:enabled,disable:disable,log:log});function enable(e){enabledString=e;enabledNamespaces=[];skippedNamespaces=[];const t=e.split(",").map((e=>e.trim()));for(const e of t){if(e.startsWith("-")){skippedNamespaces.push(e.substring(1))}else{enabledNamespaces.push(e)}}for(const e of debuggers){e.enabled=enabled(e.namespace)}}function enabled(e){if(e.endsWith("*")){return true}for(const t of skippedNamespaces){if(namespaceMatches(e,t)){return false}}for(const t of enabledNamespaces){if(namespaceMatches(e,t)){return true}}return false}function namespaceMatches(e,t){if(t.indexOf("*")===-1){return e===t}let r=t;if(t.indexOf("**")!==-1){const e=[];let n="";for(const r of t){if(r==="*"&&n==="*"){continue}else{n=r;e.push(r)}}r=e.join("")}let n=0;let s=0;const i=r.length;const o=e.length;let a=-1;let c=-1;while(n=0){s=a+1;n=c+1;if(n===o){return false}while(e[n]!==r[s]){n++;if(n===o){return false}}c=n;n++;s++;continue}else{return false}}const l=n===e.length;const u=s===r.length;const d=s===r.length-1&&r[s]==="*";return l&&(u||d)}function disable(){const e=enabledString||"";enable("");return e}function createDebugger(e){const t=Object.assign(debug,{enabled:enabled(e),destroy:destroy,log:debugObj.log,namespace:e,extend:extend});function debug(...r){if(!t.enabled){return}if(r.length>0){r[0]=`${e} ${r[0]}`}t.log(...r)}debuggers.push(t);return t}function destroy(){const e=debuggers.indexOf(this);if(e>=0){debuggers.splice(e,1);return true}return false}function extend(e){const t=createDebugger(`${this.namespace}:${e}`);t.log=this.log;return t}const logger_debug=debugObj;const TYPESPEC_RUNTIME_LOG_LEVELS=["verbose","info","warning","error"];const levelMap={verbose:400,info:300,warning:200,error:100};function patchLogMethod(e,t){t.log=(...t)=>{e.log(...t)}}function isTypeSpecRuntimeLogLevel(e){return TYPESPEC_RUNTIME_LOG_LEVELS.includes(e)}function createLoggerContext(e){const t=new Set;const r=getEnvironmentVariable(e.logLevelEnvVarName);let n;const s=logger_debug(e.namespace);s.log=(...e)=>{logger_debug.log(...e)};function contextSetLogLevel(e){if(e&&!isTypeSpecRuntimeLogLevel(e)){throw new Error(`Unknown log level '${e}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`)}n=e;const r=[];for(const e of t){if(shouldEnable(e)){r.push(e.namespace)}}logger_debug.enable(r.join(","))}if(r){if(isTypeSpecRuntimeLogLevel(r)){contextSetLogLevel(r)}else{console.error(`${e.logLevelEnvVarName} set to unknown log level '${r}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`)}}function shouldEnable(e){return Boolean(n&&levelMap[e.level]<=levelMap[n])}function createLogger(e,r){const n=Object.assign(e.extend(r),{level:r});patchLogMethod(e,n);if(shouldEnable(n)){const e=logger_debug.disable();logger_debug.enable(e+","+n.namespace)}t.add(n);return n}function contextGetLogLevel(){return n}function contextCreateClientLogger(e){const t=s.extend(e);patchLogMethod(s,t);return{error:createLogger(t,"error"),warning:createLogger(t,"warning"),info:createLogger(t,"info"),verbose:createLogger(t,"verbose")}}return{setLogLevel:contextSetLogLevel,getLogLevel:contextGetLogLevel,createClientLogger:contextCreateClientLogger,logger:s}}const logger_context=createLoggerContext({logLevelEnvVarName:"TYPESPEC_RUNTIME_LOG_LEVEL",namespace:"typeSpecRuntime"});const TypeSpecRuntimeLogger=logger_context.logger;function setLogLevel(e){logger_context.setLogLevel(e)}function getLogLevel(){return logger_context.getLogLevel()}function createClientLogger(e){return logger_context.createClientLogger(e)}function normalizeName(e){return e.toLowerCase()}function normalizeValue(e){return String(e).trim().replace(/[\r\n]/g,"")}function*headerIterator(e){for(const t of e.values()){yield[t.name,t.value]}}class HttpHeadersImpl{_headersMap;constructor(e){this._headersMap=new Map;if(e){for(const t of Object.keys(e)){this.set(t,e[t])}}}set(e,t){this._headersMap.set(normalizeName(e),{name:e,value:normalizeValue(t)})}get(e){return this._headersMap.get(normalizeName(e))?.value}has(e){return this._headersMap.has(normalizeName(e))}delete(e){this._headersMap.delete(normalizeName(e))}toJSON(e={}){const t={};if(e.preserveCase){for(const e of this._headersMap.values()){t[e.name]=e.value}}else{for(const[e,r]of this._headersMap){t[e]=r.value}}return t}toString(){return JSON.stringify(this.toJSON({preserveCase:true}))}[Symbol.iterator](){return headerIterator(this._headersMap)}}function httpHeaders_createHttpHeaders(e){return new HttpHeadersImpl(e)}function randomUUID(){return globalThis.crypto.randomUUID()}class PipelineRequestImpl{url;method;headers;timeout;withCredentials;body;multipartBody;formData;streamResponseStatusCodes;enableBrowserStreams;proxySettings;disableKeepAlive;abortSignal;requestId;allowInsecureConnection;onUploadProgress;onDownloadProgress;requestOverrides;authSchemes;constructor(e){this.url=e.url;this.body=e.body;this.headers=e.headers??httpHeaders_createHttpHeaders();this.method=e.method??"GET";this.timeout=e.timeout??0;this.multipartBody=e.multipartBody;this.formData=e.formData;this.disableKeepAlive=e.disableKeepAlive??false;this.proxySettings=e.proxySettings;this.streamResponseStatusCodes=e.streamResponseStatusCodes;this.withCredentials=e.withCredentials??false;this.abortSignal=e.abortSignal;this.onUploadProgress=e.onUploadProgress;this.onDownloadProgress=e.onDownloadProgress;this.requestId=e.requestId||randomUUID();this.allowInsecureConnection=e.allowInsecureConnection??false;this.enableBrowserStreams=e.enableBrowserStreams??false;this.requestOverrides=e.requestOverrides;this.authSchemes=e.authSchemes}}function pipelineRequest_createPipelineRequest(e){return new PipelineRequestImpl(e)}const ValidPhaseNames=new Set(["Deserialize","Serialize","Retry","Sign"]);class HttpPipeline{_policies=[];_orderedPolicies;constructor(e){this._policies=e?.slice(0)??[];this._orderedPolicies=undefined}addPolicy(e,t={}){if(t.phase&&t.afterPhase){throw new Error("Policies inside a phase cannot specify afterPhase.")}if(t.phase&&!ValidPhaseNames.has(t.phase)){throw new Error(`Invalid phase name: ${t.phase}`)}if(t.afterPhase&&!ValidPhaseNames.has(t.afterPhase)){throw new Error(`Invalid afterPhase name: ${t.afterPhase}`)}this._policies.push({policy:e,options:t});this._orderedPolicies=undefined}removePolicy(e){const t=[];this._policies=this._policies.filter((r=>{if(e.name&&r.policy.name===e.name||e.phase&&r.options.phase===e.phase){t.push(r.policy);return false}else{return true}}));this._orderedPolicies=undefined;return t}sendRequest(e,t){const r=this.getOrderedPolicies();const n=r.reduceRight(((e,t)=>r=>t.sendRequest(r,e)),(t=>e.sendRequest(t)));return n(t)}getOrderedPolicies(){if(!this._orderedPolicies){this._orderedPolicies=this.orderPolicies()}return this._orderedPolicies}clone(){return new HttpPipeline(this._policies)}static create(){return new HttpPipeline}orderPolicies(){const e=[];const t=new Map;function createPhase(e){return{name:e,policies:new Set,hasRun:false,hasAfterPolicies:false}}const r=createPhase("Serialize");const n=createPhase("None");const s=createPhase("Deserialize");const i=createPhase("Retry");const o=createPhase("Sign");const a=[r,n,s,i,o];function getPhase(e){if(e==="Retry"){return i}else if(e==="Serialize"){return r}else if(e==="Deserialize"){return s}else if(e==="Sign"){return o}else{return n}}for(const e of this._policies){const r=e.policy;const n=e.options;const s=r.name;if(t.has(s)){throw new Error("Duplicate policy names not allowed in pipeline")}const i={policy:r,dependsOn:new Set,dependants:new Set};if(n.afterPhase){i.afterPhase=getPhase(n.afterPhase);i.afterPhase.hasAfterPolicies=true}t.set(s,i);const o=getPhase(n.phase);o.policies.add(i)}for(const e of this._policies){const{policy:r,options:n}=e;const s=r.name;const i=t.get(s);if(!i){throw new Error(`Missing node for policy ${s}`)}if(n.afterPolicies){for(const e of n.afterPolicies){const r=t.get(e);if(r){i.dependsOn.add(r);r.dependants.add(i)}}}if(n.beforePolicies){for(const e of n.beforePolicies){const r=t.get(e);if(r){r.dependsOn.add(i);i.dependants.add(r)}}}}function walkPhase(r){r.hasRun=true;for(const n of r.policies){if(n.afterPhase&&(!n.afterPhase.hasRun||n.afterPhase.policies.size)){continue}if(n.dependsOn.size===0){e.push(n.policy);for(const e of n.dependants){e.dependsOn.delete(n)}t.delete(n.policy.name);r.policies.delete(n)}}}function walkPhases(){for(const e of a){walkPhase(e);if(e.policies.size>0&&e!==n){if(!n.hasRun){walkPhase(n)}return}if(e.hasAfterPolicies){walkPhase(n)}}}let c=0;while(t.size>0){c++;const t=e.length;walkPhases();if(e.length<=t&&c>1){throw new Error("Cannot satisfy policy dependencies due to requirements cycle.")}}return e}}function pipeline_createEmptyPipeline(){return HttpPipeline.create()}function isObject(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function isError(e){if(isObject(e)){const t=typeof e.name==="string";const r=typeof e.message==="string";return t&&r}return false}const custom=external_node_util_.inspect.custom;const RedactedString="REDACTED";const defaultAllowedHeaderNames=["x-ms-client-request-id","x-ms-return-client-request-id","x-ms-useragent","x-ms-correlation-request-id","x-ms-request-id","client-request-id","ms-cv","return-client-request-id","traceparent","Access-Control-Allow-Credentials","Access-Control-Allow-Headers","Access-Control-Allow-Methods","Access-Control-Allow-Origin","Access-Control-Expose-Headers","Access-Control-Max-Age","Access-Control-Request-Headers","Access-Control-Request-Method","Origin","Accept","Accept-Encoding","Cache-Control","Connection","Content-Length","Content-Type","Date","ETag","Expires","If-Match","If-Modified-Since","If-None-Match","If-Unmodified-Since","Last-Modified","Pragma","Request-Id","Retry-After","Server","Transfer-Encoding","User-Agent","WWW-Authenticate"];const defaultAllowedQueryParameters=["api-version"];class Sanitizer{allowedHeaderNames;allowedQueryParameters;constructor({additionalAllowedHeaderNames:e=[],additionalAllowedQueryParameters:t=[]}={}){e=defaultAllowedHeaderNames.concat(e);t=defaultAllowedQueryParameters.concat(t);this.allowedHeaderNames=new Set(e.map((e=>e.toLowerCase())));this.allowedQueryParameters=new Set(t.map((e=>e.toLowerCase())))}sanitize(e){const t=new Set;return JSON.stringify(e,((e,r)=>{if(r instanceof Error){return{...r,name:r.name,message:r.message}}if(e==="headers"&&isObject(r)){return this.sanitizeHeaders(r)}else if(e==="url"&&typeof r==="string"){return this.sanitizeUrl(r)}else if(e==="query"&&isObject(r)){return this.sanitizeQuery(r)}else if(e==="body"){return undefined}else if(e==="response"){return undefined}else if(e==="operationSpec"){return undefined}else if(Array.isArray(r)||isObject(r)){if(t.has(r)){return"[Circular]"}t.add(r)}return r}),2)}sanitizeUrl(e){if(typeof e!=="string"||e===null||e===""){return e}const t=new URL(e);if(!t.search){return e}for(const[e]of t.searchParams){if(!this.allowedQueryParameters.has(e.toLowerCase())){t.searchParams.set(e,RedactedString)}}return t.toString()}sanitizeHeaders(e){const t={};for(const r of Object.keys(e)){if(this.allowedHeaderNames.has(r.toLowerCase())){t[r]=e[r]}else{t[r]=RedactedString}}return t}sanitizeQuery(e){if(typeof e!=="object"||e===null){return e}const t={};for(const r of Object.keys(e)){if(this.allowedQueryParameters.has(r.toLowerCase())){t[r]=e[r]}else{t[r]=RedactedString}}return t}}const errorSanitizer=new Sanitizer;class restError_RestError extends Error{static REQUEST_SEND_ERROR="REQUEST_SEND_ERROR";static PARSE_ERROR="PARSE_ERROR";code;statusCode;request;response;details;constructor(e,t={}){super(e);this.name="RestError";this.code=t.code;this.statusCode=t.statusCode;Object.defineProperty(this,"request",{value:t.request,enumerable:false});Object.defineProperty(this,"response",{value:t.response,enumerable:false});const r=this.request?.agent?{maxFreeSockets:this.request.agent.maxFreeSockets,maxSockets:this.request.agent.maxSockets}:undefined;Object.defineProperty(this,custom,{value:()=>`RestError: ${this.message} \n ${errorSanitizer.sanitize({...this,request:{...this.request,agent:r},response:this.response})}`,enumerable:false});Object.setPrototypeOf(this,restError_RestError.prototype)}}function restError_isRestError(e){if(e instanceof restError_RestError){return true}return isError(e)&&e.name==="RestError"}var external_node_http_=__nccwpck_require__(37067);const external_node_https_namespaceObject=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");var external_node_zlib_=__nccwpck_require__(38522);var external_node_stream_=__nccwpck_require__(57075);const log_logger=createClientLogger("ts-http-runtime");const DEFAULT_TLS_SETTINGS={};function nodeHttpClient_isReadableStream(e){return e&&typeof e.pipe==="function"}function isStreamComplete(e){if(e.readable===false){return Promise.resolve()}return new Promise((t=>{const handler=()=>{t();e.removeListener("close",handler);e.removeListener("end",handler);e.removeListener("error",handler)};e.on("close",handler);e.on("end",handler);e.on("error",handler)}))}function isArrayBuffer(e){return e&&typeof e.byteLength==="number"}class ReportTransform extends external_node_stream_.Transform{loadedBytes=0;progressCallback;_transform(e,t,r){this.push(e);this.loadedBytes+=e.length;try{this.progressCallback({loadedBytes:this.loadedBytes});r()}catch(e){r(e)}}constructor(e){super();this.progressCallback=e}}class NodeHttpClient{cachedHttpAgent;cachedHttpsAgents=new WeakMap;async sendRequest(e){const t=new AbortController;let r;if(e.abortSignal){if(e.abortSignal.aborted){throw new AbortError("The operation was aborted. Request has already been canceled.")}r=e=>{if(e.type==="abort"){t.abort()}};e.abortSignal.addEventListener("abort",r)}let n;if(e.timeout>0){n=setTimeout((()=>{const r=new Sanitizer;log_logger.info(`request to '${r.sanitizeUrl(e.url)}' timed out. canceling...`);t.abort()}),e.timeout)}const s=e.headers.get("Accept-Encoding");const i=s?.includes("gzip")||s?.includes("deflate");let o=typeof e.body==="function"?e.body():e.body;if(o&&!e.headers.has("Content-Length")){const t=getBodyLength(o);if(t!==null){e.headers.set("Content-Length",t)}}let a;try{if(o&&e.onUploadProgress){const t=e.onUploadProgress;const r=new ReportTransform(t);r.on("error",(e=>{log_logger.error("Error in upload progress",e)}));if(nodeHttpClient_isReadableStream(o)){o.pipe(r)}else{r.end(o)}o=r}const r=await this.makeRequest(e,t,o);const n=getResponseHeaders(r);const s=r.statusCode??0;const c={status:s,headers:n,request:e};if(e.method==="HEAD"){r.resume();return c}a=i?getDecodedResponseStream(r,n):r;const l=e.onDownloadProgress;if(l){const e=new ReportTransform(l);e.on("error",(e=>{log_logger.error("Error in download progress",e)}));a.pipe(e);a=e}if(e.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY)||e.streamResponseStatusCodes?.has(c.status)){c.readableStreamBody=a}else{c.bodyAsText=await streamToText(a)}return c}finally{if(n!==undefined){clearTimeout(n)}if(e.abortSignal&&r){let t=Promise.resolve();if(nodeHttpClient_isReadableStream(o)){t=isStreamComplete(o)}let n=Promise.resolve();if(nodeHttpClient_isReadableStream(a)){n=isStreamComplete(a)}Promise.all([t,n]).then((()=>{if(r){e.abortSignal?.removeEventListener("abort",r)}})).catch((e=>{log_logger.warning("Error when cleaning up abortListener on httpRequest",e)}))}}}makeRequest(e,t,r){const n=new URL(e.url);const s=n.protocol!=="https:";if(s&&!e.allowInsecureConnection){throw new Error(`Cannot connect to ${e.url} while allowInsecureConnection is false.`)}const i=e.agent??this.getOrCreateAgent(e,s);const o={agent:i,hostname:n.hostname,path:`${n.pathname}${n.search}`,port:n.port,method:e.method,headers:e.headers.toJSON({preserveCase:true}),...e.requestOverrides};return new Promise(((n,i)=>{const a=s?external_node_http_.request(o,n):external_node_https_namespaceObject.request(o,n);a.once("error",(t=>{i(new restError_RestError(t.message,{code:t.code??restError_RestError.REQUEST_SEND_ERROR,request:e}))}));t.signal.addEventListener("abort",(()=>{const e=new AbortError("The operation was aborted. Rejecting from abort signal callback while making request.");a.destroy(e);i(e)}));if(r&&nodeHttpClient_isReadableStream(r)){r.pipe(a)}else if(r){if(typeof r==="string"||Buffer.isBuffer(r)){a.end(r)}else if(isArrayBuffer(r)){a.end(ArrayBuffer.isView(r)?Buffer.from(r.buffer,r.byteOffset,r.byteLength):Buffer.from(r))}else{log_logger.error("Unrecognized body type",r);i(new restError_RestError("Unrecognized body type"))}}else{a.end()}}))}getOrCreateAgent(e,t){const r=e.disableKeepAlive;if(t){if(r){return external_node_http_.globalAgent}if(!this.cachedHttpAgent){this.cachedHttpAgent=new external_node_http_.Agent({keepAlive:true})}return this.cachedHttpAgent}else{if(r&&!e.tlsSettings){return external_node_https_namespaceObject.globalAgent}const t=e.tlsSettings??DEFAULT_TLS_SETTINGS;let n=this.cachedHttpsAgents.get(t);if(n&&n.options.keepAlive===!r){return n}log_logger.info("No cached TLS Agent exist, creating a new Agent");n=new external_node_https_namespaceObject.Agent({keepAlive:!r,...t});this.cachedHttpsAgents.set(t,n);return n}}}function getResponseHeaders(e){const t=httpHeaders_createHttpHeaders();for(const r of Object.keys(e.headers)){const n=e.headers[r];if(Array.isArray(n)){if(n.length>0){t.set(r,n[0])}}else if(n){t.set(r,n)}}return t}function getDecodedResponseStream(e,t){const r=t.get("Content-Encoding");if(r==="gzip"){const t=external_node_zlib_.createGunzip();e.pipe(t);return t}else if(r==="deflate"){const t=external_node_zlib_.createInflate();e.pipe(t);return t}return e}function streamToText(e){return new Promise(((t,r)=>{const n=[];e.on("data",(e=>{if(Buffer.isBuffer(e)){n.push(e)}else{n.push(Buffer.from(e))}}));e.on("end",(()=>{t(Buffer.concat(n).toString("utf8"))}));e.on("error",(e=>{if(e&&e?.name==="AbortError"){r(e)}else{r(new restError_RestError(`Error reading response as text: ${e.message}`,{code:restError_RestError.PARSE_ERROR}))}}))}))}function getBodyLength(e){if(!e){return 0}else if(Buffer.isBuffer(e)){return e.length}else if(nodeHttpClient_isReadableStream(e)){return null}else if(isArrayBuffer(e)){return e.byteLength}else if(typeof e==="string"){return Buffer.from(e).length}else{return null}}function createNodeHttpClient(){return new NodeHttpClient}function defaultHttpClient_createDefaultHttpClient(){return createNodeHttpClient()}const logPolicyName="logPolicy";function logPolicy_logPolicy(e={}){const t=e.logger??log_logger.info;const r=new Sanitizer({additionalAllowedHeaderNames:e.additionalAllowedHeaderNames,additionalAllowedQueryParameters:e.additionalAllowedQueryParameters});return{name:logPolicyName,async sendRequest(e,n){if(!t.enabled){return n(e)}t(`Request: ${r.sanitize(e)}`);const s=await n(e);t(`Response status code: ${s.status}`);t(`Headers: ${r.sanitize({headers:s.headers})}`);return s}}}function getHeaderName(){return"User-Agent"}async function userAgentPlatform_setPlatformSpecificData(e){if(process&&process.versions){const t=`${os.type()} ${os.release()}; ${os.arch()}`;if(process.versions.bun){e.set("Bun",`${process.versions.bun} (${t})`)}else if(process.versions.deno){e.set("Deno",`${process.versions.deno} (${t})`)}else if(process.versions.node){e.set("Node",`${process.versions.node} (${t})`)}}}function userAgent_getUserAgentString(e){const t=[];for(const[r,n]of e){const e=n?`${r}/${n}`:r;t.push(e)}return t.join(" ")}function getUserAgentHeaderName(){return getHeaderName()}async function userAgent_getUserAgentValue(e){const t=new Map;t.set("ts-http-runtime",SDK_VERSION);await setPlatformSpecificData(t);const r=userAgent_getUserAgentString(t);const n=e?`${e} ${r}`:r;return n}const UserAgentHeaderName=getUserAgentHeaderName();const userAgentPolicyName="userAgentPolicy";function userAgentPolicy_userAgentPolicy(e={}){const t=getUserAgentValue(e.userAgentPrefix);return{name:userAgentPolicyName,async sendRequest(e,r){if(!e.headers.has(UserAgentHeaderName)){e.headers.set(UserAgentHeaderName,await t)}return r(e)}}}function getRandomIntegerInclusive(e,t){e=Math.ceil(e);t=Math.floor(t);const r=Math.floor(Math.random()*(t-e+1));return r+e}function calculateRetryDelay(e,t){const r=t.retryDelayInMs*Math.pow(2,e);const n=Math.min(t.maxRetryDelayInMs,r);const s=n/2+getRandomIntegerInclusive(0,n/2);return{retryAfterInMs:s}}const StandardAbortMessage="The operation was aborted.";function helpers_delay(e,t,r){return new Promise(((n,s)=>{let i=undefined;let o=undefined;const rejectOnAbort=()=>s(new AbortError(r?.abortErrorMsg?r?.abortErrorMsg:StandardAbortMessage));const removeListeners=()=>{if(r?.abortSignal&&o){r.abortSignal.removeEventListener("abort",o)}};o=()=>{if(i){clearTimeout(i)}removeListeners();return rejectOnAbort()};if(r?.abortSignal&&r.abortSignal.aborted){return rejectOnAbort()}i=setTimeout((()=>{removeListeners();n(t)}),e);if(r?.abortSignal){r.abortSignal.addEventListener("abort",o)}}))}function parseHeaderValueAsNumber(e,t){const r=e.headers.get(t);if(!r)return;const n=Number(r);if(Number.isNaN(n))return;return n}const RetryAfterHeader="Retry-After";const AllRetryAfterHeaders=["retry-after-ms","x-ms-retry-after-ms",RetryAfterHeader];function getRetryAfterInMs(e){if(!(e&&[429,503].includes(e.status)))return undefined;try{for(const t of AllRetryAfterHeaders){const r=parseHeaderValueAsNumber(e,t);if(r===0||r){const e=t===RetryAfterHeader?1e3:1;return r*e}}const t=e.headers.get(RetryAfterHeader);if(!t)return;const r=Date.parse(t);const n=r-Date.now();return Number.isFinite(n)?Math.max(0,n):undefined}catch{return undefined}}function isThrottlingRetryResponse(e){return Number.isFinite(getRetryAfterInMs(e))}function throttlingRetryStrategy_throttlingRetryStrategy(){return{name:"throttlingRetryStrategy",retry({response:e}){const t=getRetryAfterInMs(e);if(!Number.isFinite(t)){return{skipStrategy:true}}return{retryAfterInMs:t}}}}const DEFAULT_CLIENT_RETRY_INTERVAL=1e3;const DEFAULT_CLIENT_MAX_RETRY_INTERVAL=1e3*64;function exponentialRetryStrategy_exponentialRetryStrategy(e={}){const t=e.retryDelayInMs??DEFAULT_CLIENT_RETRY_INTERVAL;const r=e.maxRetryDelayInMs??DEFAULT_CLIENT_MAX_RETRY_INTERVAL;return{name:"exponentialRetryStrategy",retry({retryCount:n,response:s,responseError:i}){const o=isSystemError(i);const a=o&&e.ignoreSystemErrors;const c=isExponentialRetryResponse(s);const l=c&&e.ignoreHttpStatusCodes;const u=s&&(isThrottlingRetryResponse(s)||!c);if(u||l||a){return{skipStrategy:true}}if(i&&!o&&!c){return{errorToThrow:i}}return calculateRetryDelay(n,{retryDelayInMs:t,maxRetryDelayInMs:r})}}}function isExponentialRetryResponse(e){return Boolean(e&&e.status!==undefined&&(e.status>=500||e.status===408)&&e.status!==501&&e.status!==505)}function isSystemError(e){if(!e){return false}return e.code==="ETIMEDOUT"||e.code==="ESOCKETTIMEDOUT"||e.code==="ECONNREFUSED"||e.code==="ECONNRESET"||e.code==="ENOENT"||e.code==="ENOTFOUND"}const constants_SDK_VERSION="0.3.9";const constants_DEFAULT_RETRY_POLICY_COUNT=3;const retryPolicyLogger=createClientLogger("ts-http-runtime retryPolicy");const retryPolicyName="retryPolicy";function retryPolicy_retryPolicy(e,t={maxRetries:constants_DEFAULT_RETRY_POLICY_COUNT}){const r=t.logger||retryPolicyLogger;return{name:retryPolicyName,async sendRequest(n,s){let i;let o;let a=-1;e:while(true){a+=1;o=undefined;try{r.info(`Retry ${a}: Attempting to send request`,n.requestId);i=await s(n);r.info(`Retry ${a}: Received a response from request`,n.requestId)}catch(e){r.error(`Retry ${a}: Received an error from request`,n.requestId);if(!restError_isRestError(e)){throw e}o=e;i=e.response}if(n.abortSignal?.aborted){r.error(`Retry ${a}: Request aborted.`);const e=new AbortError;throw e}if(a>=(t.maxRetries??constants_DEFAULT_RETRY_POLICY_COUNT)){r.info(`Retry ${a}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);if(o){throw o}else if(i){return i}else{throw new Error("Maximum retries reached with no response or error to throw")}}r.info(`Retry ${a}: Processing ${e.length} retry strategies.`);t:for(const t of e){const e=t.logger||r;e.info(`Retry ${a}: Processing retry strategy ${t.name}.`);const s=t.retry({retryCount:a,response:i,responseError:o});if(s.skipStrategy){e.info(`Retry ${a}: Skipped.`);continue t}const{errorToThrow:c,retryAfterInMs:l,redirectTo:u}=s;if(c){e.error(`Retry ${a}: Retry strategy ${t.name} throws error:`,c);throw c}if(l||l===0){e.info(`Retry ${a}: Retry strategy ${t.name} retries after ${l}`);await helpers_delay(l,undefined,{abortSignal:n.abortSignal});continue e}if(u){e.info(`Retry ${a}: Retry strategy ${t.name} redirects to ${u}`);n.url=u;continue e}}if(o){r.info(`None of the retry strategies could work with the received error. Throwing it.`);throw o}if(i){r.info(`None of the retry strategies could work with the received response. Returning it.`);return i}}}}}const defaultRetryPolicyName="defaultRetryPolicy";function defaultRetryPolicy_defaultRetryPolicy(e={}){return{name:defaultRetryPolicyName,sendRequest:retryPolicy_retryPolicy([throttlingRetryStrategy_throttlingRetryStrategy(),exponentialRetryStrategy_exponentialRetryStrategy(e)],{maxRetries:e.maxRetries??constants_DEFAULT_RETRY_POLICY_COUNT}).sendRequest}}function bytesEncoding_uint8ArrayToString(e,t){return Buffer.from(e).toString(t)}function bytesEncoding_stringToUint8Array(e,t){return Buffer.from(e,t)}function convertBodyToFormDataMap(e){if(typeof FormData!=="undefined"&&e instanceof FormData){const t={};for(const[r,n]of e.entries()){const e=t[r];if(Array.isArray(e)){e.push(n)}else{t[r]=e!==undefined?[e,n]:[n]}}return t}return undefined}const formDataPolicyName="formDataPolicy";function formDataPolicy_formDataPolicy(){return{name:formDataPolicyName,async sendRequest(e,t){const r=convertBodyToFormDataMap(e.body);if(r){e.formData=r;e.body=undefined}if(e.formData){const t=e.headers.get("Content-Type");if(t&&t.indexOf("application/x-www-form-urlencoded")!==-1){e.body=wwwFormUrlEncode(e.formData)}else{await prepareFormData(e.formData,e)}e.formData=undefined}return t(e)}}}function wwwFormUrlEncode(e){const t=new URLSearchParams;for(const[r,n]of Object.entries(e)){if(Array.isArray(n)){for(const e of n){t.append(r,e.toString())}}else{t.append(r,n.toString())}}return t.toString()}async function prepareFormData(e,t){const r=t.headers.get("Content-Type");if(r&&!r.startsWith("multipart/form-data")){return}t.headers.set("Content-Type",r??"multipart/form-data");const n=[];for(const[t,r]of Object.entries(e)){for(const e of Array.isArray(r)?r:[r]){if(typeof e==="string"){n.push({headers:httpHeaders_createHttpHeaders({"Content-Disposition":`form-data; name="${t}"`}),body:bytesEncoding_stringToUint8Array(e,"utf-8")})}else if(e===undefined||e===null||typeof e!=="object"){throw new Error(`Unexpected value for key ${t}: ${e}. Value should be serialized to string first.`)}else{const r=e.name||"blob";const s=httpHeaders_createHttpHeaders();s.set("Content-Disposition",`form-data; name="${t}"; filename="${r}"`);s.set("Content-Type",e.type||"application/octet-stream");n.push({headers:s,body:e})}}}t.multipartBody={parts:n}}var dist=__nccwpck_require__(3669);var http_proxy_agent_dist=__nccwpck_require__(81970);const HTTPS_PROXY="HTTPS_PROXY";const HTTP_PROXY="HTTP_PROXY";const ALL_PROXY="ALL_PROXY";const NO_PROXY="NO_PROXY";const proxyPolicyName="proxyPolicy";const globalNoProxyList=[];let noProxyListLoaded=false;const globalBypassedMap=new Map;function getEnvironmentValue(e){if(process.env[e]){return process.env[e]}else if(process.env[e.toLowerCase()]){return process.env[e.toLowerCase()]}return undefined}function loadEnvironmentProxyValue(){if(!process){return undefined}const e=getEnvironmentValue(HTTPS_PROXY);const t=getEnvironmentValue(ALL_PROXY);const r=getEnvironmentValue(HTTP_PROXY);return e||t||r}function isBypassed(e,t,r){if(t.length===0){return false}const n=new URL(e).hostname;if(r?.has(n)){return r.get(n)}let s=false;for(const e of t){if(e[0]==="."){if(n.endsWith(e)){s=true}else{if(n.length===e.length-1&&n===e.slice(1)){s=true}}}else{if(n===e){s=true}}}r?.set(n,s);return s}function loadNoProxy(){const e=getEnvironmentValue(NO_PROXY);noProxyListLoaded=true;if(e){return e.split(",").map((e=>e.trim())).filter((e=>e.length))}return[]}function getDefaultProxySettings(e){if(!e){e=loadEnvironmentProxyValue();if(!e){return undefined}}const t=new URL(e);const r=t.protocol?t.protocol+"//":"";return{host:r+t.hostname,port:Number.parseInt(t.port||"80"),username:t.username,password:t.password}}function getDefaultProxySettingsInternal(){const e=loadEnvironmentProxyValue();return e?new URL(e):undefined}function getUrlFromProxySettings(e){let t;try{t=new URL(e.host)}catch{throw new Error(`Expecting a valid host string in proxy settings, but found "${e.host}".`)}t.port=String(e.port);if(e.username){t.username=e.username}if(e.password){t.password=e.password}return t}function setProxyAgentOnRequest(e,t,r){if(e.agent){return}const n=new URL(e.url);const s=n.protocol!=="https:";if(e.tlsSettings){log_logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.")}if(s){if(!t.httpProxyAgent){t.httpProxyAgent=new http_proxy_agent_dist.HttpProxyAgent(r)}e.agent=t.httpProxyAgent}else{if(!t.httpsProxyAgent){t.httpsProxyAgent=new dist.HttpsProxyAgent(r)}e.agent=t.httpsProxyAgent}}function proxyPolicy_proxyPolicy(e,t){if(!noProxyListLoaded){globalNoProxyList.push(...loadNoProxy())}const r=e?getUrlFromProxySettings(e):getDefaultProxySettingsInternal();const n={};return{name:proxyPolicyName,async sendRequest(e,s){if(!e.proxySettings&&r&&!isBypassed(e.url,t?.customNoProxyList??globalNoProxyList,t?.customNoProxyList?undefined:globalBypassedMap)){setProxyAgentOnRequest(e,n,r)}else if(e.proxySettings){setProxyAgentOnRequest(e,n,getUrlFromProxySettings(e.proxySettings))}return s(e)}}}const redirectPolicyName="redirectPolicy";const allowedRedirect=["GET","HEAD"];function redirectPolicy_redirectPolicy(e={}){const{maxRetries:t=20,allowCrossOriginRedirects:r=false}=e;return{name:redirectPolicyName,async sendRequest(e,n){const s=await n(e);return handleRedirect(n,s,t,r)}}}async function handleRedirect(e,t,r,n,s=0){const{request:i,status:o,headers:a}=t;const c=a.get("location");if(c&&(o===300||o===301&&allowedRedirect.includes(i.method)||o===302&&allowedRedirect.includes(i.method)||o===303&&i.method==="POST"||o===307)&&stypeof e==="function"?e():e)).map(toStream);return external_stream_.Readable.from(async function*(){for(const e of t){for await(const t of e){yield t}}}())}}function generateBoundary(){return`----AzSDKFormBoundary${randomUUID()}`}function encodeHeaders(e){let t="";for(const[r,n]of e){t+=`${r}: ${n}\r\n`}return t}function getLength(e){if(e instanceof Uint8Array){return e.byteLength}else if(typeGuards_isBlob(e)){return e.size===-1?undefined:e.size}else{return undefined}}function getTotalLength(e){let t=0;for(const r of e){const e=getLength(r);if(e===undefined){return undefined}else{t+=e}}return t}async function buildRequestBody(e,t,r){const n=[bytesEncoding_stringToUint8Array(`--${r}`,"utf-8"),...t.flatMap((e=>[bytesEncoding_stringToUint8Array("\r\n","utf-8"),bytesEncoding_stringToUint8Array(encodeHeaders(e.headers),"utf-8"),bytesEncoding_stringToUint8Array("\r\n","utf-8"),e.body,bytesEncoding_stringToUint8Array(`\r\n--${r}`,"utf-8")])),bytesEncoding_stringToUint8Array("--\r\n\r\n","utf-8")];const s=getTotalLength(n);if(s){e.headers.set("Content-Length",s)}e.body=await concat(n)}const multipartPolicy_multipartPolicyName="multipartPolicy";const maxBoundaryLength=70;const validBoundaryCharacters=new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);function assertValidBoundary(e){if(e.length>maxBoundaryLength){throw new Error(`Multipart boundary "${e}" exceeds maximum length of 70 characters`)}if(Array.from(e).some((e=>!validBoundaryCharacters.has(e)))){throw new Error(`Multipart boundary "${e}" contains invalid characters`)}}function multipartPolicy_multipartPolicy(){return{name:multipartPolicy_multipartPolicyName,async sendRequest(e,t){if(!e.multipartBody){return t(e)}if(e.body){throw new Error("multipartBody and regular body cannot be set at the same time")}let r=e.multipartBody.boundary;const n=e.headers.get("Content-Type")??"multipart/mixed";const s=n.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);if(!s){throw new Error(`Got multipart request body, but content-type header was not multipart: ${n}`)}const[,i,o]=s;if(o&&r&&o!==r){throw new Error(`Multipart boundary was specified as ${o} in the header, but got ${r} in the request body`)}r??=o;if(r){assertValidBoundary(r)}else{r=generateBoundary()}e.headers.set("Content-Type",`${i}; boundary=${r}`);await buildRequestBody(e,e.multipartBody.parts,r);e.multipartBody=undefined;return t(e)}}}function createPipelineFromOptions_createPipelineFromOptions(e){const t=createEmptyPipeline();addPlatformPolicies(t,e);t.addPolicy(formDataPolicy(),{beforePolicies:[multipartPolicyName]});t.addPolicy(userAgentPolicy(e.userAgentOptions));t.addPolicy(multipartPolicy(),{afterPhase:"Deserialize"});t.addPolicy(defaultRetryPolicy(e.retryOptions),{phase:"Retry"});t.addPolicy(logPolicy(e.loggingOptions),{afterPhase:"Sign"});return t}let insecureConnectionWarningEmmitted=false;function allowInsecureConnection(e,t){if(t.allowInsecureConnection&&e.allowInsecureConnection){const t=new URL(e.url);if(t.hostname==="localhost"||t.hostname==="127.0.0.1"){return true}}return false}function emitInsecureConnectionWarning(){const e="Sending token over insecure transport. Assume any token issued is compromised.";logger.warning(e);if(!insecureConnectionWarningEmmitted){insecureConnectionWarningEmmitted=true;emitNodeWarning(e)}}function checkInsecureConnection_ensureSecureConnection(e,t){if(!e.url.toLowerCase().startsWith("https://")){if(allowInsecureConnection(e,t)){emitInsecureConnectionWarning()}else{throw new Error("Authentication is not permitted for non-TLS protected (non-https) URLs when allowInsecureConnection is false.")}}}const apiKeyAuthenticationPolicyName="apiKeyAuthenticationPolicy";function apiKeyAuthenticationPolicy_apiKeyAuthenticationPolicy(e){return{name:apiKeyAuthenticationPolicyName,async sendRequest(t,r){ensureSecureConnection(t,e);const n=(t.authSchemes??e.authSchemes)?.find((e=>e.kind==="apiKey"));if(!n){return r(t)}if(n.apiKeyLocation!=="header"){throw new Error(`Unsupported API key location: ${n.apiKeyLocation}`)}t.headers.set(n.name,e.credential.key);return r(t)}}}const basicAuthenticationPolicyName="bearerAuthenticationPolicy";function basicAuthenticationPolicy_basicAuthenticationPolicy(e){return{name:basicAuthenticationPolicyName,async sendRequest(t,r){ensureSecureConnection(t,e);const n=(t.authSchemes??e.authSchemes)?.find((e=>e.kind==="http"&&e.scheme==="basic"));if(!n){return r(t)}const{username:s,password:i}=e.credential;const o=uint8ArrayToString(stringToUint8Array(`${s}:${i}`,"utf-8"),"base64");t.headers.set("Authorization",`Basic ${o}`);return r(t)}}}const bearerAuthenticationPolicyName="bearerAuthenticationPolicy";function bearerAuthenticationPolicy_bearerAuthenticationPolicy(e){return{name:bearerAuthenticationPolicyName,async sendRequest(t,r){ensureSecureConnection(t,e);const n=(t.authSchemes??e.authSchemes)?.find((e=>e.kind==="http"&&e.scheme==="bearer"));if(!n){return r(t)}const s=await e.credential.getBearerToken({abortSignal:t.abortSignal});t.headers.set("Authorization",`Bearer ${s}`);return r(t)}}}const oauth2AuthenticationPolicyName="oauth2AuthenticationPolicy";function oauth2AuthenticationPolicy_oauth2AuthenticationPolicy(e){return{name:oauth2AuthenticationPolicyName,async sendRequest(t,r){ensureSecureConnection(t,e);const n=(t.authSchemes??e.authSchemes)?.find((e=>e.kind==="oauth2"));if(!n){return r(t)}const s=await e.credential.getOAuth2Token(n.flows,{abortSignal:t.abortSignal});t.headers.set("Authorization",`Bearer ${s}`);return r(t)}}}let cachedHttpClient;function clientHelpers_createDefaultPipeline(e={}){const t=createPipelineFromOptions(e);t.addPolicy(apiVersionPolicy(e));const{credential:r,authSchemes:n,allowInsecureConnection:s}=e;if(r){if(isApiKeyCredential(r)){t.addPolicy(apiKeyAuthenticationPolicy({authSchemes:n,credential:r,allowInsecureConnection:s}))}else if(isBasicCredential(r)){t.addPolicy(basicAuthenticationPolicy({authSchemes:n,credential:r,allowInsecureConnection:s}))}else if(isBearerTokenCredential(r)){t.addPolicy(bearerAuthenticationPolicy({authSchemes:n,credential:r,allowInsecureConnection:s}))}else if(isOAuth2TokenCredential(r)){t.addPolicy(oauth2AuthenticationPolicy({authSchemes:n,credential:r,allowInsecureConnection:s}))}}return t}function clientHelpers_getCachedDefaultHttpsClient(){if(!cachedHttpClient){cachedHttpClient=createDefaultHttpClient()}return cachedHttpClient}function getHeaderValue(e,t){if(e.headers){const r=Object.keys(e.headers).find((e=>e.toLowerCase()===t.toLowerCase()));if(r){return e.headers[r]}}return undefined}function getPartContentType(e){const t=getHeaderValue(e,"content-type");if(t){return t}if(e.contentType===null){return undefined}if(e.contentType){return e.contentType}const{body:r}=e;if(r===null||r===undefined){return undefined}if(typeof r==="string"||typeof r==="number"||typeof r==="boolean"){return"text/plain; charset=UTF-8"}if(r instanceof Blob){return r.type||"application/octet-stream"}if(isBinaryBody(r)){return"application/octet-stream"}return"application/json"}function escapeDispositionField(e){return JSON.stringify(e)}function getContentDisposition(e){const t=getHeaderValue(e,"content-disposition");if(t){return t}if(e.dispositionType===undefined&&e.name===undefined&&e.filename===undefined){return undefined}const r=e.dispositionType??"form-data";let n=r;if(e.name){n+=`; name=${escapeDispositionField(e.name)}`}let s=undefined;if(e.filename){s=e.filename}else if(typeof File!=="undefined"&&e.body instanceof File){const t=e.body.name;if(t!==""){s=t}}if(s){n+=`; filename=${escapeDispositionField(s)}`}return n}function normalizeBody(e,t){if(e===undefined){return new Uint8Array([])}if(isBinaryBody(e)){return e}if(typeof e==="string"||typeof e==="number"||typeof e==="boolean"){return stringToUint8Array(String(e),"utf-8")}if(t&&/application\/(.+\+)?json(;.+)?/i.test(String(t))){return stringToUint8Array(JSON.stringify(e),"utf-8")}throw new RestError(`Unsupported body/content-type combination: ${e}, ${t}`)}function buildBodyPart(e){const t=getPartContentType(e);const r=getContentDisposition(e);const n=createHttpHeaders(e.headers??{});if(t){n.set("content-type",t)}if(r){n.set("content-disposition",r)}const s=normalizeBody(e.body,t);return{headers:n,body:s}}function multipart_buildMultipartBody(e){return{parts:e.map(buildBodyPart)}}async function sendRequest_sendRequest(e,t,r,n={},s){const i=s??getCachedDefaultHttpsClient();const o=buildPipelineRequest(e,t,n);try{const e=await r.sendRequest(i,o);const t=e.headers.toJSON();const s=e.readableStreamBody??e.browserStreamBody;const a=n.responseAsStream||s!==undefined?undefined:getResponseBody(e);const c=s??a;if(n?.onResponse){n.onResponse({...e,request:o,rawHeaders:t,parsedBody:a})}return{request:o,headers:t,status:`${e.status}`,body:c}}catch(e){if(isRestError(e)&&e.response&&n.onResponse){const{response:t}=e;const r=t.headers.toJSON();n?.onResponse({...t,request:o,rawHeaders:r},e)}throw e}}function getRequestContentType(e={}){if(e.contentType){return e.contentType}const t=e.headers?.["content-type"];if(typeof t==="string"){return t}return getContentType(e.body)}function getContentType(e){if(e===undefined){return undefined}if(ArrayBuffer.isView(e)){return"application/octet-stream"}if(isBlob(e)&&e.type){return e.type}if(typeof e==="string"){try{JSON.parse(e);return"application/json"}catch(e){return undefined}}return"application/json"}function buildPipelineRequest(e,t,r={}){const n=getRequestContentType(r);const{body:s,multipartBody:i}=getRequestBody(r.body,n);const o=r.accept??r.headers?.accept??(r.noDefaultAcceptHeader?undefined:"application/json");const a=createHttpHeaders({...r.headers?r.headers:{},...o!==undefined&&{accept:o},...n&&{"content-type":n}});const{allowInsecureConnection:c,abortSignal:l,onUploadProgress:u,onDownloadProgress:d,timeout:A,responseAsStream:p,noDefaultAcceptHeader:f,url:h,method:g,body:y,multipartBody:b,headers:I,...B}=r;const w=createPipelineRequest({url:t,method:e,body:s,multipartBody:i,headers:a,allowInsecureConnection:c,abortSignal:l,onUploadProgress:u,onDownloadProgress:d,timeout:A,enableBrowserStreams:true,streamResponseStatusCodes:p?new Set([Number.POSITIVE_INFINITY]):undefined});Object.assign(w,B);return w}function getRequestBody(e,t=""){if(e===undefined){return{body:undefined}}if(typeof FormData!=="undefined"&&e instanceof FormData){return{body:e}}if(isBlob(e)){return{body:e}}if(isReadableStream(e)){return{body:e}}if(typeof e==="function"){return{body:e}}if(ArrayBuffer.isView(e)){return{body:e instanceof Uint8Array?e:JSON.stringify(e)}}const r=t.split(";")[0];switch(r){case"application/json":return{body:JSON.stringify(e)};case"multipart/form-data":if(Array.isArray(e)){return{multipartBody:buildMultipartBody(e)}}return{body:JSON.stringify(e)};case"text/plain":return{body:String(e)};default:if(typeof e==="string"){return{body:e}}return{body:JSON.stringify(e)}}}function getResponseBody(e){const t=e.headers.get("content-type")??"";const r=t.split(";")[0];const n=e.bodyAsText??"";if(r==="text/plain"){return String(n)}try{return n?JSON.parse(n):undefined}catch(t){if(r==="application/json"){throw createParseError(e,t)}return String(n)}}function createParseError(e,t){const r=`Error "${t}" occurred while parsing the response body - ${e.bodyAsText}.`;const n=t.code??RestError.PARSE_ERROR;return new RestError(r,{code:n,statusCode:e.status,request:e.request,response:e})}function getClient(e,t={}){const r=t.pipeline??createDefaultPipeline(t);if(t.additionalPolicies?.length){for(const{policy:e,position:n}of t.additionalPolicies){const t=n==="perRetry"?"Sign":undefined;r.addPolicy(e,{afterPhase:t})}}const n=t.internal?.noDefaultAcceptHeader??false;const{allowInsecureConnection:s,httpClient:i}=t;const o=t.endpoint??e;const client=(e,...t)=>{const getUrl=r=>buildRequestUrl(o,e,t,{allowInsecureConnection:s,...r});return{get:(e={})=>buildOperation("GET",getUrl(e),r,e,s,i,n),post:(e={})=>buildOperation("POST",getUrl(e),r,e,s,i,n),put:(e={})=>buildOperation("PUT",getUrl(e),r,e,s,i,n),patch:(e={})=>buildOperation("PATCH",getUrl(e),r,e,s,i,n),delete:(e={})=>buildOperation("DELETE",getUrl(e),r,e,s,i,n),head:(e={})=>buildOperation("HEAD",getUrl(e),r,e,s,i,n),options:(e={})=>buildOperation("OPTIONS",getUrl(e),r,e,s,i,n),trace:(e={})=>buildOperation("TRACE",getUrl(e),r,e,s,i,n)}};return{path:client,pathUnchecked:client,pipeline:r}}function buildOperation(e,t,r,n,s,i,o=false){s=n.allowInsecureConnection??s;return{then:function(a,c){return sendRequest(e,t,r,{...n,allowInsecureConnection:s,noDefaultAcceptHeader:o},i).then(a,c)},async asBrowserStream(){if(isNodeLike){throw new Error("`asBrowserStream` is supported only in the browser environment. Use `asNodeStream` instead to obtain the response body stream. If you require a Web stream of the response in Node, consider using `Readable.toWeb` on the result of `asNodeStream`.")}else{return sendRequest(e,t,r,{...n,allowInsecureConnection:s,noDefaultAcceptHeader:o,responseAsStream:true},i)}},async asNodeStream(){if(isNodeLike){return sendRequest(e,t,r,{...n,allowInsecureConnection:s,noDefaultAcceptHeader:o,responseAsStream:true},i)}else{throw new Error("`isNodeStream` is not supported in the browser environment. Use `asBrowserStream` to obtain the response body stream.")}}}}function createRestError(e,t){const r=typeof e==="string"?t:e;const n=r.body?.error??r.body;const s=typeof e==="string"?e:n?.message??`Unexpected status code: ${r.status}`;return new RestError(s,{statusCode:statusCodeToNumber(r.status),code:n?.code,request:r.request,response:toPipelineResponse(r)})}function toPipelineResponse(e){return{headers:createHttpHeaders(e.headers),request:e.request,status:statusCodeToNumber(e.status)??-1,...typeof e.body==="string"?{bodyAsText:e.body}:{}}}function statusCodeToNumber(e){const t=Number.parseInt(e);return Number.isNaN(t)?undefined:t}function esm_pipeline_createEmptyPipeline(){return pipeline_createEmptyPipeline()}const esm_context=createLoggerContext({logLevelEnvVarName:"AZURE_LOG_LEVEL",namespace:"azure"});const AzureLogger=esm_context.logger;function esm_setLogLevel(e){esm_context.setLogLevel(e)}function esm_getLogLevel(){return esm_context.getLogLevel()}function esm_createClientLogger(e){return esm_context.createClientLogger(e)}const esm_log_logger=esm_createClientLogger("core-rest-pipeline");const agentPolicyName="agentPolicy";function agentPolicy_agentPolicy(e){return{name:agentPolicyName,sendRequest:async(t,r)=>{if(!t.agent){t.agent=e}return r(t)}}}const decompressResponsePolicyName="decompressResponsePolicy";function decompressResponsePolicy_decompressResponsePolicy(){return{name:decompressResponsePolicyName,async sendRequest(e,t){if(e.method!=="HEAD"){e.headers.set("Accept-Encoding","gzip,deflate")}return t(e)}}}const exponentialRetryPolicyName="exponentialRetryPolicy";function exponentialRetryPolicy(e={}){return retryPolicy([exponentialRetryStrategy({...e,ignoreSystemErrors:true})],{maxRetries:e.maxRetries??DEFAULT_RETRY_POLICY_COUNT})}const systemErrorRetryPolicyName="systemErrorRetryPolicy";function systemErrorRetryPolicy(e={}){return{name:systemErrorRetryPolicyName,sendRequest:retryPolicy([exponentialRetryStrategy({...e,ignoreHttpStatusCodes:true})],{maxRetries:e.maxRetries??DEFAULT_RETRY_POLICY_COUNT}).sendRequest}}const throttlingRetryPolicyName="throttlingRetryPolicy";function throttlingRetryPolicy(e={}){return{name:throttlingRetryPolicyName,sendRequest:retryPolicy([throttlingRetryStrategy()],{maxRetries:e.maxRetries??DEFAULT_RETRY_POLICY_COUNT}).sendRequest}}const tlsPolicyName="tlsPolicy";function tlsPolicy_tlsPolicy(e){return{name:tlsPolicyName,sendRequest:async(t,r)=>{if(!t.tlsSettings){t.tlsSettings=e}return r(t)}}}const logPolicy_logPolicyName=null&&tspLogPolicyName;function policies_logPolicy_logPolicy(e={}){return logPolicy_logPolicy({logger:esm_log_logger.info,...e})}const redirectPolicy_redirectPolicyName=redirectPolicyName;function policies_redirectPolicy_redirectPolicy(e={}){return redirectPolicy_redirectPolicy(e)}function userAgentPlatform_getHeaderName(){return"User-Agent"}async function util_userAgentPlatform_setPlatformSpecificData(e){if(external_node_process_namespaceObject&&external_node_process_namespaceObject.versions){const t=`${external_node_os_namespaceObject.type()} ${external_node_os_namespaceObject.release()}; ${external_node_os_namespaceObject.arch()}`;if(external_node_process_namespaceObject.versions.bun){e.set("Bun",`${external_node_process_namespaceObject.versions.bun} (${t})`)}else if(external_node_process_namespaceObject.versions.deno){e.set("Deno",`${external_node_process_namespaceObject.versions.deno} (${t})`)}else if(external_node_process_namespaceObject.versions.node){e.set("Node",`${external_node_process_namespaceObject.versions.node} (${t})`)}}}const esm_constants_SDK_VERSION="1.25.0";const esm_constants_DEFAULT_RETRY_POLICY_COUNT=3;function util_userAgent_getUserAgentString(e){const t=[];for(const[r,n]of e){const e=n?`${r}/${n}`:r;t.push(e)}return t.join(" ")}function userAgent_getUserAgentHeaderName(){return userAgentPlatform_getHeaderName()}async function util_userAgent_getUserAgentValue(e){const t=new Map;t.set("core-rest-pipeline",esm_constants_SDK_VERSION);await util_userAgentPlatform_setPlatformSpecificData(t);const r=util_userAgent_getUserAgentString(t);const n=e?`${e} ${r}`:r;return n}const userAgentPolicy_UserAgentHeaderName=userAgent_getUserAgentHeaderName();const userAgentPolicy_userAgentPolicyName="userAgentPolicy";function policies_userAgentPolicy_userAgentPolicy(e={}){const t=util_userAgent_getUserAgentValue(e.userAgentPrefix);return{name:userAgentPolicy_userAgentPolicyName,async sendRequest(e,r){if(!e.headers.has(userAgentPolicy_UserAgentHeaderName)){e.headers.set(userAgentPolicy_UserAgentHeaderName,await t)}return r(e)}}}function createFile(e,t,r={}){return createRawFile(e,t,r)}function file_isNodeReadableStream(e){return typeof e==="object"&&e!==null&&"pipe"in e&&typeof e.pipe==="function"}const unimplementedMethods={arrayBuffer:()=>{throw new Error("Not implemented")},bytes:()=>{throw new Error("Not implemented")},slice:()=>{throw new Error("Not implemented")},text:()=>{throw new Error("Not implemented")}};const rawContent=Symbol("rawContent");function hasRawContent(e){return typeof e[rawContent]==="function"}function getRawContent(e){if(hasRawContent(e)){return e[rawContent]()}else{return e}}function file_createRawFile(e,t,r={}){return{...unimplementedMethods,type:r.type??"",lastModified:r.lastModified??(new Date).getTime(),webkitRelativePath:r.webkitRelativePath??"",size:e.byteLength,name:t,arrayBuffer:async()=>toArrayBuffer(e).buffer,stream:()=>new Blob([toArrayBuffer(e)]).stream(),[rawContent]:()=>e}}function createFileFromStream(e,t,r={}){return{...unimplementedMethods,type:r.type??"",lastModified:r.lastModified??(new Date).getTime(),webkitRelativePath:r.webkitRelativePath??"",size:r.size??-1,name:t,stream:()=>{const t=e();if(file_isNodeReadableStream(t)){throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.")}return t},[rawContent]:e}}function hasArrayBuffer(e){return"resize"in e.buffer}function toArrayBuffer(e){if(hasArrayBuffer(e)){if(e.byteOffset!==0||e.byteLength!==e.buffer.byteLength){return new Uint8Array(e)}return e}return e.map((e=>e))}const policies_multipartPolicy_multipartPolicyName=multipartPolicy_multipartPolicyName;function policies_multipartPolicy_multipartPolicy(){const e=multipartPolicy_multipartPolicy();return{name:policies_multipartPolicy_multipartPolicyName,sendRequest:async(t,r)=>{if(t.multipartBody){for(const e of t.multipartBody.parts){if(hasRawContent(e.body)){e.body=getRawContent(e.body)}}}return e.sendRequest(t,r)}}}const decompressResponsePolicy_decompressResponsePolicyName=decompressResponsePolicyName;function policies_decompressResponsePolicy_decompressResponsePolicy(){return decompressResponsePolicy_decompressResponsePolicy()}const defaultRetryPolicy_defaultRetryPolicyName=null&&tspDefaultRetryPolicyName;function policies_defaultRetryPolicy_defaultRetryPolicy(e={}){return defaultRetryPolicy_defaultRetryPolicy(e)}const formDataPolicy_formDataPolicyName=null&&tspFormDataPolicyName;function policies_formDataPolicy_formDataPolicy(){return formDataPolicy_formDataPolicy()}var external_node_crypto_=__nccwpck_require__(77598);async function computeSha256Hmac(e,t,r){const n=Buffer.from(e,"base64");return createHmac("sha256",n).update(t).digest(r)}async function computeSha256Hash(e,t){return createHash("sha256").update(e).digest(t)}class AbortError_AbortError extends Error{constructor(e){super(e);this.name="AbortError"}}function createAbortablePromise(e,t){const{cleanupBeforeAbort:r,abortSignal:n,abortErrorMsg:s}=t??{};return new Promise(((t,i)=>{function rejectOnAbort(){i(new AbortError_AbortError(s??"The operation was aborted."))}function removeListeners(){n?.removeEventListener("abort",onAbort)}function onAbort(){r?.();removeListeners();rejectOnAbort()}if(n?.aborted){return rejectOnAbort()}try{e((e=>{removeListeners();t(e)}),(e=>{removeListeners();i(e)}))}catch(e){i(e)}n?.addEventListener("abort",onAbort)}))}const delay_StandardAbortMessage="The delay was aborted.";function delay_delay(e,t){let r;const{abortSignal:n,abortErrorMsg:s}=t??{};return createAbortablePromise((t=>{r=setTimeout(t,e)}),{cleanupBeforeAbort:()=>clearTimeout(r),abortSignal:n,abortErrorMsg:s??delay_StandardAbortMessage})}function getErrorMessage(e){if(isError(e)){return e.message}else{let t;try{if(typeof e==="object"&&e){t=JSON.stringify(e)}else{t=String(e)}}catch(e){t="[unable to stringify input]"}return`Unknown error ${t}`}}function esm_calculateRetryDelay(e,t){return tspRuntime.calculateRetryDelay(e,t)}function esm_computeSha256Hash(e,t){return tspRuntime.computeSha256Hash(e,t)}function esm_computeSha256Hmac(e,t,r){return tspRuntime.computeSha256Hmac(e,t,r)}function esm_getRandomIntegerInclusive(e,t){return tspRuntime.getRandomIntegerInclusive(e,t)}function esm_isError(e){return isError(e)}function esm_isObject(e){return tspRuntime.isObject(e)}function esm_randomUUID(){return randomUUID()}const esm_isBrowser=isBrowser;const esm_isBun=isBun;const esm_isDeno=isDeno;const isNode=env_isNodeLike;const esm_isNodeLike=env_isNodeLike;const esm_isNodeRuntime=isNodeRuntime;const esm_isReactNative=isReactNative;const esm_isWebWorker=isWebWorker;function esm_uint8ArrayToString(e,t){return bytesEncoding_uint8ArrayToString(e,t)}function esm_stringToUint8Array(e,t){return bytesEncoding_stringToUint8Array(e,t)}const proxyPolicy_proxyPolicyName=null&&tspProxyPolicyName;function proxyPolicy_getDefaultProxySettings(e){return getDefaultProxySettings(e)}function policies_proxyPolicy_proxyPolicy(e,t){return proxyPolicy_proxyPolicy(e,t)}const setClientRequestIdPolicyName="setClientRequestIdPolicy";function setClientRequestIdPolicy(e="x-ms-client-request-id"){return{name:setClientRequestIdPolicyName,async sendRequest(t,r){if(!t.headers.has(e)){t.headers.set(e,t.requestId)}return r(t)}}}const agentPolicy_agentPolicyName=null&&tspAgentPolicyName;function policies_agentPolicy_agentPolicy(e){return agentPolicy_agentPolicy(e)}const tlsPolicy_tlsPolicyName=null&&tspTlsPolicyName;function policies_tlsPolicy_tlsPolicy(e){return tlsPolicy_tlsPolicy(e)}const knownContextKeys={span:Symbol.for("@azure/core-tracing span"),namespace:Symbol.for("@azure/core-tracing namespace")};function createTracingContext(e={}){let t=new TracingContextImpl(e.parentContext);if(e.span){t=t.setValue(knownContextKeys.span,e.span)}if(e.namespace){t=t.setValue(knownContextKeys.namespace,e.namespace)}return t}class TracingContextImpl{_contextMap;constructor(e){this._contextMap=e instanceof TracingContextImpl?new Map(e._contextMap):new Map}setValue(e,t){const r=new TracingContextImpl(this);r._contextMap.set(e,t);return r}getValue(e){return this._contextMap.get(e)}deleteValue(e){const t=new TracingContextImpl(this);t._contextMap.delete(e);return t}}var state_cjs=__nccwpck_require__(39437);const state_state=state_cjs.w;function createDefaultTracingSpan(){return{end:()=>{},isRecording:()=>false,recordException:()=>{},setAttribute:()=>{},setStatus:()=>{},addEvent:()=>{}}}function createDefaultInstrumenter(){return{createRequestHeaders:()=>({}),parseTraceparentHeader:()=>undefined,startSpan:(e,t)=>({span:createDefaultTracingSpan(),tracingContext:createTracingContext({parentContext:t.tracingContext})}),withContext(e,t,...r){return t(...r)}}}function useInstrumenter(e){state.instrumenterImplementation=e}function getInstrumenter(){if(!state_state.instrumenterImplementation){state_state.instrumenterImplementation=createDefaultInstrumenter()}return state_state.instrumenterImplementation}function createTracingClient(e){const{namespace:t,packageName:r,packageVersion:n}=e;function startSpan(e,s,i){const o=getInstrumenter().startSpan(e,{...i,packageName:r,packageVersion:n,tracingContext:s?.tracingOptions?.tracingContext});let a=o.tracingContext;const c=o.span;if(!a.getValue(knownContextKeys.namespace)){a=a.setValue(knownContextKeys.namespace,t)}c.setAttribute("az.namespace",a.getValue(knownContextKeys.namespace));const l=Object.assign({},s,{tracingOptions:{...s?.tracingOptions,tracingContext:a}});return{span:c,updatedOptions:l}}async function withSpan(e,t,r,n){const{span:s,updatedOptions:i}=startSpan(e,t,n);try{const e=await withContext(i.tracingOptions.tracingContext,(()=>r(i,s)));s.setStatus({status:"success"});return e}catch(e){s.setStatus({status:"error",error:e});throw e}finally{s.end()}}function withContext(e,t,...r){return getInstrumenter().withContext(e,t,...r)}function parseTraceparentHeader(e){return getInstrumenter().parseTraceparentHeader(e)}function createRequestHeaders(e){return getInstrumenter().createRequestHeaders(e)}return{startSpan:startSpan,withSpan:withSpan,withContext:withContext,parseTraceparentHeader:parseTraceparentHeader,createRequestHeaders:createRequestHeaders}}const esm_restError_RestError=restError_RestError;function esm_restError_isRestError(e){return restError_isRestError(e)}const tracingPolicyName="tracingPolicy";function tracingPolicy(e={}){const t=util_userAgent_getUserAgentValue(e.userAgentPrefix);const r=new Sanitizer({additionalAllowedQueryParameters:e.additionalAllowedQueryParameters});const n=tryCreateTracingClient();return{name:tracingPolicyName,async sendRequest(e,s){if(!n){return s(e)}const i=await t;const o={"http.url":r.sanitizeUrl(e.url),"http.method":e.method,"http.user_agent":i,requestId:e.requestId};if(i){o["http.user_agent"]=i}const{span:a,tracingContext:c}=tryCreateSpan(n,e,o)??{};if(!a||!c){return s(e)}try{const t=await n.withContext(c,s,e);tryProcessResponse(a,t);return t}catch(e){tryProcessError(a,e);throw e}}}}function tryCreateTracingClient(){try{return createTracingClient({namespace:"",packageName:"@azure/core-rest-pipeline",packageVersion:esm_constants_SDK_VERSION})}catch(e){esm_log_logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`);return undefined}}function tryCreateSpan(e,t,r){try{const{span:n,updatedOptions:s}=e.startSpan(`HTTP ${t.method}`,{tracingOptions:t.tracingOptions},{spanKind:"client",spanAttributes:r});if(!n.isRecording()){n.end();return undefined}const i=e.createRequestHeaders(s.tracingOptions.tracingContext);for(const[e,r]of Object.entries(i)){t.headers.set(e,r)}return{span:n,tracingContext:s.tracingOptions.tracingContext}}catch(e){esm_log_logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`);return undefined}}function tryProcessError(e,t){try{e.setStatus({status:"error",error:esm_isError(t)?t:undefined});if(esm_restError_isRestError(t)&&t.statusCode){e.setAttribute("http.status_code",t.statusCode)}e.end()}catch(e){esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`)}}function tryProcessResponse(e,t){try{e.setAttribute("http.status_code",t.status);const r=t.headers.get("x-ms-request-id");if(r){e.setAttribute("serviceRequestId",r)}if(t.status>=400){e.setStatus({status:"error"})}e.end()}catch(e){esm_log_logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`)}}function wrapAbortSignalLike(e){if(e instanceof AbortSignal){return{abortSignal:e}}if(e.aborted){return{abortSignal:AbortSignal.abort("reason"in e?e.reason:undefined)}}const t=new AbortController;let r=true;function cleanup(){if(r){e.removeEventListener("abort",listener);r=false}}function listener(){t.abort("reason"in e?e.reason:undefined);cleanup()}e.addEventListener("abort",listener);return{abortSignal:t.signal,cleanup:cleanup}}const wrapAbortSignalLikePolicyName="wrapAbortSignalLikePolicy";function wrapAbortSignalLikePolicy(){return{name:wrapAbortSignalLikePolicyName,sendRequest:async(e,t)=>{if(!e.abortSignal){return t(e)}const{abortSignal:r,cleanup:n}=wrapAbortSignalLike(e.abortSignal);e.abortSignal=r;try{return await t(e)}finally{n?.()}}}}function esm_createPipelineFromOptions_createPipelineFromOptions(e){const t=esm_pipeline_createEmptyPipeline();if(esm_isNodeLike){if(e.agent){t.addPolicy(policies_agentPolicy_agentPolicy(e.agent))}if(e.tlsOptions){t.addPolicy(policies_tlsPolicy_tlsPolicy(e.tlsOptions))}t.addPolicy(policies_proxyPolicy_proxyPolicy(e.proxyOptions));t.addPolicy(policies_decompressResponsePolicy_decompressResponsePolicy())}t.addPolicy(wrapAbortSignalLikePolicy());t.addPolicy(policies_formDataPolicy_formDataPolicy(),{beforePolicies:[policies_multipartPolicy_multipartPolicyName]});t.addPolicy(policies_userAgentPolicy_userAgentPolicy(e.userAgentOptions));t.addPolicy(setClientRequestIdPolicy(e.telemetryOptions?.clientRequestIdHeaderName));t.addPolicy(policies_multipartPolicy_multipartPolicy(),{afterPhase:"Deserialize"});t.addPolicy(policies_defaultRetryPolicy_defaultRetryPolicy(e.retryOptions),{phase:"Retry"});t.addPolicy(tracingPolicy({...e.userAgentOptions,...e.loggingOptions}),{afterPhase:"Retry"});if(esm_isNodeLike){t.addPolicy(policies_redirectPolicy_redirectPolicy(e.redirectOptions),{afterPhase:"Retry"})}t.addPolicy(policies_logPolicy_logPolicy(e.loggingOptions),{afterPhase:"Sign"});return t}function esm_defaultHttpClient_createDefaultHttpClient(){const e=defaultHttpClient_createDefaultHttpClient();return{async sendRequest(t){const{abortSignal:r,cleanup:n}=t.abortSignal?wrapAbortSignalLike(t.abortSignal):{};try{t.abortSignal=r;return await e.sendRequest(t)}finally{n?.()}}}}function esm_httpHeaders_createHttpHeaders(e){return httpHeaders_createHttpHeaders(e)}function esm_pipelineRequest_createPipelineRequest(e){return pipelineRequest_createPipelineRequest(e)}const exponentialRetryPolicy_exponentialRetryPolicyName=null&&tspExponentialRetryPolicyName;function exponentialRetryPolicy_exponentialRetryPolicy(e={}){return tspExponentialRetryPolicy(e)}const systemErrorRetryPolicy_systemErrorRetryPolicyName=null&&tspSystemErrorRetryPolicyName;function systemErrorRetryPolicy_systemErrorRetryPolicy(e={}){return tspSystemErrorRetryPolicy(e)}const throttlingRetryPolicy_throttlingRetryPolicyName=null&&tspThrottlingRetryPolicyName;function throttlingRetryPolicy_throttlingRetryPolicy(e={}){return tspThrottlingRetryPolicy(e)}const retryPolicy_retryPolicyLogger=esm_createClientLogger("core-rest-pipeline retryPolicy");function policies_retryPolicy_retryPolicy(e,t={maxRetries:DEFAULT_RETRY_POLICY_COUNT}){return tspRetryPolicy(e,{logger:retryPolicy_retryPolicyLogger,...t})}const DEFAULT_CYCLER_OPTIONS={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:1e3*60*2};async function beginRefresh(e,t,r){async function tryGetAccessToken(){if(Date.now()e.getToken(t,a);r=beginRefresh(tryGetAccessToken,i.retryIntervalInMs,n?.expiresOnTimestamp??Date.now()).then((e=>{r=null;n=e;s=a.tenantId;return n})).catch((e=>{r=null;n=null;s=undefined;throw e}))}return r}return async(e,t)=>{const r=Boolean(t.claims);const i=s!==t.tenantId;if(r){n=null}const a=i||r||o.mustRefresh;if(a){return refresh(e,t)}if(o.shouldRefresh){refresh(e,t)}return n}}const bearerTokenAuthenticationPolicyName="bearerTokenAuthenticationPolicy";async function trySendRequest(e,t){try{return[await t(e),undefined]}catch(e){if(esm_restError_isRestError(e)&&e.response){return[e.response,e]}else{throw e}}}async function defaultAuthorizeRequest(e){const{scopes:t,getAccessToken:r,request:n}=e;const s={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions,enableCae:true};const i=await r(t,s);if(i){e.request.headers.set("Authorization",`Bearer ${i.token}`)}}function isChallengeResponse(e){return e.status===401&&e.headers.has("WWW-Authenticate")}async function authorizeRequestOnCaeChallenge(e,t){const{scopes:r}=e;const n=await e.getAccessToken(r,{enableCae:true,claims:t});if(!n){return false}e.request.headers.set("Authorization",`${n.tokenType??"Bearer"} ${n.token}`);return true}function bearerTokenAuthenticationPolicy(e){const{credential:t,scopes:r,challengeCallbacks:n}=e;const s=e.logger||esm_log_logger;const i={authorizeRequest:n?.authorizeRequest?.bind(n)??defaultAuthorizeRequest,authorizeRequestOnChallenge:n?.authorizeRequestOnChallenge?.bind(n)};const o=t?tokenCycler_createTokenCycler(t):()=>Promise.resolve(null);return{name:bearerTokenAuthenticationPolicyName,async sendRequest(e,t){if(!e.url.toLowerCase().startsWith("https://")){throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.")}await i.authorizeRequest({scopes:Array.isArray(r)?r:[r],request:e,getAccessToken:o,logger:s});let n;let a;let c;[n,a]=await trySendRequest(e,t);if(isChallengeResponse(n)){let l=getCaeChallengeClaims(n.headers.get("WWW-Authenticate"));if(l){let i;try{i=atob(l)}catch(e){s.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${l}`);return n}c=await authorizeRequestOnCaeChallenge({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:o,logger:s},i);if(c){[n,a]=await trySendRequest(e,t)}}else if(i.authorizeRequestOnChallenge){c=await i.authorizeRequestOnChallenge({scopes:Array.isArray(r)?r:[r],request:e,response:n,getAccessToken:o,logger:s});if(c){[n,a]=await trySendRequest(e,t)}if(isChallengeResponse(n)){l=getCaeChallengeClaims(n.headers.get("WWW-Authenticate")??"");if(l){let i;try{i=atob(l)}catch(e){s.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${l}`);return n}c=await authorizeRequestOnCaeChallenge({scopes:Array.isArray(r)?r:[r],response:n,request:e,getAccessToken:o,logger:s},i);if(c){[n,a]=await trySendRequest(e,t)}}}}}if(a){throw a}else{return n}}}}function parseChallenges(e){const t=/(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;const r=/(\w+)="([^"]*)"/g;const n=[];let s;while((s=t.exec(e))!==null){const e=s[1];const t=s[2];const i={};let o;while((o=r.exec(t))!==null){i[o[1]]=o[2]}n.push({scheme:e,params:i})}return n}function getCaeChallengeClaims(e){if(!e){return}const t=parseChallenges(e);return t.find((e=>e.scheme==="Bearer"&&e.params.claims&&e.params.error==="insufficient_claims"))?.params.claims}const auxiliaryAuthenticationHeaderPolicyName="auxiliaryAuthenticationHeaderPolicy";const AUTHORIZATION_AUXILIARY_HEADER="x-ms-authorization-auxiliary";async function sendAuthorizeRequest(e){const{scopes:t,getAccessToken:r,request:n}=e;const s={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions};return(await r(t,s))?.token??""}function auxiliaryAuthenticationHeaderPolicy(e){const{credentials:t,scopes:r}=e;const n=e.logger||coreLogger;const s=new WeakMap;return{name:auxiliaryAuthenticationHeaderPolicyName,async sendRequest(e,i){if(!e.url.toLowerCase().startsWith("https://")){throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.")}if(!t||t.length===0){n.info(`${auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);return i(e)}const o=[];for(const i of t){let t=s.get(i);if(!t){t=createTokenCycler(i);s.set(i,t)}o.push(sendAuthorizeRequest({scopes:Array.isArray(r)?r:[r],request:e,getAccessToken:t,logger:n}))}const a=(await Promise.all(o)).filter((e=>Boolean(e)));if(a.length===0){n.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);return i(e)}e.headers.set(AUTHORIZATION_AUXILIARY_HEADER,a.map((e=>`Bearer ${e}`)).join(", "));return i(e)}}}function isKeyCredential(e){return isObjectWithProperties(e,["key"])&&typeof e.key==="string"}class AzureNamedKeyCredential{_key;_name;get key(){return this._key}get name(){return this._name}constructor(e,t){if(!e||!t){throw new TypeError("name and key must be non-empty strings")}this._name=e;this._key=t}update(e,t){if(!e||!t){throw new TypeError("newName and newKey must be non-empty strings")}this._name=e;this._key=t}}function isNamedKeyCredential(e){return isObjectWithProperties(e,["name","key"])&&typeof e.key==="string"&&typeof e.name==="string"}class AzureSASCredential{_signature;get signature(){return this._signature}constructor(e){if(!e){throw new Error("shared access signature must be a non-empty string")}this._signature=e}update(e){if(!e){throw new Error("shared access signature must be a non-empty string")}this._signature=e}}function isSASCredential(e){return isObjectWithProperties(e,["signature"])&&typeof e.signature==="string"}function isTokenCredential(e){const t=e;return t&&typeof t.getToken==="function"&&(t.signRequest===undefined||t.getToken.length>0)}const disableKeepAlivePolicyName="DisableKeepAlivePolicy";function createDisableKeepAlivePolicy(){return{name:disableKeepAlivePolicyName,sendRequest(e,t){e.disableKeepAlive=true;return t(e)}}}function pipelineContainsDisableKeepAlivePolicy(e){return e.getOrderedPolicies().some((e=>e.name===disableKeepAlivePolicyName))}function encodeString(e){return uint8ArrayToString(stringToUint8Array(e,"utf-8"),"base64")}function encodeByteArray(e){return esm_uint8ArrayToString(e,"base64")}function decodeString(e){return esm_stringToUint8Array(e,"base64")}function base64_decodeStringToString(e){return uint8ArrayToString(stringToUint8Array(e,"base64"),"utf-8")}const XML_ATTRKEY="$";const XML_CHARKEY="_";function isPrimitiveBody(e,t){return t!=="Composite"&&t!=="Dictionary"&&(typeof e==="string"||typeof e==="number"||typeof e==="boolean"||t?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)!==null||e===undefined||e===null)}const validateISODuration=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function isDuration(e){return validateISODuration.test(e)}const validUuidRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;function isValidUuid(e){return validUuidRegex.test(e)}function handleNullableResponseAndWrappableBody(e){const t={...e.headers,...e.body};if(e.hasNullableType&&Object.getOwnPropertyNames(t).length===0){return e.shouldWrapBody?{body:null}:null}else{return e.shouldWrapBody?{...e.headers,body:e.body}:t}}function flattenResponse(e,t){const r=e.parsedHeaders;if(e.request.method==="HEAD"){return{...r,body:e.parsedBody}}const n=t&&t.bodyMapper;const s=Boolean(n?.nullable);const i=n?.type.name;if(i==="Stream"){return{...r,blobBody:e.blobBody,readableStreamBody:e.readableStreamBody}}const o=i==="Composite"&&n.type.modelProperties||{};const a=Object.keys(o).some((e=>o[e].serializedName===""));if(i==="Sequence"||a){const t=e.parsedBody??[];for(const r of Object.keys(o)){if(o[r].serializedName){t[r]=e.parsedBody?.[r]}}if(r){for(const e of Object.keys(r)){t[e]=r[e]}}return s&&!e.parsedBody&&!r&&Object.getOwnPropertyNames(o).length===0?null:t}return handleNullableResponseAndWrappableBody({body:e.parsedBody,headers:r,hasNullableType:s,shouldWrapBody:isPrimitiveBody(e.parsedBody,i)})}class SerializerImpl{modelMappers;isXML;constructor(e={},t=false){this.modelMappers=e;this.isXML=t}validateConstraints(e,t,r){const failValidation=(e,n)=>{throw new Error(`"${r}" with value "${t}" should satisfy the constraint "${e}": ${n}.`)};if(e.constraints&&t!==undefined&&t!==null){const{ExclusiveMaximum:r,ExclusiveMinimum:n,InclusiveMaximum:s,InclusiveMinimum:i,MaxItems:o,MaxLength:a,MinItems:c,MinLength:l,MultipleOf:u,Pattern:d,UniqueItems:A}=e.constraints;if(r!==undefined&&t>=r){failValidation("ExclusiveMaximum",r)}if(n!==undefined&&t<=n){failValidation("ExclusiveMinimum",n)}if(s!==undefined&&t>s){failValidation("InclusiveMaximum",s)}if(i!==undefined&&to){failValidation("MaxItems",o)}if(a!==undefined&&t.length>a){failValidation("MaxLength",a)}if(c!==undefined&&t.lengthr.indexOf(e)!==t))){failValidation("UniqueItems",A)}}}serialize(e,t,r,n={xml:{}}){const s={xml:{rootName:n.xml.rootName??"",includeRoot:n.xml.includeRoot??false,xmlCharKey:n.xml.xmlCharKey??XML_CHARKEY}};let i={};const o=e.type.name;if(!r){r=e.serializedName}if(o.match(/^Sequence$/i)!==null){i=[]}if(e.isConstant){t=e.defaultValue}const{required:a,nullable:c}=e;if(a&&c&&t===undefined){throw new Error(`${r} cannot be undefined.`)}if(a&&!c&&(t===undefined||t===null)){throw new Error(`${r} cannot be null or undefined.`)}if(!a&&c===false&&t===null){throw new Error(`${r} cannot be null.`)}if(t===undefined||t===null){i=t}else{if(o.match(/^any$/i)!==null){i=t}else if(o.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i)!==null){i=serializeBasicTypes(o,r,t)}else if(o.match(/^Enum$/i)!==null){const n=e;i=serializeEnumType(r,n.type.allowedValues,t)}else if(o.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i)!==null){i=serializeDateTypes(o,t,r)}else if(o.match(/^ByteArray$/i)!==null){i=serializeByteArrayType(r,t)}else if(o.match(/^Base64Url$/i)!==null){i=serializeBase64UrlType(r,t)}else if(o.match(/^Sequence$/i)!==null){i=serializeSequenceType(this,e,t,r,Boolean(this.isXML),s)}else if(o.match(/^Dictionary$/i)!==null){i=serializeDictionaryType(this,e,t,r,Boolean(this.isXML),s)}else if(o.match(/^Composite$/i)!==null){i=serializeCompositeType(this,e,t,r,Boolean(this.isXML),s)}}return i}deserialize(e,t,r,n={xml:{}}){const s={xml:{rootName:n.xml.rootName??"",includeRoot:n.xml.includeRoot??false,xmlCharKey:n.xml.xmlCharKey??XML_CHARKEY},ignoreUnknownProperties:n.ignoreUnknownProperties??false};if(t===undefined||t===null){if(this.isXML&&e.type.name==="Sequence"&&!e.xmlIsWrapped){t=[]}if(e.defaultValue!==undefined){t=e.defaultValue}return t}let i;const o=e.type.name;if(!r){r=e.serializedName}if(o.match(/^Composite$/i)!==null){i=deserializeCompositeType(this,e,t,r,s)}else{if(this.isXML){const e=s.xml.xmlCharKey;if(t[XML_ATTRKEY]!==undefined&&t[e]!==undefined){t=t[e]}}if(o.match(/^Number$/i)!==null){i=parseFloat(t);if(isNaN(i)){i=t}}else if(o.match(/^Boolean$/i)!==null){if(t==="true"){i=true}else if(t==="false"){i=false}else{i=t}}else if(o.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i)!==null){i=t}else if(o.match(/^(Date|DateTime|DateTimeRfc1123)$/i)!==null){i=new Date(t)}else if(o.match(/^UnixTime$/i)!==null){i=unixTimeToDate(t)}else if(o.match(/^ByteArray$/i)!==null){i=decodeString(t)}else if(o.match(/^Base64Url$/i)!==null){i=base64UrlToByteArray(t)}else if(o.match(/^Sequence$/i)!==null){i=deserializeSequenceType(this,e,t,r,s)}else if(o.match(/^Dictionary$/i)!==null){i=deserializeDictionaryType(this,e,t,r,s)}}if(e.isConstant){i=e.defaultValue}return i}}function createSerializer(e={},t=false){return new SerializerImpl(e,t)}function trimEnd(e,t){let r=e.length;while(r-1>=0&&e[r-1]===t){--r}return e.substr(0,r)}function bufferToBase64Url(e){if(!e){return undefined}if(!(e instanceof Uint8Array)){throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`)}const t=encodeByteArray(e);return trimEnd(t,"=").replace(/\+/g,"-").replace(/\//g,"_")}function base64UrlToByteArray(e){if(!e){return undefined}if(e&&typeof e.valueOf()!=="string"){throw new Error("Please provide an input of type string for converting to Uint8Array")}e=e.replace(/-/g,"+").replace(/_/g,"/");return decodeString(e)}function splitSerializeName(e){const t=[];let r="";if(e){const n=e.split(".");for(const e of n){if(e.charAt(e.length-1)==="\\"){r+=e.substr(0,e.length-1)+"."}else{r+=e;t.push(r);r=""}}}return t}function dateToUnixTime(e){if(!e){return undefined}if(typeof e.valueOf()==="string"){e=new Date(e)}return Math.floor(e.getTime()/1e3)}function unixTimeToDate(e){if(!e){return undefined}return new Date(e*1e3)}function serializeBasicTypes(e,t,r){if(r!==null&&r!==undefined){if(e.match(/^Number$/i)!==null){if(typeof r!=="number"){throw new Error(`${t} with value ${r} must be of type number.`)}}else if(e.match(/^String$/i)!==null){if(typeof r.valueOf()!=="string"){throw new Error(`${t} with value "${r}" must be of type string.`)}}else if(e.match(/^Uuid$/i)!==null){if(!(typeof r.valueOf()==="string"&&isValidUuid(r))){throw new Error(`${t} with value "${r}" must be of type string and a valid uuid.`)}}else if(e.match(/^Boolean$/i)!==null){if(typeof r!=="boolean"){throw new Error(`${t} with value ${r} must be of type boolean.`)}}else if(e.match(/^Stream$/i)!==null){const e=typeof r;if(e!=="string"&&typeof r.pipe!=="function"&&typeof r.tee!=="function"&&!(r instanceof ArrayBuffer)&&!ArrayBuffer.isView(r)&&!((typeof Blob==="function"||typeof Blob==="object")&&r instanceof Blob)&&e!=="function"){throw new Error(`${t} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`)}}}return r}function serializeEnumType(e,t,r){if(!t){throw new Error(`Please provide a set of allowedValues to validate ${e} as an Enum Type.`)}const n=t.some((e=>{if(typeof e.valueOf()==="string"){return e.toLowerCase()===r.toLowerCase()}return e===r}));if(!n){throw new Error(`${r} is not a valid value for ${e}. The valid values are: ${JSON.stringify(t)}.`)}return r}function serializeByteArrayType(e,t){if(t!==undefined&&t!==null){if(!(t instanceof Uint8Array)){throw new Error(`${e} must be of type Uint8Array.`)}t=encodeByteArray(t)}return t}function serializeBase64UrlType(e,t){if(t!==undefined&&t!==null){if(!(t instanceof Uint8Array)){throw new Error(`${e} must be of type Uint8Array.`)}t=bufferToBase64Url(t)}return t}function serializeDateTypes(e,t,r){if(t!==undefined&&t!==null){if(e.match(/^Date$/i)!==null){if(!(t instanceof Date||typeof t.valueOf()==="string"&&!isNaN(Date.parse(t)))){throw new Error(`${r} must be an instanceof Date or a string in ISO8601 format.`)}t=t instanceof Date?t.toISOString().substring(0,10):new Date(t).toISOString().substring(0,10)}else if(e.match(/^DateTime$/i)!==null){if(!(t instanceof Date||typeof t.valueOf()==="string"&&!isNaN(Date.parse(t)))){throw new Error(`${r} must be an instanceof Date or a string in ISO8601 format.`)}t=t instanceof Date?t.toISOString():new Date(t).toISOString()}else if(e.match(/^DateTimeRfc1123$/i)!==null){if(!(t instanceof Date||typeof t.valueOf()==="string"&&!isNaN(Date.parse(t)))){throw new Error(`${r} must be an instanceof Date or a string in RFC-1123 format.`)}t=t instanceof Date?t.toUTCString():new Date(t).toUTCString()}else if(e.match(/^UnixTime$/i)!==null){if(!(t instanceof Date||typeof t.valueOf()==="string"&&!isNaN(Date.parse(t)))){throw new Error(`${r} must be an instanceof Date or a string in RFC-1123/ISO8601 format `+`for it to be serialized in UnixTime/Epoch format.`)}t=dateToUnixTime(t)}else if(e.match(/^TimeSpan$/i)!==null){if(!isDuration(t)){throw new Error(`${r} must be a string in ISO 8601 format. Instead was "${t}".`)}}}return t}function serializeSequenceType(e,t,r,n,s,i){if(!Array.isArray(r)){throw new Error(`${n} must be of type Array.`)}let o=t.type.element;if(!o||typeof o!=="object"){throw new Error(`"element" metadata for an Array must be defined in the `+`mapper and it must be of type "object" in ${n}.`)}if(o.type.name==="Composite"&&o.type.className){o=e.modelMappers[o.type.className]??o}const a=[];for(let t=0;te!==s));if(a){Object.defineProperty(o,s,{value:e.serialize(c,r[s],n+'["'+s+'"]',i),enumerable:true,configurable:true,writable:true})}}}return o}return r}function getXmlObjectValue(e,t,r,n){if(!r||!e.xmlNamespace){return t}const s=e.xmlNamespacePrefix?`xmlns:${e.xmlNamespacePrefix}`:"xmlns";const i={[s]:e.xmlNamespace};if(["Composite"].includes(e.type.name)){if(t[XML_ATTRKEY]){return t}else{const e={...t};e[XML_ATTRKEY]=i;return e}}const o={};o[n.xml.xmlCharKey]=t;o[XML_ATTRKEY]=i;return o}function isSpecialXmlProperty(e,t){return[XML_ATTRKEY,t.xml.xmlCharKey].includes(e)}function deserializeCompositeType(e,t,r,n,s){const i=s.xml.xmlCharKey??XML_CHARKEY;if(getPolymorphicDiscriminatorRecursively(e,t)){t=getPolymorphicMapper(e,t,r,"serializedName")}const o=resolveModelProperties(e,t,n);let a={};const c=[];for(const l of Object.keys(o)){const u=o[l];const d=splitSerializeName(o[l].serializedName);c.push(d[0]);const{serializedName:A,xmlName:p,xmlElementName:f}=u;let h=n;if(A!==""&&A!==undefined){h=n+"."+A}const g=u.headerCollectionPrefix;if(g){const t={};for(const n of Object.keys(r)){if(n.startsWith(g)){t[n.substring(g.length)]=e.deserialize(u.type.value,r[n],h,s)}c.push(n)}a[l]=t}else if(e.isXML){if(u.xmlIsAttribute&&r[XML_ATTRKEY]){a[l]=e.deserialize(u,r[XML_ATTRKEY][p],h,s)}else if(u.xmlIsMsText){if(r[i]!==undefined){a[l]=r[i]}else if(typeof r==="string"){a[l]=r}}else{const t=f||p||A;if(u.xmlIsWrapped){const t=r[p];const n=t?.[f]??[];Object.defineProperty(a,l,{value:e.deserialize(u,n,h,s),enumerable:true,configurable:true,writable:true});c.push(p)}else{const n=r[t];a[l]=e.deserialize(u,n,h,s);c.push(t)}}}else{let n;let i=r;let c=0;for(const e of d){if(!i)break;c++;i=i[e]}if(i===null&&c{for(const t of Object.keys(o)){const r=splitSerializeName(o[t].serializedName);if(r[0]===e){return false}}return true};for(const t of Object.keys(r)){if(isAdditionalProperty(t)){const i=e.deserialize(l,r[t],n+'["'+t+'"]',s);Object.defineProperty(a,t,{value:i,enumerable:true,configurable:true,writable:true})}}}else if(r&&!s.ignoreUnknownProperties){for(const e of Object.keys(r)){if(a[e]===undefined&&!c.includes(e)&&!isSpecialXmlProperty(e,s)){Object.defineProperty(a,e,{value:r[e],enumerable:true,configurable:true,writable:true})}}}return a}function deserializeDictionaryType(e,t,r,n,s){const i=t.type.value;if(!i||typeof i!=="object"){throw new Error(`"value" metadata for a Dictionary must be defined in the `+`mapper and it must of type "object" in ${n}`)}if(r){const t={};for(const o of Object.keys(r)){t[o]=e.deserialize(i,r[o],n,s)}return t}return r}function deserializeSequenceType(e,t,r,n,s){let i=t.type.element;if(!i||typeof i!=="object"){throw new Error(`"element" metadata for an Array must be defined in the `+`mapper and it must be of type "object" in ${n}`)}if(r){if(!Array.isArray(r)){r=[r]}if(i.type.name==="Composite"&&i.type.className){i=e.modelMappers[i.type.className]??i}const t=[];for(let o=0;o0){if(s.isConstant){i=s.defaultValue}else{let t=getPropertyFromParameterPath(e,n);if(!t.propertyFound&&r){t=getPropertyFromParameterPath(r,n)}let o=false;if(!t.propertyFound){o=s.required||n[0]==="options"&&n.length===2}i=o?s.defaultValue:t.propertyValue}}}else{if(s.required){i={}}for(const[t,o]of Object.entries(n)){const n=s.type.modelProperties[t];const a=getOperationArgumentValueFromParameter(e,{parameterPath:o,mapper:n},r);if(a!==undefined){if(!i){i={}}Object.defineProperty(i,t,{value:a,enumerable:true,configurable:true,writable:true})}}}return i}function getPropertyFromParameterPath(e,t){const r={propertyFound:false};let n=0;for(;n=200&&r.status<300}if(c.headersMapper){i.parsedHeaders=a.serializer.deserialize(c.headersMapper,i.headers.toJSON(),"operationRes.parsedHeaders",{xml:{},ignoreUnknownProperties:true})}}return i}function isOperationSpecEmpty(e){const t=Object.keys(e.responses);return t.length===0||t.length===1&&t[0]==="default"}function handleErrorResponse(e,t,r,n){const s=200<=e.status&&e.status<300;const i=isOperationSpecEmpty(t)?s:!!r;if(i){if(r){if(!r.isError){return{error:null,shouldReturnResponse:false}}}else{return{error:null,shouldReturnResponse:false}}}const o=r??t.responses.default;const a=e.request.streamResponseStatusCodes?.has(e.status)?`Unexpected status code: ${e.status}`:e.bodyAsText;const c=new esm_restError_RestError(a,{statusCode:e.status,request:e.request,response:e});if(!o&&!(e.parsedBody?.error?.code&&e.parsedBody?.error?.message)){throw c}const l=o?.bodyMapper;const u=o?.headersMapper;try{if(e.parsedBody){const r=e.parsedBody;let s;if(l){let e=r;if(t.isXML&&l.type.name===MapperTypeNames.Sequence){e=[];const t=l.xmlElementName;if(typeof r==="object"&&t){e=r[t]}}s=t.serializer.deserialize(l,e,"error.response.parsedBody",n)}const i=r.error||s||r;c.code=i.code;if(i.message){c.message=i.message}if(l){c.response.parsedBody=s}}if(e.headers&&u){c.response.parsedHeaders=t.serializer.deserialize(u,e.headers.toJSON(),"operationRes.parsedHeaders")}}catch(t){c.message=`Error "${t.message}" occurred in deserializing the responseBody - "${e.bodyAsText}" for the default response.`}return{error:c,shouldReturnResponse:false}}async function deserializationPolicy_parse(e,t,r,n,s){if(!r.request.streamResponseStatusCodes?.has(r.status)&&r.bodyAsText){const i=r.bodyAsText;const o=r.headers.get("Content-Type")||"";const a=!o?[]:o.split(";").map((e=>e.toLowerCase()));try{if(a.length===0||a.some((t=>e.indexOf(t)!==-1))){r.parsedBody=JSON.parse(i);return r}else if(a.some((e=>t.indexOf(e)!==-1))){if(!s){throw new Error("Parsing XML not supported.")}const e=await s(i,n.xml);r.parsedBody=e;return r}}catch(e){const t=`Error "${e}" occurred while parsing the response body - ${r.bodyAsText}.`;const n=e.code||esm_restError_RestError.PARSE_ERROR;const s=new esm_restError_RestError(t,{code:n,statusCode:r.status,request:r.request,response:r});throw s}}return r}function getStreamingResponseStatusCodes(e){const t=new Set;for(const[r,n]of Object.entries(e.responses)){if(n.bodyMapper&&n.bodyMapper.type.name===MapperTypeNames.Stream){t.add(Number(r))}}return t}function getPathStringFromParameter(e){const{parameterPath:t,mapper:r}=e;let n;if(typeof t==="string"){n=t}else if(Array.isArray(t)){n=t.join(".")}else{n=r.serializedName}return n}const serializationPolicyName="serializationPolicy";function serializationPolicy(e={}){const t=e.stringifyXML;return{name:serializationPolicyName,sendRequest(e,r){const n=getOperationRequestInfo(e);const s=n?.operationSpec;const i=n?.operationArguments;if(s&&i){serializeHeaders(e,i,s);serializeRequestBody(e,i,s,t)}return r(e)}}}function serializeHeaders(e,t,r){if(r.headerParameters){for(const n of r.headerParameters){let s=getOperationArgumentValueFromParameter(t,n);if(s!==null&&s!==undefined||n.mapper.required){s=r.serializer.serialize(n.mapper,s,getPathStringFromParameter(n));const t=n.mapper.headerCollectionPrefix;if(t){for(const r of Object.keys(s)){e.headers.set(t+r,s[r])}}else{e.headers.set(n.mapper.serializedName||getPathStringFromParameter(n),s)}}}}const n=t.options?.requestOptions?.customHeaders;if(n){for(const t of Object.keys(n)){e.headers.set(t,n[t])}}}function serializeRequestBody(e,t,r,n=function(){throw new Error("XML serialization unsupported!")}){const s=t.options?.serializerOptions;const i={xml:{rootName:s?.xml.rootName??"",includeRoot:s?.xml.includeRoot??false,xmlCharKey:s?.xml.xmlCharKey??XML_CHARKEY}};const o=i.xml.xmlCharKey;if(r.requestBody&&r.requestBody.mapper){e.body=getOperationArgumentValueFromParameter(t,r.requestBody);const s=r.requestBody.mapper;const{required:a,serializedName:c,xmlName:l,xmlElementName:u,xmlNamespace:d,xmlNamespacePrefix:A,nullable:p}=s;const f=s.type.name;try{if(e.body!==undefined&&e.body!==null||p&&e.body===null||a){const t=getPathStringFromParameter(r.requestBody);e.body=r.serializer.serialize(s,e.body,t,i);const a=f===MapperTypeNames.Stream;if(r.isXML){const t=A?`xmlns:${A}`:"xmlns";const r=getXmlValueWithNamespace(d,t,f,e.body,i);if(f===MapperTypeNames.Sequence){e.body=n(prepareXMLRootList(r,u||l||c,t,d),{rootName:l||c,xmlCharKey:o})}else if(!a){e.body=n(r,{rootName:l||c,xmlCharKey:o})}}else if(f===MapperTypeNames.String&&(r.contentType?.match("text/plain")||r.mediaType==="text")){return}else if(!a){e.body=JSON.stringify(e.body)}}}catch(e){throw new Error(`Error "${e.message}" occurred in serializing the payload - ${JSON.stringify(c,undefined," ")}.`,{cause:e})}}else if(r.formDataParameters&&r.formDataParameters.length>0){e.formData={};for(const n of r.formDataParameters){const s=getOperationArgumentValueFromParameter(t,n);if(s!==undefined&&s!==null){const t=n.mapper.serializedName||getPathStringFromParameter(n);e.formData[t]=r.serializer.serialize(n.mapper,s,getPathStringFromParameter(n),i)}}}}function getXmlValueWithNamespace(e,t,r,n,s){if(e&&!["Composite","Sequence","Dictionary"].includes(r)){const r={};r[s.xml.xmlCharKey]=n;r[XML_ATTRKEY]={[t]:e};return r}return n}function prepareXMLRootList(e,t,r,n){if(!Array.isArray(e)){e=[e]}if(!r||!n){return{[t]:e}}const s={[t]:e};s[XML_ATTRKEY]={[r]:n};return s}function createClientPipeline(e={}){const t=esm_createPipelineFromOptions_createPipelineFromOptions(e??{});if(e.credentialOptions){t.addPolicy(bearerTokenAuthenticationPolicy({credential:e.credentialOptions.credential,scopes:e.credentialOptions.credentialScopes}))}t.addPolicy(serializationPolicy(e.serializationOptions),{phase:"Serialize"});t.addPolicy(deserializationPolicy(e.deserializationOptions),{phase:"Deserialize"});return t}let httpClientCache_cachedHttpClient;function getCachedDefaultHttpClient(){if(!httpClientCache_cachedHttpClient){httpClientCache_cachedHttpClient=esm_defaultHttpClient_createDefaultHttpClient()}return httpClientCache_cachedHttpClient}const CollectionFormatToDelimiterMap={CSV:",",SSV:" ",Multi:"Multi",TSV:"\t",Pipes:"|"};function getRequestUrl(e,t,r,n){const s=calculateUrlReplacements(t,r,n);let i=false;let o=replaceAll(e,s);if(t.path){let e=replaceAll(t.path,s);if(t.path==="/{nextLink}"&&e.startsWith("/")){e=e.substring(1)}if(isAbsoluteUrl(e)){o=e;i=true}else{o=appendPath(o,e)}}const{queryParams:a,sequenceParams:c}=calculateQueryParameters(t,r,n);o=appendQueryParams(o,a,c,i);return o}function replaceAll(e,t){let r=e;for(const[e,n]of t){r=r.split(e).join(n)}return r}function calculateUrlReplacements(e,t,r){const n=new Map;if(e.urlParameters?.length){for(const s of e.urlParameters){let i=getOperationArgumentValueFromParameter(t,s,r);const o=getPathStringFromParameter(s);i=e.serializer.serialize(s.mapper,i,o);if(!s.skipEncoding){i=encodeURIComponent(i)}n.set(`{${s.mapper.serializedName||o}}`,i)}}return n}function isAbsoluteUrl(e){return e.includes("://")}function appendPath(e,t){if(!t){return e}const r=new URL(e);let n=r.pathname;if(!n.endsWith("/")){n=`${n}/`}if(t.startsWith("/")){t=t.substring(1)}const s=t.indexOf("?");if(s!==-1){const e=t.substring(0,s);const i=t.substring(s+1);n=n+e;if(i){r.search=r.search?`${r.search}&${i}`:i}}else{n=n+t}Object.assign(r,{pathname:n});return r.toString()}function calculateQueryParameters(e,t,r){const n=new Map;const s=new Set;if(e.queryParameters?.length){for(const i of e.queryParameters){if(i.mapper.type.name==="Sequence"&&i.mapper.serializedName){s.add(i.mapper.serializedName)}let o=getOperationArgumentValueFromParameter(t,i,r);if(o!==undefined&&o!==null||i.mapper.required){o=e.serializer.serialize(i.mapper,o,getPathStringFromParameter(i));const t=i.collectionFormat?CollectionFormatToDelimiterMap[i.collectionFormat]:"";if(Array.isArray(o)){o=o.map((e=>{if(e===null||e===undefined){return""}return e}))}if(i.collectionFormat==="Multi"&&o.length===0){continue}else if(Array.isArray(o)&&(i.collectionFormat==="SSV"||i.collectionFormat==="TSV")){o=o.join(t)}if(!i.skipEncoding){if(Array.isArray(o)){o=o.map((e=>encodeURIComponent(e)))}else{o=encodeURIComponent(o)}}if(Array.isArray(o)&&(i.collectionFormat==="CSV"||i.collectionFormat==="Pipes")){o=o.join(t)}n.set(i.mapper.serializedName||getPathStringFromParameter(i),o)}}}return{queryParams:n,sequenceParams:s}}function simpleParseQueryParams(e){const t=new Map;if(!e||e[0]!=="?"){return t}e=e.slice(1);const r=e.split("&");for(const e of r){const[r,n]=e.split("=",2);const s=t.get(r);if(s){if(Array.isArray(s)){s.push(n)}else{t.set(r,[s,n])}}else{t.set(r,n)}}return t}function appendQueryParams(e,t,r,n=false){if(t.size===0){return e}const s=new URL(e);const i=simpleParseQueryParams(s.search);for(const[e,s]of t){const t=i.get(e);if(Array.isArray(t)){if(Array.isArray(s)){t.push(...s);const r=new Set(t);i.set(e,Array.from(r))}else{t.push(s)}}else if(t){if(Array.isArray(s)){s.unshift(t)}else if(r.has(e)){i.set(e,[t,s])}if(!n){i.set(e,s)}}else{i.set(e,s)}}const o=[];for(const[e,t]of i){if(typeof t==="string"){o.push(`${e}=${t}`)}else if(Array.isArray(t)){for(const r of t){o.push(`${e}=${r}`)}}else{o.push(`${e}=${t}`)}}s.search=o.length?`?${o.join("&")}`:"";return s.toString()}const dist_esm_log_logger=esm_createClientLogger("core-client");class ServiceClient{_endpoint;_requestContentType;_allowInsecureConnection;_httpClient;pipeline;constructor(e={}){this._requestContentType=e.requestContentType;this._endpoint=e.endpoint??e.baseUri;if(e.baseUri){dist_esm_log_logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.")}this._allowInsecureConnection=e.allowInsecureConnection;this._httpClient=e.httpClient||getCachedDefaultHttpClient();this.pipeline=e.pipeline||serviceClient_createDefaultPipeline(e);if(e.additionalPolicies?.length){for(const{policy:t,position:r}of e.additionalPolicies){const e=r==="perRetry"?"Sign":undefined;this.pipeline.addPolicy(t,{afterPhase:e})}}}sendRequest(e){return this.pipeline.sendRequest(this._httpClient,e)}async sendOperationRequest(e,t){const r=t.baseUrl||this._endpoint;if(!r){throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.")}const n=getRequestUrl(r,t,e,this);const s=esm_pipelineRequest_createPipelineRequest({url:n});s.method=t.httpMethod;const i=getOperationRequestInfo(s);i.operationSpec=t;i.operationArguments=e;const o=t.contentType||this._requestContentType;if(o&&t.requestBody){s.headers.set("Content-Type",o)}const a=e.options;if(a){const e=a.requestOptions;if(e){if(e.timeout){s.timeout=e.timeout}if(e.onUploadProgress){s.onUploadProgress=e.onUploadProgress}if(e.onDownloadProgress){s.onDownloadProgress=e.onDownloadProgress}if(e.shouldDeserialize!==undefined){i.shouldDeserialize=e.shouldDeserialize}if(e.allowInsecureConnection){s.allowInsecureConnection=true}}if(a.abortSignal){s.abortSignal=a.abortSignal}if(a.tracingOptions){s.tracingOptions=a.tracingOptions}}if(this._allowInsecureConnection){s.allowInsecureConnection=true}if(s.streamResponseStatusCodes===undefined){s.streamResponseStatusCodes=getStreamingResponseStatusCodes(t)}try{const e=await this.sendRequest(s);const r=flattenResponse(e,t.responses[e.status]);if(a?.onResponse){a.onResponse(e,r)}return r}catch(e){if(typeof e==="object"&&e?.response){const r=e.response;const n=flattenResponse(r,t.responses[e.statusCode]||t.responses["default"]);e.details=n;if(a?.onResponse){a.onResponse(r,n,e)}}throw e}}}function serviceClient_createDefaultPipeline(e){const t=getCredentialScopes(e);const r=e.credential&&t?{credentialScopes:t,credential:e.credential}:undefined;return createClientPipeline({...e,credentialOptions:r})}function getCredentialScopes(e){if(e.credentialScopes){return e.credentialScopes}if(e.endpoint){return`${e.endpoint}/.default`}if(e.baseUri){return`${e.baseUri}/.default`}if(e.credential){throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`)}return undefined}function parseCAEChallenge(e){const t=`, ${e.trim()}`.split(", Bearer ").filter((e=>e));return t.map((e=>{const t=`${e.trim()}, `.split('", ').filter((e=>e));const r=t.map((e=>(([e,t])=>({[e]:t}))(e.trim().split('="'))));return r.reduce(((e,t)=>({...e,...t})),{})}))}async function authorizeRequestOnClaimChallenge(e){const{scopes:t,response:r}=e;const n=e.logger||coreClientLogger;const s=r.headers.get("WWW-Authenticate");if(!s){n.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);return false}const i=parseCAEChallenge(s)||[];const o=i.find((e=>e.claims));if(!o){n.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);return false}const a=await e.getAccessToken(o.scope?[o.scope]:t,{claims:decodeStringToString(o.claims)});if(!a){return false}e.request.headers.set("Authorization",`${a.tokenType??"Bearer"} ${a.token}`);return true}const Constants={DefaultScope:"/.default",HeaderConstants:{AUTHORIZATION:"authorization"}};function isUuid(e){return/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(e)}const authorizeRequestOnTenantChallenge=async e=>{const t=requestToOptions(e.request);const r=getChallenge(e.response);if(r){const n=parseChallenge(r);const s=buildScopes(e,n);const i=extractTenantId(n);if(!i){return false}const o=await e.getAccessToken(s,{...t,tenantId:i});if(!o){return false}e.request.headers.set(Constants.HeaderConstants.AUTHORIZATION,`${o.tokenType??"Bearer"} ${o.token}`);return true}return false};function extractTenantId(e){const t=new URL(e.authorization_uri);const r=t.pathname.split("/");const n=r[1];if(n&&isUuid(n)){return n}return undefined}function buildScopes(e,t){if(!t.resource_id){return e.scopes}const r=new URL(t.resource_id);let n=new URL(Constants.DefaultScope,r.origin).toString();if(n==="https://disk.azure.com/.default"){n="https://disk.azure.com//.default"}return[n]}function getChallenge(e){const t=e.headers.get("WWW-Authenticate");if(e.status===401&&t){return t}return}function parseChallenge(e){const t=e.slice("Bearer ".length);const r=`${t.trim()} `.split(" ").filter((e=>e));const n=r.map((e=>(([e,t])=>({[e]:t}))(e.trim().split("="))));return n.reduce(((e,t)=>({...e,...t})),{})}function requestToOptions(e){return{abortSignal:e.abortSignal,requestOptions:{timeout:e.timeout},tracingOptions:e.tracingOptions}}const util_originalRequestSymbol=Symbol("Original PipelineRequest");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(e,t={}){const r=e;const n=r[util_originalRequestSymbol];const s=esm_httpHeaders_createHttpHeaders(e.headers.toJson({preserveCase:true}));if(n){n.headers=s;return n}else{const r=esm_pipelineRequest_createPipelineRequest({url:e.url,method:e.method,headers:s,withCredentials:e.withCredentials,timeout:e.timeout,requestId:e.requestId,abortSignal:e.abortSignal,body:e.body,formData:e.formData,disableKeepAlive:!!e.keepAlive,onDownloadProgress:e.onDownloadProgress,onUploadProgress:e.onUploadProgress,proxySettings:e.proxySettings,streamResponseStatusCodes:e.streamResponseStatusCodes,agent:e.agent,requestOverrides:e.requestOverrides});if(t.originalRequest){r[originalClientRequestSymbol]=t.originalRequest}return r}}function toWebResourceLike(e,t){const r=t?.originalRequest??e;const n={url:e.url,method:e.method,headers:toHttpHeadersLike(e.headers),withCredentials:e.withCredentials,timeout:e.timeout,requestId:e.headers.get("x-ms-client-request-id")||e.requestId,abortSignal:e.abortSignal,body:e.body,formData:e.formData,keepAlive:!!e.disableKeepAlive,onDownloadProgress:e.onDownloadProgress,onUploadProgress:e.onUploadProgress,proxySettings:e.proxySettings,streamResponseStatusCodes:e.streamResponseStatusCodes,agent:e.agent,requestOverrides:e.requestOverrides,clone(){throw new Error("Cannot clone a non-proxied WebResourceLike")},prepare(){throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat")},validateRequestProperties(){}};if(t?.createProxy){return new Proxy(n,{get(t,s,i){if(s===util_originalRequestSymbol){return e}else if(s==="clone"){return()=>toWebResourceLike(toPipelineRequest(n,{originalRequest:r}),{createProxy:true,originalRequest:r})}return Reflect.get(t,s,i)},set(t,r,n,s){if(r==="keepAlive"){e.disableKeepAlive=!n}if(typeof r==="string"&&passThroughProps.has(r)){e[r]=n}return Reflect.set(t,r,n,s)}})}else{return n}}function toHttpHeadersLike(e){return new HttpHeaders(e.toJSON({preserveCase:true}))}function getHeaderKey(e){return e.toLowerCase()}class HttpHeaders{_headersMap;constructor(e){this._headersMap={};if(e){for(const t in e){this.set(t,e[t])}}}set(e,t){this._headersMap[getHeaderKey(e)]={name:e,value:t.toString()}}get(e){const t=this._headersMap[getHeaderKey(e)];return!t?undefined:t.value}contains(e){return!!this._headersMap[getHeaderKey(e)]}remove(e){const t=this.contains(e);delete this._headersMap[getHeaderKey(e)];return t}rawHeaders(){return this.toJson({preserveCase:true})}headersArray(){const e=[];for(const t in this._headersMap){e.push(this._headersMap[t])}return e}headerNames(){const e=[];const t=this.headersArray();for(let r=0;r{const r=await e.sendRequest(toWebResourceLike(t,{createProxy:true}));return response_toPipelineResponse(r)}}}class Expression{constructor(e,t={},r){this.pattern=e;this.separator=t.separator||".";this.segments=this._parse(e);this.data=r;this._hasDeepWildcard=this.segments.some((e=>e.type==="deep-wildcard"));this._hasAttributeCondition=this.segments.some((e=>e.attrName!==undefined));this._hasPositionSelector=this.segments.some((e=>e.position!==undefined))}_parse(e){const t=[];let r=0;let n="";while(r0?e[e.length-1].tag:undefined}getCurrentNamespace(){const e=this._matcher.path;return e.length>0?e[e.length-1].namespace:undefined}getAttrValue(e){const t=this._matcher.path;if(t.length===0)return undefined;return t[t.length-1].values?.[e]}hasAttr(e){const t=this._matcher.path;if(t.length===0)return false;const r=t[t.length-1];return r.values!==undefined&&e in r.values}getAnyParentAttr(e){return this._matcher.getAnyParentAttr(e)}hasAnyParentAttr(e){return this._matcher.hasAnyParentAttr(e)}getPosition(){const e=this._matcher.path;if(e.length===0)return-1;return e[e.length-1].position??0}getCounter(){const e=this._matcher.path;if(e.length===0)return-1;return e[e.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(e,t=true){return this._matcher.toString(e,t)}toArray(){return this._matcher.path.map((e=>e.tag))}matches(e){return this._matcher.matches(e)}matchesAny(e){return e.matchesAny(this._matcher)}}class Matcher{constructor(e={}){this.separator=e.separator||".";this.path=[];this.siblingStacks=[];this._pathStringCache=null;this._view=new MatcherView(this);this._keptAttrs=[]}push(e,t=null,r=null,n=null){this._pathStringCache=null;if(this.path.length>0){this.path[this.path.length-1].values=undefined}const s=this.path.length;let i=this.siblingStacks[s];if(!i){i={counts:new Map,total:0};this.siblingStacks[s]=i}const o=r?`${r}:${e}`:e;const a=i.counts.get(o)||0;const c=i.total;i.counts.set(o,a+1);i.total++;const l={tag:e,position:c,counter:a};if(r!==null&&r!==undefined){l.namespace=r}if(t!==null&&t!==undefined){l.values=t}this.path.push(l);const u=this.path.length;const d=n!==null?n.keep:null;if(d!==null&&d!==undefined&&d.length>0&&t){for(let e=0;ethis.path.length+1){this.siblingStacks.length=this.path.length+1}const t=this.path.length+1;while(this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=t){this._keptAttrs.pop()}return e}updateCurrent(e){if(this.path.length>0){const t=this.path[this.path.length-1];if(e!==null&&e!==undefined){t.values=e}}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:undefined}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:undefined}getAttrValue(e){if(this.path.length===0)return undefined;return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(this.path.length===0)return false;const t=this.path[this.path.length-1];return t.values!==undefined&&e in t.values}getAnyParentAttr(e){const t=this._keptAttrs;for(let r=t.length-1;r>=0;r--){if(t[r].name===e)return t[r].value}return undefined}hasAnyParentAttr(e){const t=this._keptAttrs;for(let r=t.length-1;r>=0;r--){if(t[r].name===e)return true}return false}getPosition(){if(this.path.length===0)return-1;return this.path[this.path.length-1].position??0}getCounter(){if(this.path.length===0)return-1;return this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=true){const r=e||this.separator;const n=r===this.separator&&t===true;if(n){if(this._pathStringCache!==null){return this._pathStringCache}const e=this.path.map((e=>e.namespace?`${e.namespace}:${e.tag}`:e.tag)).join(r);this._pathStringCache=e;return e}return this.path.map((e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag)).join(r)}toArray(){return this.path.map((e=>e.tag))}reset(){this._pathStringCache=null;this.path=[];this.siblingStacks=[];this._keptAttrs=[]}matches(e){const t=e.segments;if(t.length===0){return false}if(e.hasDeepWildcard()){return this._matchWithDeepWildcard(t)}return this._matchSimple(t)}_matchSimple(e){if(this.path.length!==e.length){return false}for(let t=0;t=0&&t>=0){const n=e[r];if(n.type==="deep-wildcard"){r--;if(r<0){return true}const n=e[r];let s=false;for(let e=t;e>=0;e--){if(this._matchSegment(n,this.path[e],e===this.path.length-1)){t=e-1;r--;s=true;break}}if(!s){return false}}else{if(!this._matchSegment(n,this.path[t],t===this.path.length-1)){return false}t--;r--}}return r<0}_matchSegment(e,t,r){if(e.tag!=="*"&&e.tag!==t.tag){return false}if(e.namespace!==undefined){if(e.namespace!=="*"&&e.namespace!==t.namespace){return false}}if(e.attrName!==undefined){if(!r){return false}if(!t.values||!(e.attrName in t.values)){return false}if(e.attrValue!==undefined){if(String(t.values[e.attrName])!==String(e.attrValue)){return false}}}if(e.position!==undefined){if(!r){return false}const n=t.counter??0;if(e.position==="first"&&n!==0){return false}else if(e.position==="odd"&&n%2!==1){return false}else if(e.position==="even"&&n%2!==0){return false}else if(e.position==="nth"&&n!==e.positionValue){return false}}return true}matchesAny(e){return e.matchesAny(this)}snapshot(){return{path:this.path.map((e=>({...e}))),siblingStacks:this.siblingStacks.map((e=>e?{counts:new Map(e.counts),total:e.total}:e)),keptAttrs:this._keptAttrs.map((e=>({...e})))}}restore(e){this._pathStringCache=null;this.path=e.path.map((e=>({...e})));this.siblingStacks=e.siblingStacks.map((e=>e?{counts:new Map(e.counts),total:e.total}:e));this._keptAttrs=(e.keptAttrs||[]).map((e=>({...e})))}readOnly(){return this._view}}function valToStr(e){return typeof e==="number"&&Object.is(e,-0)?"-0":String(e)}function safeComment(e){return valToStr(e).replace(/--/g,"- -").replace(/--/g,"- -").replace(/-$/,"- ")}function safeCdata(e){return valToStr(e).replace(/\]\]>/g,"]]]]>")}function escapeAttribute(e){return valToStr(e).replace(/"/g,""").replace(/'/g,"'")}const nameStartChar10=":A-Za-z_"+"À-ÖØ-öø-˿"+"Ͱ-ͽ"+"Ϳ-҆҈-῿"+"‌-‍"+"⁰-↏"+"Ⰰ-⿯"+"、-퟿"+"豈-﷏"+"ﷰ-�";const nameChar10=nameStartChar10+"\\-\\.\\d"+"·"+"̀-ͯ"+"‿-⁀";const nameStartChar11=":A-Za-z_"+"À-˿"+"Ͱ-ͽ"+"Ϳ-҆҈-῿"+"‌-‍"+"⁰-↏"+"Ⰰ-⿯"+"、-퟿"+"豈-﷏"+"ﷰ-�"+"𐀀-󯿿";const nameChar11=nameStartChar11+"\\-\\.\\d"+"·"+"̀-ͯ"+"҇"+"‿-⁀";const buildRegexes=(e,t,r="")=>{const n=e.replace(":","");const s=t.replace(":","");const i=`[${n}][${s}]*`;return{name:new RegExp(`^[${e}][${t}]*$`,r),ncName:new RegExp(`^${i}$`,r),qName:new RegExp(`^${i}(?::${i})?$`,r),nmToken:new RegExp(`^[${t}]+$`,r),nmTokens:new RegExp(`^[${t}]+(?:\\s+[${t}]+)*$`,r)}};const regexes10=buildRegexes(nameStartChar10,nameChar10);const regexes11=buildRegexes(nameStartChar11,nameChar11,"u");const nameStartCharAscii=":A-Za-z_";const nameCharAscii=nameStartCharAscii+"\\-\\.\\d";const regexesAscii=buildRegexes(nameStartCharAscii,nameCharAscii);const getRegexes=(e="1.0",t=false)=>{if(t)return regexesAscii;return e==="1.1"?regexes11:regexes10};const src_name=(e,{xmlVersion:t="1.0",asciiOnly:r=false}={})=>getRegexes(t,r).name.test(e);const ncName=(e,{xmlVersion:t="1.0",asciiOnly:r=false}={})=>getRegexes(t,r).ncName.test(e);const qName=(e,{xmlVersion:t="1.0",asciiOnly:r=false}={})=>getRegexes(t,r).qName.test(e);const nmToken=(e,{xmlVersion:t="1.0",asciiOnly:r=false}={})=>getRegexes(t,r).nmToken.test(e);const nmTokens=(e,{xmlVersion:t="1.0",asciiOnly:r=false}={})=>getRegexes(t,r).nmTokens.test(e);const PRODUCTIONS=["name","ncName","qName","nmToken","nmTokens"];const createValidator=(e,{xmlVersion:t="1.0",asciiOnly:r=false,maxCacheSize:n=2048}={})=>{if(!PRODUCTIONS.includes(e)){throw new TypeError(`Unknown production "${e}". Must be one of: ${PRODUCTIONS.join(", ")}`)}const s=getRegexes(t,r)[e];let i=new Map;const validator=e=>{const t=i.get(e);if(t!==undefined)return t;const r=s.test(e);if(i.size{i=new Map};return validator};const validate=(e,t,{xmlVersion:r="1.0",asciiOnly:n=false}={})=>{if(!PRODUCTIONS.includes(t)){throw new TypeError(`Unknown production "${t}". Must be one of: ${PRODUCTIONS.join(", ")}`)}const s={name:src_name,ncName:ncName,qName:qName,nmToken:nmToken,nmTokens:nmTokens};const i=s[t](e,{xmlVersion:r,asciiOnly:n});if(i)return{valid:true,production:t,input:e};let o="Does not match the production rules";let a;const c=n?/^[:A-Za-z_]/:/^[:A-Za-z_\u00C0-\uFFFD]/;const l=n?/[\w\-\\.:]/:/[\w\-\\.:\u00B7\u00C0-\uFFFD]/;if(e.length===0){o="Input is empty"}else if(t==="ncName"&&e.includes(":")){a=e.indexOf(":");o="Colon is not allowed in NCName"}else if(t==="qName"&&e.startsWith(":")){o="QName cannot start with a colon";a=0}else if(t==="qName"&&e.endsWith(":")){o="QName cannot end with a colon";a=e.length-1}else if(t==="qName"&&(e.match(/:/g)||[]).length>1){o="QName can have at most one colon";a=e.lastIndexOf(":")}else if(["name","ncName","qName"].includes(t)&&!c.test(e[0])){o=`First character "${e[0]}" is not a valid NameStartChar`;a=0}else{for(let t=0;te.map((e=>validate(e,t,r)));const sanitize=(e,t="name",{replacement:r="_",asciiOnly:n=false}={})=>{if(!e)return r;let s=e;if(t==="ncName"){s=s.replace(/:/g,"")}const i=n?/[^\w\-\.:]/g:/[^\w\-\.:\u00B7\u00C0-\uFFFD]/g;s=s.replace(i,r);if(t!=="nmToken"&&t!=="nmTokens"){if(/^[\-\.\d]/.test(s)){s=r+s}}return s||r};const EOL="\n";function detectXmlVersionFromArray(e,t){if(!Array.isArray(e)||e.length===0)return"1.0";const r=e[0];const n=propName(r);if(n==="?xml"){const e=r[":@"];if(e){const r=t.attributeNamePrefix+"version";if(e[r])return e[r]}}return"1.0"}function resolveTagName(e,t,r,n,s){if(!r.sanitizeName)return e;if(s(e))return e;return r.sanitizeName(e,{isAttribute:t,matcher:n.readOnly()})}function toXml(e,t){let r="";if(t.format){r=EOL}const n=[];if(t.stopNodes&&Array.isArray(t.stopNodes)){for(let e=0;et.maxNestedTags){throw new Error("Maximum nested tags exceeded")}if(!Array.isArray(e)){if(e!==undefined&&e!==null){let r=valToStr(e);r=replaceEntitiesValue(r,t);return r}return""}for(let c=0;c`;a=false;n.pop();continue}else if(A===t.commentPropName){const e=l[u][0][t.textNodeName];const s=safeComment(e);o+=r+`\x3c!--${s}--\x3e`;a=true;n.pop();continue}else if(A[0]==="?"){const e=attr_to_str(l[":@"],t,f,n,i);const s=A==="?xml"?"":r;o+=s+`<${A}${e}?>`;a=true;n.pop();continue}let h=r;if(h!==""){h+=t.indentBy}const g=attr_to_str(l[":@"],t,f,n,i);const y=r+`<${A}${g}`;let b;if(f){b=orderedJs2Xml_getRawContent(l[u],t)}else{b=arrToStr(l[u],t,h,n,s,i)}if(t.unpairedTags.indexOf(A)!==-1){if(t.suppressUnpairedNode)o+=y+">";else o+=y+"/>"}else if((!b||b.length===0)&&t.suppressEmptyNode){o+=y+"/>"}else if(b&&b.endsWith(">")){o+=y+`>${b}${r}`}else{o+=y+">";if(b&&r!==""&&(b.includes("/>")||b.includes("`}a=true;n.pop()}return o}function extractAttributeValues(e,t){if(!e||t.ignoreAttributes)return null;const r={};let n=false;for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;const i=s.startsWith(t.attributeNamePrefix)?s.substr(t.attributeNamePrefix.length):s;r[i]=escapeAttribute(e[s]);n=true}return n?r:null}function orderedJs2Xml_getRawContent(e,t){if(!Array.isArray(e)){if(e!==undefined&&e!==null){return valToStr(e)}return""}let r="";for(let n=0;n`}else{r+=`<${i}${e}>${n}`}}}return r}function attr_to_str_raw(e,t){let r="";if(e&&!t.ignoreAttributes){for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let s=e[n];if(s===true&&t.suppressBooleanAttributes){r+=` ${n.substr(t.attributeNamePrefix.length)}`}else{r+=` ${n.substr(t.attributeNamePrefix.length)}="${escapeAttribute(s)}"`}}}return r}function propName(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities){for(let r=0;r{for(const r of e){if(typeof r==="string"&&t===r){return true}if(r instanceof RegExp&&r.test(t)){return true}}}}return()=>false}const defaultOptions={attributeNamePrefix:"@_",attributesGroupName:false,textNodeName:"#text",ignoreAttributes:true,cdataPropName:false,format:false,indentBy:" ",suppressEmptyNode:false,suppressUnpairedNode:true,suppressBooleanAttributes:true,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:false,commentPropName:false,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","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 Builder(e){this.options=Object.assign({},defaultOptions,e);if(this.options.stopNodes&&Array.isArray(this.options.stopNodes)){this.options.stopNodes=this.options.stopNodes.map((e=>{if(typeof e==="string"&&e.startsWith("*.")){return".."+e.substring(2)}return e}))}this.stopNodeExpressions=[];if(this.options.stopNodes&&Array.isArray(this.options.stopNodes)){for(let e=0;e\n";this.newLine="\n"}else{this.indentate=function(){return""};this.tagEndChar=">";this.newLine=""}}function detectXmlVersionFromObj(e,t){const r=e["?xml"];if(r&&typeof r==="object"){if(t.attributesGroupName&&r[t.attributesGroupName]){const e=r[t.attributesGroupName][t.attributeNamePrefix+"version"];if(e)return e}const e=r[t.attributeNamePrefix+"version"];if(e)return e}return"1.0"}function fxb_resolveTagName(e,t,r,n,s){if(!r.sanitizeName)return e;if(s(e))return e;return r.sanitizeName(e,{isAttribute:t,matcher:n.readOnly()})}Builder.prototype.build=function(e){if(this.options.preserveOrder){return toXml(e,this.options)}else{if(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1){e={[this.options.arrayNodeName]:e}}const t=new Matcher;const r=detectXmlVersionFromObj(e,this.options);const n=createValidator("qName",{xmlVersion:r});return this.j2x(e,0,t,n).val}};Builder.prototype.j2x=function(e,t,r,n){let s="";let i="";if(this.options.maxNestedTags&&r.getDepth()>=this.options.maxNestedTags){throw new Error("Maximum nested tags exceeded")}const o=this.options.jPath?r.toString():r;const a=this.checkStopNode(r);for(let c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;const l=c===this.options.textNodeName||c===this.options.cdataPropName||c===this.options.commentPropName||this.options.attributesGroupName&&c===this.options.attributesGroupName||this.isAttribute(c)||c[0]==="?";const u=l?c:fxb_resolveTagName(c,false,this.options,r,n);if(typeof e[c]==="undefined"){if(this.isAttribute(c)){i+=""}}else if(e[c]===null){if(this.isAttribute(c)){i+=""}else if(u===this.options.cdataPropName||u===this.options.commentPropName){i+=""}else if(u[0]==="?"){i+=this.indentate(t)+"<"+u+"?"+this.tagEndChar}else{i+=this.indentate(t)+"<"+u+"/"+this.tagEndChar}}else if(e[c]instanceof Date){i+=this.buildTextValNode(e[c],u,"",t,r)}else if(typeof e[c]!=="object"){const l=this.isAttribute(c);if(l&&!this.ignoreAttributesFn(l,o)){const t=fxb_resolveTagName(l,true,this.options,r,n);s+=this.buildAttrPairStr(t,valToStr(e[c]),a)}else if(!l){if(c===this.options.textNodeName){let t=this.options.tagValueProcessor(c,valToStr(e[c]));i+=this.replaceEntitiesValue(t)}else{r.push(u);const n=this.checkStopNode(r);r.pop();if(n){const r=valToStr(e[c]);if(r===""){i+=this.indentate(t)+"<"+u+this.closeTag(u)+this.tagEndChar}else{i+=this.indentate(t)+"<"+u+">"+r+""+e+"${e}`}else if(typeof e==="object"&&e!==null){const n=this.buildRawContent(e);const s=this.buildAttributesForStopNode(e);if(n===""){t+=`<${r}${s}/>`}else{t+=`<${r}${s}>${n}`}}}}else if(typeof n==="object"&&n!==null){const e=this.buildRawContent(n);const s=this.buildAttributesForStopNode(n);if(e===""){t+=`<${r}${s}/>`}else{t+=`<${r}${s}>${e}`}}else{t+=`<${r}>${n}`}}return t};Builder.prototype.buildAttributesForStopNode=function(e){if(!e||typeof e!=="object")return"";let t="";if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){const r=e[this.options.attributesGroupName];for(let e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;const n=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e;const s=r[e];if(s===true&&this.options.suppressBooleanAttributes){t+=" "+n}else{t+=" "+n+'="'+escapeAttribute(s)+'"'}}}else{for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;const n=this.isAttribute(r);if(n){const s=e[r];if(s===true&&this.options.suppressBooleanAttributes){t+=" "+n}else{t+=" "+n+'="'+escapeAttribute(s)+'"'}}}}return t};Builder.prototype.buildObjectNode=function(e,t,r,n){if(e===""){if(t[0]==="?")return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar;else{return this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar}}else if(t[0]==="?"){return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar}else{let s=""+e+s}else if(this.options.commentPropName!==false&&t===this.options.commentPropName&&i.length===0){return this.indentate(n)+`\x3c!--${safeComment(e)}--\x3e`+this.newLine}else{return this.indentate(n)+"<"+t+r+i+this.tagEndChar+e+this.indentate(n)+s}}};Builder.prototype.closeTag=function(e){let t="";if(this.options.unpairedTags.indexOf(e)!==-1){if(!this.options.suppressUnpairedNode)t="/"}else if(this.options.suppressEmptyNode){t="/"}else{t=`>`+this.newLine}else if(this.options.commentPropName!==false&&t===this.options.commentPropName){const t=safeComment(e);return this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine}else if(t[0]==="?"){return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar}else{let s=this.options.tagValueProcessor(t,e);s=this.replaceEntitiesValue(s);s=valToStr(s);if(s===""){return this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar}else{return this.indentate(n)+"<"+t+r+">"+s+"0&&this.options.processEntities){for(let t=0;t"&&e[i]!==" "&&e[i]!=="\t"&&e[i]!=="\n"&&e[i]!=="\r";i++){c+=e[i]}c=c.trim();if(c[c.length-1]==="/"){c=c.substring(0,c.length-1);i--}if(!validateTagName(c)){let t;if(c.trim().length===0){t="Invalid space after '<'."}else{t="Tag '"+c+"' is an invalid name."}return getErrorObject("InvalidTag",t,getLineNumberForPosition(e,i))}const l=readAttributeStr(e,i);if(l===false){return getErrorObject("InvalidAttr","Attributes for '"+c+"' have open quote.",getLineNumberForPosition(e,i))}let u=l.value;i=l.index;if(u[u.length-1]==="/"){const r=i-u.length;u=u.substring(0,u.length-1);const s=validateAttributeString(u,t);if(s===true){n=true}else{return getErrorObject(s.err.code,s.err.msg,getLineNumberForPosition(e,r+s.err.line))}}else if(a){if(!l.tagClosed){return getErrorObject("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",getLineNumberForPosition(e,i))}else if(u.trim().length>0){return getErrorObject("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",getLineNumberForPosition(e,o))}else if(r.length===0){return getErrorObject("InvalidTag","Closing tag '"+c+"' has not been opened.",getLineNumberForPosition(e,o))}else{const t=r.pop();if(c!==t.tagName){let r=getLineNumberForPosition(e,t.tagStartPos);return getErrorObject("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+c+"'.",getLineNumberForPosition(e,o))}if(r.length==0){s=true}}}else{const a=validateAttributeString(u,t);if(a!==true){return getErrorObject(a.err.code,a.err.msg,getLineNumberForPosition(e,i-u.length+a.err.line))}if(s===true){return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(e,i))}else if(t.unpairedTags.indexOf(c)!==-1){}else{r.push({tagName:c,tagStartPos:o})}n=true}for(i++;i0){return getErrorObject("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}return true}function isWhiteSpace(e){return e===" "||e==="\t"||e==="\n"||e==="\r"}function readPI(e,t){const r=t;for(;t5&&n==="xml"){return getErrorObject("InvalidXml","XML declaration allowed only at the start of the document.",getLineNumberForPosition(e,t))}else if(e[t]=="?"&&e[t+1]==">"){t++;break}else{continue}}}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t"){t+=2;break}}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let r=1;for(t+=8;t"){r--;if(r===0){break}}}}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t"){t+=2;break}}}return t}const doubleQuote='"';const singleQuote="'";function readAttributeStr(e,t){let r="";let n="";let s=false;for(;t"){if(n===""){s=true;break}}r+=e[t]}if(n!==""){return false}return{value:r,index:t,tagClosed:s}}function scanAttributeTokens(e){const t=[];const r=e.length;let n=0;while(n=r)break;if(e[n]==="="){n=s+1;continue}const i=e.slice(s,n);const o=n;while(n{if(DANGEROUS_PROPERTY_NAMES.includes(e)){return"__"+e}return e};const OptionsBuilder_defaultOptions={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(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:false,isArray:()=>false,commentPropName:false,unpairedTags:[],processEntities:true,htmlEntities:false,entityDecoder:null,ignoreDeclaration:false,ignorePiTags:false,transformTagName:false,transformAttributeName:false,updateTag:function(e,t,r){return e},captureMetaData:false,maxNestedTags:100,strictReservedNames:true,jPath:true,onDangerousProperty:defaultOnDangerousProperty};function validatePropertyName(e,t){if(typeof e!=="string"){return}const r=e.toLowerCase();if(DANGEROUS_PROPERTY_NAMES.some((e=>r===e.toLowerCase()))){throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}if(criticalProperties.some((e=>r===e.toLowerCase()))){throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}}function normalizeProcessEntities(e,t){if(typeof e==="boolean"){return{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:Infinity,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}}if(typeof e==="object"&&e!==null){return{enabled:e.enabled!==false,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??Infinity),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}}return normalizeProcessEntities(true)}const buildOptions=function(e){const t=Object.assign({},OptionsBuilder_defaultOptions,e);const r=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(const{value:e,name:t}of r){if(e){validatePropertyName(e,t)}}if(t.onDangerousProperty===null){t.onDangerousProperty=defaultOnDangerousProperty}t.processEntities=normalizeProcessEntities(t.processEntities,t.htmlEntities);t.unpairedTagsSet=new Set(t.unpairedTags);if(t.stopNodes&&Array.isArray(t.stopNodes)){t.stopNodes=t.stopNodes.map((e=>{if(typeof e==="string"&&e.startsWith("*.")){return".."+e.substring(2)}return e}))}return t};let METADATA_SYMBOL;if(typeof Symbol!=="function"){METADATA_SYMBOL="@@xmlMetadata"}else{METADATA_SYMBOL=Symbol("XML Node Metadata")}class XmlNode{constructor(e){this.tagname=e;this.child=[];this[":@"]=Object.create(null)}add(e,t){if(e==="__proto__")e="#__proto__";this.child.push({[e]:t})}addChild(e,t){if(e.tagname==="__proto__")e.tagname="#__proto__";if(e[":@"]&&Object.keys(e[":@"]).length>0){this.child.push({[e.tagname]:e.child,[":@"]:e[":@"]})}else{this.child.push({[e.tagname]:e.child})}this.addStartIndex(t)}addStartIndex(e){if(e!==undefined){this.child[this.child.length-1][METADATA_SYMBOL]={startIndex:e}}}addEndIndex(e){const t=this.child[this.child.length-1];if(t!==undefined&&t[METADATA_SYMBOL]!==undefined&&t[METADATA_SYMBOL].endIndex===undefined){t[METADATA_SYMBOL].endIndex=e}}static getMetaDataSymbol(){return METADATA_SYMBOL}}class DocTypeReader{constructor(e,t){this.suppressValidationErr=!e;this.options=e;this.xmlVersion=t||1}setXmlVersion(e=1){this.xmlVersion=e}readDocType(e,t){const r=Object.create(null);let n=0;if(e[t+3]==="O"&&e[t+4]==="C"&&e[t+5]==="T"&&e[t+6]==="Y"&&e[t+7]==="P"&&e[t+8]==="E"){t=t+9;let s=1;let i=false,o=false;let a=null;let c="";for(;t=this.options.maxEntityCount){throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`)}r[s]=i;n++}}else if(i&&hasSeq(e,"!ELEMENT",t)){t+=8;const{index:r}=this.readElementExp(e,t+1);t=r}else if(i&&hasSeq(e,"!ATTLIST",t)){t+=8}else if(i&&hasSeq(e,"!NOTATION",t)){t+=9;const{index:r}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=r}else if(hasSeq(e,"!--",t))o=true;else throw new Error(`Invalid DOCTYPE`);s++;c=""}else if(e[t]===">"){if(o){if(e[t-1]==="-"&&e[t-2]==="-"){o=false;s--}}else{s--}if(s===0){break}}else if(e[t]==="["){i=true}else{c+=e[t]}}if(a!==null||s!==0){throw new Error(`Unclosed DOCTYPE`)}}else{throw new Error(`Invalid Tag instead of DOCTYPE`)}return{entities:r,i:t}}readEntityExp(e,t){t=skipWhitespace(e,t);const r=t;while(tthis.options.maxEntitySize){throw new Error(`Entity "${n}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`)}t--;return[n,s,t]}readNotationExp(e,t){t=skipWhitespace(e,t);const r=t;while(t{while(t=CHAR_0&&s<=CHAR_9||s===CHAR_MINUS)continue;if(s=55296&&s<=56319){if(n+1=56320&&t<=57343){const e=65536+(s-55296<<10)+(t-56320);if(HIGH_MAP.has(e)){r=n;break}}}continue}if(TABLE[s-TABLE_OFFSET]!==NOT_DIGIT||MINUS_SET.has(s)){r=n;break}}if(r===-1)return e;const n=[];if(r>0)n.push(e.slice(0,r));for(let s=r;s=CHAR_0&&r<=CHAR_9||r===CHAR_MINUS){n.push(e[s]);continue}if(r=55296&&r<=56319){if(s+1=56320&&t<=57343){const e=65536+(r-55296<<10)+(t-56320);const i=HIGH_MAP.get(e);if(i!==undefined){n.push(String.fromCharCode(i+48));s++;continue}}}n.push(e[s]);continue}if(MINUS_SET.has(r)){n.push("-");continue}const i=TABLE[r-TABLE_OFFSET];n.push(i!==NOT_DIGIT?String.fromCharCode(i+48):e[s])}return n.join("")}const anynum_anynum=anynum;const hexRegex=/^[-+]?0x[a-fA-F0-9]+$/;const binRegex=/^0b[01]+$/;const octRegex=/^0o[0-7]+$/;const numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;const consider={hex:true,binary:false,octal:false,leadingZeros:true,decimalPoint:".",eNotation:true,infinity:"original",unicode:false};function toNumber(e,t={}){t=Object.assign({},consider,t);if(!e||typeof e!=="string")return e;let r=e.trim();if(r.length===0)return e;else if(t.skipLike!==undefined&&t.skipLike.test(r))return e;else if(r==="0")return 0;if(t.unicode){r=anynum_anynum(r);if(r==="0")return 0}if(t.hex&&hexRegex.test(r)){return parse_int(r,16)}else if(t.binary&&binRegex.test(r)){return parse_int(r,2)}else if(t.octal&&octRegex.test(r)){return parse_int(r,8)}else if(!isFinite(r)){return handleInfinity(e,Number(r),t)}else if(r.includes("e")||r.includes("E")){return resolveEnotation(e,r,t)}else{const n=numRegex.exec(r);if(n){const s=n[1]||"";const i=n[2];let o=trimZeros(n[3]);const a=s?e[i.length+1]===".":e[i.length]===".";if(!t.leadingZeros&&(i.length>1||i.length===1&&!a)){return e}else{const n=Number(r);const a=String(n);if(n===0)return n;if(a.search(/[eE]/)!==-1){if(t.eNotation)return n;else return e}else if(r.indexOf(".")!==-1){if(a==="0")return n;else if(a===o)return n;else if(a===`${s}${o}`)return n;else return e}let c=i?o:r;if(i){return c===a||s+c===a?n:e}else{return c===a||c===s+a?n:e}}}else{return e}}}const eNotationRegx=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,r){if(!r.eNotation)return e;const n=t.match(eNotationRegx);if(n){let s=n[1]||"";const i=n[3].indexOf("e")===-1?"E":"e";const o=n[2];const a=s?e[o.length+1]===i:e[o.length]===i;if(o.length>1&&a)return e;else if(o.length===1&&(n[3].startsWith(`.${i}`)||n[3][0]===i)){return Number(t)}else if(o.length>0){if(r.leadingZeros&&!a){t=(n[1]||"")+n[3];return Number(t)}else return e}else{return Number(t)}}else{return e}}function trimZeros(e){if(e&&e.indexOf(".")!==-1){let t=e.length;while(t>0&&e.charCodeAt(t-1)===48)t--;e=e.slice(0,t);if(e===".")e="0";else if(e[0]===".")e="0"+e;else if(e[e.length-1]===".")e=e.substring(0,e.length-1);return e}return e}function parse_int(e,t){const r=e.trim();if(t===2||t===8)e=r.substring(2);if(parseInt)return parseInt(e,t);else if(Number.parseInt)return Number.parseInt(e,t);else if(window&&window.parseInt)return window.parseInt(e,t);else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function handleInfinity(e,t,r){const n=t===Infinity;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return n?"Infinity":"-Infinity";case"original":default:return e}}function ignoreAttributes_getIgnoreAttributesFn(e){if(typeof e==="function"){return e}if(Array.isArray(e)){return t=>{for(const r of e){if(typeof r==="string"&&t===r){return true}if(r instanceof RegExp&&r.test(t)){return true}}}}return()=>false}class ExpressionSet{constructor(){this._byDepthAndTag=new Map;this._wildcardByDepth=new Map;this._deepWildcards=[];this._deepByTerminalTag=new Map;this._patterns=new Set;this._sealed=false}add(e){if(this._sealed){throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.")}if(this._patterns.has(e.pattern))return this;this._patterns.add(e.pattern);if(e.hasDeepWildcard()){const t=e.segments[e.segments.length-1];if(t&&t.type!=="deep-wildcard"&&t.tag!=="*"){const r=t.tag;if(!this._deepByTerminalTag.has(r))this._deepByTerminalTag.set(r,[]);this._deepByTerminalTag.get(r).push(e)}else{this._deepWildcards.push(e)}return this}const t=e.length;const r=e.segments[e.segments.length-1];const n=r?.tag;if(!n||n==="*"){if(!this._wildcardByDepth.has(t))this._wildcardByDepth.set(t,[]);this._wildcardByDepth.get(t).push(e)}else{const r=`${t}:${n}`;if(!this._byDepthAndTag.has(r))this._byDepthAndTag.set(r,[]);this._byDepthAndTag.get(r).push(e)}return this}addAll(e){for(const t of e)this.add(t);return this}has(e){return this._patterns.has(e.pattern)}get size(){return this._patterns.size}seal(){this._sealed=true;return this}get isSealed(){return this._sealed}matchesAny(e){return this.findMatch(e)!==null}findMatch(e){const t=e.getDepth();const r=e.getCurrentTag();const n=`${t}:${r}`;const s=this._byDepthAndTag.get(n);if(s){for(let t=0;t",GT:">",quot:'"',QUOT:'"',apos:"'",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",lsquor:"‚",rsquor:"’",ldquor:"„",bdquo:"„",comma:",",period:".",colon:":",semi:";",excl:"!",quest:"?",num:"#",dollar:"$",percent:"%",ast:"*",commat:"@",lowbar:"_",verbar:"|",vert:"|",sol:"/",bsol:"\\",lbrace:"{",rbrace:"}",lbrack:"[",rbrack:"]",lpar:"(",rpar:")",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",COPY:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",REG:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",half:"½",frac34:"¾",iquest:"¿",times:"×",div:"÷",divide:"÷"};const LATIN_ACCENTS={Agrave:"À",agrave:"à",Aacute:"Á",aacute:"á",Acirc:"Â",acirc:"â",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",Aring:"Å",aring:"å",AElig:"Æ",aelig:"æ",Ccedil:"Ç",ccedil:"ç",Egrave:"È",egrave:"è",Eacute:"É",eacute:"é",Ecirc:"Ê",ecirc:"ê",Euml:"Ë",euml:"ë",Igrave:"Ì",igrave:"ì",Iacute:"Í",iacute:"í",Icirc:"Î",icirc:"î",Iuml:"Ï",iuml:"ï",ETH:"Ð",eth:"ð",Ntilde:"Ñ",ntilde:"ñ",Ograve:"Ò",ograve:"ò",Oacute:"Ó",oacute:"ó",Ocirc:"Ô",ocirc:"ô",Otilde:"Õ",otilde:"õ",Ouml:"Ö",ouml:"ö",Oslash:"Ø",oslash:"ø",Ugrave:"Ù",ugrave:"ù",Uacute:"Ú",uacute:"ú",Ucirc:"Û",ucirc:"û",Uuml:"Ü",uuml:"ü",Yacute:"Ý",yacute:"ý",THORN:"Þ",thorn:"þ",szlig:"ß",yuml:"ÿ",Yuml:"Ÿ"};const LATIN_EXTENDED={Amacr:"Ā",amacr:"ā",Abreve:"Ă",abreve:"ă",Aogon:"Ą",aogon:"ą",Cacute:"Ć",cacute:"ć",Ccirc:"Ĉ",ccirc:"ĉ",Cdot:"Ċ",cdot:"ċ",Ccaron:"Č",ccaron:"č",Dcaron:"Ď",dcaron:"ď",Dstrok:"Đ",dstrok:"đ",Emacr:"Ē",emacr:"ē",Ecaron:"Ě",ecaron:"ě",Edot:"Ė",edot:"ė",Eogon:"Ę",eogon:"ę",Gcirc:"Ĝ",gcirc:"ĝ",Gbreve:"Ğ",gbreve:"ğ",Gdot:"Ġ",gdot:"ġ",Gcedil:"Ģ",Hcirc:"Ĥ",hcirc:"ĥ",Hstrok:"Ħ",hstrok:"ħ",Itilde:"Ĩ",itilde:"ĩ",Imacr:"Ī",imacr:"ī",Iogon:"Į",iogon:"į",Idot:"İ",IJlig:"IJ",ijlig:"ij",Jcirc:"Ĵ",jcirc:"ĵ",Kcedil:"Ķ",kcedil:"ķ",kgreen:"ĸ",Lacute:"Ĺ",lacute:"ĺ",Lcedil:"Ļ",lcedil:"ļ",Lcaron:"Ľ",lcaron:"ľ",Lmidot:"Ŀ",lmidot:"ŀ",Lstrok:"Ł",lstrok:"ł",Nacute:"Ń",nacute:"ń",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ENG:"Ŋ",eng:"ŋ",Omacr:"Ō",omacr:"ō",Odblac:"Ő",odblac:"ő",OElig:"Œ",oelig:"œ",Racute:"Ŕ",racute:"ŕ",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",Sacute:"Ś",sacute:"ś",Scirc:"Ŝ",scirc:"ŝ",Scedil:"Ş",scedil:"ş",Scaron:"Š",scaron:"š",Tcedil:"Ţ",tcedil:"ţ",Tcaron:"Ť",tcaron:"ť",Tstrok:"Ŧ",tstrok:"ŧ",Utilde:"Ũ",utilde:"ũ",Umacr:"Ū",umacr:"ū",Ubreve:"Ŭ",ubreve:"ŭ",Uring:"Ů",uring:"ů",Udblac:"Ű",udblac:"ű",Uogon:"Ų",uogon:"ų",Wcirc:"Ŵ",wcirc:"ŵ",Ycirc:"Ŷ",ycirc:"ŷ",Zacute:"Ź",zacute:"ź",Zdot:"Ż",zdot:"ż",Zcaron:"Ž",zcaron:"ž"};const GREEK={Alpha:"Α",alpha:"α",Beta:"Β",beta:"β",Gamma:"Γ",gamma:"γ",Delta:"Δ",delta:"δ",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",varepsilon:"ϵ",Zeta:"Ζ",zeta:"ζ",Eta:"Η",eta:"η",Theta:"Θ",theta:"θ",thetasym:"ϑ",vartheta:"ϑ",Iota:"Ι",iota:"ι",Kappa:"Κ",kappa:"κ",kappav:"ϰ",varkappa:"ϰ",Lambda:"Λ",lambda:"λ",Mu:"Μ",mu:"μ",Nu:"Ν",nu:"ν",Xi:"Ξ",xi:"ξ",Omicron:"Ο",omicron:"ο",Pi:"Π",pi:"π",piv:"ϖ",varpi:"ϖ",Rho:"Ρ",rho:"ρ",rhov:"ϱ",varrho:"ϱ",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",varsigma:"ς",Tau:"Τ",tau:"τ",Upsilon:"Υ",upsilon:"υ",upsi:"υ",Upsi:"ϒ",upsih:"ϒ",Phi:"Φ",phi:"φ",phiv:"ϕ",varphi:"ϕ",Chi:"Χ",chi:"χ",Psi:"Ψ",psi:"ψ",Omega:"Ω",omega:"ω",ohm:"Ω",Gammad:"Ϝ",gammad:"ϝ",digamma:"ϝ"};const CYRILLIC={Afr:"𝔄",afr:"𝔞",Acy:"А",acy:"а",Bcy:"Б",bcy:"б",Vcy:"В",vcy:"в",Gcy:"Г",gcy:"г",Dcy:"Д",dcy:"д",IEcy:"Е",iecy:"е",IOcy:"Ё",iocy:"ё",ZHcy:"Ж",zhcy:"ж",Zcy:"З",zcy:"з",Icy:"И",icy:"и",Jcy:"Й",jcy:"й",Kcy:"К",kcy:"к",Lcy:"Л",lcy:"л",Mcy:"М",mcy:"м",Ncy:"Н",ncy:"н",Ocy:"О",ocy:"о",Pcy:"П",pcy:"п",Rcy:"Р",rcy:"р",Scy:"С",scy:"с",Tcy:"Т",tcy:"т",Ucy:"У",ucy:"у",Fcy:"Ф",fcy:"ф",KHcy:"Х",khcy:"х",TScy:"Ц",tscy:"ц",CHcy:"Ч",chcy:"ч",SHcy:"Ш",shcy:"ш",SHCHcy:"Щ",shchcy:"щ",HARDcy:"Ъ",hardcy:"ъ",Ycy:"Ы",ycy:"ы",SOFTcy:"Ь",softcy:"ь",Ecy:"Э",ecy:"э",YUcy:"Ю",yucy:"ю",YAcy:"Я",yacy:"я",DJcy:"Ђ",djcy:"ђ",GJcy:"Ѓ",gjcy:"ѓ",Jukcy:"Є",jukcy:"є",DScy:"Ѕ",dscy:"ѕ",Iukcy:"І",iukcy:"і",YIcy:"Ї",yicy:"ї",Jsercy:"Ј",jsercy:"ј",LJcy:"Љ",ljcy:"љ",NJcy:"Њ",njcy:"њ",TSHcy:"Ћ",tshcy:"ћ",KJcy:"Ќ",kjcy:"ќ",Ubrcy:"Ў",ubrcy:"ў",DZcy:"Џ",dzcy:"џ"};const MATH={plus:"+",pm:"±",times:"×",div:"÷",divide:"÷",sdot:"⋅",star:"☆",starf:"★",bigstar:"★",lowast:"∗",ast:"*",midast:"*",compfn:"∘",smallcircle:"∘",bullet:"•",bull:"•",nbsp:" ",hellip:"…",mldr:"…",prime:"′",Prime:"″",tprime:"‴",bprime:"‵",backprime:"‵",minus:"−",minusd:"∸",dotminus:"∸",plusdo:"∔",dotplus:"∔",plusmn:"±",minusplus:"∓",mnplus:"∓",mp:"∓",setminus:"∖",smallsetminus:"∖",Backslash:"∖",setmn:"∖",ssetmn:"∖",lowbar:"_",verbar:"|",vert:"|",VerticalLine:"|",colon:":",Colon:"∷",Proportion:"∷",ratio:"∶",equals:"=",ne:"≠",nequiv:"≢",equiv:"≡",Congruent:"≡",sim:"∼",thicksim:"∼",thksim:"∼",sime:"≃",simeq:"≃",TildeEqual:"≃",asymp:"≈",approx:"≈",thickapprox:"≈",thkap:"≈",TildeTilde:"≈",ncong:"≇",cong:"≅",TildeFullEqual:"≅",asympeq:"≍",CupCap:"≍",bump:"≎",Bumpeq:"≎",HumpDownHump:"≎",bumpe:"≏",bumpeq:"≏",HumpEqual:"≏",le:"≤",LessEqual:"≤",ge:"≥",GreaterEqual:"≥",lesseqgtr:"⋚",lesseqqgtr:"⪋",greater:">",less:"<"};const MATH_ADVANCED={alefsym:"ℵ",aleph:"ℵ",beth:"ℶ",gimel:"ℷ",daleth:"ℸ",forall:"∀",ForAll:"∀",part:"∂",PartialD:"∂",exist:"∃",Exists:"∃",nexist:"∄",nexists:"∄",empty:"∅",emptyset:"∅",emptyv:"∅",varnothing:"∅",nabla:"∇",Del:"∇",isin:"∈",isinv:"∈",in:"∈",Element:"∈",notin:"∉",notinva:"∉",ni:"∋",niv:"∋",SuchThat:"∋",ReverseElement:"∋",notni:"∌",notniva:"∌",prod:"∏",Product:"∏",coprod:"∐",Coproduct:"∐",sum:"∑",Sum:"∑",minus:"−",mp:"∓",plusdo:"∔",dotplus:"∔",setminus:"∖",lowast:"∗",radic:"√",Sqrt:"√",prop:"∝",propto:"∝",Proportional:"∝",varpropto:"∝",infin:"∞",infintie:"⧝",ang:"∠",angle:"∠",angmsd:"∡",measuredangle:"∡",angsph:"∢",mid:"∣",VerticalBar:"∣",nmid:"∤",nsmid:"∤",npar:"∦",parallel:"∥",spar:"∥",nparallel:"∦",nspar:"∦",and:"∧",wedge:"∧",or:"∨",vee:"∨",cap:"∩",cup:"∪",int:"∫",Integral:"∫",conint:"∮",ContourIntegral:"∮",Conint:"∯",DoubleContourIntegral:"∯",Cconint:"∰",there4:"∴",therefore:"∴",Therefore:"∴",becaus:"∵",because:"∵",Because:"∵",ratio:"∶",Proportion:"∷",minusd:"∸",dotminus:"∸",mDDot:"∺",homtht:"∻",sim:"∼",bsimg:"∽",backsim:"∽",ac:"∾",mstpos:"∾",acd:"∿",VerticalTilde:"≀",wr:"≀",wreath:"≀",nsime:"≄",nsimeq:"≄",ncong:"≇",simne:"≆",ncongdot:"⩭̸",ngsim:"≵",nsim:"≁",napprox:"≉",nap:"≉",ngeq:"≱",nge:"≱",nleq:"≰",nle:"≰",ngtr:"≯",ngt:"≯",nless:"≮",nlt:"≮",nprec:"⊀",npr:"⊀",nsucc:"⊁",nsc:"⊁"};const ARROWS={larr:"←",leftarrow:"←",LeftArrow:"←",uarr:"↑",uparrow:"↑",UpArrow:"↑",rarr:"→",rightarrow:"→",RightArrow:"→",darr:"↓",downarrow:"↓",DownArrow:"↓",harr:"↔",leftrightarrow:"↔",LeftRightArrow:"↔",varr:"↕",updownarrow:"↕",UpDownArrow:"↕",nwarr:"↖",nwarrow:"↖",UpperLeftArrow:"↖",nearr:"↗",nearrow:"↗",UpperRightArrow:"↗",searr:"↘",searrow:"↘",LowerRightArrow:"↘",swarr:"↙",swarrow:"↙",LowerLeftArrow:"↙",lArr:"⇐",Leftarrow:"⇐",uArr:"⇑",Uparrow:"⇑",rArr:"⇒",Rightarrow:"⇒",dArr:"⇓",Downarrow:"⇓",hArr:"⇔",Leftrightarrow:"⇔",iff:"⇔",vArr:"⇕",Updownarrow:"⇕",lAarr:"⇚",Lleftarrow:"⇚",rAarr:"⇛",Rrightarrow:"⇛",lrarr:"⇆",leftrightarrows:"⇆",rlarr:"⇄",rightleftarrows:"⇄",lrhar:"⇋",leftrightharpoons:"⇋",ReverseEquilibrium:"⇋",rlhar:"⇌",rightleftharpoons:"⇌",Equilibrium:"⇌",udarr:"⇅",UpArrowDownArrow:"⇅",duarr:"⇵",DownArrowUpArrow:"⇵",llarr:"⇇",leftleftarrows:"⇇",rrarr:"⇉",rightrightarrows:"⇉",ddarr:"⇊",downdownarrows:"⇊",har:"↽",lhard:"↽",leftharpoondown:"↽",lharu:"↼",leftharpoonup:"↼",rhard:"⇁",rightharpoondown:"⇁",rharu:"⇀",rightharpoonup:"⇀",lsh:"↰",Lsh:"↰",rsh:"↱",Rsh:"↱",ldsh:"↲",rdsh:"↳",hookleftarrow:"↩",hookrightarrow:"↪",mapstoleft:"↤",mapstoup:"↥",map:"↦",mapsto:"↦",mapstodown:"↧",crarr:"↵",nleftarrow:"↚",nleftrightarrow:"↮",nrightarrow:"↛",nrarr:"↛",larrtl:"↢",rarrtl:"↣",leftarrowtail:"↢",rightarrowtail:"↣",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Larr:"↞",Rarr:"↠",larrhk:"↩",rarrhk:"↪",larrlp:"↫",looparrowleft:"↫",rarrlp:"↬",looparrowright:"↬",harrw:"↭",leftrightsquigarrow:"↭",nrarrw:"↝̸",rarrw:"↝",rightsquigarrow:"↝",larrbfs:"⤟",rarrbfs:"⤠",nvHarr:"⤄",nvlArr:"⤂",nvrArr:"⤃",larrfs:"⤝",rarrfs:"⤞",Map:"⤅",larrsim:"⥳",rarrsim:"⥴",harrcir:"⥈",Uarrocir:"⥉",lurdshar:"⥊",ldrdhar:"⥧",ldrushar:"⥋",rdldhar:"⥩",lrhard:"⥭",uharr:"↾",uharl:"↿",dharr:"⇂",dharl:"⇃",Uarr:"↟",Darr:"↡",zigrarr:"⇝",nwArr:"⇖",neArr:"⇗",seArr:"⇘",swArr:"⇙",nharr:"↮",nhArr:"⇎",nlarr:"↚",nlArr:"⇍",nrArr:"⇏",larrb:"⇤",LeftArrowBar:"⇤",rarrb:"⇥",RightArrowBar:"⇥"};const SHAPES={square:"□",Square:"□",squ:"□",squf:"▪",squarf:"▪",blacksquar:"▪",blacksquare:"▪",FilledVerySmallSquare:"▪",blk34:"▓",blk12:"▒",blk14:"░",block:"█",srect:"▭",rect:"▭",sdot:"⋅",sdotb:"⊡",dotsquare:"⊡",triangle:"▵",tri:"▵",trine:"▵",utri:"▵",triangledown:"▿",dtri:"▿",tridown:"▿",triangleleft:"◃",ltri:"◃",triangleright:"▹",rtri:"▹",blacktriangle:"▴",utrif:"▴",blacktriangledown:"▾",dtrif:"▾",blacktriangleleft:"◂",ltrif:"◂",blacktriangleright:"▸",rtrif:"▸",loz:"◊",lozenge:"◊",blacklozenge:"⧫",lozf:"⧫",bigcirc:"◯",xcirc:"◯",circ:"ˆ",Circle:"○",cir:"○",o:"○",bullet:"•",bull:"•",hellip:"…",mldr:"…",nldr:"‥",boxh:"─",HorizontalLine:"─",boxv:"│",boxdr:"┌",boxdl:"┐",boxur:"└",boxul:"┘",boxvr:"├",boxvl:"┤",boxhd:"┬",boxhu:"┴",boxvh:"┼",boxH:"═",boxV:"║",boxdR:"╒",boxDr:"╓",boxDR:"╔",boxDl:"╕",boxdL:"╖",boxDL:"╗",boxuR:"╘",boxUr:"╙",boxUR:"╚",boxUl:"╜",boxuL:"╛",boxUL:"╝",boxvR:"╞",boxVr:"╟",boxVR:"╠",boxVl:"╢",boxvL:"╡",boxVL:"╣",boxHd:"╤",boxhD:"╥",boxHD:"╦",boxHu:"╧",boxhU:"╨",boxHU:"╩",boxvH:"╪",boxVh:"╫",boxVH:"╬"};const PUNCTUATION={excl:"!",iexcl:"¡",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",nbsp:" ",comma:",",period:".",colon:":",semi:";",vert:"|",Verbar:"‖",verbar:"|",dblac:"˝",circ:"ˆ",caron:"ˇ",breve:"˘",dot:"˙",ring:"˚",ogon:"˛",tilde:"˜",DiacriticalGrave:"`",DiacriticalAcute:"´",DiacriticalTilde:"˜",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",grave:"`"};const CURRENCY={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"};const FRACTIONS={frac12:"½",half:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄"};const MISC_SYMBOLS={trade:"™",TRADE:"™",telrec:"⌕",target:"⌖",ulcorn:"⌜",ulcorner:"⌜",urcorn:"⌝",urcorner:"⌝",dlcorn:"⌞",llcorner:"⌞",drcorn:"⌟",lrcorner:"⌟",intercal:"⊺",intcal:"⊺",oplus:"⊕",CirclePlus:"⊕",ominus:"⊖",CircleMinus:"⊖",otimes:"⊗",CircleTimes:"⊗",osol:"⊘",odot:"⊙",CircleDot:"⊙",oast:"⊛",circledast:"⊛",odash:"⊝",circleddash:"⊝",ocirc:"⊚",circledcirc:"⊚",boxplus:"⊞",plusb:"⊞",boxminus:"⊟",minusb:"⊟",boxtimes:"⊠",timesb:"⊠",boxdot:"⊡",sdotb:"⊡",veebar:"⊻",vee:"∨",barvee:"⊽",and:"∧",wedge:"∧",Cap:"⋒",Cup:"⋓",Fork:"⋔",pitchfork:"⋔",epar:"⋕",ltlarr:"⥶",nvap:"≍⃒",nvsim:"∼⃒",nvge:"≥⃒",nvle:"≤⃒",nvlt:"<⃒",nvgt:">⃒",nvltrie:"⊴⃒",nvrtrie:"⊵⃒",Vdash:"⊩",dashv:"⊣",vDash:"⊨",Vvdash:"⊪",nvdash:"⊬",nvDash:"⊭",nVdash:"⊮",nVDash:"⊯"};const XML={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'};const COMMON_HTML={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"};const ENTITY_ACTION=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"});const SPECIAL_CHARS=new Set("!?\\\\/[]$%{}^&*()<>|+");function EntityDecoder_validateEntityName(e){if(e[0]==="#"){throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`)}for(const t of e){if(SPECIAL_CHARS.has(t)){throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`)}}return e}function mergeEntityMaps(...e){const t=Object.create(null);for(const r of e){if(!r)continue;for(const e of Object.keys(r)){const n=r[e];if(typeof n==="string"){t[e]=n}else if(n&&typeof n==="object"&&n.val!==undefined){const r=n.val;if(typeof r==="string"){t[e]=r}}}}return t}const LIMIT_TIER_EXTERNAL="external";const LIMIT_TIER_BASE="base";const LIMIT_TIER_ALL="all";function parseLimitTiers(e){if(!e||e===LIMIT_TIER_EXTERNAL)return new Set([LIMIT_TIER_EXTERNAL]);if(e===LIMIT_TIER_ALL)return new Set([LIMIT_TIER_ALL]);if(e===LIMIT_TIER_BASE)return new Set([LIMIT_TIER_BASE]);if(Array.isArray(e))return new Set(e);return new Set([LIMIT_TIER_EXTERNAL])}const NCR_LEVEL=Object.freeze({allow:0,leave:1,remove:2,throw:3});const XML10_ALLOWED_C0=new Set([9,10,13]);function parseNCRConfig(e){if(!e){return{xmlVersion:1,onLevel:NCR_LEVEL.allow,nullLevel:NCR_LEVEL.remove}}const t=e.xmlVersion===1.1?1.1:1;const r=NCR_LEVEL[e.onNCR]??NCR_LEVEL.allow;const n=NCR_LEVEL[e.nullNCR]??NCR_LEVEL.remove;const s=Math.max(n,NCR_LEVEL.remove);return{xmlVersion:t,onLevel:r,nullLevel:s}}class EntityDecoder{constructor(e={}){this._limit=e.limit||{};this._maxTotalExpansions=this._limit.maxTotalExpansions||0;this._maxExpandedLength=this._limit.maxExpandedLength||0;this._postCheck=typeof e.postCheck==="function"?e.postCheck:e=>e;this._limitTiers=parseLimitTiers(this._limit.applyLimitsTo??LIMIT_TIER_EXTERNAL);this._numericAllowed=e.numericAllowed??true;this._baseMap=mergeEntityMaps(XML,e.namedEntities||null);this._externalMap=Object.create(null);this._inputMap=Object.create(null);this._totalExpansions=0;this._expandedLength=0;this._removeSet=new Set(e.remove&&Array.isArray(e.remove)?e.remove:[]);this._leaveSet=new Set(e.leave&&Array.isArray(e.leave)?e.leave:[]);const t=parseNCRConfig(e.ncr);this._ncrXmlVersion=t.xmlVersion;this._ncrOnLevel=t.onLevel;this._ncrNullLevel=t.nullLevel;this._onExternalEntity=typeof e.onExternalEntity==="function"?e.onExternalEntity:null;this._onInputEntity=typeof e.onInputEntity==="function"?e.onInputEntity:null}_applyRegistrationHook(e,t,r,n){if(!e)return true;const s=e(t,r);if(s===ENTITY_ACTION.BLOCK)return false;if(s===ENTITY_ACTION.THROW){throw new Error(`[EntityDecoder] Registration of ${n} entity "&${t};" was rejected by hook`)}return true}setExternalEntities(e){if(e){for(const t of Object.keys(e)){EntityDecoder_validateEntityName(t)}}if(!this._onExternalEntity){this._externalMap=mergeEntityMaps(e);return}const t=mergeEntityMaps(e);const r=Object.create(null);for(const[e,n]of Object.entries(t)){if(this._applyRegistrationHook(this._onExternalEntity,e,n,"external")){r[e]=n}}this._externalMap=r}addExternalEntity(e,t){EntityDecoder_validateEntityName(e);if(typeof t==="string"&&t.indexOf("&")===-1){if(this._applyRegistrationHook(this._onExternalEntity,e,t,"external")){this._externalMap[e]=t}}}addInputEntities(e){this._totalExpansions=0;this._expandedLength=0;if(!this._onInputEntity){this._inputMap=mergeEntityMaps(e);return}const t=mergeEntityMaps(e);const r=Object.create(null);for(const[e,n]of Object.entries(t)){if(this._applyRegistrationHook(this._onInputEntity,e,n,"input")){r[e]=n}}this._inputMap=r}reset(){this._inputMap=Object.create(null);this._totalExpansions=0;this._expandedLength=0;return this}setXmlVersion(e){this._ncrXmlVersion=e===1.1?1.1:1}decode(e){if(typeof e!=="string"||e.length===0)return e;if(e.indexOf("&")===-1)return e;const t=e;const r=[];const n=e.length;let s=0;let i=0;const o=this._maxTotalExpansions>0;const a=this._maxExpandedLength>0;const c=o||a;while(i=n||e.charCodeAt(t)!==59){i++;continue}const l=e.slice(i+1,t);if(l.length===0){i++;continue}let u;let d;if(this._removeSet.has(l)){u="";if(d===undefined){d=LIMIT_TIER_EXTERNAL}}else if(this._leaveSet.has(l)){i++;continue}else if(l.charCodeAt(0)===35){const e=this._resolveNCR(l);if(e===undefined){i++;continue}u=e;d=LIMIT_TIER_BASE}else{const e=this._resolveName(l);u=e?.value;d=e?.tier}if(u===undefined){i++;continue}if(i>s)r.push(e.slice(s,i));r.push(u);s=t+1;i=s;if(c&&this._tierCounts(d)){if(o){this._totalExpansions++;if(this._totalExpansions>this._maxTotalExpansions){throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: `+`${this._totalExpansions} > ${this._maxTotalExpansions}`)}}if(a){const e=u.length-(l.length+2);if(e>0){this._expandedLength+=e;if(this._expandedLength>this._maxExpandedLength){throw new Error(`[EntityReplacer] Expanded content length limit exceeded: `+`${this._expandedLength} > ${this._maxExpandedLength}`)}}}}}if(s=55296&&e<=57343)return NCR_LEVEL.remove;if(this._ncrXmlVersion===1){if(e>=1&&e<=31&&!XML10_ALLOWED_C0.has(e))return NCR_LEVEL.remove}return-1}_applyNCRAction(e,t,r){switch(e){case NCR_LEVEL.allow:return String.fromCodePoint(r);case NCR_LEVEL.remove:return"";case NCR_LEVEL.leave:return undefined;case NCR_LEVEL.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference `+`&${t}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(e){const t=e.charCodeAt(1);let r;if(t===120||t===88){r=parseInt(e.slice(2),16)}else{r=parseInt(e.slice(1),10)}if(Number.isNaN(r)||r<0||r>1114111)return undefined;const n=this._classifyNCR(r);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