openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 65.8 kB
JavaScript
import{c as e}from"./fs-safe-copy.worker-error-coercion-AIKMMQJR.mjs";import{a as t,r as n}from"./fs-safe-copy.worker-fs-safe-filesystem-worker-BMcghtFh.mjs";import{B as r,b as i,c as a}from"./fs-safe-copy.worker-redact-BQxLxSX2.mjs";import{a as o,i as s,n as c,t as l}from"./fs-safe-copy.worker-store.shared-Bv7dKXsQ.mjs";import{_ as u,c as d,m as f}from"./fs-safe-copy.worker-number-coercion-1FVMw2ic.mjs";import{b as p}from"./fs-safe-copy.worker-diagnostic-events-CJsrCJVq.mjs";import{i as m}from"./fs-safe-copy.worker-record-coerce-BUlpHiHI.mjs";import"./fs-safe-copy.worker-src-DQ9uH8Sw.mjs";import{a as h,i as g,r as _}from"./fs-safe-copy.worker-src-DSFoKngP.mjs";import{n as v}from"./fs-safe-copy.worker-sleep-BA4lY26w.mjs";import{i as y}from"./fs-safe-copy.worker-worker-diagnostic-script-C6p7spUr.mjs";import{a as b,c as x,l as S,r as C,t as w}from"./fs-safe-copy.worker-subsystem-CSYDX9_J.mjs";import{n as T,r as E}from"./fs-safe-copy.worker-store-DrNx4Q-U.mjs";import{t as ee}from"./fs-safe-copy.worker-promise-like-3qqJObCs.mjs";import{t as D}from"./fs-safe-copy.worker-expect-Cp38ZrcJ.mjs";import{t as O}from"./fs-safe-copy.worker-errors-HcCRJmGG.mjs";import{t as k}from"./fs-safe-copy.worker-retry-BGpYCcSw.mjs";import{a as A,n as j,o as M,r as N,t as P}from"./fs-safe-copy.worker-http-response-body-timeout-BHyWNWPL.mjs";import{createRequire as te}from"node:module";import{readFileSync as ne}from"node:fs";import"node:fs/promises";import{MIMEType as F}from"node:util";import{AsyncLocalStorage as re}from"node:async_hooks";import{release as ie,version as I}from"node:os";import{EventEmitter as L}from"node:events";import{channel as ae}from"node:diagnostics_channel";import oe,*as se from"node:net";import{lookup as ce}from"node:dns";import le from"node:dns/promises";import{isTransientNetworkError as R}from"@openclaw/ai/diagnostics";var ue=Object.create,z=Object.defineProperty,B=Object.getOwnPropertyDescriptor,V=Object.getOwnPropertyNames,H=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=V(t),a=0,o=i.length,s;a<o;a++)s=i[a],!U.call(e,s)&&s!==n&&z(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=B(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:ue(H(e)),__copyProps(t||!e||!e.__esModule||!U.call(e,`default`)?z(n,`default`,{value:e,enumerable:!0}):n,e));async function consumeResponseBytes(e){let t=0;for(;;){let{done:n,value:r}=await e.read();if(n)return{size:t,truncated:!1};if(e.skipEmptyChunks!==!1&&!r?.length)continue;let i=e.maxBytes-t;if(t+=r.length,t>e.maxBytes||e.stopAtLimit&&t===e.maxBytes)return i>0&&e.onChunk(r.subarray(0,i)),await e.onLimit(t),{size:t,truncated:!0};e.onChunk(r)}}function decodeTextPrefix(e,t={}){return new TextDecoder(t.encoding).decode(e,t.truncated?{stream:!0}:void 0)}function monotonicNow(){return performance.now()}function isFormDataLike(e){return typeof e==`object`&&!!e&&typeof e.entries==`function`&&e[Symbol.toStringTag]===`FormData`}function readProxyEnvValue(e,t){let n=t[e];return u(typeof n==`string`?n:t[e.toUpperCase()])}function resolveEnvHttpProxyUrl(e,t=process.env){let n=readProxyEnvValue(`http_proxy`,t),r=readProxyEnvValue(`https_proxy`,t);return e===`https`?r??n:n}function hasEnvHttpProxyConfigured(e=`https`,t=process.env){return resolveEnvHttpProxyUrl(e,t)!==void 0}function shouldUseEnvHttpProxyForUrl(e,t=process.env){let n=URL.parse(e);return!n||n.protocol!==`http:`&&n.protocol!==`https:`?!1:hasEnvHttpProxyConfigured(n.protocol===`https:`?`https`:`http`,t)&&!matchesNoProxy(n,t)}function matchesNoProxy(e,t=process.env){let n=t.no_proxy??t.NO_PROXY??``;if(!n)return!1;let r=e instanceof URL?e:URL.parse(e);if(!r)return!1;let i=r.hostname.toLowerCase().replace(/^\[|\]$/g,``).replace(/^(.+)\.$/,`$1`);if(!i)return!1;if(n===`*`)return!0;let a=parseIpv4Address(i),o=r.port===``?r.protocol===`https:`?`443`:r.protocol===`http:`?`80`:``:r.port;for(let e of n.split(/[,\s]/)){let t=e.trim().toLowerCase();if(!t)continue;let n,r;if(t.startsWith(`[`)){let e=t.match(/^\[([^\]]+)\](?::(\d+))?$/);if(!e)continue;n=D(e[1],`m capture group 1`),r=e[2]}else{let e=t.indexOf(`:`),i=t.lastIndexOf(`:`);e>-1&&e===i&&/^\d+$/.test(t.slice(i+1))?(n=t.slice(0,i),r=t.slice(i+1)):n=t}if(r&&r!==o)continue;let s=n.replace(/^\*?\./,``).replace(/^(.+)\.$/,`$1`);if(s&&s!==`*`&&(matchesIpv4NoProxyPattern(a,s)||i===s||i.endsWith(`.`+s)))return!0}return!1}function parseIpv4Address(e){let t=e.split(`.`);if(t.length!==4)return;let n=0;for(let e of t){if(!/^\d{1,3}$/.test(e))return;let t=Number(e);if(t>255)return;n=n<<8|t}return n>>>0}function matchesIpv4NoProxyPattern(e,t){if(e===void 0)return!1;let n=t.match(/^(\d{1,3}(?:\.\d{1,3}){3})\/(\d{1,2})$/);if(n){let t=parseIpv4Address(D(n[1],`cidr match capture group 1`)),r=Number(n[2]);if(t===void 0||r>32)return!1;let i=r===0?0:4294967295<<32-r>>>0;return(e&i)===(t&i)}if(!t.includes(`*`))return!1;let r=t.split(`.`);if(r.length>4)return!1;for(let[t,n]of r.entries())if(n===`*`){if(t===r.length-1)return!0}else if(!/^\d{1,3}$/.test(n)||Number(n)!==(e>>>(3-t)*8&255))return!1;return r.length===4}function parseActiveManagedProxyLoopbackMode(e){if(e===`gateway-only`||e===`proxy`||e===`block`)return e}function readInheritedActiveManagedProxyLoopbackMode(){if(process.env.OPENCLAW_PROXY_ACTIVE===`1`)return parseActiveManagedProxyLoopbackMode(process.env.OPENCLAW_PROXY_LOOPBACK_MODE)??`gateway-only`}function getActiveManagedProxyLoopbackMode(){return readInheritedActiveManagedProxyLoopbackMode()}function resolveManagedProxyCaFileForUrl(e){if(e.proxyUrl&&URL.parse(e.proxyUrl)?.protocol===`https:`)return u(e.caFileOverride)??u(e.config?.tls?.caFile)}function loadManagedProxyTlsOptionsSync(e){if(e)try{return{ca:ne(e,`utf8`)}}catch(t){throw Error(`proxy CA file could not be read (${e}): ${O(t)}`,{cause:t})}}function normalizeProxyUrl(e){return e?URL.parse(e)?.href:void 0}function resolveManagedProxyUrl(e=process.env){if(e.OPENCLAW_PROXY_ACTIVE===`1`)return normalizeProxyUrl(resolveEnvHttpProxyUrl(`https`,e))}function resolveActiveManagedProxyTlsOptions(e){let t=e?.env??process.env,n=resolveManagedProxyUrl(t),r=normalizeProxyUrl(e?.proxyUrl??resolveEnvHttpProxyUrl(`https`,t));if(!n||r!==n)return;let i=resolveManagedProxyCaFileForUrl({proxyUrl:n,caFileOverride:t.OPENCLAW_PROXY_CA_FILE});try{return loadManagedProxyTlsOptionsSync(i)}catch{return}}function readProxyTlsRecord(e){if(e&&`proxyTls`in e)return m(e.proxyTls)?e.proxyTls:void 0}function readProxyUrlFromOptions(e){if(e){if(`uri`in e){let t=e.uri;return t instanceof URL?t.href:typeof t==`string`?t:void 0}if(`httpsProxy`in e||`httpProxy`in e){let t=Reflect.get(e,`httpsProxy`),n=Reflect.get(e,`httpProxy`);return typeof t==`string`?t:typeof n==`string`?n:void 0}}}function addActiveManagedProxyTlsOptions(e,t){let n=resolveActiveManagedProxyTlsOptions({proxyUrl:readProxyUrlFromOptions(e),env:t?.env});if(!n)return e;let r=readProxyTlsRecord(e);return{...e,proxyTls:{...n,...r}}}const de=/^([a-z][a-z0-9-]{1,20}):\s+(.*)$/i;function splitSubsystem(e){let t=e.match(de);if(!t)return null;let n=t.at(1),r=t.at(2);return n===void 0||r===void 0?null:{subsystem:n,rest:r}}function logWithSubsystem(e,t,n){let r=n===x?splitSubsystem(t):null;if(r){w(r.subsystem)[e](r.rest);return}let i=e===`error`?`error`:`log`,a=E[e](t);n===x&&C(i,a)||n[i](a),b()[e](t)}function logWarn(e,t=x){logWithSubsystem(`warn`,e,t)}function logDebug(e){b().debug(e),S()&&console.log(E.muted(e))}const W=/* @__PURE__ */ new WeakSet;function logUndiciDispatcherError(e){logDebug(`undici: internal dispatcher error: ${O(e)}`)}function observeDispatcherValue(e){if(!(typeof e!=`object`&&typeof e!=`function`||e===null)&&!W.has(e)){if(W.add(e),e instanceof L){L.prototype.on.call(e,`error`,logUndiciDispatcherError),L.prototype.on.call(e,`connect`,(e,t)=>{observeDispatcherValue(t)});for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&observeDispatcherValue(n.value)}}else if(Array.isArray(e)||e instanceof Set||e instanceof Map)for(let t of e instanceof Map?e.values():e)observeDispatcherValue(t)}}function withUndiciErrorDiagnostics(e){return observeDispatcherValue(e),e}function isWSL2Sync(){if(process.platform!==`linux`)return!1;try{let e=f(`${ie()} ${I()}`);return e.includes(`wsl2`)||e.includes(`microsoft-standard`)}catch{return!1}}function resolveUndiciAutoSelectFamily(){let e=se.getDefaultAutoSelectFamily();return e&&isWSL2Sync()?!1:e}function createUndiciAutoSelectFamilyConnectOptions(e){if(e!==void 0)return{autoSelectFamily:e,autoSelectFamilyAttemptTimeout:300}}function resolveUndiciAutoSelectFamilyConnectOptions(){return createUndiciAutoSelectFamilyConnectOptions(resolveUndiciAutoSelectFamily())}const fe=te(import.meta.url);let pe,G;function loadUndiciModule(e){let t=globalThis.__OPENCLAW_TEST_UNDICI_RUNTIME_DEPS__;return m(t)&&e.every(e=>typeof t[e]==`function`)?t:pe??=fe(`undici/index.js`)}function createHttp1ProxyClient(e,t){let n=m(t)?t.connect:void 0;return createUndiciPool(e,{...t,...typeof n==`function`?{connect:(e,t)=>{let{servername:r,...i}=e;return n(r&&oe.isIP(r.replace(/^\[|\]$/g,``))?i:e,t)}}:{}})}function buildProxyConnectOptions(e,t){let n={...resolveUndiciAutoSelectFamilyConnectOptions(),...typeof e.connect==`object`?e.connect:{}},r=d(t);return{autoSelectFamily:n.autoSelectFamily,autoSelectFamilyAttemptTimeout:n.autoSelectFamilyAttemptTimeout,family:`family`in n?n.family:void 0,keepAlive:n.keepAlive,keepAliveInitialDelay:n.keepAliveInitialDelay,timeout:e.connectTimeout,...e.proxyTls,...r===void 0?{}:{timeout:r},allowH2:!1}}function createUndiciClient(e,t){let{Client:n}=loadUndiciModule([`Client`]);return withUndiciErrorDiagnostics(new n(e,t))}function createUndiciPool(e,t){let{Pool:n}=loadUndiciModule([`Pool`]);return withUndiciErrorDiagnostics(new n(e,{...t,factory:createUndiciClient}))}function createUndiciOriginDispatcher(e,t){return t.connections===1?createUndiciClient(e,t):createUndiciPool(e,t)}function buildHttp1AgentOptions(e={},t){let n=d(t);return{factory:createUndiciOriginDispatcher,...e,allowH2:!1,connect:typeof e.connect==`function`?e.connect:{...resolveUndiciAutoSelectFamilyConnectOptions(),...e.connect,...n===void 0?{}:{timeout:n}},bodyTimeout:n??e.bodyTimeout??G,headersTimeout:n??e.headersTimeout??G}}function buildHttp1ProxyAgentOptions(e,t,n){let r=typeof e==`string`||e instanceof URL?{uri:e.toString()}:e,{clientFactory:i=createHttp1ProxyClient}=r,a=addActiveManagedProxyTlsOptions(r,{env:n});return{proxyTunnel:!0,...a,...buildHttp1AgentOptions(a,t),clientFactory:i}}function loadUndiciRuntimeDeps(){return loadUndiciModule([`Agent`,`EnvHttpProxyAgent`,`ProxyAgent`,`fetch`])}function createHttp1Agent(e,t){let{Agent:n}=loadUndiciRuntimeDeps();return withUndiciErrorDiagnostics(new n(buildHttp1AgentOptions(e,t)))}function isSocksProxy(e){return e!==void 0&&[`socks:`,`socks5:`].includes(URL.parse(e)?.protocol??``)}function createSocksProxyAgent(e,t){let{Agent:n,Socks5ProxyAgent:r,buildConnector:i,errors:a}=loadUndiciModule([`Agent`,`Socks5ProxyAgent`,`buildConnector`]);if(typeof e.clientFactory!=`function`)throw new a.InvalidArgumentError(`Proxy opts.clientFactory must be a function.`);if(e.auth&&e.token)throw new a.InvalidArgumentError(`opts.auth cannot be used in combination with opts.token`);let o=i(buildProxyConnectOptions(e,t));class SocksProxyAgent extends n{}let s=withUndiciErrorDiagnostics(new SocksProxyAgent({...e,factory:()=>withUndiciErrorDiagnostics(new r(e.uri,{...e,connect:o}))})),c={connections:e.connections,pipelining:e.pipelining,bodyTimeout:e.bodyTimeout,headersTimeout:e.headersTimeout};return s.compose(e=>(t,n)=>{let r=t.headers,i=Array.isArray(r)?r.filter((e,t)=>t%2==0):[];if(!Array.isArray(r))for(let e in r)i.push(e);if(i.some(e=>typeof e==`string`&&e.toLowerCase()===`proxy-authorization`))throw new a.InvalidArgumentError(`Proxy-Authorization should be sent in ProxyAgent constructor`);return e({...c,...t},n)})}function completeProxyLifecycle(t,n){if(n!==void 0&&typeof n!=`function`){let{errors:e}=loadUndiciModule([]);throw new e.InvalidArgumentError(`invalid callback`)}let r=t().then(()=>void 0);if(n)r.then(()=>n(null,null),t=>n(e(t,`Proxy shutdown failed`),null));else return r}function createHttp1EnvHttpProxyAgent(e,t,n){let{EnvHttpProxyAgent:r}=loadUndiciRuntimeDeps(),i=e?.httpProxy??process.env.http_proxy??process.env.HTTP_PROXY,a=(e?.httpsProxy??process.env.https_proxy??process.env.HTTPS_PROXY)||i,o=/* @__PURE__ */ new Map;for(let r of[i,a])r&&!o.has(r)&&o.set(r,createHttp1ProxyAgent({...e,uri:r},t,n));let s=withUndiciErrorDiagnostics(new r({...buildHttp1AgentOptions(e,t),httpProxy:``,httpsProxy:``,noProxy:`*`}));if(o.size===0)return s;let c=[s,...o.values()],isDestroyed=()=>c.every(e=>Reflect.get(e,`destroyed`)===!0),l;return new Proxy(s,{get(t,n,r){return n===`destroyed`?isDestroyed():n===`dispatch`?(n,r)=>{let s=n?.origin?URL.parse(String(n.origin)):null,c=s?.protocol===`https:`?a:i,l=c&&o.get(c),u=e?.noProxy===void 0?process.env:{no_proxy:e.noProxy};return l&&s&&!matchesNoProxy(s,u)?l.dispatch(n,r):t.dispatch(n,r)}:n===`close`?e=>completeProxyLifecycle(()=>isDestroyed()?t.close():l??=Promise.all(c.map(e=>e.close())).finally(()=>{l=void 0}),e):n===`destroy`?(e,t)=>completeProxyLifecycle(()=>Promise.all(c.map(t=>t.destroy(typeof e==`function`?null:e??null))),typeof e==`function`?e:t):Reflect.get(t,n,r)}})}function createHttp1ProxyAgent(e,t,n){let r=buildHttp1ProxyAgentOptions(e,t,n);if(isSocksProxy(r.uri))return createSocksProxyAgent(r,t);let{ProxyAgent:i}=loadUndiciRuntimeDeps();return withUndiciErrorDiagnostics(new i({...r,proxyTls:buildProxyConnectOptions(r,t)}))}function isMockedFetch(e){return typeof e==`function`&&typeof e.mock==`object`}async function fetchWithRuntimeDispatcher(e,t){return await fetchWithPreparedRuntimeDispatcher(loadUndiciRuntimeDeps(),e,t)}function fetchWithPreparedRuntimeDispatcher(e,t,n){let r=e.fetch,i=M(n),a=e.FormData;if(!n||!isFormDataLike(n.body)||typeof a!=`function`||n.body instanceof a)return r(t,i);let o=new a;for(let[e,t]of n.body.entries()){let n=t,r=typeof n.name==`string`&&n.name.trim()?n.name:void 0;r?o.append(e,t,r):o.append(e,t)}let s=new Headers(i?.headers);return s.delete(`content-length`),s.delete(`content-type`),r(t,{...i,headers:s,body:o})}async function fetchWithRuntimeDispatcherOrMockedGlobal(e,t){return isMockedFetch(globalThis.fetch)?await globalThis.fetch(e,t):await fetchWithRuntimeDispatcher(e,t)}function parseMediaContentLength(e){if(e===null)return null;let t=e.split(`,`).map(e=>e.replace(/^[\t ]+|[\t ]+$/g,``)),n=t[0]??``,r=Number(n);if(!/^\d+$/.test(n)||t.some(e=>e!==n)||!Number.isSafeInteger(r))throw Error(`invalid content-length header: ${e}`);return r}ae(`http.server.response.finish`);async function cancelUnreadResponseBody(e){e&&!e.bodyUsed&&e.body?.cancel().catch(()=>void 0)}async function readResponsePrefix(e,t,n,r){if(!Number.isFinite(t)||t<0)throw RangeError(`maxBytes must be a non-negative finite number: ${t}`);let i;try{i=typeof r?.timeoutMs==`function`?r.timeoutMs():r?.timeoutMs}catch(t){throw e.body?.cancel(t).catch(()=>void 0),t}let a=e.body,o=a&&typeof a.getReader==`function`?a.getReader():void 0;try{return await N({timeoutMs:i,onTimeout:r?.onTimeout,signal:r?.signal,cancel:async e=>await(o??a)?.cancel(e),read:async()=>{if(!o){let n=Buffer.from(await e.arrayBuffer()),r=n.length>t;return{materializeBuffer:()=>r?n.subarray(0,t):n,size:n.length,truncated:r}}let i=[],a=await j(o,r?.chunkTimeoutMs||void 0,r?.onIdleTimeout,e=>consumeResponseBytes({maxBytes:t,stopAtLimit:n,read:()=>(e?.(),o.read()),onChunk:e=>i.push(e),onLimit:()=>{o.cancel().catch(()=>void 0)}}));return{materializeBuffer:()=>Buffer.concat(i,Math.floor(Math.min(a.size,t))),...a}}})}finally{o?.releaseLock()}}async function readResponseTextPrefix(e,t,n){let r=await readResponsePrefix(e,t,!0,n);return{text:decodeTextPrefix(r.materializeBuffer(),{truncated:r.truncated}),size:r.size,truncated:r.truncated}}async function readResponseTextSnippet(e,t){let n=t?.maxBytes??8192,i=t?.maxChars??200,a=await readResponseTextPrefix(e,n,t),o=a.text.replace(/\s+/g,` `).trim();if(o)return o.length>i?`${r(o,i)}…`:a.truncated?`${o}…`:o}const K=2147483647;function resolveSafeTimeoutDelayMs(e,t){let n=t?.minMs??1,r=Math.min(K,Math.max(0,Number.isFinite(n)?Math.floor(n):1));return Math.min(K,Math.max(r,Number.isFinite(e)?Math.floor(e):r))}const me=w(`fetch-timeout`),he=/[?#]/;function sanitizeTimeoutLogUrl(e){let t=e?.trim();if(t)try{let e=new URL(t);e.username=``,e.password=``,e.search=``,e.hash=``;let n=i(e.toString());return n.length>500?`${r(n,500)}...`:n}catch{let e=t.split(he,1)[0]??``,n=i(e.replace(/[\r\n\u2028\u2029]+/g,` `).replace(/\p{Cc}+/gu,` `).replace(/\s+/g,` `).trim());return n?n.length>500?`${r(n,500)}...`:n:void 0}}function abortDueToTimeout(e,t,n,r,i,a,o=!0){if(a?.aborted??e.signal.aborted)return;let s=sanitizeTimeoutLogUrl(i),c=Math.max(0,monotonicNow()-n),l=Math.max(0,c-t),u=l>=Math.max(1e3,t*.5)?`timer delayed ${l}ms, likely event-loop starvation`:null,d=[`fetch timeout after ${t}ms`,`(elapsed ${c}ms)`,u,r?`operation=${r}`:null,s?`url=${s}`:null].filter(e=>!!e).join(` `);o&&me.warn(`fetch timeout reached; aborting operation`,{timeoutMs:t,elapsedMs:c,...u?{timerDelayMs:l,eventLoopDelayHint:u}:{},consoleMessage:d,...r?{operation:r}:{},...s?{url:s}:{}});let f=/* @__PURE__ */ Error(`request timed out`);f.name=`TimeoutError`,e.abort(f)}function buildTimeoutAbortSignal(e){let{timeoutMs:t,signal:n}=e;if(!t)return{signal:n,cleanup:()=>{},refresh:()=>{}};let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=resolveSafeTimeoutDelayMs(t),o=!0,s,scheduleTimeout=()=>{s=setTimeout(abortDueToTimeout,a,r,a,monotonicNow(),e.operation,e.url,i,e.logTimeout)};return scheduleTimeout(),{signal:i,refresh:()=>{o&&!i.aborted&&(clearTimeout(s),scheduleTimeout())},cleanup:()=>{o=!1,clearTimeout(s)}}}var q=/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((e,t,n)=>{(function(e){let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=/* @__PURE__ */ RegExp(`^0[0-7]+$`,`i`),a=/* @__PURE__ */ RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function expandIPv6(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>=t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(t[e].length>4?NaN:parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function matchCIDR(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function parseIntAuto(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function padPart(e,t){for(;e.length<t;)e=`0${e}`;return e}let l={};l.IPv4=(function(){function IPv4(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return IPv4.prototype.SpecialRanges={unspecified:[[new IPv4([0,0,0,0]),8]],broadcast:[[new IPv4([255,255,255,255]),32]],multicast:[[new IPv4([224,0,0,0]),4]],linkLocal:[[new IPv4([169,254,0,0]),16]],loopback:[[new IPv4([127,0,0,0]),8]],carrierGradeNat:[[new IPv4([100,64,0,0]),10]],private:[[new IPv4([10,0,0,0]),8],[new IPv4([172,16,0,0]),12],[new IPv4([192,168,0,0]),16]],reserved:[[new IPv4([192,0,0,0]),24],[new IPv4([192,0,2,0]),24],[new IPv4([192,88,99,0]),24],[new IPv4([198,18,0,0]),15],[new IPv4([198,51,100,0]),24],[new IPv4([203,0,113,0]),24],[new IPv4([240,0,0,0]),4]],as112:[[new IPv4([192,175,48,0]),24],[new IPv4([192,31,196,0]),24]],amt:[[new IPv4([192,52,193,0]),24]]},IPv4.prototype.kind=function(){return`ipv4`},IPv4.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return matchCIDR(this.octets,e.octets,8,t)},IPv4.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},IPv4.prototype.range=function(){return l.subnetMatch(this,this.SpecialRanges)},IPv4.prototype.toByteArray=function(){return this.octets.slice(0)},IPv4.prototype.toIPv4MappedAddress=function(){return l.IPv6.parse(`::ffff:${this.toString()}`)},IPv4.prototype.toNormalizedString=function(){return this.toString()},IPv4.prototype.toString=function(){return this.octets.join(`.`)},IPv4})(),l.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv4 CIDR format`,{cause:e})}},l.IPv4.isIPv4=function(e){return this.parser(e)!==null},l.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},l.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},l.IPv4.isValidFourPartDecimal=function(e){return!!(l.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},l.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!l.IPv4.isValidCIDR(e)||!t?!1:l.IPv4.isValidFourPartDecimal(t[1])},l.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv4 CIDR format`,{cause:e})}},l.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},l.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,"toString",{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},l.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(parseIntAuto(n));return r})();if(t=e.match(r.longValue)){if(i=parseIntAuto(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t=0;for(;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}return(t=e.match(r.twoOctet))?(function(){let e=t.slice(1,4),n=[];if(i=parseIntAuto(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(parseIntAuto(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})():(t=e.match(r.threeOctet))?(function(){let e=t.slice(1,5),n=[];if(i=parseIntAuto(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(parseIntAuto(e[0])),n.push(parseIntAuto(e[1])),n.push(i>>8&255),n.push(i&255),n})():null},l.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),Number.isNaN(e)||e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},l.IPv6=(function(){function IPv6(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return IPv6.prototype.SpecialRanges={unspecified:[new IPv6([0,0,0,0,0,0,0,0]),128],linkLocal:[new IPv6([65152,0,0,0,0,0,0,0]),10],multicast:[new IPv6([65280,0,0,0,0,0,0,0]),8],loopback:[new IPv6([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new IPv6([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new IPv6([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new IPv6([65216,0,0,0,0,0,0,0]),10],discard:[new IPv6([256,0,0,0,0,0,0,0]),64],rfc6145:[new IPv6([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new IPv6([100,65435,0,0,0,0,0,0]),96],[new IPv6([100,65435,1,0,0,0,0,0]),48]],"6to4":[new IPv6([8194,0,0,0,0,0,0,0]),16],teredo:[new IPv6([8193,0,0,0,0,0,0,0]),32],benchmarking:[new IPv6([8193,2,0,0,0,0,0,0]),48],amt:[new IPv6([8193,3,0,0,0,0,0,0]),32],as112v6:[[new IPv6([8193,4,274,0,0,0,0,0]),48],[new IPv6([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new IPv6([8193,16,0,0,0,0,0,0]),28],orchid2:[new IPv6([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new IPv6([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new IPv6([24320,0,0,0,0,0,0,0]),16],reserved:[[new IPv6([8193,0,0,0,0,0,0,0]),23],[new IPv6([8193,3512,0,0,0,0,0,0]),32],[new IPv6([16383,0,0,0,0,0,0,0]),20]]},IPv6.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},IPv6.prototype.kind=function(){return`ipv6`},IPv6.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return matchCIDR(this.parts,e.parts,16,t)},IPv6.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},IPv6.prototype.range=function(){return l.subnetMatch(this,this.SpecialRanges)},IPv6.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},IPv6.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(padPart(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},IPv6.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new l.IPv4([t>>8,t&255,n>>8,n&255])},IPv6.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},IPv6.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=``;this.zoneId&&(t=`%${this.zoneId}`);let n=this.toNormalizedString(),r=n.slice(0,n.length-t.length),i=0,a=-1,o=-1,s;for(;s=e.exec(r);){let e=(s[0].match(/0/g)||[]).length;e>o&&(o=e,i=s.index,a=s[0].length)}return a<0?r+t:`${r.substring(0,i)}::${r.substring(i+a)}${t}`},IPv6.prototype.toString=function(){return this.toRFC5952String()},IPv6})(),l.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format`,{cause:e})}},l.IPv6.isIPv6=function(e){return this.parser(e)!==null},l.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},l.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},l.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format`,{cause:e})}},l.IPv6.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},l.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,"toString",{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},l.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return expandIPv6(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=expandIPv6(t+o,6),t&&t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},l.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),Number.isNaN(e)||e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},l.fromByteArray=function(e){let t=e.length;if(t===4)return new l.IPv4(e);if(t===16)return new l.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},l.isValid=function(e){return l.IPv6.isValid(e)||l.IPv4.isValid(e)},l.isValidCIDR=function(e){return l.IPv6.isValidCIDR(e)||l.IPv4.isValidCIDR(e)},l.parse=function(e){if(l.IPv6.isValid(e))return l.IPv6.parse(e);if(l.IPv4.isValid(e))return l.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},l.parseCIDR=function(e){try{return l.IPv6.parseCIDR(e)}catch{try{return l.IPv4.parseCIDR(e)}catch(e){throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`,{cause:e})}}},l.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},l.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=l:e.ipaddr=l})(n)})))(),1);function expectIpv6Hextets(e){let[t,n,r,i,a,o,s,c]=e;if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0)throw Error(`expected IPv6 address to expose 8 hextets`);return[t,n,r,i,a,o,s,c]}const ge=/* @__PURE__ */ new Set([`unspecified`,`broadcast`,`multicast`,`linkLocal`,`loopback`,`carrierGradeNat`,`private`,`reserved`]),_e=/* @__PURE__ */ new Set([`unicast`,`ipv4Mapped`,`rfc6145`,`rfc6052`,`6to4`,`teredo`]),ve=[q.default.IPv4.parse(`198.18.0.0`),15],J=/* @__PURE__ */ new Set([`100.100.100.200`,`fd00:ec2::254`]);function isIpv4Address(e){return e.kind()===`ipv4`}function isIpv6Address(e){return e.kind()===`ipv6`}function normalizeIpv4MappedAddress(e){return isIpv6Address(e)&&e.isIPv4MappedAddress()?e.toIPv4Address():e}function normalizeIpParseInput(e){let t=u(e);if(t)return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function parseCanonicalIpAddress(e){let t=normalizeIpParseInput(e);if(t)return q.default.IPv4.isValidFourPartDecimal(t)||q.default.IPv6.isValid(t)?q.default.parse(t):void 0}function parseLooseIpAddress(e){let t=normalizeIpParseInput(e);if(t)return q.default.isValid(t)?q.default.parse(t):void 0}function isCanonicalDottedDecimalIPv4(e){let t=normalizeIpParseInput(e);return t!==void 0&&q.default.IPv4.isValidFourPartDecimal(t)}function isLegacyIpv4Literal(e){let t=normalizeIpParseInput(e);if(!t||t.includes(`:`)||isCanonicalDottedDecimalIPv4(t))return!1;let n=t.split(`.`);return n.length<=4&&n.every(e=>/^[0-9]+$/.test(e)||/^0x[0-9a-f]+$/i.test(e))}function isLoopbackIpAddress(e){let t=parseCanonicalIpAddress(e);return t?normalizeIpv4MappedAddress(t).range()===`loopback`:!1}function isLinkLocalIpAddress(e){let t=parseLooseIpAddress(e);if(!t)return!1;let n=normalizeIpv4MappedAddress(t);return isIpv4Address(n)?n.range()===`linkLocal`:extractEmbeddedIpv4FromIpv6(n)?.range()===`linkLocal`||n.range()===`linkLocal`}function isUnspecifiedIpAddress(e){let t=parseCanonicalIpAddress(e);return!t||t.range()===`loopback`?!1:(isIpv6Address(t)?extractEmbeddedIpv4FromIpv6(t)??t:t).range()===`unspecified`}function isCloudMetadataIpAddress(e){let t=parseLooseIpAddress(e);if(!t)return!1;let n=normalizeIpv4MappedAddress(t);if(isIpv6Address(n)){let e=extractEmbeddedIpv4FromIpv6(n);if(e&&J.has(e.toString()))return!0}return J.has(n.toString())}function isBlockedSpecialUseIpv6Address(e,t={}){let n=e.range();return isRfc8215Nat64LocalUseAddress(e)||isCloudMetadataIpAddress(e.toString())?!0:n===`uniqueLocal`&&t.allowUniqueLocalRange===!0?!1:!_e.has(n)}function isBlockedSpecialUseIpv4Address(e,t={}){let n=e.match(ve);return n&&t.allowRfc2544BenchmarkRange===!0?!1:ge.has(e.range())||n}function decodeIpv4FromHextets(e,t){let n=[e>>>8&255,e&255,t>>>8&255,t&255];return q.default.IPv4.parse(n.join(`.`))}function isRfc8215Nat64LocalUseAddress(e){let t=expectIpv6Hextets(e.parts);return t[0]===100&&t[1]===65435&&t[2]===1}function extractEmbeddedIpv4FromIpv6(e){let t=expectIpv6Hextets(e.parts);switch(e.range()){case`ipv4Mapped`:return e.toIPv4Address();case`rfc6145`:return decodeIpv4FromHextets(t[6],t[7]);case`rfc6052`:return isRfc8215Nat64LocalUseAddress(e)?void 0:decodeIpv4FromHextets(t[6],t[7]);case`6to4`:return decodeIpv4FromHextets(t[1],t[2]);case`teredo`:return decodeIpv4FromHextets(t[6]^65535,t[7]^65535)}let n=t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0,r=!(t[4]&64767)&&t[5]===24318;if(n||r)return decodeIpv4FromHextets(t[6],t[7])}function normalizeHostname(e){let t=f(e).replace(/\.+$/,``);return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}const Y=/* @__PURE__ */ new WeakSet;function withTrustedHostPodmanGatewayLinkLocalExemption(e){let t={...e};return Y.add(t),t}function hasTrustedHostPodmanGatewayLinkLocalExemption(e){return e!==void 0&&Y.has(e)}var SsrFBlockedError=class extends Error{constructor(e){super(e),this.name=`SsrFBlockedError`}};function normalizePolicyHostnames(e){return p(e?.map(e=>normalizeHostname(e)))}function parseHttpBaseUrl(e){let t=e.trim();if(t)try{let e=new URL(t);return e.protocol!==`http:`&&e.protocol!==`https:`?void 0:e}catch{return}}function normalizeSsrFPolicyOrigin(e){let t=parseHttpBaseUrl(e);if(t)return t.hostname=t.hostname.replace(/\.+$/,``),t.origin.toLowerCase()}function normalizeSsrFPolicyOrigins(e){return!e||e.length===0?[]:Array.from(new Set(e.map(e=>normalizeSsrFPolicyOrigin(e)).filter(e=>!!e))).toSorted()}const ye=/* @__PURE__ */ new Set([`localhost`,`localhost.localdomain`,`metadata.google.internal`]);function normalizeHostnameAllowlist(e){return normalizePolicyHostnames(e).filter(e=>e!==`*`&&e!==`*.`)}function isPrivateNetworkAllowedByPolicy(e){return e?.dangerouslyAllowPrivateNetwork===!0||e?.allowPrivateNetwork===!0}function shouldSkipPrivateNetworkChecks(e,t){return isPrivateNetworkAllowedByPolicy(t)||normalizePolicyHostnames(t?.allowedHostnames).includes(e)}function resolveSsrFPolicyForUrl(e,t){if(!t?.allowedOrigins?.length)return t;let n=normalizeSsrFPolicyOrigin(e.toString());return!n||!normalizeSsrFPolicyOrigins(t.allowedOrigins).includes(n)?t:{...t,allowedHostnames:Array.from(/* @__PURE__ */ new Set([...t.allowedHostnames??[],normalizeHostname(e.hostname)]))}}function isHostnameAllowedByPattern(e,t){if(t.startsWith(`*.`)){let n=t.slice(2);return!n||e===n?!1:e.endsWith(`.${n}`)}return e===t}function matchesHostnameAllowlist(e,t){return t.length===0||t.some(t=>isHostnameAllowedByPattern(e,t))}function looksLikeUnsupportedIpv4Literal(e){let t=e.split(`.`);return t.length>4?!1:t.some(e=>e.length===0)?!0:t.every(e=>/^[0-9]+$/.test(e)||/^0x/i.test(e))}function isPrivateIpAddress(e,t){let n=normalizeHostname(e);if(!n)return!1;let r={allowRfc2544BenchmarkRange:t?.allowRfc2544BenchmarkRange===!0},i={allowUniqueLocalRange:t?.allowIpv6UniqueLocalRange===!0},a=parseCanonicalIpAddress(n);if(a){if(isIpv4Address(a))return isBlockedSpecialUseIpv4Address(a,r);if(isBlockedSpecialUseIpv6Address(a,i))return!0;let e=extractEmbeddedIpv4FromIpv6(a);return e?isBlockedSpecialUseIpv4Address(e,r):!1}return n.includes(`:`)&&!parseLooseIpAddress(n)||!isCanonicalDottedDecimalIPv4(n)&&isLegacyIpv4Literal(n)?!0:looksLikeUnsupportedIpv4Literal(n)}function isBlockedHostnameNormalized(e){return ye.has(e)||e.endsWith(`.localhost`)||e.endsWith(`.local`)||e.endsWith(`.internal`)}function isBlockedHostnameOrIp(e,t){let n=normalizeHostname(e);return n?isBlockedHostnameNormalized(n)||isPrivateIpAddress(n,t):!1}const X=`Blocked: resolves to private/internal/special-use IP address`;function resolveHostnamePolicyChecks(e,t){let n=normalizeHostname(e);if(!n)throw Error(`Invalid hostname`);if(normalizeHostnameAllowlist(t?.blockedHostnames).some(e=>isHostnameAllowedByPattern(n,e)))throw new SsrFBlockedError(`Domain policy: Blocked hostname (configured blocklist): ${e}. Try a URL on a different domain or ask the operator to review blockedHostnames.`);let r=normalizeHostnameAllowlist(t?.hostnameAllowlist);if(!matchesHostnameAllowlist(n,r))throw new SsrFBlockedError(`Domain policy: Blocked hostname (not in allowlist): ${e}. Permitted hostname patterns: ${r.join(`, `)}. Try a URL on a permitted domain.`);let i=shouldSkipPrivateNetworkChecks(n,t);if(!i&&isBlockedHostnameOrIp(n,t))throw new SsrFBlockedError(`Blocked hostname or private/internal/special-use IP address`);return{normalized:n,skipPrivateNetworkChecks:i}}function assertAllowedResolvedAddressesOrThrow(e,t){for(let n of e)if(isBlockedHostnameOrIp(n.address,t))throw new SsrFBlockedError(X)}function isLoopbackIpAddressIncludingEmbeddedIpv4(e){if(isLoopbackIpAddress(e))return!0;let t=parseCanonicalIpAddress(e);return!t||isIpv4Address(t)?!1:extractEmbeddedIpv4FromIpv6(t)?.range()===`loopback`}function isBlockedTrustedResolvedIpv6Address(e){let t=parseCanonicalIpAddress(e);if(!t||isIpv4Address(t))return!1;let n=t.range();return n!==`unicast`&&n!==`rfc6052`?!1:isBlockedSpecialUseIpv6Address(t)}function isExplicitLoopbackHostname(e){return e===`localhost`||e===`localhost.localdomain`||e.endsWith(`.localhost`)||isLoopbackIpAddressIncludingEmbeddedIpv4(e)}const be=/* @__PURE__ */ new Set([`169.254.0.23`,`169.254.42.42`,`169.254.169.254`,`169.254.170.2`,`169.254.170.23`]);function assertAllowedTrustedHostnameResolvedAddressesOrThrow(e,t,n){let r=isExplicitLoopbackHostname(t),i=hasTrustedHostPodmanGatewayLinkLocalExemption(n);for(let t of e)if(isUnspecifiedIpAddress(t.address)||!r&&isLoopbackIpAddressIncludingEmbeddedIpv4(t.address)||isBlockedTrustedResolvedIpv6Address(t.address)||isLinkLocalIpAddress(t.address)&&(!i||!isCanonicalDottedDecimalIPv4(t.address)||be.has(t.address))||isCloudMetadataIpAddress(t.address))throw new SsrFBlockedError(X)}function normalizeLookupResults(e){return Array.isArray(e)?e:[e]}function createPinnedLookup(e){let t=normalizeHostname(e.hostname);if(e.addresses.length===0)throw Error(`Pinned lookup requires at least one address for ${e.hostname}`);let n=e.fallback??ce,r=e.addresses.map(e=>({address:e,family:e.includes(`:`)?6:4})),i=r.filter(e=>e.family===4),a=i.length>0?i:r,o=0;return((e,i,s)=>{let c=typeof i==`function`?i:s;if(!c)return;let l=normalizeHostname(e);if(!l||l!==t)return typeof i==`function`||i===void 0?n(e,c):n(e,i,c);let u=typeof i==`object`&&i?i:{},d=typeof i==`number`?i:typeof u.family==`number`?u.family:0,f=d===4||d===6?r.filter(e=>e.family===d):u.all?r:a,p=f.length>0?f:a;if(u.all){process.nextTick(()=>{c(null,p)});return}let m=D(p[o%p.length],`usable entry at index % usable.length`);o+=1,process.nextTick(()=>{c(null,m.address,m.family)})})}function dedupeAndPreferIpv4(e){let t=/* @__PURE__ */ new Set,n=[],r=[];for(let i of e)t.has(i.address)||(t.add(i.address),i.family===4?n.push(i.address):r.push(i.address));return[...n,...r]}async function resolvePinnedHostnameWithPolicy(e,t={}){t.signal?.throwIfAborted();let{normalized:n,skipPrivateNetworkChecks:r}=resolveHostnamePolicyChecks(e,t.policy),i=t.lookupFn??le.lookup,a=normalizeLookupResults(await _(()=>i(n,{all:!0}),t.signal,e=>e.reason));if(t.signal?.throwIfAborted(),a.length===0)throw Error(`Unable to resolve hostname: ${e}`);r?isPrivateNetworkAllowedByPolicy(t.policy)||assertAllowedTrustedHostnameResolvedAddressesOrThrow(a,n,t.policy):assertAllowedResolvedAddressesOrThrow(a,t.policy);let o=dedupeAndPreferIpv4(a);return{hostname:n,addresses:o,lookup:createPinnedLookup({hostname:n,addresses:o})}}function assertHostnameAllowedWithPolicy(e,t){return resolveHostnamePolicyChecks(e,t).normalized}function withPinnedLookup(e,t){return{...t,lookup:e}}function resolvePinnedDispatcherLookup(e,t,n){if(!t)return e.lookup;let r=normalizeHostname(t.hostname);if(!r||r!==e.hostname)throw Error(`Pinned dispatcher override hostname mismatch: expected ${e.hostname}, got ${t.hostname}`);let i=t.addresses.map(e=>({address:e,family:e.includes(`:`)?6:4}));return shouldSkipPrivateNetworkChecks(e.hostname,n)?isPrivateNetworkAllowedByPolicy(n)||assertAllowedTrustedHostnameResolvedAddressesOrThrow(i,e.hostname,n):assertAllowedResolvedAddressesOrThrow(i,n),createPinnedLookup({hostname:e.hostname,addresses:[...t.addresses],fallback:e.lookup})}function createPinnedDispatcher(e,t,n,r,i){let a=resolvePinnedDispatcherLookup(e,t?.pinnedHostname,n),o={bodyTimeout:i,headersTimeout:i};if(!t||t.mode===`direct`)return createHttp1Agent({...o,connect:withPinnedLookup(a,t?.connect)},r);if(t.mode===`env-proxy`)return createHttp1EnvHttpProxyAgent({...o,connect:withPinnedLookup(a,t.connect),...t.proxyTls?{proxyTls:{...t.proxyTls}}:{}},r);let s=t.proxyUrl.trim(),c=withPinnedLookup(a,t.proxyTls);return createHttp1ProxyAgent({...o,uri:s,requestTls:c},r)}function destroyDispatcher(e){try{e.destroy?.()}catch{}}async function waitForDispatcherClose(e){let t=e.close;if(typeof t!=`function`)destroyDispatcher(e);else try{await g(Promise.resolve(t.call(e)),100,()=>destroyDispatcher(e),{ref:!1})}catch(t){throw destroyDispatcher(e),t}}async function closeDispatcher(e){if(!e)return;let t=e;try{await waitForDispatcherClose(t)}catch{}}function parseHttpUrl(e){let t=URL.parse(e.trim());if(!(!t||t.protocol!==`http:`&&t.protocol!==`https:`))return t.hostname=t.hostname.replace(/\.+$/,``),t}function isLoopbackManagedProxyBypassHost(e){let t=normalizeHostname(e);return t===`localhost`||isLoopbackIpAddress(t)}function shouldResolveConfiguredLocalOriginManagedProxyBypass(e){if(e.managedProxyBypass?.kind!==`configured-local-origin`)return!1;let t=parseHttpUrl(e.managedProxyBypass.baseUrl);return!t||!isLoopbackManagedProxyBypassHost(t.hostname)?!1:parseHttpUrl(e.url.toString())?.origin.toLowerCase()===t.origin.toLowerCase()}function shouldUseConfiguredLocalOriginManagedProxyBypass(e){if(!shouldResolveConfiguredLocalOriginManagedProxyBypass(e))return!1;let t=getActiveManagedProxyLoopbackMode();if(t===`proxy`)return!1;if(t===`block`&&isLoopbackManagedProxyBypassHost(e.url.hostname))throw new SsrFBlockedError(`proxy: configured local provider loopback connections are blocked by proxy.loopbackMode`);return e.resolvedAddresses.length>0&&e.resolvedAddresses.every(e=>isLoopbackIpAddress(e))}function resolveConfiguredLocalOriginLinkLocalHopPolicy(e){let{policy:t,managedProxyBypass:n}=e;if(!t||n?.allowPodmanHostGatewayLinkLocal!==!0)return t;let r=parseHttpUrl(n.baseUrl);return r?.hostname!==`host.containers.internal`||parseHttpUrl(e.url.href)?.origin!==r.origin?t:withTrustedHostPodmanGatewayLinkLocalExemption(t)}const xe=new y(Symbol.for(`openclaw.guardedFetchRequestAuthority`));function captureGuardedFetchRequestAuthority(){let e=xe.getStore();return e?()=>{e.assertCurrent(),e.beforeRequest?.()}:void 0}const Z=new FinalizationRegistry(e=>{e.finalize().catch(()=>void 0)});function attachBodyAbort(e,t,n){let abort=()=>{let r=t.deref();if(!r)return;let i=e.reason??new DOMException(`This operation was aborted`,`AbortError`),a=n(i);r.error(i),a.catch(()=>void 0)};return e.aborted?abort():e.addEventListener(`abort`,abort,{once:!0}),()=>e.removeEventListener(`abort`,abort)}function wrapBodyStream(e,t){let n=e.body.getReader(),r=!1,i=!1,detachAbort=()=>{},a={},finalize=async(i=async()=>{await n.cancel().catch(()=>void 0)})=>{if(r)return;r=!0,detachAbort(),Z.unregister(a);let[o,s,c]=await Promise.allSettled([i(),(async()=>n.releaseLock())(),(async()=>await e.cleanup())()]);if(c.status===`rejected`&&t===`release`)throw c.reason;if(s.status===`rejected`)throw s.reason;if(o.status===`rejected`&&t===`cancellation`)throw o.reason},cancel=async e=>await finalize(async()=>await n.cancel(e)),o=new ReadableStream((()=>{let onError,onChunk;return{start(n){onError=async e=>{r||(t===`release`&&await finalize(),n.error(e),await finalize())},onChunk=t=>{try{if(t.done)return n.close(),finalize().catch(onError);e.refreshTimeout?.(),n.enqueue(t.value);return}catch(e){return onError(e)}}},pull(t){let a=e.signal;if(a&&!i&&(i=!0,detachAbort=attachBodyAbort(a,new WeakRef(t),cancel)),!r)return n.read().then(onChunk,onError)},cancel}})(),e.signal?{highWaterMark:0}:void 0);return Z.register(o,{finalize},a),o}function responseWithAbortSignal(e,t,n=()=>{}){return!e.body||!t?(n(),e):preserveResponseMetadata(e,new Response(wrapBodyStream({body:e.body,cleanup:n,signal:t},`cancellation`),{status:e.status,statusText:e.statusText,headers:e.headers}),e.headers)}function preserveResponseMetadata(e,t,n){return n&&Object.defineProperty(t,"headers",{value:n}),Object.defineProperties(t,{url:{value:e.url},redirected:{value:e.redirected},type:{value:e.type},clone:{configurable:!0,value:()=>preserveResponseMetadata(e,Response.prototype.clone.call(t),n),writable:!0}}),t}re.snapshot();const Se=/* @__PURE__ */ new Set([`accept`,`accept-encoding`,`accept-language`,`cache-control`,`content-language`,`content-type`,`if-match`,`if-modified-since`,`if-none-match`,`if-unmodified-since`,`pragma`,`range`,`user-agent`]);function retainSafeHeadersForCrossOriginRedirect$1(e){if(!e)return e;let t=new Headers(A(e)),n={};for(let[e,r]of t.entries())Se.has(e)&&(n[e]=r);return n}function restoreRedirectAuthorization(e){if(!e.authorization)return e.init;let t=new Headers(e.init?.headers);return t.set(`Authorization`,e.authorization),{...e.init,headers:t}}function dropBodyHeaders(e){if(!e)return e;let t=new Headers(A(e));return t.delete(`content-encoding`),t.delete(`content-language`),t.delete(`content-length`),t.delete(`content-location`),t.delete(`content-type`),t.delete(`transfer-encoding`),t}const Q={STRICT:`strict`,TRUSTED_ENV_PROXY:`trusted_env_proxy`,TRUSTED_EXPLICIT_PROXY:`trusted_explicit_proxy`};var GuardedFetchRedirectError=class extends Error{constructor(e){super(`Too many redirects (limit: ${e.maxRedirects})`),this.name=`GuardedFetchRedirectError`,this.status=e.status,this.maxRedirects=e.maxRedirects}};function getRedirectVisitKey(e,t){return`${t?.method?.toUpperCase()??`GET`} ${e}`}function isTruthyEnvValue(e){return e===`1`||e===`true`||e===`yes`||e===`on`}function withStrictGuardedFetchMode(e){return{...e,mode:Q.STRICT}}function withTrustedExplicitProxyGuardedFetchMode(e){return{...e,mode:Q.TRUSTED_EXPLICIT_PROXY}}function resolveGuardedFetchMode(e){return e.mode?e.mode:e.proxy===`env`&&e.dangerouslyAllowEnvProxyWithoutPinnedDns===!0?Q.TRUSTED_ENV_PROXY:Q.STRICT}function isManagedProxyActive(){return process.env.OPENCLAW_PROXY_ACTIVE===`1`}function assertExplicitProxySupportsPinnedDns(e,t,n){if(n!==!1&&t?.mode===`explicit-proxy`&&e.protocol!==`https:`)throw Error(`Explicit proxy SSRF pinning requires HTTPS targets; plain HTTP targets are not supported`)}function createPolicyDispatcherWithoutPinnedDns(e,t,n){if(!e&&n===void 0)return null;let r={bodyTimeout:n,headersTimeout:n};if(!e||e.mode===`direct`)return createHttp1Agent({...r,connect:e?.connect},t);if(e.mode===`env-proxy`)return createHttp1EnvHttpProxyAgent({...r,...e.connect?{connect:{...e.connect}}:{},...e.proxyTls?{proxyTls:{...e.proxyTls}}:{}},t);let i=e.proxyUrl.trim(),a=e.proxyTls;return createHttp1ProxyAgent({...r,uri:i,...a?{requestTls:{...a}}:{}},t)}async function assertExplicitProxyAllowed(e,t,n,r,i){if(!e||e.mode!==`explicit-proxy`)return;let a;try{a=new URL(e.proxyUrl)}catch{throw Error(`Invalid explicit proxy URL`)}let o=i&&[`socks:`,`socks5:`].includes(a.protocol);if(![`http:`,`https:`].includes(a.protocol)&&!o)throw Error(`Explicit proxy URL must use http or https`);let s=n||e.allowPrivateProxy===!0?{...n,hostnameAllowlist:void 0,...e.allowPrivateProxy===!0?{allowPrivateNetwork:!0}:{}}:void 0;await resolvePinnedHostnameWithPolicy(a.hostname,{lookupFn:t,policy:s,signal:r})}function isRedirectStatus(e){return e===301||e===302||e===303||e===307||e===308}function isAmbientGlobalFetch(e){return typeof e.fetchImpl==`function`&&typeof e.globalFetch==`function`&&e.fetchImpl===e.globalFetch}async function prepareGuardedFetchCapture(e,t){if(e.capture===!1||!isTruthyEnvValue(process.env.OPENCLAW_DEBUG_PROXY_ENABLED))return{fetchImpl:t};let{prepareHttpCaptureForTransport:n,resolveDebugProxyFetchTransport:r}=await import(`./fs-safe-copy.worker-runtime-CsMb3AHM.mjs`);return{fetchImpl:r(t),capture:n()}}function retainSafeHeadersForCrossOriginRedirect(e){return e?.headers?{...e,headers:retainSafeHeadersForCrossOriginRedirect$1(e.headers)}:e}function resolveRetainedAuthorizationForRedirect(e){let t=e.init;if(!t?.headers||!e.hostnameAllowlist?.length||e.nextUrl.protocol!==`https:`||!e.hostnameAllowlist.includes(`*`)&&!matchesHostnameAllowlist(e.nextUrl.hostname,e.hostnameAllowlist))return;let n=M(t);if(n?.headers)return new Headers(n.headers).get(`authorization`)??void 0}function rewriteRedirectInit(e){let{init:t,status:n}=e;if(!t)return t;let r=t.method?.toUpperCase()??`GET`,i=n===303?r!==`GET`&&r!==`HEAD`:(n===301||n===302)&&r===`POST`,a=e.crossOrigin&&!e.allowUnsafeReplay&&r!==`GET`&&r!==`HEAD`;return!i&&!a?t:{...t,...i?{method:`GET`}:{},body:void 0,headers:dropBodyHeaders(t.headers)}}async function fetchWithSsrFGuard(e){let{managedProxyBypass:t,...n}=e;return await fetchWithSsrFGuardInternal(n)}async function fetchWithSsrFGuardInternal(e){let t=captureGuardedFetchRequestAuthority(),n=o();if(e.allowCrossOriginUnsafeRedirectReplay===!0&&e.rejectCrossOriginUnsafeRedirectReplay===!0)throw TypeError(`Cross-origin unsafe redirect replay cannot be both allowed and rejected`);let r=globalThis.fetch,i=e.fetchImpl??r;if(!i)throw Error(`fetch is not available`);let a=isMockedFetch(i),s=e.fetchImpl!==void 0&&!isAmbientGlobalFetch({fetchImpl:e.fetchImpl,globalFetch:r})||a,c=await prepareGuardedFetchCapture(e,i),l=typeof e.maxRedirects==`number`&&Number.isFinite(e.maxRedirects)?Math.max(0,Math.floor(e.maxRedirects)):3,u=resolveGuardedFetchMode(e),{signal:d,cleanup:f,refresh:p}=buildTimeoutAbortSignal({timeoutMs:e.timeoutMs,signal:e.signal??e.init?.signal??void 0,operation:`fetchWithSsrFGuard`,url:e.url}),m=!1,finishRequest=async e=>{m||(m=!0,f(),await e?.())},h=e.url,g=M(e.init?{...e.init}:void 0),_=/* @__PURE__ */ new Set([getRedirectVisitKey(h,g)]),v=0;for(;;){let r;try{r=new URL(h)}catch{throw await finishRequest(),Error(`Invalid URL: must be http or https`)}if(![`http:`,`https:`].includes(r.protocol))throw await finishRequest(),Error(`Invalid URL: must be http or https`);if(e.requireHttps===!0&&r.protocol!==`https:`)throw await finishRequest(),Error(`URL must use https`);let i=null,o,f,m=new AbortController,releaseDispatcher=async()=>{m.abort(),await cancelUnreadResponseBody(f),await(o?o.release():closeDispatcher(i))},y=resolveConfiguredLocalOriginLinkLocalHopPolicy({url:r,policy:resolveSsrFPolicyForUrl(r,e.policy),managedProxyBypass:e.managedProxyBypass}),b=e.resolveDispatcherPolicy?.(r)??e.dispatcherPolicy,resolvePinnedHostname=async()=>await resolvePinnedHostnameWithPolicy(r.hostname,{lookupFn:e.lookupFn,policy:y,signal:d});try{let x=u===Q.TRUSTED_EXPLICIT_PROXY&&b?.mode===`explicit-proxy`;assertExplicitProxySupportsPinnedDns(r,b,!x&&e.pinDns),await assertExplicitProxyAllowed(b,e.lookupFn,e.policy,d,x);let S=u===Q.STRICT&&isManagedProxyActive(),C=S&&shouldResolveConfiguredLocalOriginManagedProxyBypass({url:r,managedProxyBypass:e.managedProxyBypass}),w=S&&(shouldUseEnvHttpProxyForUrl(r.toString())||C),T=(u===Q.TRUSTED_ENV_PROXY||e.useEnvProxyForEligibleUrls===!0&&!w)&&!b&&shouldUseEnvHttpProxyForUrl(r.toString()),E=a&&e.lookupFn===void 0&&!T&&!w&&!x&&e.pinDns!==!1,D=e.timeoutMs,O=e.streamTimeoutMs,k={bodyTimeout:O,headersTimeout:O};if((T||w||e.pinDns===!1)&&assertHostnameAllowedWithPolicy(r.hostname,y),T)i=createHttp1EnvHttpProxyAgent(k,D);else if(w){if(C){let t=await resolvePinnedHostname();i=shouldUseConfiguredLocalOriginManagedProxyBypass({url:r,managedProxyBypass:e.managedProxyBypass,resolvedAddresses:t.addresses})?createPinnedDispatcher(t,b,y,D,O):createHttp1EnvHttpProxyAgent({...k,noProxy:``,...b?.mode===`direct`&&b.connect?{requestTls:{...b.connect}}:{}},D)}else i=createHttp1EnvHttpProxyAgent(k,D)}else if(x)assertHostnameAllowedWithPolicy(r.hostname,y),i=createPolicyDispatcherWithoutPinnedDns(b,D,O);else if(E)assertHostnameAllowedWithPolicy(r.hostname,y);else if(e.pinDns===!1)await resolvePinnedHostname(),i=createPolicyDispatcherWithoutPinnedDns(b,D,O);else{let t=await resolvePinnedHostname();if(e.dispatcherPool&&u===Q.STRICT&&b===void 0){let n=resolveUndiciAutoSelectFamilyConnectOptions(),a=JSON.stringify({origin:r.origin,addresses:[...t.addresses].toSorted(),timeoutMs:D??null,streamTimeoutMs:D??O??G??null,familyConnect:n??null,policy:y??null,podmanGatewayLinkLocalExempt:hasTrustedHostPodmanGatewayLinkLocalExemption(y)});o=e.dispatcherPool.acquire({key:a,createDispatcher:()=>createPinnedDispatcher(t,n?{mode:`direct`,connect:n}:void 0,y,D,O)}),i=o?o.dispatcher:createPinnedDispatcher(t,void 0,y,D,O)}else i=createPinnedDispatcher(t,b,y,D,O)}let A={...g?{...g}:{},redirect:`manual`,...i?{dispatcher:i}:{},signal:d?AbortSignal.any([d,m.signal]):m.signal},j=g?.body??null;if(A.body instanceof Blob){let e=A.body,t=new Headers(A.headers);t.has(`content-length`)||t.set(`content-length`,String(e.size)),!t.has(`content-type`)&&e.type&&t.set(`content-type`,e.type),A.headers=t;let n=new Uint8Array(await e.arrayBuffer());A.body=n,j=c.capture?Buffer.from(n):j}let M=!!i&&!s,N={url:r.toString(),method:g?.method??`GET`,signal:process.versions.bun?A.signal??void 0:void 0,requestHeaders:g?.headers,requestBody:j,transport:`http`,flowId:e.capture===!1?void 0:e.capture?.flowId,meta:{captureOrigin:`guarded-fetch`,...e.auditContext?{auditContext:e.auditContext}:{},...e.capture===!1?{}:e.capture?.meta,...e.capture&&e.capture.sensitiveRequestHeaderNames?{sensitiveRequestHeaderNames:e.capture.sensitiveRequestHeaderNames}:{}}},P=!1;try{f=await n.initiate(()=>{let n=e.beforeRequest?.();if(ee(n))throw Promise.resolve(n).catch(()=>void 0),TypeError(`beforeRequest must be synchronous.`);return t?.(),P=!0,M?fetchWithRuntimeDispatcher(r.toString(),A):c.fetchImpl(r.toString(),A)})}catch(e){throw P&&c.capture?.({...N,error:e}),e}if(e.onResponse?.(f.status),c.capture?.({...N,response:f}),isRedirectStatus(f.status)){if(v+=1,v>l)throw new GuardedFetchRedirectError({status:f.status,maxRedirects:l});let t=f.headers.get(`location`);if(!t)throw Error(`Redirect missing location header (${f.status})`);let n=new URL(t,r),i=n.toString(),a=resolveRetainedAuthorizationForRedirect({init:g,nextUrl:n,hostnameAllowlist:e.retainAuthorizationRedirectHostnameAllowlist}),o=n.origin!==r.origin;if(o&&hasTrustedHostPodmanGatewayLinkLocalExemption(y))throw new SsrFBlockedError(`Blocked cross-origin redirect from configured Podman host gateway`);let s=rewriteRedirectInit({init:g,status:f.status,crossOrigin:!1,allowUnsafeReplay:!0});if(o){let t=s?.method?.toUpperCase()??`GET`,i=s?.body;if(e.rejectCrossOriginUnsafeRedirectReplay===!0&&t!==`GET`&&t!==`HEAD`&&i!=null)throw Error(`Refusing to follow cross-origin redirect for ${t} request body (${r.origin} -> ${n.origin})`)}g=rewriteRedirectInit({init:s,status:f.status,crossOrigin:o,allowUnsafeReplay:e.allowCrossOriginUnsafeRedirectReplay===!0}),o&&(g=retainSafeHeadersForCrossOriginRedirect(g),g=restoreRedirectAuthorization({init:g,authorization:a}));let c=getRedirectVisitKey(i,g);if(_.has(c))throw Error(`Redirect loop detected`);_.add(c),await releaseDispatcher(),h=i;continue}return{response:process.versions.bun&&!(f instanceof Response)?responseWithAbortSignal(f,A.signal??void 0):f,signal:d,finalUrl:h,release:async()=>finishRequest(releaseDispatcher),refreshTimeout:p,dispatcherReused:o?.reused}}catch(t){throw t instanceof SsrFBlockedError&&logWarn(`security: blocked URL fetch (${e.auditContext??`url-fetch`}) targetOrigin=${r.origin} reason=${t.message}`),await finishRequest(releaseDispatcher),t}}}async function withMediaReadScope(e,t){return!c()&&!e.assertCurrent?await t(e):await s(e.assertCurrent??(()=>{}),async()=>{let n=c(),r=e.beforeRequest;return await t({...e,beforeRequest:e.assertCurrent?()=>(n.assertCurrent(),r?.()):r,requestInit:{...e.requestInit,signal:n.signal}})},e.requestInit?.signal??void 0)}var MediaFetchError=class extends Error{constructor(e,t,n){super(t,n),this.code=e,this.status=n?.status,this.name=`MediaFetchError`}};function decodeRemoteFileNameComponent(e){try{return decodeURIComponent(e).replace(/[\\/]/g,`_`)}catch{return e}}function decodeExtendedRemoteFileName(e){let t=/^([^']*)'[^']*'(.*)$/u.exec(e);if(!t)return;let n=t[1]?.toLowerCase(),r=t[2]??``;try{if(n===`utf-8`)return decodeURIComponent(r).replace(/[\\/]/g,`_`);if(n===`iso-8859-1`)return/%(?![\da-f]{2})/iu.test(r)?void 0:r.replace(/%([\da-f]{2})/giu,(e,t)=>String.fromCharCode(Number.parseInt(t,16))).replace(/[\\/]/g,`_`)}catch{return}}function*parseContentDispositionParameters(e){let t=0,n=!1,r=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(r||n&&a===`\\`){r=!r;continue}if(a===`"`){n=!n;continue}if(i!==e.length&&(n||a!==`;`))continue;let o=e.slice(t,i).trim();t=i+1;let s=o.indexOf(`=`);s>0&&(yield{name:o.slice(0,s).trim().toLowerCase(),value:o.slice(s+1).trim().replace(/^"|"$/g,``)})}}function decodeQuotedRemoteFileName(e){let t=/^[a-z]:[\\/]/iu.test(e),n=e.startsWith(`\\\\`),r=e.includes(`/`)&&e.includes(`\\`),i=/\\[\p{L}\p{N}]/u.test(e)&&/^[^\\/:]+(?:\\[^\\]+)+$/u.test(e);if(!t&&!n&&!r&&!i)return e.replace(/\\(.)/gu,`$1`);let a=e.lastIndexOf(`/`);if(a>=0)return`${e.slice(0,a+1)}${e.slice(a+1).replace(/\\([^\p{L}\p{N}])/gu,`$1`)}`;let o=e.indexOf(`\\`);return!t&&!n&&o===e.lastIndexOf(`\\`)&&/\\[^\p{L}\p{N}]/u.test(e)?e.replace(/\\(.)/gu,`$1`):e.replace(/\\"/gu,`"`)}function parseContentDispositionFileName(e){if(!e)return;let n;for(let r of parseContentDispositionParameters(e)){if(r.name===`filename`){n??=t(decodeQuotedRemoteFileName(r.value))||void 0;continue}if(r.name!==`filename*`)continue;let e=t(decodeExtendedRemoteFileName(r.value)??``);if(e)return e}return n}function createMediaFetchFailure(e,t){return new MediaFetchError(`fetch_failed`,`Failed to fetch media from ${e}: ${O(t)}`,{cause:t})}async function fetchGuardedMediaResponse(e){let{url:t,fetchImpl:n,beforeRequest:r,requestInit:i,maxRedirects:o,requireHttps:s,timeoutMs:c,responseHeaderTimeoutMs:l=9e5,ssrfPolicy:u,lookupFn:d,dispatcherPolicy:f,dispatcherAttempts:p,shouldRetryFetchError:m,trustExplicitProxyDns:h}=e,g=a(t),_=p&&p.length>0?p:[{dispatcherPolicy:f,lookupFn:d}],v=buildTimeoutAbortSignal({timeoutMs:l,signal:i?.signal??void 0,operation:`media response headers`,url:t}),y=v.signal;try{let e,a=[];for(let[l,f]of _.entries())try{e=await fetchWithSsrFGuard((h&&f.dispatcherPolicy?.mode===`explicit-proxy`?withTrustedExplicitProxyGuardedFetchMode:withStrictGuardedFetchMode)({url:t,fetchImpl:n,...r?{beforeRequest:r}:{},init:i,maxRedirects:o,...s===void 0?{}:{requireHttps:s},...c===void 0?{}:{timeoutMs:c},...y?{signal:y}:{},policy:u,lookupFn:f.lookupFn??d,dispatcherPolicy:f.dispatcherPolicy}));break}catch(e){if(typeof m!=`function`||!m(e)||l===_.length-1)throw a.length>0?Object.assign(Error(`Primary fetch failed and fallback fetch also failed for ${g}`,{cause:e}),{primaryError:a[0],attemptErrors:[...a,e]}):e;a.push(e)}return{response:e.response,finalUrl:e.finalUrl,release:e.release,sourceUrl:g}}catch(e){throw createMediaFetchFailure(g,e)}finally{v.cleanup()}}async function assertMediaResponseOk(e){let{res:t,url:n,finalUrl:r,sourceUrl:i,readIdleTimeoutMs:o}=e;if(t.ok&&t.body)return;let s=t.statusText?` ${t.statusText}`:``,c=r===n?``:` (redirected to ${a(r)})`,l=`HTTP ${t.status}${s}`;if(t.ok)l+=`; empty response body`;else if(t.body){let e=await readResponseTextSnippet(t,{maxBytes:8192,chunkTimeoutMs:o}).catch(()=>void 0);e&&(l+=`; body: ${e}`)}throw new MediaFetchError(`http_error`,`Failed to fetch media from ${i}${c}: ${a(l)}`,{status:t.status})}function assertMediaContentLength(e){let t;try{t=parseMediaContentLength(e.res.headers.get(`content-length`))}catch(t){throw e.res.body?.cancel().catch(()=>void 0),new MediaFetchError(`http_error`,`Failed to fetch media from ${e.sourceUrl}: ${O(t)}`,{cause:t})}if(t!==null&&t>e.maxBytes)throw e.res.body?.cancel().catch(()=>void 0),new MediaFetchError(`max_bytes`,`Failed to fetch media from ${e.sourceUrl}: content length ${t} exceeds maxBytes ${e.maxBytes}`)}function resolveRemoteFileName(e){let n=parseContentDispositionFileName(e.res.headers.get(`content-disposition`))||(e.filePathHint?t(e.filePathHint):void 0);if(n)return n;try{let n=new URL(e.finalUrl);return decodeRemoteFileNameComponent(t(n.pathname))||void 0}catch{return}}function isGenericResponseContentType(e){let t=e?.split(`;`)[0]?.trim().toLowerCase();return!t||t===`application/octet-stream`||t===`binary/octet-stream`||t===`application/zip`}function resolveResponseContentType(e){if(!e.fallbackContentType)return e.headerContentType??void 0;if(isGenericResponseContentType(e.headerContentType))return e.fallbackContentType;let t=e.headerContentType?.split(`;`)[0]?.trim().toLowerCase(),n=e.fallbackContentType.split(`;`)[0]?.trim().toLowerCase();return t?.startsWith(`video/`)&&n?.startsWith(`audio/`)&&t.slice(6)===n.slice(6)?e.fallbackContentType:e.headerContentType??e.fallbackContentType}async function*responseBodyChunks(e,t){let n=c(),r=e.getReader(),i=!1;try{for(;;){n?.assertCurrent();let{done:e,value:a}=t?await P(r,t):await r.read();if(n?.assertCurrent(),e){i=!0;return}a?.byteLength&&(yield a)}}finally{i||r.cancel().catch(()=>void 0);try{r.releaseLock()}catch{}}}async function saveOkMediaResponse(e){assertMediaContentLength({res:e.res,sourceUrl:e.sourceUrl,maxBytes:e.maxBytes});let t=resolveRemoteFileName({res:e.res,finalUrl:e.finalUrl,filePathHint:e.filePathHint}),n=resolveResponseContentType({headerContentType:e.res.headers.get(`content-type`),fallbackContentType:e.fallbackContentType}),r=isGenericResponseContentType(n)?e.filePathHint??t:void 0;try{let i=D(e.res.body,`media response body`),a=await T(responseBodyChunks(i,e.readIdleTimeoutMs),n??void 0,e.subdir??`inbound`,e.maxBytes,e.originalFilename,r);if(n&&a.contentType)try{let e=new F(n).params.get(`charset`);if(e!==null){let t=new F(a.contentType);t.params.set(`charset`,e),a.contentType=t.toString()}}catch{}return{...a,...t?{fileName:t}:{}}}catch(t){throw t instanceof MediaFetchError?t:t instanceof l&&t.code===`too-large`?new MediaFetchError(`max_bytes`,`Failed to fetch media from ${e.sourceUrl}: payload exceeds maxBytes ${e.maxBytes}`,{cause:t}):createMediaFetchFailure(e.sourceUrl,t)}}function shouldRetryMediaFetch(e){return e instanceof MediaFetchError?e.code===`max_bytes`?!1:e.code===`http_error`?typeof e.status==`number`&&(e.status===408||e.status>=500):e.code===`fetch_failed`?v(e)||v(e.cause)?!1:R(e.cause??e):!1:R(e)}async function saveRemoteMedia(e){return await withMediaReadScope(e,e=>withGuardedMediaResponse(e,({response:t,finalUrl:n,sourceUrl:r})=>saveOkMediaResponse({...e,res:t,finalUrl:n,sourceUrl:r,maxBytes:e.maxBytes??104857600})))}async function withGuardedMediaResponse(e,t){let run=async()=>{let n=await fetchGuardedMediaResponse(e),{release:r}=n;try{return await assertMediaResponseOk({res:n.response,url:e.url,finalUrl:n.finalUrl,sourceUrl:n.sourceUrl,readIdleTimeoutMs:e.readIdleTimeoutMs}),await t(n)}finally{await r()}},n=e.retry;return n?await k(run,{label:`media:fetch`,...n,shouldRetry:(e,t)=>n.shouldRetry?n.shouldRetry(e,t):shouldRetryMediaFetch(e),sleep:n.sleep??(t=>h(t,e.requestInit?.signal??void 0).catch(t=>{throw createMediaFetchFailure(a(e.url),t)}))}):await run()}const $=3e4,fetchWithoutIgnoredBody=async(e,t)=>{let n=await fetchWithRuntimeDispatcherOrMockedGlobal(e,t);return n.ok?n:(n.body?.cancel().catch(()=>void 0),new Response(null,{status:n.status,statusText:n.statusText,headers:n.headers}))};async function saveRemoteMediaForStore(e){let{id:t,path:r,size:i,contentType:a}=await saveRemoteMedia({url:e.source,fetchImpl:fetchWithoutIgnoredBody,requestInit:{headers:e.headers,signal:e.abortSignal},filePathHint:e.source,originalFilename:`_${n(e.source)??``}`,maxBytes:e.maxBytes,maxRedirects:5,responseHeaderTimeoutMs:$,readIdleTimeoutMs:$,subdir:e.subdir});return{id:t,path:r,size:i,contentType:a}}export{saveRemoteMediaForStore};