@doubao-dev/cli 0.0.39 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk.js CHANGED
@@ -235,7 +235,7 @@ ${_(r)}\r
235
235
  line-height: var(--doubao-picker-view-item-line-height);
236
236
  font-weight: var(--doubao-picker-view-item-font-weight);
237
237
  color: var(--doubao-picker-view-item-selected-color);
238
- }`,iZ="widgets";r4.sep;let iJ=`base${r4.sep}manifest.json`,iV=`base${r4.sep}manifest.sign`,iH="mcp-privacy-login-card",iU="__doubao_apps__expired-widget",iY="bundle.keystore",iz={"@byted-lynx/react":"React","@lynx-js/react":"React","@lynx-js/react/internal":"ReactInternal","@lynx-js/react/jsx-dev-runtime":"ReactJSXDevRuntime","@lynx-js/react/jsx-runtime":"ReactJSXRuntime","@lynx-js/react/lepus/jsx-dev-runtime":"ReactJSXLepusDevRuntime","@lynx-js/react/lepus/jsx-runtime":"ReactJSXLepusRuntime","@lynx-js/react/experimental/lazy/import":"ReactLazyImport","@lynx-js/react/legacy-react-runtime":"ReactLegacyRuntime","@lynx-js/react/runtime-components":"ReactComponents","@lynx-js/react/worklet-runtime/bindings":"ReactWorkletRuntime","@lynx-js/react/debug":"ReactDebug",preact:"Preact",react:"React"},iW="client-tool",i0=x=>x===iH||x===iU,i1="app.config",i2=[".js",".ts",".mjs"],i3="com.larus.nova";class i6{}function i4(x,e=3e3){return O(x,{timeout:e}).catch(()=>({stdout:"",stderr:""}))}async function i5(x,e){return O(`adb -s ${x} ${e}`,{timeout:3e3})}async function i7(x){let e=(await i4(`adb -s ${x} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return e?.[1]}async function i8(x,e){let t=(await i5(x,`shell pidof ${e}`).catch(()=>({stdout:""}))).stdout.trim();return t?t.split(/\s+/)[0]:void 0}async function i9(x){let e=await i7(x);return(e===i3||"com.flow.aisdk.example"===e)&&(await i4(`adb -s ${x} shell am force-stop ${e}`),await i4(`adb -s ${x} shell monkey -p ${e} -c android.intent.category.LAUNCHER 1`),!0)}async function ox(){return(await i4("adb devices")).stdout.split("\n").slice(1).map(x=>x.split(" ")[0].trim()).filter(Boolean)}async function oe(){let x=await ox(),e=process.env.ANDROID_SERIAL;if(e){if(!x.includes(e))throw Error(`Android device ${e} is not connected`);return e}if(x.length>1){let{device:e}=await H.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:e=>x.filter(x=>x.toLowerCase().includes(e?.toLowerCase()??""))}]);return e}return x[0]}class ot extends i6{deviceId;options;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(x,e={}){if(super(),this.deviceId=x,this.options=e,e.skipForegroundAppWatch)return;let t=setInterval(()=>{this.watchAppProcess().catch(x=>{console.warn("Failed to refresh the Android host app:",x)})},500);process.once("exit",()=>clearInterval(t))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let x=await i8(this.deviceId,i3);void 0!==this.lastAppProcessId&&void 0!==x&&this.lastAppProcessId!==x&&await this.reloadOnAppRestart(x),void 0!==x&&(this.lastAppProcessId=x)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(x){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(x=>setTimeout(x,5e3)),await i8(this.deviceId,i3)!==x)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(x){this.latestLoadParams=x;let{appId:e,isSigned:t}=x,r=process.env.DEV_SERVER_HOST??this.options.appletHost??x.appletUrl,a=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${e} --es appletHost ${r} --es appletType 1 --es isSigned ${t}`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${a}`)),await i5(this.deviceId,a)}async openPage(x){let{appId:e,pageId:t,pageData:r,pageSettings:a,mode:n}=x,_=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${e} --es appletPageName ${t} --es appletPageData '${r}' --es appletPageSettings '${a}' --es mode '${n}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${_}`)),await i5(this.deviceId,_)}async openPageUrl(x){let{appId:e,url:t}=x,r=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${e} --es appletPageUrl '${t}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${r}`)),await i5(this.deviceId,r)}async pushWidget(x){let{appId:e,widgetId:t,widgetData:r,botId:a}=x,n=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${e} --es widgetName ${t} --es widgetData '${r}' --es botId ${a||process.env.DEBUG_BOT_ID}`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${n}`)),await i5(this.deviceId,n)}async callTool(x){let{appId:e,toolId:t,toolData:r}=x,a=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${e} --es toolName '${t}' --es toolData '${r}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${a}`)),await i5(this.deviceId,a)}}class or extends i6{async load(x){}async openPage(x){}async openPageUrl(x){}async pushWidget(x){}async callTool(x){}}K.child("cli");let oa=K.child("config"),on=K.child("security"),o_=K.child("build"),oA=K.child("deploy"),os=K.child("dev-server");class oi{options;currentUrl=null;debugDriver=null;appId=null;constructor(x){this.options=x}async start(x,e,t){if(null!==this.currentUrl){this.currentUrl=x,this.debugDriver?.getAllAppClients().forEach(x=>this.onConnect(x,t));return}this.currentUrl=x,this.appId=e;let{getDebugDriver:r,toolkitExecutor:a}=await import("./@byted-hdt/cli.js").then(I.bind(I,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_@types+express@5.0.6_encoding@0.1.13/node_modules/@byted-hdt/cli/dist/es/index.js"));await a({runType:"rspeedy",openWebview:this.options.devtool});let n=r();this.debugDriver=n,n.getAllAppClients().forEach(x=>this.onConnect(x,t)),n.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(x){this.debugDriver?.getAllAppClients().forEach(e=>{try{e.sendCustomizedMessage(x.method,x.params,-1,"CDP")}catch(x){os.error("向 HDT 客户端发送消息失败",{error:x})}})}onConnect=(x,e)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:e}})}}class oo extends i6{server;constructor(){super(),this.server=new oi({devtool:!0,open:!0})}async load(x){let{appletUrl:e,appId:t,isSigned:r}=x;this.server.start(e,t,r)}async openPage(x){let{appId:e,pageId:t,pageData:r,pageSettings:a,mode:n}=x;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:e,appletPageName:t,appletPageData:r,appletPageSettings:a,mode:n}})}async openPageUrl(x){let{appId:e,url:t}=x;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:e,url:t}})}async pushWidget(x){let{appId:e,widgetId:t,widgetData:r,botId:a}=x;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:e,widgetName:t,widgetData:r,botId:a||process.env.DEBUG_BOT_ID}})}async callTool(x){let{appId:e,toolId:t,toolData:r}=x;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:e,toolName:t,toolData:r}})}}async function ol(e={}){if(e.debugDriver&&"object"==typeof e.debugDriver)return e.debugDriver;if(!x){let t=e.debugDriver??xx.Adb;if(!xr(t))throw Error(`无效的调试驱动 "${t}",可选值:${xe.join(", ")}。`);switch(t){case xx.Hdt:x=new oo;break;case xx.DevTools:x=new or;break;case xx.Adb:{let t=e.deviceId??await oe();t&&(x=new ot(t,{skipForegroundAppWatch:e.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${t}",可选值:${xe.join(", ")}。`)}}return x}let oc=/\{\{\s*([^{}\s]+)\s*\}\}/g;function ov(x){return!!x&&"object"==typeof x&&!Array.isArray(x)}function od(x,e){if(void 0!==x&&"string"!=typeof x)throw Error(`字段 ${e} 必须是字符串`)}function of(x){return Object.entries(x.variables||{})}function ob(x){return"string"==typeof x?x:JSON.stringify(x)}function ou(x,e={}){let t={...x.input||{},...function(x,e={}){let t={};for(let[r,a]of of(x))Object.prototype.hasOwnProperty.call(e,r)?t[r]=e[r]:null!==a&&(t[r]=a);return{...t,...e}}(x,e)};if("page"===x.type){let e=function(x,e){var t;let r=new Set(Array.from(x.url.matchAll(oc),x=>x[1])),a=(t=x.url,t.replace(oc,(x,t)=>{if(!Object.prototype.hasOwnProperty.call(e,t))return x;let r=ob(e[t]);return void 0===r?x:encodeURIComponent(r)})),n=a.indexOf("#"),_=n<0?a:a.slice(0,n),A=n<0?"":a.slice(n),s=_.indexOf("?"),i=new Set(new URLSearchParams(s<0?"":_.slice(s+1)).keys()),o=new URLSearchParams;for(let[x,t]of Object.entries(e)){if(r.has(x)||i.has(x))continue;let e=ob(t);void 0!==e&&o.set(x,e)}let l=o.toString();if(!l)return a;let c=s<0?"?":_.endsWith("?")||_.endsWith("&")?"":"&";return`${_}${c}${l}${A}`}(x,t);return{type:"page",unresolvedVariables:function(x){let e=new Set;for(let t of x.matchAll(oc))e.add(t[1]);return Array.from(e)}(e),url:e}}return"widget"===x.type?{type:"widget",id:x.id,resolvedInput:t,botId:x.botId}:{type:"tool",id:x.id,resolvedInput:t}}function op(x){return x.replaceAll("\\","/").replace(/^src\//,"").replace(/\.(?:bundle|tsx?|jsx?)$/,"")}(rN=rM||(rM={})).REACT_LYNX="lynx",rN.LYNX="lynx";let om={REACT_LYNX:rM.REACT_LYNX,LYNX:rM.LYNX};(rB=rZ||(rZ={}))[rB.INBOX=0]="INBOX",rB[rB.FULL_BOX=3]="FULL_BOX",rB[rB.CUSTOM_BOX=4]="CUSTOM_BOX",(rF=rJ||(rJ={}))[rF.NORMAL=0]="NORMAL",rF[rF.FLOAT=1]="FLOAT",rF[rF.NONE=2]="NONE";let oh={NONE:rJ.NONE,NORMAL:rJ.NORMAL,FLOAT:rJ.FLOAT},oE={INBOX:rZ.INBOX,FULL_BOX:rZ.FULL_BOX,CUSTOM_BOX:rZ.CUSTOM_BOX},oj={definePrivacyLoginWidget:{id:"mcp-privacy-login-card",name:"应用插件同意登录和隐私协议卡片",description:"展示应用插件同意登录和隐私协议的卡片组件"},defineLoginPage:{id:"mcp-login-page",name:"应用插件登录页面",path:"/pages/mcp-login-page/index",description:"展示应用插件登录页面"}};function og(x,e={}){let t=String(x??"").trim();if(!t)return;let r=function(x,{addProtocolToBareHost:e=!1,allowRootRelative:t=!1,defaultProtocol:r="http"}={}){var a;if(/^https?:\/\//i.test(x))return x;if(x.startsWith("//"))return`${oy(r,x.slice(2))}:${x}`;if(t&&x.startsWith("/"))return x;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(x)||e&&(a=x,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(a))?`${oy(r,x)}://${x}`:x}(t,e);try{let x=e.baseUrl?new URL(r,e.baseUrl):new URL(r);if("http:"!==x.protocol&&"https:"!==x.protocol)return;return x.toString()}catch{return}}function oy(x,e){return"function"==typeof x?x(e):x}function oS(x){return!!x&&"object"==typeof x&&!Array.isArray(x)}let oI="developer.doubao.com",oN=`https://${oI}`;async function oB(x){let e=(0,r4.join)(x,"debug-scene");try{return(await (0,aa.readdir)(e,{withFileTypes:!0})).filter(x=>x.isFile()&&x.name.endsWith(".json")).map(x=>({name:x.name.slice(0,-5),path:(0,r4.join)(e,x.name)}))}catch{return[]}}async function oF(x){try{var e=JSON.parse(await (0,aa.readFile)(x,"utf8"));if(!ov(e))throw Error("Scene 内容必须是 JSON 对象");if("page"!==e.type&&"widget"!==e.type&&"tool"!==e.type)throw Error("字段 type 必须是 page、widget 或 tool");if(od(e.id,"id"),od(e.url,"url"),od(e.botId,"botId"),"page"===e.type){if(!e.url?.trim())throw Error("Page Scene 必须配置 url");if(void 0!==e.id)throw Error("Page Scene 不支持 id,请使用 url")}else if(!e.id?.trim())throw Error(`${"widget"===e.type?"Widget":"Tool"} Scene 必须配置 id`);if(void 0!==e.input&&!ov(e.input))throw Error("字段 input 必须是 JSON 对象");if(void 0!==e.variables){if(!ov(e.variables))throw Error("字段 variables 必须是 JSON 对象");for(let[x,t]of Object.entries(e.variables))if(null!==t&&"string"!=typeof t)throw Error(`变量 ${x} 的默认值必须是字符串或 null`)}if(void 0!==e.settings&&"string"!=typeof e.settings&&!ov(e.settings))throw Error("字段 settings 必须是字符串或 JSON 对象");return e}catch(e){return Z()&&console.warn(`[DoubaoApps] 加载调试场景 "${x}" 失败:${e instanceof Error?e.message:String(e)}`),null}}async function ow(x,e){let{matchedScene:t,appId:r,driver:a,variables:n}=x,_=e??await oF(t.path);if(!_)return;let A=ou(_,n);if("page"===A.type){var s,i;s=t.name,0!==(i=A.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${s}" 存在未解析的变量占位符:${i.map(x=>`{{${x}}}`).join(", ")}`),await a.openPageUrl({appId:r,url:A.url})}else if("widget"===A.type){let x=JSON.stringify(A.resolvedInput),e={appId:r,widgetId:A.id,widgetData:x,botId:A.botId};await a.pushWidget(e)}else{let x=JSON.stringify(A.resolvedInput),e={appId:r,toolId:A.id,toolData:x};await a.callTool(e)}}let oC="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function oP(x){if("string"==typeof x){let e=x.length>0?x:oC;return{"1x":e,"2x":e,"3x":e}}return{"1x":x?.["1x"]||oC,"2x":x?.["2x"]||oC,"3x":x?.["3x"]||oC}}function ok(x){let e=Object.keys(x);return e.sort(),e.reduce((e,t)=>(e[t]=x[t],e),{})}class oD{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class oL extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(x,e,t){let r=this._metadata;return{id:r.id,name:r.name,path:r.path,description:r.description,keywords:r.keywords,digest:e,prop:r.prop,entry:x,renderType:t,title:r.title,chat:r.chat}}}class oq extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(x,e,t,r=[]){let a=this._metadata;return{widgetId:a.id,name:a.name,description:a.description,keywords:a.keywords,digest:e,prop:a.prop,entry:x,renderType:t,border:a.border,appSettings:r,boxType:oq.BOX_TYPE_MAP[a.boxType??"inbox"]??oE.INBOX,titleType:a.titleType?oq.TITLE_TYPE_MAP[a.titleType]:void 0}}}oq.BOX_TYPE_MAP={inbox:oE.INBOX,full_box:oE.FULL_BOX,custom_box:oE.CUSTOM_BOX},oq.TITLE_TYPE_MAP={none:2,normal:0,float:1};class oT extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(){let x=this._metadata;return{id:x.id,name:x.name,description:x.description,timeout:x.timeout}}}class oR extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest({toolsMetadata:x,hashCode:e,appRuntimeEntry:t,appRuntimeType:r}){return{name:this._metadata.name,description:this._metadata.description,appletId:this._metadata.appId,appletEntry:"index",pages:[],darkMode:this._metadata.darkMode,chat:this._metadata.chat,keywords:this._metadata.keywords,icons:oP(this._metadata.icons),digest:e,prop:"",tools:Object.values(x).map(x=>x.toManifest()),appRuntimeEntry:t,appRuntimeType:r}}}class o${constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(x){this.metadata.app.metadata?this.metadata.app.assign(x):this.metadata.app=new oR(x)}addToolMeta(x,e){this.metadata.tools[x]?this.metadata.tools[x].assign(e):this.metadata.tools[x]=new oT(e)}addPageMeta(x,e){this.metadata.pages[x]?this.metadata.pages[x].assign(e):this.metadata.pages[x]=new oL(e)}addWidgetMeta(x,e){this.metadata.widgets[x]?this.metadata.widgets[x].assign(e):this.metadata.widgets[x]=new oq(e)}getData(){let{tools:x,pages:e,widgets:t,app:r}=this.metadata;return{app:r.metadata??{},tools:ok(Object.fromEntries(Object.keys(x).map(e=>[e,x[e].metadata]))),pages:ok(Object.fromEntries(Object.keys(e).map(x=>[x,e[x].metadata]))),widgets:ok(Object.fromEntries(Object.keys(t).map(x=>[x,t[x].metadata])))}}getInstance(){let{tools:x,pages:e,widgets:t,app:r}=this.metadata;return{app:r,tools:ok(x),pages:ok(e),widgets:ok(t)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}(rw=rV||(rV={})).DEV="dev",rw.BUILD="build",rw.PERF="perf",rw.DEPLOY="deploy",rw.ANALYZE="analyze";let oG={DEV:rV.DEV,BUILD:rV.BUILD,PERF:rV.PERF,DEPLOY:rV.DEPLOY,ANALYZE:rV.ANALYZE};var oO=Array.isArray,oX="object"==typeof globalThis&&globalThis&&globalThis.Object===Object&&globalThis,oK="object"==typeof self&&self&&self.Object===Object&&self,oQ=oX||oK||Function("return this")(),oM=oQ.Symbol,oZ=Object.prototype,oJ=oZ.hasOwnProperty,oV=oZ.toString,oH=oM?oM.toStringTag:void 0;let oU=function(x){var e=oJ.call(x,oH),t=x[oH];try{x[oH]=void 0;var r=!0}catch(x){}var a=oV.call(x);return r&&(e?x[oH]=t:delete x[oH]),a};var oY=Object.prototype.toString,oz=oM?oM.toStringTag:void 0;let oW=function(x){return null==x?void 0===x?"[object Undefined]":"[object Null]":oz&&oz in Object(x)?oU(x):oY.call(x)},o0=function(x){return null!=x&&"object"==typeof x},o1=function(x){return"symbol"==typeof x||o0(x)&&"[object Symbol]"==oW(x)};var o2=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o3=/^\w*$/;let o6=function(x,e){if(oO(x))return!1;var t=typeof x;return!!("number"==t||"symbol"==t||"boolean"==t||null==x||o1(x))||o3.test(x)||!o2.test(x)||null!=e&&x in Object(e)},o4=function(x){var e=typeof x;return null!=x&&("object"==e||"function"==e)},o5=function(x){if(!o4(x))return!1;var e=oW(x);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e};var o7=oQ["__core-js_shared__"],o8=(rC=/[^.]+$/.exec(o7&&o7.keys&&o7.keys.IE_PROTO||""))?"Symbol(src)_1."+rC:"",o9=Function.prototype.toString;let lx=function(x){if(null!=x){try{return o9.call(x)}catch(x){}try{return x+""}catch(x){}}return""};var le=/^\[object .+?Constructor\]$/,lt=Object.prototype,lr=Function.prototype.toString,la=lt.hasOwnProperty,ln=RegExp("^"+lr.call(la).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");let l_=function(x){return!!o4(x)&&(!o8||!(o8 in x))&&(o5(x)?ln:le).test(lx(x))},lA=function(x,e){var t=null==x?void 0:x[e];return l_(t)?t:void 0};var ls=lA(Object,"create"),li=Object.prototype.hasOwnProperty,lo=Object.prototype.hasOwnProperty;function ll(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}ll.prototype.clear=function(){this.__data__=ls?ls(null):{},this.size=0},ll.prototype.delete=function(x){var e=this.has(x)&&delete this.__data__[x];return this.size-=!!e,e},ll.prototype.get=function(x){var e=this.__data__;if(ls){var t=e[x];return"__lodash_hash_undefined__"===t?void 0:t}return li.call(e,x)?e[x]:void 0},ll.prototype.has=function(x){var e=this.__data__;return ls?void 0!==e[x]:lo.call(e,x)},ll.prototype.set=function(x,e){var t=this.__data__;return this.size+=+!this.has(x),t[x]=ls&&void 0===e?"__lodash_hash_undefined__":e,this};let lc=function(x,e){return x===e||x!=x&&e!=e},lv=function(x,e){for(var t=x.length;t--;)if(lc(x[t][0],e))return t;return -1};var ld=Array.prototype.splice;function lf(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}lf.prototype.clear=function(){this.__data__=[],this.size=0},lf.prototype.delete=function(x){var e=this.__data__,t=lv(e,x);return!(t<0)&&(t==e.length-1?e.pop():ld.call(e,t,1),--this.size,!0)},lf.prototype.get=function(x){var e=this.__data__,t=lv(e,x);return t<0?void 0:e[t][1]},lf.prototype.has=function(x){return lv(this.__data__,x)>-1},lf.prototype.set=function(x,e){var t=this.__data__,r=lv(t,x);return r<0?(++this.size,t.push([x,e])):t[r][1]=e,this};var lb=lA(oQ,"Map");let lu=function(x){var e=typeof x;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==x:null===x},lp=function(x,e){var t=x.__data__;return lu(e)?t["string"==typeof e?"string":"hash"]:t.map};function lm(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}function lh(x,e){if("function"!=typeof x||null!=e&&"function"!=typeof e)throw TypeError("Expected a function");var t=function(){var r=arguments,a=e?e.apply(this,r):r[0],n=t.cache;if(n.has(a))return n.get(a);var _=x.apply(this,r);return t.cache=n.set(a,_)||n,_};return t.cache=new(lh.Cache||lm),t}lm.prototype.clear=function(){this.size=0,this.__data__={hash:new ll,map:new(lb||lf),string:new ll}},lm.prototype.delete=function(x){var e=lp(this,x).delete(x);return this.size-=!!e,e},lm.prototype.get=function(x){return lp(this,x).get(x)},lm.prototype.has=function(x){return lp(this,x).has(x)},lm.prototype.set=function(x,e){var t=lp(this,x),r=t.size;return t.set(x,e),this.size+=+(t.size!=r),this},lh.Cache=lm;var lE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,lj=/\\(\\)?/g,lg=(rk=(rP=lh(function(x){var e=[];return 46===x.charCodeAt(0)&&e.push(""),x.replace(lE,function(x,t,r,a){e.push(r?a.replace(lj,"$1"):t||x)}),e},function(x){return 500===rk.size&&rk.clear(),x})).cache,rP);let ly=function(x,e){for(var t=-1,r=null==x?0:x.length,a=Array(r);++t<r;)a[t]=e(x[t],t,x);return a};var lS=1/0,lI=oM?oM.prototype:void 0,lN=lI?lI.toString:void 0;let lB=function x(e){if("string"==typeof e)return e;if(oO(e))return ly(e,x)+"";if(o1(e))return lN?lN.call(e):"";var t=e+"";return"0"==t&&1/e==-lS?"-0":t},lF=function(x,e){return oO(x)?x:o6(x,e)?[x]:lg(null==x?"":lB(x))};var lw=1/0;let lC=function(x){if("string"==typeof x||o1(x))return x;var e=x+"";return"0"==e&&1/x==-lw?"-0":e},lP=function(x,e){e=lF(e,x);for(var t=0,r=e.length;null!=x&&t<r;)x=x[lC(e[t++])];return t&&t==r?x:void 0},lk=function(x,e,t){var r=null==x?void 0:lP(x,e);return void 0===r?t:r},lD={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},lL={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},lq={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},lT={...lD,...lL,...lq},lR={...lD,...lL,...lq};(rD=rH||(rH={}))[rD.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",rD[rD.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",rD[rD.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",rD[rD.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let l$=I("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function lG(){return{modifyEnvironment:new l$.FU(["arg0"]),modifyEntryOption:new l$.BD(["arg0"]),beforeBuild:new l$.FU(["arg0"]),collectMetaData:new l$.FU(["arg0"]),build:new l$.FU(["arg0"]),afterBuild:new l$.FU(["arg0"])}}function lO({hooks:x,stages:e}){return{hooks:x,...e}}class lX{constructor(x,e=[]){this.plugins=[],this.api={...{worker:lO({hooks:lG(),stages:lR}),view:lO({hooks:lG(),stages:lT}),assets:lO({hooks:{beforeEmit:new l$.FU(["arg0"]),afterEmit:new l$.FU(["arg0"])},stages:rH}),deploy:lO({hooks:{beforeDeploy:new l$.FU(["arg0"]),deploy:new l$.FU(["arg0"]),afterDeploy:new l$.FU(["arg0"])},stages:{}})},context:x},this.addPlugins(e)}getScopeHooks(x){return this.api[x].hooks}addPlugins(x){this.plugins.push(...x)}async bootstrap(){for await(let x of this.plugins)await x.setup(this.api)}async callScopeHooks(x,e,...t){let r=lk(this.getScopeHooks(x),e);return await r.promise(...t)}async callWorkerHooks(x,...e){return this.callScopeHooks("worker",x,...e)}async callViewHooks(x,...e){return this.callScopeHooks("view",x,...e)}async callAssetsHooks(x,...e){return this.callScopeHooks("assets",x,...e)}async callDeployHooks(x,...e){return this.callScopeHooks("deploy",x,...e)}}async function lK(x,e,t,r){try{return await V({source:e,destination:x,prefix:t}),r?.deleteResource&&r5.rmSync(e,{recursive:!0}),J.success("Compiled artifacts packaged",{file:r4.basename(x)}),""}catch(x){throw J.error("An error occurred during packaging",{error:x}),x}}async function lQ({channelName:x,manifest:e,rootPath:t}){let r=r4.resolve(t),a=r4.resolve(t,"doubao_app_output"),n=r4.resolve(a,e.packageName),_={outputFolder:a,transformFolder:n,manifest:e};r5.existsSync(a)&&r5.rmSync(a,{recursive:!0}),r5.mkdirSync(a),r5.mkdirSync(n),function(x,e){let{transformFolder:t,manifest:r}=e,{applet:a,widgets:n}=r,_=r4.resolve(x,"base"),A=r4.resolve(t,"base");r5.mkdirSync(A),r5.cpSync(_,A,{filter:(x,e)=>null===x.match(/(.)*\.map$/),recursive:!0});let s=r4.resolve(x,a.appletId),i=r4.resolve(t,a.appletId);r5.mkdirSync(i),a.pages.length>0&&r5.cpSync(s,i,{filter:(x,e)=>null===x.match(/(.)*\.map$/),recursive:!0}),n.forEach(e=>{let r=r4.resolve(x,e.widgetId),a=r4.resolve(t,e.widgetId);r5.mkdirSync(a),r5.cpSync(r,a,{filter:x=>null===x.match(/(.)*\.map$/),recursive:!0})});let o=r4.resolve(x,`web_${r.versionCode}`);if(r5.existsSync(o)){let x=r4.resolve(t,`web_${r.versionCode}`);r5.cpSync(o,x,{recursive:!0})}}(r,_);let A=await lM(x,_);return J.debug("Package resource created",{packageResource:A}),{packageResource:A}}async function lM(x,e){if(!/([a-z0-9_-]+)/.test(x))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:t,outputFolder:r,transformFolder:a}=e,{applet:n,widgets:_,packageName:A,versionCode:s}=t,i=r4.resolve(r,"deploy-package"),o=r4.resolve(i,x),l=r4.resolve(o,A);r5.mkdirSync(i),r5.mkdirSync(o),r5.mkdirSync(l),r5.cpSync(a,l,{recursive:!0});let c={},v=r5.readdirSync(l).filter(x=>r5.statSync(r4.resolve(l,x)).isDirectory()),d=r4.resolve(i,`${x}.zip`);try{if(await Promise.all(v.map(x=>{if(x===`web_${s}`)return Promise.resolve();if("base"===x)return lK(r4.resolve(l,`${x}_${s}.zip`),r4.resolve(l,x),x,{deleteResource:!0});if(x===n.appletId){let e=`${x}_${n.digest}.zip`;return c[n.appletId]=e,lK(r4.resolve(l,e),r4.resolve(l,x),x,{deleteResource:!0})}let e=_.find(e=>e.widgetId===x);if(e){let t=`${x}_${e.digest}.zip`;return c[e.widgetId]=t,lK(r4.resolve(l,t),r4.resolve(l,x),x,{deleteResource:!0})}return J.error("Invalid package directory",{directory:x}),Promise.resolve()})),await lK(d,o,x),process.env.BUILD_VERSION){let x=r4.resolve(r,"scm-deploy-package"),e=r4.resolve(x,A);r5.mkdirSync(x),r5.mkdirSync(e),r5.cpSync(l,e,{recursive:!0})}return J.success("Deploy package archived",{destination:d}),{resource:d,fileNames:c}}catch(x){throw Error(`ERROR: Archive the deploy-package failed. ${x}`)}}(rL=rU||(rU={})).NORMAL="normal",rL.SELF_BUILT_CREATE="selfBuiltCreate",rL.SELF_BUILT_PUBLISH="selfBuiltPublish",rL.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",rL.SELF_BUILT_STOP="selfBuiltStop",rL.SELF_BUILT_ROLLBACK="selfBuiltRollback";let lZ={NORMAL:rU.NORMAL,SELF_BUILT_CREATE:rU.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:rU.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:rU.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:rU.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:rU.SELF_BUILT_ROLLBACK};function lJ(x,e){let t=(e||x).replace(/^\/+/,"").split("/").filter(Boolean);return t.length>1&&"index"===t[t.length-1]?t[t.length-2]||"index":t[t.length-1]||"index"}function lV(x,e){let[t]=(e??x).split(/[?#]/,1),r=t.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return r?`/${r}`:"/"}function lH(x,e,t){let r=lV(e).slice(1);return`${x}/${r}/${t}`}function lU(x){var e=this.__data__=new lf(x);this.size=e.size}lU.prototype.clear=function(){this.__data__=new lf,this.size=0},lU.prototype.delete=function(x){var e=this.__data__,t=e.delete(x);return this.size=e.size,t},lU.prototype.get=function(x){return this.__data__.get(x)},lU.prototype.has=function(x){return this.__data__.has(x)},lU.prototype.set=function(x,e){var t=this.__data__;if(t instanceof lf){var r=t.__data__;if(!lb||r.length<199)return r.push([x,e]),this.size=++t.size,this;t=this.__data__=new lm(r)}return t.set(x,e),this.size=t.size,this};var lY=function(){try{var x=lA(Object,"defineProperty");return x({},"",{}),x}catch(x){}}();let lz=function(x,e,t){"__proto__"==e&&lY?lY(x,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):x[e]=t},lW=function(x,e,t){(void 0===t||lc(x[e],t))&&(void 0!==t||e in x)||lz(x,e,t)},l0=function(x,e,t){for(var r=-1,a=Object(x),n=t(x),_=n.length;_--;){var A=n[++r];if(!1===e(a[A],A,a))break}return x};var l1="object"==typeof exports&&exports&&!exports.nodeType&&exports,l2=l1&&"object"==typeof module&&module&&!module.nodeType&&module,l3=l2&&l2.exports===l1?oQ.Buffer:void 0,l6=l3?l3.allocUnsafe:void 0;let l4=function(x,e){if(e)return x.slice();var t=x.length,r=l6?l6(t):new x.constructor(t);return x.copy(r),r};var l5=oQ.Uint8Array;let l7=function(x){var e=new x.constructor(x.byteLength);return new l5(e).set(new l5(x)),e},l8=function(x,e){var t=e?l7(x.buffer):x.buffer;return new x.constructor(t,x.byteOffset,x.length)},l9=function(x,e){var t=-1,r=x.length;for(e||(e=Array(r));++t<r;)e[t]=x[t];return e};var cx=Object.create,ce=function(){function x(){}return function(e){if(!o4(e))return{};if(cx)return cx(e);x.prototype=e;var t=new x;return x.prototype=void 0,t}}(),ct=(rq=Object.getPrototypeOf,rT=Object,function(x){return rq(rT(x))}),cr=Object.prototype;let ca=function(x){var e=x&&x.constructor;return x===("function"==typeof e&&e.prototype||cr)},cn=function(x){return o0(x)&&"[object Arguments]"==oW(x)};var c_=Object.prototype,cA=c_.hasOwnProperty,cs=c_.propertyIsEnumerable,ci=cn(function(){return arguments}())?cn:function(x){return o0(x)&&cA.call(x,"callee")&&!cs.call(x,"callee")};let co=function(x){return"number"==typeof x&&x>-1&&x%1==0&&x<=0x1fffffffffffff},cl=function(x){return null!=x&&co(x.length)&&!o5(x)};var cc="object"==typeof exports&&exports&&!exports.nodeType&&exports,cv=cc&&"object"==typeof module&&module&&!module.nodeType&&module,cd=cv&&cv.exports===cc?oQ.Buffer:void 0;let cf=(cd?cd.isBuffer:void 0)||function(){return!1};var cb=Object.prototype,cu=Function.prototype.toString,cp=cb.hasOwnProperty,cm=cu.call(Object);let ch=function(x){if(!o0(x)||"[object Object]"!=oW(x))return!1;var e=ct(x);if(null===e)return!0;var t=cp.call(e,"constructor")&&e.constructor;return"function"==typeof t&&t instanceof t&&cu.call(t)==cm};var cE={};cE["[object Float32Array]"]=cE["[object Float64Array]"]=cE["[object Int8Array]"]=cE["[object Int16Array]"]=cE["[object Int32Array]"]=cE["[object Uint8Array]"]=cE["[object Uint8ClampedArray]"]=cE["[object Uint16Array]"]=cE["[object Uint32Array]"]=!0,cE["[object Arguments]"]=cE["[object Array]"]=cE["[object ArrayBuffer]"]=cE["[object Boolean]"]=cE["[object DataView]"]=cE["[object Date]"]=cE["[object Error]"]=cE["[object Function]"]=cE["[object Map]"]=cE["[object Number]"]=cE["[object Object]"]=cE["[object RegExp]"]=cE["[object Set]"]=cE["[object String]"]=cE["[object WeakMap]"]=!1;var cj="object"==typeof exports&&exports&&!exports.nodeType&&exports,cg=cj&&"object"==typeof module&&module&&!module.nodeType&&module,cy=cg&&cg.exports===cj&&oX.process,cS=function(){try{var x=cg&&cg.require&&cg.require("util").types;if(x)return x;return cy&&cy.binding&&cy.binding("util")}catch(x){}}(),cI=cS&&cS.isTypedArray,cN=cI?function(x){return cI(x)}:function(x){return o0(x)&&co(x.length)&&!!cE[oW(x)]};let cB=function(x,e){if(("constructor"!==e||"function"!=typeof x[e])&&"__proto__"!=e)return x[e]};var cF=Object.prototype.hasOwnProperty;let cw=function(x,e,t){var r=x[e];cF.call(x,e)&&lc(r,t)&&(void 0!==t||e in x)||lz(x,e,t)},cC=function(x,e,t,r){var a=!t;t||(t={});for(var n=-1,_=e.length;++n<_;){var A=e[n],s=r?r(t[A],x[A],A,t,x):void 0;void 0===s&&(s=x[A]),a?lz(t,A,s):cw(t,A,s)}return t},cP=function(x,e){for(var t=-1,r=Array(x);++t<x;)r[t]=e(t);return r};var ck=/^(?:0|[1-9]\d*)$/;let cD=function(x,e){var t=typeof x;return!!(e=null==e?0x1fffffffffffff:e)&&("number"==t||"symbol"!=t&&ck.test(x))&&x>-1&&x%1==0&&x<e};var cL=Object.prototype.hasOwnProperty;let cq=function(x,e){var t=oO(x),r=!t&&ci(x),a=!t&&!r&&cf(x),n=!t&&!r&&!a&&cN(x),_=t||r||a||n,A=_?cP(x.length,String):[],s=A.length;for(var i in x)(e||cL.call(x,i))&&!(_&&("length"==i||a&&("offset"==i||"parent"==i)||n&&("buffer"==i||"byteLength"==i||"byteOffset"==i)||cD(i,s)))&&A.push(i);return A},cT=function(x){var e=[];if(null!=x)for(var t in Object(x))e.push(t);return e};var cR=Object.prototype.hasOwnProperty;let c$=function(x){if(!o4(x))return cT(x);var e=ca(x),t=[];for(var r in x)"constructor"==r&&(e||!cR.call(x,r))||t.push(r);return t},cG=function(x){return cl(x)?cq(x,!0):c$(x)},cO=function(x,e,t,r,a,n,_){var A=cB(x,t),s=cB(e,t),i=_.get(s);if(i)return void lW(x,t,i);var o=n?n(A,s,t+"",x,e,_):void 0,l=void 0===o;if(l){var c=oO(s),v=!c&&cf(s),d=!c&&!v&&cN(s);(o=s,c||v||d)?oO(A)?o=A:o0(A)&&cl(A)?o=l9(A):v?(l=!1,o=l4(s,!0)):d?(l=!1,o=l8(s,!0)):o=[]:ch(s)||ci(s)?(o=A,ci(A))?o=cC(A,cG(A)):(!o4(A)||o5(A))&&(o="function"!=typeof s.constructor||ca(s)?{}:ce(ct(s))):l=!1}l&&(_.set(s,o),a(o,s,r,n,_),_.delete(s)),lW(x,t,o)},cX=function x(e,t,r,a,n){e!==t&&l0(t,function(_,A){if(n||(n=new lU),o4(_))cO(e,t,A,r,x,a,n);else{var s=a?a(cB(e,A),_,A+"",e,t,n):void 0;void 0===s&&(s=_),lW(e,A,s)}},cG)},cK=function(x){return x},cQ=function(x,e,t){switch(t.length){case 0:return x.call(e);case 1:return x.call(e,t[0]);case 2:return x.call(e,t[0],t[1]);case 3:return x.call(e,t[0],t[1],t[2])}return x.apply(e,t)};var cM=Math.max,cZ=Date.now,cJ=(rR=lY?function(x,e){return lY(x,"toString",{configurable:!0,enumerable:!1,value:function(){return e},writable:!0})}:cK,r$=0,rG=0,function(){var x=cZ(),e=16-(x-rG);if(rG=x,e>0){if(++r$>=800)return arguments[0]}else r$=0;return rR.apply(void 0,arguments)});let cV=function(x,e){var t;return cJ((t=cM(void 0===(t=e)?x.length-1:t,0),function(){for(var e=arguments,r=-1,a=cM(e.length-t,0),n=Array(a);++r<a;)n[r]=e[t+r];r=-1;for(var _=Array(t+1);++r<t;)_[r]=e[r];return _[t]=cK(n),cQ(x,this,_)}),x+"")},cH=function(x,e,t){if(!o4(t))return!1;var r=typeof e;return("number"==r?!!(cl(t)&&cD(e,t.length)):"string"==r&&e in t)&&lc(t[e],x)},cU=function(x){return cV(function(e,t){var r=-1,a=t.length,n=a>1?t[a-1]:void 0,_=a>2?t[2]:void 0;for(n=x.length>3&&"function"==typeof n?(a--,n):void 0,_&&cH(t[0],t[1],_)&&(n=a<3?void 0:n,a=1),e=Object(e);++r<a;){var A=t[r];A&&x(e,A,r,n)}return e})};var cY=cU(function(x,e,t,r){cX(x,e,t,r)});function cz(x,...e){return cY(x,...e,(x,e,t)=>Array.isArray(x)?x.concat(e):Buffer.isBuffer(e)?e:void 0)}let cW=(x,e)=>r4.relative(x,e).replaceAll(r4.sep,"/"),c0="@byted-doubao-apps/framework",c1="@doubao-dev/framework",c2=[c0,c1];function c3(x){return`${x}/components`}function c6(x){let e=r4.resolve(x,"package.json");if(r5.existsSync(e))try{let x=JSON.parse(r5.readFileSync(e,"utf8")),t={...x.dependencies,...x.devDependencies,...x.peerDependencies};if(t[c1])return c1;if(t[c0])return c0}catch{}}function c4(x){return c6(x)??c0}class c5{constructor(x,e=""){this.imports=[],this.contents=[],this._filename=x,e&&this.appendContent(e)}appendImports(...x){this.imports.push(...x)}appendContent(...x){this.contents.push(...x)}unshiftContent(...x){this.contents.unshift(...x)}get filename(){return this._filename}toString(){return[this.imports.map(x=>{if(x.importSpecifiers&&x.importSpecifiers.length>0){let e="",t=x.importSpecifiers.find(x=>"default"===x.propertyName),r=x.importSpecifiers.filter(x=>"default"!==x.propertyName);return t&&(e+=`${t.name}`),r.length&&(t&&(e+=", "),e+=`{ ${r.map(x=>x.name===x.propertyName?x.name:`${x.propertyName} as ${x.name}`).join(", ")} }`),`import ${e} from "${x.moduleSpecifier}";`}return`import "${x.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(x){if(this._filename){let e=r7.dirname(this._filename);(0,r1.existsSync)(e)||(0,r1.mkdirSync)(e,{recursive:!0}),(0,r1.writeFileSync)(this._filename,this.toString(),x)}return this._filename}}function c7(x,e,t=!1,r=!1){return Object.keys(x).reduce((a,n)=>{let{filename:_,isVirtualFile:A,isSpecial:s}=x[n];if(A||s)return a;let i=`${iX}${r4.sep}${n}${r4.extname(_)}`,o=cW(r4.join(e,i,".."),_),l=c4(e),c=t?"defineWidget":"definePage";return a[n]=new c5(i),a[n].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:l,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:c,name:c}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),a[n].appendContent(`
238
+ }`,iZ="widgets";r4.sep;let iJ=`base${r4.sep}manifest.json`,iV=`base${r4.sep}manifest.sign`,iH="mcp-privacy-login-card",iU="__doubao_apps__expired-widget",iY="bundle.keystore",iz={"@byted-lynx/react":"React","@lynx-js/react":"React","@lynx-js/react/internal":"ReactInternal","@lynx-js/react/jsx-dev-runtime":"ReactJSXDevRuntime","@lynx-js/react/jsx-runtime":"ReactJSXRuntime","@lynx-js/react/lepus/jsx-dev-runtime":"ReactJSXLepusDevRuntime","@lynx-js/react/lepus/jsx-runtime":"ReactJSXLepusRuntime","@lynx-js/react/experimental/lazy/import":"ReactLazyImport","@lynx-js/react/legacy-react-runtime":"ReactLegacyRuntime","@lynx-js/react/runtime-components":"ReactComponents","@lynx-js/react/worklet-runtime/bindings":"ReactWorkletRuntime","@lynx-js/react/debug":"ReactDebug",preact:"Preact",react:"React"},iW="client-tool",i0=x=>x===iH||x===iU,i1="app.config",i2=[".js",".ts",".mjs"],i3="com.larus.nova";class i6{}function i4(x,e=3e3){return O(x,{timeout:e}).catch(()=>({stdout:"",stderr:""}))}async function i5(x,e){return O(`adb -s ${x} ${e}`,{timeout:3e3})}async function i7(x){let e=(await i4(`adb -s ${x} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return e?.[1]}async function i8(x,e){let t=(await i5(x,`shell pidof ${e}`).catch(()=>({stdout:""}))).stdout.trim();return t?t.split(/\s+/)[0]:void 0}async function i9(x){let e=await i7(x);return(e===i3||"com.flow.aisdk.example"===e)&&(await i4(`adb -s ${x} shell am force-stop ${e}`),await i4(`adb -s ${x} shell monkey -p ${e} -c android.intent.category.LAUNCHER 1`),!0)}async function ox(){return(await i4("adb devices")).stdout.split("\n").slice(1).map(x=>x.split(" ")[0].trim()).filter(Boolean)}async function oe(){let x=await ox(),e=process.env.ANDROID_SERIAL;if(e){if(!x.includes(e))throw Error(`Android device ${e} is not connected`);return e}if(x.length>1){let{device:e}=await H.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:e=>x.filter(x=>x.toLowerCase().includes(e?.toLowerCase()??""))}]);return e}return x[0]}class ot extends i6{deviceId;options;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(x,e={}){if(super(),this.deviceId=x,this.options=e,e.skipForegroundAppWatch)return;let t=setInterval(()=>{this.watchAppProcess().catch(x=>{console.warn("Failed to refresh the Android host app:",x)})},500);process.once("exit",()=>clearInterval(t))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let x=await i8(this.deviceId,i3);void 0!==this.lastAppProcessId&&void 0!==x&&this.lastAppProcessId!==x&&await this.reloadOnAppRestart(x),void 0!==x&&(this.lastAppProcessId=x)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(x){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(x=>setTimeout(x,5e3)),await i8(this.deviceId,i3)!==x)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(x){this.latestLoadParams=x;let{appId:e,isSigned:t}=x,r=process.env.DEV_SERVER_HOST??this.options.appletHost??x.appletUrl,a=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${e} --es appletHost ${r} --es appletType 1 --es isSigned ${t}`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${a}`)),await i5(this.deviceId,a)}async openPage(x){let{appId:e,pageId:t,pageData:r,pageSettings:a,mode:n}=x,_=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${e} --es appletPageName ${t} --es appletPageData '${r}' --es appletPageSettings '${a}' --es mode '${n}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${_}`)),await i5(this.deviceId,_)}async openPageUrl(x){let{appId:e,url:t}=x,r=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${e} --es appletPageUrl '${t}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${r}`)),await i5(this.deviceId,r)}async pushWidget(x){let{appId:e,widgetId:t,widgetData:r,botId:a}=x,n=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${e} --es widgetName ${t} --es widgetData '${r}' --es botId ${a||process.env.DEBUG_BOT_ID}`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${n}`)),await i5(this.deviceId,n)}async callTool(x){let{appId:e,toolId:t,toolData:r}=x,a=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${e} --es toolName '${t}' --es toolData '${r}'`;Z()&&console.log(Y.dim(`adb -s ${this.deviceId} ${a}`)),await i5(this.deviceId,a)}}class or extends i6{async load(x){}async openPage(x){}async openPageUrl(x){}async pushWidget(x){}async callTool(x){}}K.child("cli");let oa=K.child("config"),on=K.child("security"),o_=K.child("build"),oA=K.child("deploy"),os=K.child("dev-server");class oi{options;currentUrl=null;debugDriver=null;appId=null;constructor(x){this.options=x}async start(x,e,t){if(null!==this.currentUrl){this.currentUrl=x,this.debugDriver?.getAllAppClients().forEach(x=>this.onConnect(x,t));return}this.currentUrl=x,this.appId=e;let{getDebugDriver:r,toolkitExecutor:a}=await import("./@byted-hdt/cli.js").then(I.bind(I,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_@types+express@5.0.6_encoding@0.1.13/node_modules/@byted-hdt/cli/dist/es/index.js"));await a({runType:"rspeedy",openWebview:this.options.devtool});let n=r();this.debugDriver=n,n.getAllAppClients().forEach(x=>this.onConnect(x,t)),n.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(x){this.debugDriver?.getAllAppClients().forEach(e=>{try{e.sendCustomizedMessage(x.method,x.params,-1,"CDP")}catch(x){os.error("向 HDT 客户端发送消息失败",{error:x})}})}onConnect=(x,e)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:e}})}}class oo extends i6{server;constructor(){super(),this.server=new oi({devtool:!0,open:!0})}async load(x){let{appletUrl:e,appId:t,isSigned:r}=x;this.server.start(e,t,r)}async openPage(x){let{appId:e,pageId:t,pageData:r,pageSettings:a,mode:n}=x;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:e,appletPageName:t,appletPageData:r,appletPageSettings:a,mode:n}})}async openPageUrl(x){let{appId:e,url:t}=x;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:e,url:t}})}async pushWidget(x){let{appId:e,widgetId:t,widgetData:r,botId:a}=x;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:e,widgetName:t,widgetData:r,botId:a||process.env.DEBUG_BOT_ID}})}async callTool(x){let{appId:e,toolId:t,toolData:r}=x;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:e,toolName:t,toolData:r}})}}async function ol(e={}){if(e.debugDriver&&"object"==typeof e.debugDriver)return e.debugDriver;if(!x){let t=e.debugDriver??xx.Adb;if(!xr(t))throw Error(`无效的调试驱动 "${t}",可选值:${xe.join(", ")}。`);switch(t){case xx.Hdt:x=new oo;break;case xx.DevTools:x=new or;break;case xx.Adb:{let t=e.deviceId??await oe();t&&(x=new ot(t,{skipForegroundAppWatch:e.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${t}",可选值:${xe.join(", ")}。`)}}return x}let oc=/\{\{\s*([^{}\s]+)\s*\}\}/g;function ov(x){return!!x&&"object"==typeof x&&!Array.isArray(x)}function od(x,e){if(void 0!==x&&"string"!=typeof x)throw Error(`字段 ${e} 必须是字符串`)}function of(x){return Object.entries(x.variables||{})}function ob(x){return"string"==typeof x?x:JSON.stringify(x)}function ou(x,e={}){let t={...x.input||{},...function(x,e={}){let t={};for(let[r,a]of of(x))Object.prototype.hasOwnProperty.call(e,r)?t[r]=e[r]:null!==a&&(t[r]=a);return{...t,...e}}(x,e)};if("page"===x.type){let e=function(x,e){var t;let r=new Set(Array.from(x.url.matchAll(oc),x=>x[1])),a=(t=x.url,t.replace(oc,(x,t)=>{if(!Object.prototype.hasOwnProperty.call(e,t))return x;let r=ob(e[t]);return void 0===r?x:encodeURIComponent(r)})),n=a.indexOf("#"),_=n<0?a:a.slice(0,n),A=n<0?"":a.slice(n),s=_.indexOf("?"),i=new Set(new URLSearchParams(s<0?"":_.slice(s+1)).keys()),o=new URLSearchParams;for(let[x,t]of Object.entries(e)){if(r.has(x)||i.has(x))continue;let e=ob(t);void 0!==e&&o.set(x,e)}let l=o.toString();if(!l)return a;let c=s<0?"?":_.endsWith("?")||_.endsWith("&")?"":"&";return`${_}${c}${l}${A}`}(x,t);return{type:"page",unresolvedVariables:function(x){let e=new Set;for(let t of x.matchAll(oc))e.add(t[1]);return Array.from(e)}(e),url:e}}return"widget"===x.type?{type:"widget",id:x.id,resolvedInput:t,botId:x.botId}:{type:"tool",id:x.id,resolvedInput:t}}function op(x){return x.replaceAll("\\","/").replace(/^src\//,"").replace(/\.(?:bundle|tsx?|jsx?)$/,"")}(rN=rM||(rM={})).REACT_LYNX="lynx",rN.LYNX="lynx";let om={REACT_LYNX:rM.REACT_LYNX,LYNX:rM.LYNX};(rB=rZ||(rZ={}))[rB.INBOX=0]="INBOX",rB[rB.FULL_BOX=3]="FULL_BOX",rB[rB.CUSTOM_BOX=4]="CUSTOM_BOX",(rF=rJ||(rJ={}))[rF.NORMAL=0]="NORMAL",rF[rF.FLOAT=1]="FLOAT",rF[rF.NONE=2]="NONE";let oh={NONE:rJ.NONE,NORMAL:rJ.NORMAL,FLOAT:rJ.FLOAT},oE={INBOX:rZ.INBOX,FULL_BOX:rZ.FULL_BOX,CUSTOM_BOX:rZ.CUSTOM_BOX},oj={definePrivacyLoginWidget:{id:"mcp-privacy-login-card",name:"应用插件同意登录和隐私协议卡片",description:"展示应用插件同意登录和隐私协议的卡片组件"},defineLoginPage:{id:"mcp-login-page",name:"应用插件登录页面",path:"/pages/mcp-login-page/index",description:"展示应用插件登录页面"}};function og(x,e={}){let t=String(x??"").trim();if(!t)return;let r=function(x,{addProtocolToBareHost:e=!1,allowRootRelative:t=!1,defaultProtocol:r="http"}={}){var a;if(/^https?:\/\//i.test(x))return x;if(x.startsWith("//"))return`${oy(r,x.slice(2))}:${x}`;if(t&&x.startsWith("/"))return x;return/^(?:\[[^\]]+\]|[a-z0-9.-]+):\d+(?:[/?#]|$)/i.test(x)||e&&(a=x,/^(?:\[[^\]]+\]|[a-z0-9.-]+)(?:[/?#]|$)/i.test(a))?`${oy(r,x)}://${x}`:x}(t,e);try{let x=e.baseUrl?new URL(r,e.baseUrl):new URL(r);if("http:"!==x.protocol&&"https:"!==x.protocol)return;return x.toString()}catch{return}}function oy(x,e){return"function"==typeof x?x(e):x}function oS(x){return!!x&&"object"==typeof x&&!Array.isArray(x)}let oI="developer.doubao.com",oN=`https://${oI}`;async function oB(x){let e=(0,r4.join)(x,"debug-scene");try{return(await (0,aa.readdir)(e,{withFileTypes:!0})).filter(x=>x.isFile()&&x.name.endsWith(".json")).map(x=>({name:x.name.slice(0,-5),path:(0,r4.join)(e,x.name)}))}catch{return[]}}async function oF(x){try{var e=JSON.parse(await (0,aa.readFile)(x,"utf8"));if(!ov(e))throw Error("Scene 内容必须是 JSON 对象");if("page"!==e.type&&"widget"!==e.type&&"tool"!==e.type)throw Error("字段 type 必须是 page、widget 或 tool");if(od(e.id,"id"),od(e.url,"url"),od(e.botId,"botId"),"page"===e.type){if(!e.url?.trim())throw Error("Page Scene 必须配置 url");if(void 0!==e.id)throw Error("Page Scene 不支持 id,请使用 url")}else if(!e.id?.trim())throw Error(`${"widget"===e.type?"Widget":"Tool"} Scene 必须配置 id`);if(void 0!==e.input&&!ov(e.input))throw Error("字段 input 必须是 JSON 对象");if(void 0!==e.variables){if(!ov(e.variables))throw Error("字段 variables 必须是 JSON 对象");for(let[x,t]of Object.entries(e.variables))if(null!==t&&"string"!=typeof t)throw Error(`变量 ${x} 的默认值必须是字符串或 null`)}if(void 0!==e.settings&&"string"!=typeof e.settings&&!ov(e.settings))throw Error("字段 settings 必须是字符串或 JSON 对象");return e}catch(e){return Z()&&console.warn(`[DoubaoApps] 加载调试场景 "${x}" 失败:${e instanceof Error?e.message:String(e)}`),null}}async function ow(x,e){let{matchedScene:t,appId:r,driver:a,variables:n}=x,_=e??await oF(t.path);if(!_)return;let A=ou(_,n);if("page"===A.type){var s,i;s=t.name,0!==(i=A.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${s}" 存在未解析的变量占位符:${i.map(x=>`{{${x}}}`).join(", ")}`),await a.openPageUrl({appId:r,url:A.url})}else if("widget"===A.type){let x=JSON.stringify(A.resolvedInput),e={appId:r,widgetId:A.id,widgetData:x,botId:A.botId};await a.pushWidget(e)}else{let x=JSON.stringify(A.resolvedInput),e={appId:r,toolId:A.id,toolData:x};await a.callTool(e)}}let oC="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function oP(x){if("string"==typeof x){let e=x.length>0?x:oC;return{"1x":e,"2x":e,"3x":e}}return{"1x":x?.["1x"]||oC,"2x":x?.["2x"]||oC,"3x":x?.["3x"]||oC}}function ok(x){let e=Object.keys(x);return e.sort(),e.reduce((e,t)=>(e[t]=x[t],e),{})}class oD{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class oL extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(x,e,t){let r=this._metadata;return{id:r.id,name:r.name,path:r.path,description:r.description,keywords:r.keywords,digest:e,prop:r.prop,entry:x,renderType:t,title:r.title,chat:r.chat}}}class oq extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(x,e,t,r=[]){let a=this._metadata;return{widgetId:a.id,name:a.name,description:a.description,keywords:a.keywords,digest:e,prop:a.prop,entry:x,renderType:t,border:a.border,appSettings:r,boxType:oq.BOX_TYPE_MAP[a.boxType??"inbox"]??oE.INBOX,titleType:a.titleType?oq.TITLE_TYPE_MAP[a.titleType]:void 0}}}oq.BOX_TYPE_MAP={inbox:oE.INBOX,full_box:oE.FULL_BOX,custom_box:oE.CUSTOM_BOX},oq.TITLE_TYPE_MAP={none:2,normal:0,float:1};class oT extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest(){let x=this._metadata;return{id:x.id,name:x.name,description:x.description,timeout:x.timeout}}}class oR extends oD{constructor(x){super(),this._metadata=x}assign(x){this._metadata={...this._metadata,...x}}toManifest({toolsMetadata:x,hashCode:e,appRuntimeEntry:t,appRuntimeType:r}){return{name:this._metadata.name,description:this._metadata.description,appletId:this._metadata.appId,appletEntry:"index",pages:[],darkMode:this._metadata.darkMode,chat:this._metadata.chat,keywords:this._metadata.keywords,icons:oP(this._metadata.icons),digest:e,prop:"",tools:Object.values(x).map(x=>x.toManifest()),appRuntimeEntry:t,appRuntimeType:r}}}class o${constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(x){this.metadata.app.metadata?this.metadata.app.assign(x):this.metadata.app=new oR(x)}addToolMeta(x,e){this.metadata.tools[x]?this.metadata.tools[x].assign(e):this.metadata.tools[x]=new oT(e)}addPageMeta(x,e){this.metadata.pages[x]?this.metadata.pages[x].assign(e):this.metadata.pages[x]=new oL(e)}addWidgetMeta(x,e){this.metadata.widgets[x]?this.metadata.widgets[x].assign(e):this.metadata.widgets[x]=new oq(e)}getData(){let{tools:x,pages:e,widgets:t,app:r}=this.metadata;return{app:r.metadata??{},tools:ok(Object.fromEntries(Object.keys(x).map(e=>[e,x[e].metadata]))),pages:ok(Object.fromEntries(Object.keys(e).map(x=>[x,e[x].metadata]))),widgets:ok(Object.fromEntries(Object.keys(t).map(x=>[x,t[x].metadata])))}}getInstance(){let{tools:x,pages:e,widgets:t,app:r}=this.metadata;return{app:r,tools:ok(x),pages:ok(e),widgets:ok(t)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}(rw=rV||(rV={})).DEV="dev",rw.BUILD="build",rw.PERF="perf",rw.DEPLOY="deploy",rw.ANALYZE="analyze";let oG={DEV:rV.DEV,BUILD:rV.BUILD,PERF:rV.PERF,DEPLOY:rV.DEPLOY,ANALYZE:rV.ANALYZE};var oO=Array.isArray,oX="object"==typeof globalThis&&globalThis&&globalThis.Object===Object&&globalThis,oK="object"==typeof self&&self&&self.Object===Object&&self,oQ=oX||oK||Function("return this")(),oM=oQ.Symbol,oZ=Object.prototype,oJ=oZ.hasOwnProperty,oV=oZ.toString,oH=oM?oM.toStringTag:void 0;let oU=function(x){var e=oJ.call(x,oH),t=x[oH];try{x[oH]=void 0;var r=!0}catch(x){}var a=oV.call(x);return r&&(e?x[oH]=t:delete x[oH]),a};var oY=Object.prototype.toString,oz=oM?oM.toStringTag:void 0;let oW=function(x){return null==x?void 0===x?"[object Undefined]":"[object Null]":oz&&oz in Object(x)?oU(x):oY.call(x)},o0=function(x){return null!=x&&"object"==typeof x},o1=function(x){return"symbol"==typeof x||o0(x)&&"[object Symbol]"==oW(x)};var o2=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o3=/^\w*$/;let o6=function(x,e){if(oO(x))return!1;var t=typeof x;return!!("number"==t||"symbol"==t||"boolean"==t||null==x||o1(x))||o3.test(x)||!o2.test(x)||null!=e&&x in Object(e)},o4=function(x){var e=typeof x;return null!=x&&("object"==e||"function"==e)},o5=function(x){if(!o4(x))return!1;var e=oW(x);return"[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e};var o7=oQ["__core-js_shared__"],o8=(rC=/[^.]+$/.exec(o7&&o7.keys&&o7.keys.IE_PROTO||""))?"Symbol(src)_1."+rC:"",o9=Function.prototype.toString;let lx=function(x){if(null!=x){try{return o9.call(x)}catch(x){}try{return x+""}catch(x){}}return""};var le=/^\[object .+?Constructor\]$/,lt=Object.prototype,lr=Function.prototype.toString,la=lt.hasOwnProperty,ln=RegExp("^"+lr.call(la).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");let l_=function(x){return!!o4(x)&&(!o8||!(o8 in x))&&(o5(x)?ln:le).test(lx(x))},lA=function(x,e){var t=null==x?void 0:x[e];return l_(t)?t:void 0};var ls=lA(Object,"create"),li=Object.prototype.hasOwnProperty,lo=Object.prototype.hasOwnProperty;function ll(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}ll.prototype.clear=function(){this.__data__=ls?ls(null):{},this.size=0},ll.prototype.delete=function(x){var e=this.has(x)&&delete this.__data__[x];return this.size-=!!e,e},ll.prototype.get=function(x){var e=this.__data__;if(ls){var t=e[x];return"__lodash_hash_undefined__"===t?void 0:t}return li.call(e,x)?e[x]:void 0},ll.prototype.has=function(x){var e=this.__data__;return ls?void 0!==e[x]:lo.call(e,x)},ll.prototype.set=function(x,e){var t=this.__data__;return this.size+=+!this.has(x),t[x]=ls&&void 0===e?"__lodash_hash_undefined__":e,this};let lc=function(x,e){return x===e||x!=x&&e!=e},lv=function(x,e){for(var t=x.length;t--;)if(lc(x[t][0],e))return t;return -1};var ld=Array.prototype.splice;function lf(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}lf.prototype.clear=function(){this.__data__=[],this.size=0},lf.prototype.delete=function(x){var e=this.__data__,t=lv(e,x);return!(t<0)&&(t==e.length-1?e.pop():ld.call(e,t,1),--this.size,!0)},lf.prototype.get=function(x){var e=this.__data__,t=lv(e,x);return t<0?void 0:e[t][1]},lf.prototype.has=function(x){return lv(this.__data__,x)>-1},lf.prototype.set=function(x,e){var t=this.__data__,r=lv(t,x);return r<0?(++this.size,t.push([x,e])):t[r][1]=e,this};var lb=lA(oQ,"Map");let lu=function(x){var e=typeof x;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==x:null===x},lp=function(x,e){var t=x.__data__;return lu(e)?t["string"==typeof e?"string":"hash"]:t.map};function lm(x){var e=-1,t=null==x?0:x.length;for(this.clear();++e<t;){var r=x[e];this.set(r[0],r[1])}}function lh(x,e){if("function"!=typeof x||null!=e&&"function"!=typeof e)throw TypeError("Expected a function");var t=function(){var r=arguments,a=e?e.apply(this,r):r[0],n=t.cache;if(n.has(a))return n.get(a);var _=x.apply(this,r);return t.cache=n.set(a,_)||n,_};return t.cache=new(lh.Cache||lm),t}lm.prototype.clear=function(){this.size=0,this.__data__={hash:new ll,map:new(lb||lf),string:new ll}},lm.prototype.delete=function(x){var e=lp(this,x).delete(x);return this.size-=!!e,e},lm.prototype.get=function(x){return lp(this,x).get(x)},lm.prototype.has=function(x){return lp(this,x).has(x)},lm.prototype.set=function(x,e){var t=lp(this,x),r=t.size;return t.set(x,e),this.size+=+(t.size!=r),this},lh.Cache=lm;var lE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,lj=/\\(\\)?/g,lg=(rk=(rP=lh(function(x){var e=[];return 46===x.charCodeAt(0)&&e.push(""),x.replace(lE,function(x,t,r,a){e.push(r?a.replace(lj,"$1"):t||x)}),e},function(x){return 500===rk.size&&rk.clear(),x})).cache,rP);let ly=function(x,e){for(var t=-1,r=null==x?0:x.length,a=Array(r);++t<r;)a[t]=e(x[t],t,x);return a};var lS=1/0,lI=oM?oM.prototype:void 0,lN=lI?lI.toString:void 0;let lB=function x(e){if("string"==typeof e)return e;if(oO(e))return ly(e,x)+"";if(o1(e))return lN?lN.call(e):"";var t=e+"";return"0"==t&&1/e==-lS?"-0":t},lF=function(x,e){return oO(x)?x:o6(x,e)?[x]:lg(null==x?"":lB(x))};var lw=1/0;let lC=function(x){if("string"==typeof x||o1(x))return x;var e=x+"";return"0"==e&&1/x==-lw?"-0":e},lP=function(x,e){e=lF(e,x);for(var t=0,r=e.length;null!=x&&t<r;)x=x[lC(e[t++])];return t&&t==r?x:void 0},lk=function(x,e,t){var r=null==x?void 0:lP(x,e);return void 0===r?t:r},lD={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},lL={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},lq={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},lT={...lD,...lL,...lq},lR={...lD,...lL,...lq};(rD=rH||(rH={}))[rD.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",rD[rD.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",rD[rD.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",rD[rD.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",rD[rD.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let l$=I("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function lG(){return{modifyEnvironment:new l$.FU(["arg0"]),modifyEntryOption:new l$.BD(["arg0"]),beforeBuild:new l$.FU(["arg0"]),collectMetaData:new l$.FU(["arg0"]),build:new l$.FU(["arg0"]),afterBuild:new l$.FU(["arg0"])}}function lO({hooks:x,stages:e}){return{hooks:x,...e}}class lX{constructor(x,e=[]){this.plugins=[],this.api={...{worker:lO({hooks:lG(),stages:lR}),view:lO({hooks:lG(),stages:lT}),assets:lO({hooks:{beforeEmit:new l$.FU(["arg0"]),afterEmit:new l$.FU(["arg0"])},stages:rH}),deploy:lO({hooks:{beforeDeploy:new l$.FU(["arg0"]),deploy:new l$.FU(["arg0"]),afterDeploy:new l$.FU(["arg0"])},stages:{}})},context:x},this.addPlugins(e)}getScopeHooks(x){return this.api[x].hooks}addPlugins(x){this.plugins.push(...x)}async bootstrap(){for await(let x of this.plugins)await x.setup(this.api)}async callScopeHooks(x,e,...t){let r=lk(this.getScopeHooks(x),e);return await r.promise(...t)}async callWorkerHooks(x,...e){return this.callScopeHooks("worker",x,...e)}async callViewHooks(x,...e){return this.callScopeHooks("view",x,...e)}async callAssetsHooks(x,...e){return this.callScopeHooks("assets",x,...e)}async callDeployHooks(x,...e){return this.callScopeHooks("deploy",x,...e)}}async function lK(x,e,t,r){try{return await V({source:e,destination:x,prefix:t}),r?.deleteResource&&r5.rmSync(e,{recursive:!0}),J.success("Compiled artifacts packaged",{file:r4.basename(x)}),""}catch(x){throw J.error("An error occurred during packaging",{error:x}),x}}async function lQ({channelName:x,manifest:e,rootPath:t}){let r=r4.resolve(t),a=r4.resolve(t,"doubao_app_output"),n=r4.resolve(a,e.packageName),_={outputFolder:a,transformFolder:n,manifest:e};r5.existsSync(a)&&r5.rmSync(a,{recursive:!0}),r5.mkdirSync(a),r5.mkdirSync(n),function(x,e){let{transformFolder:t,manifest:r}=e,{applet:a,widgets:n}=r,_=r4.resolve(x,"base"),A=r4.resolve(t,"base");r5.mkdirSync(A),r5.cpSync(_,A,{filter:(x,e)=>null===x.match(/(.)*\.map$/),recursive:!0});let s=r4.resolve(x,a.appletId),i=r4.resolve(t,a.appletId);for(let e of(r5.mkdirSync(i),a.pages.length>0&&r5.cpSync(s,i,{filter:(x,e)=>null===x.match(/(.)*\.map$/),recursive:!0}),n.forEach(e=>{let r=r4.resolve(x,e.widgetId),a=r4.resolve(t,e.widgetId);r5.mkdirSync(a),r5.cpSync(r,a,{filter:x=>null===x.match(/(.)*\.map$/),recursive:!0})}),[`web_${r.versionCode}`,`preview_${r.versionCode}`])){let r=r4.resolve(x,e);r5.existsSync(r)&&r5.cpSync(r,r4.resolve(t,e),{recursive:!0})}}(r,_);let A=await lM(x,_);return J.debug("Package resource created",{packageResource:A}),{packageResource:A}}async function lM(x,e){if(!/([a-z0-9_-]+)/.test(x))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:t,outputFolder:r,transformFolder:a}=e,{applet:n,widgets:_,packageName:A,versionCode:s}=t,i=r4.resolve(r,"deploy-package"),o=r4.resolve(i,x),l=r4.resolve(o,A);r5.mkdirSync(i),r5.mkdirSync(o),r5.mkdirSync(l),r5.cpSync(a,l,{recursive:!0});let c={},v=r5.readdirSync(l).filter(x=>r5.statSync(r4.resolve(l,x)).isDirectory()),d=r4.resolve(i,`${x}.zip`);try{if(await Promise.all(v.map(x=>{if(x===`web_${s}`||x===`preview_${s}`)return Promise.resolve();if("base"===x)return lK(r4.resolve(l,`${x}_${s}.zip`),r4.resolve(l,x),x,{deleteResource:!0});if(x===n.appletId){let e=`${x}_${n.digest}.zip`;return c[n.appletId]=e,lK(r4.resolve(l,e),r4.resolve(l,x),x,{deleteResource:!0})}let e=_.find(e=>e.widgetId===x);if(e){let t=`${x}_${e.digest}.zip`;return c[e.widgetId]=t,lK(r4.resolve(l,t),r4.resolve(l,x),x,{deleteResource:!0})}return J.error("Invalid package directory",{directory:x}),Promise.resolve()})),await lK(d,o,x),process.env.BUILD_VERSION){let x=r4.resolve(r,"scm-deploy-package"),e=r4.resolve(x,A);r5.mkdirSync(x),r5.mkdirSync(e),r5.cpSync(l,e,{recursive:!0})}return J.success("Deploy package archived",{destination:d}),{resource:d,fileNames:c}}catch(x){throw Error(`ERROR: Archive the deploy-package failed. ${x}`)}}(rL=rU||(rU={})).NORMAL="normal",rL.SELF_BUILT_CREATE="selfBuiltCreate",rL.SELF_BUILT_PUBLISH="selfBuiltPublish",rL.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",rL.SELF_BUILT_STOP="selfBuiltStop",rL.SELF_BUILT_ROLLBACK="selfBuiltRollback";let lZ={NORMAL:rU.NORMAL,SELF_BUILT_CREATE:rU.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:rU.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:rU.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:rU.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:rU.SELF_BUILT_ROLLBACK};function lJ(x){var e=this.__data__=new lf(x);this.size=e.size}lJ.prototype.clear=function(){this.__data__=new lf,this.size=0},lJ.prototype.delete=function(x){var e=this.__data__,t=e.delete(x);return this.size=e.size,t},lJ.prototype.get=function(x){return this.__data__.get(x)},lJ.prototype.has=function(x){return this.__data__.has(x)},lJ.prototype.set=function(x,e){var t=this.__data__;if(t instanceof lf){var r=t.__data__;if(!lb||r.length<199)return r.push([x,e]),this.size=++t.size,this;t=this.__data__=new lm(r)}return t.set(x,e),this.size=t.size,this};var lV=function(){try{var x=lA(Object,"defineProperty");return x({},"",{}),x}catch(x){}}();let lH=function(x,e,t){"__proto__"==e&&lV?lV(x,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):x[e]=t},lU=function(x,e,t){(void 0===t||lc(x[e],t))&&(void 0!==t||e in x)||lH(x,e,t)},lY=function(x,e,t){for(var r=-1,a=Object(x),n=t(x),_=n.length;_--;){var A=n[++r];if(!1===e(a[A],A,a))break}return x};var lz="object"==typeof exports&&exports&&!exports.nodeType&&exports,lW=lz&&"object"==typeof module&&module&&!module.nodeType&&module,l0=lW&&lW.exports===lz?oQ.Buffer:void 0,l1=l0?l0.allocUnsafe:void 0;let l2=function(x,e){if(e)return x.slice();var t=x.length,r=l1?l1(t):new x.constructor(t);return x.copy(r),r};var l3=oQ.Uint8Array;let l6=function(x){var e=new x.constructor(x.byteLength);return new l3(e).set(new l3(x)),e},l4=function(x,e){var t=e?l6(x.buffer):x.buffer;return new x.constructor(t,x.byteOffset,x.length)},l5=function(x,e){var t=-1,r=x.length;for(e||(e=Array(r));++t<r;)e[t]=x[t];return e};var l7=Object.create,l8=function(){function x(){}return function(e){if(!o4(e))return{};if(l7)return l7(e);x.prototype=e;var t=new x;return x.prototype=void 0,t}}(),l9=(rq=Object.getPrototypeOf,rT=Object,function(x){return rq(rT(x))}),cx=Object.prototype;let ce=function(x){var e=x&&x.constructor;return x===("function"==typeof e&&e.prototype||cx)},ct=function(x){return o0(x)&&"[object Arguments]"==oW(x)};var cr=Object.prototype,ca=cr.hasOwnProperty,cn=cr.propertyIsEnumerable,c_=ct(function(){return arguments}())?ct:function(x){return o0(x)&&ca.call(x,"callee")&&!cn.call(x,"callee")};let cA=function(x){return"number"==typeof x&&x>-1&&x%1==0&&x<=0x1fffffffffffff},cs=function(x){return null!=x&&cA(x.length)&&!o5(x)};var ci="object"==typeof exports&&exports&&!exports.nodeType&&exports,co=ci&&"object"==typeof module&&module&&!module.nodeType&&module,cl=co&&co.exports===ci?oQ.Buffer:void 0;let cc=(cl?cl.isBuffer:void 0)||function(){return!1};var cv=Object.prototype,cd=Function.prototype.toString,cf=cv.hasOwnProperty,cb=cd.call(Object);let cu=function(x){if(!o0(x)||"[object Object]"!=oW(x))return!1;var e=l9(x);if(null===e)return!0;var t=cf.call(e,"constructor")&&e.constructor;return"function"==typeof t&&t instanceof t&&cd.call(t)==cb};var cp={};cp["[object Float32Array]"]=cp["[object Float64Array]"]=cp["[object Int8Array]"]=cp["[object Int16Array]"]=cp["[object Int32Array]"]=cp["[object Uint8Array]"]=cp["[object Uint8ClampedArray]"]=cp["[object Uint16Array]"]=cp["[object Uint32Array]"]=!0,cp["[object Arguments]"]=cp["[object Array]"]=cp["[object ArrayBuffer]"]=cp["[object Boolean]"]=cp["[object DataView]"]=cp["[object Date]"]=cp["[object Error]"]=cp["[object Function]"]=cp["[object Map]"]=cp["[object Number]"]=cp["[object Object]"]=cp["[object RegExp]"]=cp["[object Set]"]=cp["[object String]"]=cp["[object WeakMap]"]=!1;var cm="object"==typeof exports&&exports&&!exports.nodeType&&exports,ch=cm&&"object"==typeof module&&module&&!module.nodeType&&module,cE=ch&&ch.exports===cm&&oX.process,cj=function(){try{var x=ch&&ch.require&&ch.require("util").types;if(x)return x;return cE&&cE.binding&&cE.binding("util")}catch(x){}}(),cg=cj&&cj.isTypedArray,cy=cg?function(x){return cg(x)}:function(x){return o0(x)&&cA(x.length)&&!!cp[oW(x)]};let cS=function(x,e){if(("constructor"!==e||"function"!=typeof x[e])&&"__proto__"!=e)return x[e]};var cI=Object.prototype.hasOwnProperty;let cN=function(x,e,t){var r=x[e];cI.call(x,e)&&lc(r,t)&&(void 0!==t||e in x)||lH(x,e,t)},cB=function(x,e,t,r){var a=!t;t||(t={});for(var n=-1,_=e.length;++n<_;){var A=e[n],s=r?r(t[A],x[A],A,t,x):void 0;void 0===s&&(s=x[A]),a?lH(t,A,s):cN(t,A,s)}return t},cF=function(x,e){for(var t=-1,r=Array(x);++t<x;)r[t]=e(t);return r};var cw=/^(?:0|[1-9]\d*)$/;let cC=function(x,e){var t=typeof x;return!!(e=null==e?0x1fffffffffffff:e)&&("number"==t||"symbol"!=t&&cw.test(x))&&x>-1&&x%1==0&&x<e};var cP=Object.prototype.hasOwnProperty;let ck=function(x,e){var t=oO(x),r=!t&&c_(x),a=!t&&!r&&cc(x),n=!t&&!r&&!a&&cy(x),_=t||r||a||n,A=_?cF(x.length,String):[],s=A.length;for(var i in x)(e||cP.call(x,i))&&!(_&&("length"==i||a&&("offset"==i||"parent"==i)||n&&("buffer"==i||"byteLength"==i||"byteOffset"==i)||cC(i,s)))&&A.push(i);return A},cD=function(x){var e=[];if(null!=x)for(var t in Object(x))e.push(t);return e};var cL=Object.prototype.hasOwnProperty;let cq=function(x){if(!o4(x))return cD(x);var e=ce(x),t=[];for(var r in x)"constructor"==r&&(e||!cL.call(x,r))||t.push(r);return t},cT=function(x){return cs(x)?ck(x,!0):cq(x)},cR=function(x,e,t,r,a,n,_){var A=cS(x,t),s=cS(e,t),i=_.get(s);if(i)return void lU(x,t,i);var o=n?n(A,s,t+"",x,e,_):void 0,l=void 0===o;if(l){var c=oO(s),v=!c&&cc(s),d=!c&&!v&&cy(s);(o=s,c||v||d)?oO(A)?o=A:o0(A)&&cs(A)?o=l5(A):v?(l=!1,o=l2(s,!0)):d?(l=!1,o=l4(s,!0)):o=[]:cu(s)||c_(s)?(o=A,c_(A))?o=cB(A,cT(A)):(!o4(A)||o5(A))&&(o="function"!=typeof s.constructor||ce(s)?{}:l8(l9(s))):l=!1}l&&(_.set(s,o),a(o,s,r,n,_),_.delete(s)),lU(x,t,o)},c$=function x(e,t,r,a,n){e!==t&&lY(t,function(_,A){if(n||(n=new lJ),o4(_))cR(e,t,A,r,x,a,n);else{var s=a?a(cS(e,A),_,A+"",e,t,n):void 0;void 0===s&&(s=_),lU(e,A,s)}},cT)},cG=function(x){return x},cO=function(x,e,t){switch(t.length){case 0:return x.call(e);case 1:return x.call(e,t[0]);case 2:return x.call(e,t[0],t[1]);case 3:return x.call(e,t[0],t[1],t[2])}return x.apply(e,t)};var cX=Math.max,cK=Date.now,cQ=(rR=lV?function(x,e){return lV(x,"toString",{configurable:!0,enumerable:!1,value:function(){return e},writable:!0})}:cG,r$=0,rG=0,function(){var x=cK(),e=16-(x-rG);if(rG=x,e>0){if(++r$>=800)return arguments[0]}else r$=0;return rR.apply(void 0,arguments)});let cM=function(x,e){var t;return cQ((t=cX(void 0===(t=e)?x.length-1:t,0),function(){for(var e=arguments,r=-1,a=cX(e.length-t,0),n=Array(a);++r<a;)n[r]=e[t+r];r=-1;for(var _=Array(t+1);++r<t;)_[r]=e[r];return _[t]=cG(n),cO(x,this,_)}),x+"")},cZ=function(x,e,t){if(!o4(t))return!1;var r=typeof e;return("number"==r?!!(cs(t)&&cC(e,t.length)):"string"==r&&e in t)&&lc(t[e],x)},cJ=function(x){return cM(function(e,t){var r=-1,a=t.length,n=a>1?t[a-1]:void 0,_=a>2?t[2]:void 0;for(n=x.length>3&&"function"==typeof n?(a--,n):void 0,_&&cZ(t[0],t[1],_)&&(n=a<3?void 0:n,a=1),e=Object(e);++r<a;){var A=t[r];A&&x(e,A,r,n)}return e})};var cV=cJ(function(x,e,t){c$(x,e,t)});let cH=I("crypto");class cU{constructor(x,e,t){this._content=e,this._hashCode=t,this.source=x}get content(){return this._content}get hashCode(){var x;return this._hashCode||(x=this.content,cH.createHash("sha256").update("string"==typeof x?x:new DataView(x.buffer,x.byteOffset,x.byteLength)).digest("hex").substring(0,8))}}class cY extends cU{constructor(x,e){super(x,e),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=cV(this._manifest,JSON.parse(e))}catch(x){}this.destination=x}get manifest(){return this._manifest}get content(){return JSON.stringify({manifestVersion:this._manifest.manifestVersion,packageName:this._manifest.packageName,appId:this._manifest.appId,scmVersion:this._manifest.scmVersion,versionName:this._manifest.versionName,versionTag:this._manifest.versionTag,versionCode:this._manifest.versionCode,runtimeVersion:this._manifest.runtimeVersion,sourceType:this._manifest.sourceType,permissions:this._manifest.permissions,settings:this._manifest.settings,applet:this._manifest.applet,widgets:this._manifest.widgets},null,2)}setManifestVersion(x){this._manifest.manifestVersion=x}setRuntimeVersion(x){this._manifest.runtimeVersion=x}setPackageName(x){this._manifest.packageName=x}setVersionName(x){this._manifest.versionName=x}assignBasicManifest(x){Object.assign(this._manifest,x)}mergeBasicManifest(x){cV(this._manifest,x)}setSCMVersion(x){this._manifest.scmVersion=x}setVersionCode(x){this._manifest.versionCode=x}setAppletManifest(x){this._manifest.applet=x}mergeAppletManifest(x){cV(this._manifest.applet,x)}setRenderType(x=om.REACT_LYNX){this._manifest.renderType=x}appendWidget(x){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(x)}appendPage(x){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(x)}toString(){return JSON.stringify(this._manifest,null,2)}}function cz(x,e){let t=(e||x).replace(/^\/+/,"").split("/").filter(Boolean);return t.length>1&&"index"===t[t.length-1]?t[t.length-2]||"index":t[t.length-1]||"index"}function cW(x,e){let[t]=(e??x).split(/[?#]/,1),r=t.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return r?`/${r}`:"/"}function c0(x,e,t){let r=cW(e).slice(1);return`${x}/${r}/${t}`}var c1=cJ(function(x,e,t,r){c$(x,e,t,r)});function c2(x,...e){return c1(x,...e,(x,e,t)=>Array.isArray(x)?x.concat(e):Buffer.isBuffer(e)?e:void 0)}let c3=(x,e)=>r4.relative(x,e).replaceAll(r4.sep,"/"),c6="@byted-doubao-apps/framework",c4="@doubao-dev/framework",c5=[c6,c4];function c7(x){return`${x}/components`}function c8(x){let e=r4.resolve(x,"package.json");if(r5.existsSync(e))try{let x=JSON.parse(r5.readFileSync(e,"utf8")),t={...x.dependencies,...x.devDependencies,...x.peerDependencies};if(t[c4])return c4;if(t[c6])return c6}catch{}}function c9(x){return c8(x)??c6}class vx{constructor(x,e=""){this.imports=[],this.contents=[],this._filename=x,e&&this.appendContent(e)}appendImports(...x){this.imports.push(...x)}appendContent(...x){this.contents.push(...x)}unshiftContent(...x){this.contents.unshift(...x)}get filename(){return this._filename}toString(){return[this.imports.map(x=>{if(x.importSpecifiers&&x.importSpecifiers.length>0){let e="",t=x.importSpecifiers.find(x=>"default"===x.propertyName),r=x.importSpecifiers.filter(x=>"default"!==x.propertyName);return t&&(e+=`${t.name}`),r.length&&(t&&(e+=", "),e+=`{ ${r.map(x=>x.name===x.propertyName?x.name:`${x.propertyName} as ${x.name}`).join(", ")} }`),`import ${e} from "${x.moduleSpecifier}";`}return`import "${x.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(x){if(this._filename){let e=r7.dirname(this._filename);(0,r1.existsSync)(e)||(0,r1.mkdirSync)(e,{recursive:!0}),(0,r1.writeFileSync)(this._filename,this.toString(),x)}return this._filename}}function ve(x,e,t=!1,r=!1){return Object.keys(x).reduce((a,n)=>{let{filename:_,isVirtualFile:A,isSpecial:s}=x[n];if(A||s)return a;let i=`${iX}${r4.sep}${n}${r4.extname(_)}`,o=c3(r4.join(e,i,".."),_),l=c9(e),c=t?"defineWidget":"definePage";return a[n]=new vx(i),a[n].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:l,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:c,name:c}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),a[n].appendContent(`
239
239
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
240
240
 
241
241
  const View = ${c}({
@@ -250,18 +250,18 @@ root.render(<FC />);`,r?`
250
250
  if (import.meta.webpackHot) {
251
251
  import.meta.webpackHot.accept()
252
252
  }
253
- `:""),a},{})}let c8=I("module"),c9="doubao:plugin:taro";class vx extends c5{toString(){return this.contents.join("\n").trim()}}async function ve({config:x,pluginSystem:e}){let t=x.context.environment;await e.callWorkerHooks("modifyEnvironment",{environment:t}),x.context.setEnvironment(t);let{entry:r}=await e.callWorkerHooks("modifyEntryOption",{entry:{app:new vx(`.${r4.sep}app.js`,"")}});return{entry:r}}let vt=x=>void 0!==process.env[x],vr=()=>vt("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||vt("LEGACY_FRAMEWORK"),va=()=>vt("DISABLE_APP_TEMPLATE_JS")||vt("LEGACY_FRAMEWORK");function vn({mcpEndpoint:x}={}){let e=x?.trim();return e||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}async function v_({compiler:x,compilation:e,assets:t,metadata:r,resolveAppInfo:a,resolveVersionTag:n,isNative:_,shouldInjectAsset:A}){var s;let i,o=Object.keys(t).reduce((x,t)=>{if(!A(t))return x;let r=e.getAsset(t);return r&&x.push(r),x},[]);if(0===o.length)return;let l=r.app,c=await a?.(),v=(s=n?.(),i=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:c?.appKey||l.appId,appId:c?.appKey||l.appId,name:c?.appName||l.name,icons:c?.iconUrl?oP(c.iconUrl):l.icons})};
253
+ `:""),a},{})}let vt=I("module"),vr="doubao:plugin:taro";class va extends vx{toString(){return this.contents.join("\n").trim()}}async function vn({config:x,pluginSystem:e}){let t=x.context.environment;await e.callWorkerHooks("modifyEnvironment",{environment:t}),x.context.setEnvironment(t);let{entry:r}=await e.callWorkerHooks("modifyEntryOption",{entry:{app:new va(`.${r4.sep}app.js`,"")}});return{entry:r}}let v_=x=>void 0!==process.env[x],vA=()=>v_("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||v_("LEGACY_FRAMEWORK"),vs=()=>v_("DISABLE_APP_TEMPLATE_JS")||v_("LEGACY_FRAMEWORK");function vi({mcpEndpoint:x}={}){let e=x?.trim();return e||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}async function vo({compiler:x,compilation:e,assets:t,metadata:r,resolveAppInfo:a,resolveVersionTag:n,isNative:_,shouldInjectAsset:A}){var s;let i,o=Object.keys(t).reduce((x,t)=>{if(!A(t))return x;let r=e.getAsset(t);return r&&x.push(r),x},[]);if(0===o.length)return;let l=r.app,c=await a?.(),v=(s=n?.(),i=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:c?.appKey||l.appId,appId:c?.appKey||l.appId,name:c?.appName||l.name,icons:c?.iconUrl?oP(c.iconUrl):l.icons})};
254
254
  `,s?`${i}globalThis.__VERSION_TAG__ = ${JSON.stringify(s)};
255
255
  `:i),d=new Map;if(_){let{pages:x,widgets:t}=r.getData();for(let[r,a]of e.entrypoints){let e="app"===r?{type:"app",key:r}:r===iW?{type:"client_tool",key:r}:x[r]?{type:"page",key:r,id:x[r].path}:t[r]?{type:"widget",key:r,id:t[r].id}:void 0;if(!e)continue;let n=`try {
256
256
  const key = Symbol.for('doubao-apps.runtime-error-state');
257
257
  const state = globalThis[key] || (globalThis[key] = {});
258
258
  state.entry = Object.freeze(${JSON.stringify(e)});
259
259
  } catch {}
260
- `;for(let x of a.getEntrypointChunk().files)d.set(x,n)}}o.forEach(t=>{let r=v+(d.get(t.name)??"");if(t.source.source().toString().startsWith(r))return;let a=new x.webpack.sources.ReplaceSource(t.source,t.name);a.insert(0,r),e.updateAsset(t.name,a,t.info)})}function vA(x){let e=r4.posix.basename(x);return"background.js"===e||"main-thread.js"===e||/^background\.[^/]+\.js$/.test(e)||/^main-thread\.[^/]+\.js$/.test(e)}function vs(x){let e=x.replaceAll("\\","/");return e.split("/").some(x=>x.startsWith("__doubao_web__"))&&vA(e)}class vi{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(vi.name,e=>{e.hooks.processAssets.tapPromise({name:vi.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async t=>{await v_({compiler:x,compilation:e,assets:t,...this.options})})})}}let vo="index.web.bundle",vl="base/app.web.bundle",vc="base/client-tool/index.web.bundle";function vv(x){return`__doubao_web__${x.replaceAll("\\","/").replaceAll("/","__")}`}function vd(x,e,t){return e[t]?.id??lJ(t,x[t]?.folderName)}function vf(x){return!!x?.internal}function vb(x={},e={},t="configured"){return"all"===t?x:function(x={},e={}){return Object.fromEntries(Object.entries(x).filter(([x,t])=>vf(t)||!!e[x]?.web))}(x,e)}class vu{apply(x){x.hooks.thisCompilation.tap(vu.name,e=>{e.hooks.processAssets.tapPromise({name:vu.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let t=vp(e,"app"),r=t?e.getAsset(t):void 0;if(!t||!r)throw Error("未生成 Worker 入口产物");await vm(e,x,t,vl);let a=vp(e,iW);a&&await vm(e,x,a,vc)})})}}function vp(x,e){let t=x.entrypoints.get(e)?.getEntrypointChunk();return[...t?.files??[]].find(e=>e.endsWith(".js")&&!x.getAsset(e)?.info?.hotModuleReplacement)}async function vm(x,e,t,r){let a=x.getAsset(t);if(!a)throw Error(`未生成 Worker 入口产物:${t}`);x.emitAsset(r,new e.webpack.sources.RawSource(await vh(a.source.source().toString())));let n=x.getAsset(`${t}.map`);n&&x.emitAsset(`${r}.map`,n.source,n.info),x.deleteAsset(t)}async function vh(x){let{encode:e}=await import("./@lynx-js/web-core.js");return Buffer.from(e({styleInfo:{},manifest:{"/app-service.js":x},cardType:"react",appType:"card",pageConfig:{enableCSSSelector:!0,enableFiberArch:!0,useLepusNG:!0,enableReuseContext:!0,bundleModuleMode:"ReturnByFunction",targetSdkVersion:"3.2"},lepusCode:{root:"void 0;"},customSections:{},elementTemplates:{}}))}class vE{options;isNative;constructor(x,e){this.options=x,this.isNative=e}apply(x){new x.webpack.experiments.VirtualModulesPlugin({[iK]:"",[iQ]:iM,...Object.fromEntries(Object.entries(this.options.entry).map(([,x])=>[x.filename,x.toString()]))}).apply(x),x.hooks.make.tapPromise(vE.name,async x=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(vE.name,e=>{e.hooks.optimizeTree.tapPromise(vE.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies}).catch(x=>e.errors.push(x))}),e.hooks.processAssets.tapPromise({name:vE.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async t=>{var r,a,n;let _,A=vp(e,"app");if(!A||!e.getAsset(A))throw Error("未生成 Worker 入口产物");this.isNative&&(r=e,a=this.options.context,n=A,a.setAppAssetPath(n),_=`${n}.map`,r.getAsset(_)&&a.setAppMapAssetPath(_));let s=vp(e,iW);await v_({compiler:x,compilation:e,assets:t,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),resolveVersionTag:()=>this.options.context.versionTag,isNative:this.isNative,shouldInjectAsset:x=>x===A||x===s})})}),x.hooks.done.tapPromise(vE.name,async x=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:x})})}}let vj=I("process"),vg=I("../../../node_modules/.pnpm/@lynx-js+type-config@4.2.0/node_modules/@lynx-js/type-config/index.js");var vy={},vS={};function vI(x){var e=vS[x];if(void 0!==e)return e.exports;var t=vS[x]={exports:{}};return vy[x](t,t.exports,vI),t.exports}vI.m=vy,vI.n=x=>{var e=x&&x.__esModule?()=>x.default:()=>x;return vI.d(e,{a:e}),e},vI.d=(x,e,t)=>{var r=(e,t)=>{for(var r in e)vI.o(e,r)&&!vI.o(x,r)&&Object.defineProperty(x,r,{enumerable:!0,[t]:e[r]})};r(e,"get"),r(t,"value")},vI.add=function(x){Object.assign(vI.m,x)},vI.o=(x,e)=>Object.prototype.hasOwnProperty.call(x,e),vI.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(x){x.exports=function(x){return null!=x&&"object"==typeof x&&!1===Array.isArray(x)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(x,e,t){var r=t("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");x.exports=function(x,e){if(!r(x)&&"function"!=typeof x)return{};var t={};if("string"==typeof e)return e in x&&(t[e]=x[e]),t;for(var a=e.length,n=-1;++n<a;){var _=e[n];_ in x&&(t[_]=x[_])}return t}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(x){let e=vj||{},t=e.argv||[],r=e.env||{},a=!(r.NO_COLOR||t.includes("--no-color"))&&(!!r.FORCE_COLOR||t.includes("--color")||"win32"===e.platform||(e.stdout||{}).isTTY&&"dumb"!==r.TERM||!!r.CI),n=(x,e,t=x)=>r=>{let a=""+r,n=a.indexOf(e,x.length);return~n?x+_(a,e,t,n)+e:x+a+e},_=(x,e,t,r)=>{let a="",n=0;do a+=x.substring(n,r)+t,n=r+e.length,r=x.indexOf(e,n);while(~r);return a+x.substring(n)},A=(x=a)=>{let e=x?n:()=>String;return{isColorSupported:x,reset:e("\x1b[0m","\x1b[0m"),bold:e("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:e("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:e("\x1b[3m","\x1b[23m"),underline:e("\x1b[4m","\x1b[24m"),inverse:e("\x1b[7m","\x1b[27m"),hidden:e("\x1b[8m","\x1b[28m"),strikethrough:e("\x1b[9m","\x1b[29m"),black:e("\x1b[30m","\x1b[39m"),red:e("\x1b[31m","\x1b[39m"),green:e("\x1b[32m","\x1b[39m"),yellow:e("\x1b[33m","\x1b[39m"),blue:e("\x1b[34m","\x1b[39m"),magenta:e("\x1b[35m","\x1b[39m"),cyan:e("\x1b[36m","\x1b[39m"),white:e("\x1b[37m","\x1b[39m"),gray:e("\x1b[90m","\x1b[39m"),bgBlack:e("\x1b[40m","\x1b[49m"),bgRed:e("\x1b[41m","\x1b[49m"),bgGreen:e("\x1b[42m","\x1b[49m"),bgYellow:e("\x1b[43m","\x1b[49m"),bgBlue:e("\x1b[44m","\x1b[49m"),bgMagenta:e("\x1b[45m","\x1b[49m"),bgCyan:e("\x1b[46m","\x1b[49m"),bgWhite:e("\x1b[47m","\x1b[49m"),blackBright:e("\x1b[90m","\x1b[39m"),redBright:e("\x1b[91m","\x1b[39m"),greenBright:e("\x1b[92m","\x1b[39m"),yellowBright:e("\x1b[93m","\x1b[39m"),blueBright:e("\x1b[94m","\x1b[39m"),magentaBright:e("\x1b[95m","\x1b[39m"),cyanBright:e("\x1b[96m","\x1b[39m"),whiteBright:e("\x1b[97m","\x1b[39m"),bgBlackBright:e("\x1b[100m","\x1b[49m"),bgRedBright:e("\x1b[101m","\x1b[49m"),bgGreenBright:e("\x1b[102m","\x1b[49m"),bgYellowBright:e("\x1b[103m","\x1b[49m"),bgBlueBright:e("\x1b[104m","\x1b[49m"),bgMagentaBright:e("\x1b[105m","\x1b[49m"),bgCyanBright:e("\x1b[106m","\x1b[49m"),bgWhiteBright:e("\x1b[107m","\x1b[49m")}};x.exports=A(),x.exports.createColors=A}});let vN=globalThis.window?.document!==void 0;globalThis.process?.versions?.node,globalThis.process?.versions?.bun,globalThis.Deno?.version?.deno,globalThis.process?.versions?.electron,globalThis.navigator?.userAgent?.includes("jsdom");let vB=globalThis.navigator?.userAgentData?.platform;function vF(x,e=globalThis.Deno?globalThis.Deno.args:q.argv){let t=x.startsWith("-")?"":1===x.length?"-":"--",r=e.indexOf(t+x),a=e.indexOf("--");return -1!==r&&(-1===a||r<a)}"macOS"===vB||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===vB||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===vB||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===vB||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===vB||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,vN||q.env.TERM_PROGRAM,vN||q.platform,vN||q.cwd;let{env:vw}=q;function vC(x,t={}){var r;return 0!==(r=function(x,{streamIsTTY:t,sniffFlags:r=!0}={}){let a=function(){if(!("FORCE_COLOR"in vw))return;if("true"===vw.FORCE_COLOR)return 1;if("false"===vw.FORCE_COLOR)return 0;if(0===vw.FORCE_COLOR.length)return 1;let x=Math.min(Number.parseInt(vw.FORCE_COLOR,10),3);if([0,1,2,3].includes(x))return x}();void 0!==a&&(e=a);let n=r?e:a;if(0===n)return 0;if(r){if(vF("color=16m")||vF("color=full")||vF("color=truecolor"))return 3;if(vF("color=256"))return 2}if("TF_BUILD"in vw&&"AGENT_NAME"in vw)return 1;if(x&&!t&&void 0===n)return 0;let _=n||0;if("dumb"===vw.TERM)return _;if("win32"===q.platform){let x=ib.release().split(".");return Number(x[0])>=10&&Number(x[2])>=10586?Number(x[2])>=14931?3:2:1}if("CI"in vw)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(x=>x in vw)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(x=>x in vw)||"codeship"===vw.CI_NAME?1:_;if("TEAMCITY_VERSION"in vw)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(vw.TEAMCITY_VERSION);if("truecolor"===vw.COLORTERM||"xterm-kitty"===vw.TERM||"xterm-ghostty"===vw.TERM||"wezterm"===vw.TERM)return 3;if("TERM_PROGRAM"in vw){let x=Number.parseInt((vw.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(vw.TERM_PROGRAM){case"iTerm.app":return x>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(vw.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(vw.TERM)||"COLORTERM"in vw?1:_}(x,{streamIsTTY:x&&x.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function vP(x,e=vj.argv){let t=x.startsWith("-")?"":1===x.length?"-":"--",r=e.indexOf(t+x),a=e.indexOf("--");return -1!==r&&(-1===a||r<a)}function vk(x=""){if(/^\d{3,4}$/.test(x)){let e=/(\d{1,2})(\d{2})/.exec(x)??[];return{major:0,minor:Number.parseInt(e[1],10),patch:Number.parseInt(e[2],10)}}let e=(x??"").split(".").map(x=>Number.parseInt(x,10));return{major:e[0],minor:e[1],patch:e[2]}}function vD(x){let{CI:e,CURSOR_TRACE_ID:t,FORCE_HYPERLINK:r,NETLIFY:a,TEAMCITY_VERSION:n,TERM_PROGRAM:_,TERM_PROGRAM_VERSION:A,VTE_VERSION:s,TERM:i}=q.env;if(r)return!(r.length>0&&0===Number.parseInt(r,10));if(vP("no-hyperlink")||vP("no-hyperlinks")||vP("hyperlink=false")||vP("hyperlink=never"))return!1;if(vP("hyperlink=true")||vP("hyperlink=always")||a)return!0;if(!vC(x)||x&&!x.isTTY)return!1;if("WT_SESSION"in q.env)return!0;if("win32"===q.platform||e||n)return!1;if(_){let x=vk(A);switch(_){case"iTerm.app":if(3===x.major)return x.minor>=1;return x.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(A))return A.slice(11)>="2020-06-20";return x.major>=0x1343cac;case"vscode":if(t)return!0;return x.major>1||1===x.major&&x.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(s){if("0.50.0"===s)return!1;let x=vk(s);return x.major>0||x.minor>=50}switch(i){case"alacritty":case"xterm-kitty":return!0}return!1}vF("no-color")||vF("no-colors")||vF("color=false")||vF("color=never")?e=0:(vF("color")||vF("colors")||vF("color=true")||vF("color=always"))&&(e=1),vC({isTTY:L.isatty(1)}),vC({isTTY:L.isatty(2)});let vL={stdout:vD(q.stdout),stderr:vD(q.stderr)};function vq(x,e,{target:t="stdout",...r}={}){return vL[t]?["\x1b]","8",";",";",e,"\x07",x,"\x1b]","8",";",";","\x07"].join(""):!1===r.fallback?x:"function"==typeof r.fallback?r.fallback(x,e):`${x} ${e}`}vq.isSupported=vL.stdout,vq.stderr=(x,e,t={})=>vq(x,e,{target:"stderr",...t}),vq.stderr.isSupported=vL.stderr;let vT=vI("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var vR=vI.n(vT);class v${options;constructor(x){this.options=x}name="LynxConfigWebpackPlugin";apply(x){x.hooks.thisCompilation.tap(this.name,x=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(x).beforeEncode.tap(this.name,x=>{let{config:e}=this.options;return x.encodeData.compilerOptions={...x.encodeData.compilerOptions,...vR()(e,this.options.compilerOptionsKeys)},x.encodeData.sourceContent.config={...x.encodeData.sourceContent.config,...vR()(e,this.options.configKeys)},x})})}}let vG=x=>vO.has(x),vO=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"]);(rO=rY||(rY={}))[rO.Start=0]="Start",rO[rO.Property=1]="Property",rO[rO.StringKey=2]="StringKey",rO[rO.NumberKey=3]="NumberKey";let vX=vI("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var vK=vI.n(vX);let vQ=Object.assign(f=x=>{if(!1===("object"==typeof x&&null!==x&&!1===Array.isArray(x)&&((x,e=!0)=>(void 0===x.alignMouseEventWithW3C||"boolean"==typeof x.alignMouseEventWithW3C)&&(void 0===x.disableLongpressAfterScroll||"boolean"==typeof x.disableLongpressAfterScroll)&&(void 0===x.enableA11y||"boolean"==typeof x.enableA11y)&&(void 0===x.enableAccessibilityElement||"boolean"==typeof x.enableAccessibilityElement)&&(void 0===x.enableCSSInheritance||"boolean"==typeof x.enableCSSInheritance)&&(void 0===x.enableCSSInlineVariables||"boolean"==typeof x.enableCSSInlineVariables)&&(void 0===x.enableCSSRule||"boolean"==typeof x.enableCSSRule)&&(void 0===x.enableEndGestureAtLastFingerUp||"boolean"==typeof x.enableEndGestureAtLastFingerUp)&&(void 0===x.enableEventHandleRefactor||"boolean"==typeof x.enableEventHandleRefactor)&&(void 0===x.enableEventThrough||"boolean"==typeof x.enableEventThrough)&&(void 0===x.enableEventThroughInheritFromPage||"boolean"==typeof x.enableEventThroughInheritFromPage)&&(void 0===x.enableFetchAPIStandardStreaming||"boolean"==typeof x.enableFetchAPIStandardStreaming)&&(void 0===x.enableFixedNew||"boolean"==typeof x.enableFixedNew)&&(void 0===x.enableFlexBasisZeroPercent||"boolean"==typeof x.enableFlexBasisZeroPercent)&&(void 0===x.enableGridPlacementShorthands||"boolean"==typeof x.enableGridPlacementShorthands)&&(void 0===x.enableJsBindingApiThrowException||"boolean"==typeof x.enableJsBindingApiThrowException)&&(void 0===x.enableLayoutOnlyEventThrough||"boolean"==typeof x.enableLayoutOnlyEventThrough)&&(void 0===x.enableListNewArchitecture||"boolean"==typeof x.enableListNewArchitecture)&&(void 0===x.enableMouseDragScroll||"boolean"==typeof x.enableMouseDragScroll)&&(void 0===x.enableMultiTouch||"boolean"==typeof x.enableMultiTouch)&&(void 0===x.enableNativeList||"boolean"==typeof x.enableNativeList)&&(void 0===x.enableNewGesture||"boolean"==typeof x.enableNewGesture)&&(void 0===x.enableNewIntersectionObserver||"boolean"==typeof x.enableNewIntersectionObserver)&&(void 0===x.enableNewTransformOrigin||"boolean"==typeof x.enableNewTransformOrigin)&&(void 0===x.enableParseIntFlex||"boolean"==typeof x.enableParseIntFlex)&&(void 0===x.enableReloadLifecycle||"boolean"==typeof x.enableReloadLifecycle)&&(void 0===x.enableSimultaneousTap||"boolean"==typeof x.enableSimultaneousTap)&&(void 0===x.enableTextOverflow||"boolean"==typeof x.enableTextOverflow)&&(void 0===x.enableTransformedTouchPosition||"boolean"==typeof x.enableTransformedTouchPosition)&&(void 0===x.fontScaleEffectiveOnlyOnSp||"boolean"==typeof x.fontScaleEffectiveOnlyOnSp)&&(void 0===x.includeFontPadding||"boolean"==typeof x.includeFontPadding)&&(void 0===x.keyboardCallbackPassRelativeHeight||"boolean"==typeof x.keyboardCallbackPassRelativeHeight)&&(void 0===x.longPressDuration||"number"==typeof x.longPressDuration)&&(void 0===x.removeDescendantSelectorScope||"boolean"==typeof x.removeDescendantSelectorScope)&&(void 0===x.tapSlop||"string"==typeof x.tapSlop)&&(void 0===x.unifyVWVHBehavior||"boolean"==typeof x.unifyVWVHBehavior)&&(0===Object.keys(x).length||Object.keys(x).every(e=>!!["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(x=>e===x)||void 0===x[e])))(x,!0))){var e;e=v=[],d=(x,t)=>(x&&(x=>{if(0===e.length)return!0;let t=e[e.length-1].path;return x.length>t.length||t.substring(0,x.length)!==x})(t.path)&&(void 0===t.value&&(t.description??=`The value at this path is \`undefined\`.
260
+ `;for(let x of a.getEntrypointChunk().files)d.set(x,n)}}o.forEach(t=>{let r=v+(d.get(t.name)??"");if(t.source.source().toString().startsWith(r))return;let a=new x.webpack.sources.ReplaceSource(t.source,t.name);a.insert(0,r),e.updateAsset(t.name,a,t.info)})}function vl(x){let e=r4.posix.basename(x);return"background.js"===e||"main-thread.js"===e||/^background\.[^/]+\.js$/.test(e)||/^main-thread\.[^/]+\.js$/.test(e)}function vc(x){let e=x.replaceAll("\\","/");return e.split("/").some(x=>x.startsWith("__doubao_web__"))&&vl(e)}class vv{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(vv.name,e=>{e.hooks.processAssets.tapPromise({name:vv.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async t=>{await vo({compiler:x,compilation:e,assets:t,...this.options})})})}}let vd="index.web.bundle",vf="base/app.web.bundle",vb="base/client-tool/index.web.bundle";function vu(x){return`__doubao_web__${x.replaceAll("\\","/").replaceAll("/","__")}`}function vp(x,e,t){return e[t]?.id??cz(t,x[t]?.folderName)}function vm(x={},e={}){return Object.fromEntries(Object.entries(x).filter(([x,t])=>t.internal||e[x]?.web))}class vh{apply(x){x.hooks.thisCompilation.tap(vh.name,e=>{e.hooks.processAssets.tapPromise({name:vh.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let t=vE(e,"app"),r=t?e.getAsset(t):void 0;if(!t||!r)throw Error("未生成 Worker 入口产物");await vj(e,x,t,vf);let a=vE(e,iW);a&&await vj(e,x,a,vb)})})}}function vE(x,e){let t=x.entrypoints.get(e)?.getEntrypointChunk();return[...t?.files??[]].find(e=>e.endsWith(".js")&&!x.getAsset(e)?.info?.hotModuleReplacement)}async function vj(x,e,t,r){let a=x.getAsset(t);if(!a)throw Error(`未生成 Worker 入口产物:${t}`);x.emitAsset(r,new e.webpack.sources.RawSource(await vg(a.source.source().toString())));let n=x.getAsset(`${t}.map`);n&&x.emitAsset(`${r}.map`,n.source,n.info),x.deleteAsset(t)}async function vg(x){let{encode:e}=await import("./@lynx-js/web-core.js");return Buffer.from(e({styleInfo:{},manifest:{"/app-service.js":x},cardType:"react",appType:"card",pageConfig:{enableCSSSelector:!0,enableFiberArch:!0,useLepusNG:!0,enableReuseContext:!0,bundleModuleMode:"ReturnByFunction",targetSdkVersion:"3.2"},lepusCode:{root:"void 0;"},customSections:{},elementTemplates:{}}))}class vy{options;isNative;constructor(x,e){this.options=x,this.isNative=e}apply(x){new x.webpack.experiments.VirtualModulesPlugin({[iK]:"",[iQ]:iM,...Object.fromEntries(Object.entries(this.options.entry).map(([,x])=>[x.filename,x.toString()]))}).apply(x),x.hooks.make.tapPromise(vy.name,async x=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(vy.name,e=>{e.hooks.optimizeTree.tapPromise(vy.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies}).catch(x=>e.errors.push(x))}),e.hooks.processAssets.tapPromise({name:vy.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async t=>{var r,a,n;let _,A=vE(e,"app");if(!A||!e.getAsset(A))throw Error("未生成 Worker 入口产物");this.isNative&&(r=e,a=this.options.context,n=A,a.setAppAssetPath(n),_=`${n}.map`,r.getAsset(_)&&a.setAppMapAssetPath(_));let s=vE(e,iW);await vo({compiler:x,compilation:e,assets:t,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),resolveVersionTag:()=>this.options.context.versionTag,isNative:this.isNative,shouldInjectAsset:x=>x===A||x===s})})}),x.hooks.done.tapPromise(vy.name,async x=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:x})})}}let vS=I("process"),vI=I("../../../node_modules/.pnpm/@lynx-js+type-config@4.2.0/node_modules/@lynx-js/type-config/index.js");var vN={},vB={};function vF(x){var e=vB[x];if(void 0!==e)return e.exports;var t=vB[x]={exports:{}};return vN[x](t,t.exports,vF),t.exports}vF.m=vN,vF.n=x=>{var e=x&&x.__esModule?()=>x.default:()=>x;return vF.d(e,{a:e}),e},vF.d=(x,e,t)=>{var r=(e,t)=>{for(var r in e)vF.o(e,r)&&!vF.o(x,r)&&Object.defineProperty(x,r,{enumerable:!0,[t]:e[r]})};r(e,"get"),r(t,"value")},vF.add=function(x){Object.assign(vF.m,x)},vF.o=(x,e)=>Object.prototype.hasOwnProperty.call(x,e),vF.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(x){x.exports=function(x){return null!=x&&"object"==typeof x&&!1===Array.isArray(x)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(x,e,t){var r=t("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");x.exports=function(x,e){if(!r(x)&&"function"!=typeof x)return{};var t={};if("string"==typeof e)return e in x&&(t[e]=x[e]),t;for(var a=e.length,n=-1;++n<a;){var _=e[n];_ in x&&(t[_]=x[_])}return t}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(x){let e=vS||{},t=e.argv||[],r=e.env||{},a=!(r.NO_COLOR||t.includes("--no-color"))&&(!!r.FORCE_COLOR||t.includes("--color")||"win32"===e.platform||(e.stdout||{}).isTTY&&"dumb"!==r.TERM||!!r.CI),n=(x,e,t=x)=>r=>{let a=""+r,n=a.indexOf(e,x.length);return~n?x+_(a,e,t,n)+e:x+a+e},_=(x,e,t,r)=>{let a="",n=0;do a+=x.substring(n,r)+t,n=r+e.length,r=x.indexOf(e,n);while(~r);return a+x.substring(n)},A=(x=a)=>{let e=x?n:()=>String;return{isColorSupported:x,reset:e("\x1b[0m","\x1b[0m"),bold:e("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:e("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:e("\x1b[3m","\x1b[23m"),underline:e("\x1b[4m","\x1b[24m"),inverse:e("\x1b[7m","\x1b[27m"),hidden:e("\x1b[8m","\x1b[28m"),strikethrough:e("\x1b[9m","\x1b[29m"),black:e("\x1b[30m","\x1b[39m"),red:e("\x1b[31m","\x1b[39m"),green:e("\x1b[32m","\x1b[39m"),yellow:e("\x1b[33m","\x1b[39m"),blue:e("\x1b[34m","\x1b[39m"),magenta:e("\x1b[35m","\x1b[39m"),cyan:e("\x1b[36m","\x1b[39m"),white:e("\x1b[37m","\x1b[39m"),gray:e("\x1b[90m","\x1b[39m"),bgBlack:e("\x1b[40m","\x1b[49m"),bgRed:e("\x1b[41m","\x1b[49m"),bgGreen:e("\x1b[42m","\x1b[49m"),bgYellow:e("\x1b[43m","\x1b[49m"),bgBlue:e("\x1b[44m","\x1b[49m"),bgMagenta:e("\x1b[45m","\x1b[49m"),bgCyan:e("\x1b[46m","\x1b[49m"),bgWhite:e("\x1b[47m","\x1b[49m"),blackBright:e("\x1b[90m","\x1b[39m"),redBright:e("\x1b[91m","\x1b[39m"),greenBright:e("\x1b[92m","\x1b[39m"),yellowBright:e("\x1b[93m","\x1b[39m"),blueBright:e("\x1b[94m","\x1b[39m"),magentaBright:e("\x1b[95m","\x1b[39m"),cyanBright:e("\x1b[96m","\x1b[39m"),whiteBright:e("\x1b[97m","\x1b[39m"),bgBlackBright:e("\x1b[100m","\x1b[49m"),bgRedBright:e("\x1b[101m","\x1b[49m"),bgGreenBright:e("\x1b[102m","\x1b[49m"),bgYellowBright:e("\x1b[103m","\x1b[49m"),bgBlueBright:e("\x1b[104m","\x1b[49m"),bgMagentaBright:e("\x1b[105m","\x1b[49m"),bgCyanBright:e("\x1b[106m","\x1b[49m"),bgWhiteBright:e("\x1b[107m","\x1b[49m")}};x.exports=A(),x.exports.createColors=A}});let vw=globalThis.window?.document!==void 0;globalThis.process?.versions?.node,globalThis.process?.versions?.bun,globalThis.Deno?.version?.deno,globalThis.process?.versions?.electron,globalThis.navigator?.userAgent?.includes("jsdom");let vC=globalThis.navigator?.userAgentData?.platform;function vP(x,e=globalThis.Deno?globalThis.Deno.args:q.argv){let t=x.startsWith("-")?"":1===x.length?"-":"--",r=e.indexOf(t+x),a=e.indexOf("--");return -1!==r&&(-1===a||r<a)}"macOS"===vC||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===vC||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===vC||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===vC||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===vC||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,vw||q.env.TERM_PROGRAM,vw||q.platform,vw||q.cwd;let{env:vk}=q;function vD(x,t={}){var r;return 0!==(r=function(x,{streamIsTTY:t,sniffFlags:r=!0}={}){let a=function(){if(!("FORCE_COLOR"in vk))return;if("true"===vk.FORCE_COLOR)return 1;if("false"===vk.FORCE_COLOR)return 0;if(0===vk.FORCE_COLOR.length)return 1;let x=Math.min(Number.parseInt(vk.FORCE_COLOR,10),3);if([0,1,2,3].includes(x))return x}();void 0!==a&&(e=a);let n=r?e:a;if(0===n)return 0;if(r){if(vP("color=16m")||vP("color=full")||vP("color=truecolor"))return 3;if(vP("color=256"))return 2}if("TF_BUILD"in vk&&"AGENT_NAME"in vk)return 1;if(x&&!t&&void 0===n)return 0;let _=n||0;if("dumb"===vk.TERM)return _;if("win32"===q.platform){let x=ib.release().split(".");return Number(x[0])>=10&&Number(x[2])>=10586?Number(x[2])>=14931?3:2:1}if("CI"in vk)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(x=>x in vk)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(x=>x in vk)||"codeship"===vk.CI_NAME?1:_;if("TEAMCITY_VERSION"in vk)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(vk.TEAMCITY_VERSION);if("truecolor"===vk.COLORTERM||"xterm-kitty"===vk.TERM||"xterm-ghostty"===vk.TERM||"wezterm"===vk.TERM)return 3;if("TERM_PROGRAM"in vk){let x=Number.parseInt((vk.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(vk.TERM_PROGRAM){case"iTerm.app":return x>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(vk.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(vk.TERM)||"COLORTERM"in vk?1:_}(x,{streamIsTTY:x&&x.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function vL(x,e=vS.argv){let t=x.startsWith("-")?"":1===x.length?"-":"--",r=e.indexOf(t+x),a=e.indexOf("--");return -1!==r&&(-1===a||r<a)}function vq(x=""){if(/^\d{3,4}$/.test(x)){let e=/(\d{1,2})(\d{2})/.exec(x)??[];return{major:0,minor:Number.parseInt(e[1],10),patch:Number.parseInt(e[2],10)}}let e=(x??"").split(".").map(x=>Number.parseInt(x,10));return{major:e[0],minor:e[1],patch:e[2]}}function vT(x){let{CI:e,CURSOR_TRACE_ID:t,FORCE_HYPERLINK:r,NETLIFY:a,TEAMCITY_VERSION:n,TERM_PROGRAM:_,TERM_PROGRAM_VERSION:A,VTE_VERSION:s,TERM:i}=q.env;if(r)return!(r.length>0&&0===Number.parseInt(r,10));if(vL("no-hyperlink")||vL("no-hyperlinks")||vL("hyperlink=false")||vL("hyperlink=never"))return!1;if(vL("hyperlink=true")||vL("hyperlink=always")||a)return!0;if(!vD(x)||x&&!x.isTTY)return!1;if("WT_SESSION"in q.env)return!0;if("win32"===q.platform||e||n)return!1;if(_){let x=vq(A);switch(_){case"iTerm.app":if(3===x.major)return x.minor>=1;return x.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(A))return A.slice(11)>="2020-06-20";return x.major>=0x1343cac;case"vscode":if(t)return!0;return x.major>1||1===x.major&&x.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(s){if("0.50.0"===s)return!1;let x=vq(s);return x.major>0||x.minor>=50}switch(i){case"alacritty":case"xterm-kitty":return!0}return!1}vP("no-color")||vP("no-colors")||vP("color=false")||vP("color=never")?e=0:(vP("color")||vP("colors")||vP("color=true")||vP("color=always"))&&(e=1),vD({isTTY:L.isatty(1)}),vD({isTTY:L.isatty(2)});let vR={stdout:vT(q.stdout),stderr:vT(q.stderr)};function v$(x,e,{target:t="stdout",...r}={}){return vR[t]?["\x1b]","8",";",";",e,"\x07",x,"\x1b]","8",";",";","\x07"].join(""):!1===r.fallback?x:"function"==typeof r.fallback?r.fallback(x,e):`${x} ${e}`}v$.isSupported=vR.stdout,v$.stderr=(x,e,t={})=>v$(x,e,{target:"stderr",...t}),v$.stderr.isSupported=vR.stderr;let vG=vF("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var vO=vF.n(vG);class vX{options;constructor(x){this.options=x}name="LynxConfigWebpackPlugin";apply(x){x.hooks.thisCompilation.tap(this.name,x=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(x).beforeEncode.tap(this.name,x=>{let{config:e}=this.options;return x.encodeData.compilerOptions={...x.encodeData.compilerOptions,...vO()(e,this.options.compilerOptionsKeys)},x.encodeData.sourceContent.config={...x.encodeData.sourceContent.config,...vO()(e,this.options.configKeys)},x})})}}let vK=x=>vQ.has(x),vQ=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with"]);(rO=rY||(rY={}))[rO.Start=0]="Start",rO[rO.Property=1]="Property",rO[rO.StringKey=2]="StringKey",rO[rO.NumberKey=3]="NumberKey";let vM=vF("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var vZ=vF.n(vM);let vJ=Object.assign(f=x=>{if(!1===("object"==typeof x&&null!==x&&!1===Array.isArray(x)&&((x,e=!0)=>(void 0===x.alignMouseEventWithW3C||"boolean"==typeof x.alignMouseEventWithW3C)&&(void 0===x.disableLongpressAfterScroll||"boolean"==typeof x.disableLongpressAfterScroll)&&(void 0===x.enableA11y||"boolean"==typeof x.enableA11y)&&(void 0===x.enableAccessibilityElement||"boolean"==typeof x.enableAccessibilityElement)&&(void 0===x.enableCSSInheritance||"boolean"==typeof x.enableCSSInheritance)&&(void 0===x.enableCSSInlineVariables||"boolean"==typeof x.enableCSSInlineVariables)&&(void 0===x.enableCSSRule||"boolean"==typeof x.enableCSSRule)&&(void 0===x.enableEndGestureAtLastFingerUp||"boolean"==typeof x.enableEndGestureAtLastFingerUp)&&(void 0===x.enableEventHandleRefactor||"boolean"==typeof x.enableEventHandleRefactor)&&(void 0===x.enableEventThrough||"boolean"==typeof x.enableEventThrough)&&(void 0===x.enableEventThroughInheritFromPage||"boolean"==typeof x.enableEventThroughInheritFromPage)&&(void 0===x.enableFetchAPIStandardStreaming||"boolean"==typeof x.enableFetchAPIStandardStreaming)&&(void 0===x.enableFixedNew||"boolean"==typeof x.enableFixedNew)&&(void 0===x.enableFlexBasisZeroPercent||"boolean"==typeof x.enableFlexBasisZeroPercent)&&(void 0===x.enableGridPlacementShorthands||"boolean"==typeof x.enableGridPlacementShorthands)&&(void 0===x.enableJsBindingApiThrowException||"boolean"==typeof x.enableJsBindingApiThrowException)&&(void 0===x.enableLayoutOnlyEventThrough||"boolean"==typeof x.enableLayoutOnlyEventThrough)&&(void 0===x.enableListNewArchitecture||"boolean"==typeof x.enableListNewArchitecture)&&(void 0===x.enableMouseDragScroll||"boolean"==typeof x.enableMouseDragScroll)&&(void 0===x.enableMultiTouch||"boolean"==typeof x.enableMultiTouch)&&(void 0===x.enableNativeList||"boolean"==typeof x.enableNativeList)&&(void 0===x.enableNewGesture||"boolean"==typeof x.enableNewGesture)&&(void 0===x.enableNewIntersectionObserver||"boolean"==typeof x.enableNewIntersectionObserver)&&(void 0===x.enableNewTransformOrigin||"boolean"==typeof x.enableNewTransformOrigin)&&(void 0===x.enableParseIntFlex||"boolean"==typeof x.enableParseIntFlex)&&(void 0===x.enableReloadLifecycle||"boolean"==typeof x.enableReloadLifecycle)&&(void 0===x.enableSimultaneousTap||"boolean"==typeof x.enableSimultaneousTap)&&(void 0===x.enableTextOverflow||"boolean"==typeof x.enableTextOverflow)&&(void 0===x.enableTransformedTouchPosition||"boolean"==typeof x.enableTransformedTouchPosition)&&(void 0===x.fontScaleEffectiveOnlyOnSp||"boolean"==typeof x.fontScaleEffectiveOnlyOnSp)&&(void 0===x.includeFontPadding||"boolean"==typeof x.includeFontPadding)&&(void 0===x.keyboardCallbackPassRelativeHeight||"boolean"==typeof x.keyboardCallbackPassRelativeHeight)&&(void 0===x.longPressDuration||"number"==typeof x.longPressDuration)&&(void 0===x.removeDescendantSelectorScope||"boolean"==typeof x.removeDescendantSelectorScope)&&(void 0===x.tapSlop||"string"==typeof x.tapSlop)&&(void 0===x.unifyVWVHBehavior||"boolean"==typeof x.unifyVWVHBehavior)&&(0===Object.keys(x).length||Object.keys(x).every(e=>!!["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(x=>e===x)||void 0===x[e])))(x,!0))){var e;e=v=[],d=(x,t)=>(x&&(x=>{if(0===e.length)return!0;let t=e[e.length-1].path;return x.length>t.length||t.substring(0,x.length)!==x})(t.path)&&(void 0===t.value&&(t.description??=`The value at this path is \`undefined\`.
261
261
 
262
- Please fill the \`${t.expected}\` typed value next time.`),e.push(t)),!1),((x,e,t=!0)=>("object"==typeof x&&null!==x&&!1===Array.isArray(x)||d(!0,{path:e+"",expected:"Config",value:x}))&&((x,e,t=!0)=>[void 0===x.alignMouseEventWithW3C||"boolean"==typeof x.alignMouseEventWithW3C||d(t,{path:e+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:x.alignMouseEventWithW3C}),void 0===x.disableLongpressAfterScroll||"boolean"==typeof x.disableLongpressAfterScroll||d(t,{path:e+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:x.disableLongpressAfterScroll}),void 0===x.enableA11y||"boolean"==typeof x.enableA11y||d(t,{path:e+".enableA11y",expected:"(boolean | undefined)",value:x.enableA11y}),void 0===x.enableAccessibilityElement||"boolean"==typeof x.enableAccessibilityElement||d(t,{path:e+".enableAccessibilityElement",expected:"(boolean | undefined)",value:x.enableAccessibilityElement}),void 0===x.enableCSSInheritance||"boolean"==typeof x.enableCSSInheritance||d(t,{path:e+".enableCSSInheritance",expected:"(boolean | undefined)",value:x.enableCSSInheritance}),void 0===x.enableCSSInlineVariables||"boolean"==typeof x.enableCSSInlineVariables||d(t,{path:e+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:x.enableCSSInlineVariables}),void 0===x.enableCSSRule||"boolean"==typeof x.enableCSSRule||d(t,{path:e+".enableCSSRule",expected:"(boolean | undefined)",value:x.enableCSSRule}),void 0===x.enableEndGestureAtLastFingerUp||"boolean"==typeof x.enableEndGestureAtLastFingerUp||d(t,{path:e+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:x.enableEndGestureAtLastFingerUp}),void 0===x.enableEventHandleRefactor||"boolean"==typeof x.enableEventHandleRefactor||d(t,{path:e+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:x.enableEventHandleRefactor}),void 0===x.enableEventThrough||"boolean"==typeof x.enableEventThrough||d(t,{path:e+".enableEventThrough",expected:"(boolean | undefined)",value:x.enableEventThrough}),void 0===x.enableEventThroughInheritFromPage||"boolean"==typeof x.enableEventThroughInheritFromPage||d(t,{path:e+".enableEventThroughInheritFromPage",expected:"(boolean | undefined)",value:x.enableEventThroughInheritFromPage}),void 0===x.enableFetchAPIStandardStreaming||"boolean"==typeof x.enableFetchAPIStandardStreaming||d(t,{path:e+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:x.enableFetchAPIStandardStreaming}),void 0===x.enableFixedNew||"boolean"==typeof x.enableFixedNew||d(t,{path:e+".enableFixedNew",expected:"(boolean | undefined)",value:x.enableFixedNew}),void 0===x.enableFlexBasisZeroPercent||"boolean"==typeof x.enableFlexBasisZeroPercent||d(t,{path:e+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:x.enableFlexBasisZeroPercent}),void 0===x.enableGridPlacementShorthands||"boolean"==typeof x.enableGridPlacementShorthands||d(t,{path:e+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:x.enableGridPlacementShorthands}),void 0===x.enableJsBindingApiThrowException||"boolean"==typeof x.enableJsBindingApiThrowException||d(t,{path:e+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:x.enableJsBindingApiThrowException}),void 0===x.enableLayoutOnlyEventThrough||"boolean"==typeof x.enableLayoutOnlyEventThrough||d(t,{path:e+".enableLayoutOnlyEventThrough",expected:"(boolean | undefined)",value:x.enableLayoutOnlyEventThrough}),void 0===x.enableListNewArchitecture||"boolean"==typeof x.enableListNewArchitecture||d(t,{path:e+".enableListNewArchitecture",expected:"(boolean | undefined)",value:x.enableListNewArchitecture}),void 0===x.enableMouseDragScroll||"boolean"==typeof x.enableMouseDragScroll||d(t,{path:e+".enableMouseDragScroll",expected:"(boolean | undefined)",value:x.enableMouseDragScroll}),void 0===x.enableMultiTouch||"boolean"==typeof x.enableMultiTouch||d(t,{path:e+".enableMultiTouch",expected:"(boolean | undefined)",value:x.enableMultiTouch}),void 0===x.enableNativeList||"boolean"==typeof x.enableNativeList||d(t,{path:e+".enableNativeList",expected:"(boolean | undefined)",value:x.enableNativeList}),void 0===x.enableNewGesture||"boolean"==typeof x.enableNewGesture||d(t,{path:e+".enableNewGesture",expected:"(boolean | undefined)",value:x.enableNewGesture}),void 0===x.enableNewIntersectionObserver||"boolean"==typeof x.enableNewIntersectionObserver||d(t,{path:e+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:x.enableNewIntersectionObserver}),void 0===x.enableNewTransformOrigin||"boolean"==typeof x.enableNewTransformOrigin||d(t,{path:e+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:x.enableNewTransformOrigin}),void 0===x.enableParseIntFlex||"boolean"==typeof x.enableParseIntFlex||d(t,{path:e+".enableParseIntFlex",expected:"(boolean | undefined)",value:x.enableParseIntFlex}),void 0===x.enableReloadLifecycle||"boolean"==typeof x.enableReloadLifecycle||d(t,{path:e+".enableReloadLifecycle",expected:"(boolean | undefined)",value:x.enableReloadLifecycle}),void 0===x.enableSimultaneousTap||"boolean"==typeof x.enableSimultaneousTap||d(t,{path:e+".enableSimultaneousTap",expected:"(boolean | undefined)",value:x.enableSimultaneousTap}),void 0===x.enableTextOverflow||"boolean"==typeof x.enableTextOverflow||d(t,{path:e+".enableTextOverflow",expected:"(boolean | undefined)",value:x.enableTextOverflow}),void 0===x.enableTransformedTouchPosition||"boolean"==typeof x.enableTransformedTouchPosition||d(t,{path:e+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:x.enableTransformedTouchPosition}),void 0===x.fontScaleEffectiveOnlyOnSp||"boolean"==typeof x.fontScaleEffectiveOnlyOnSp||d(t,{path:e+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:x.fontScaleEffectiveOnlyOnSp}),void 0===x.includeFontPadding||"boolean"==typeof x.includeFontPadding||d(t,{path:e+".includeFontPadding",expected:"(boolean | undefined)",value:x.includeFontPadding}),void 0===x.keyboardCallbackPassRelativeHeight||"boolean"==typeof x.keyboardCallbackPassRelativeHeight||d(t,{path:e+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:x.keyboardCallbackPassRelativeHeight}),void 0===x.longPressDuration||"number"==typeof x.longPressDuration||d(t,{path:e+".longPressDuration",expected:"(number | undefined)",value:x.longPressDuration}),void 0===x.removeDescendantSelectorScope||"boolean"==typeof x.removeDescendantSelectorScope||d(t,{path:e+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:x.removeDescendantSelectorScope}),void 0===x.tapSlop||"string"==typeof x.tapSlop||d(t,{path:e+".tapSlop",expected:"(string | undefined)",value:x.tapSlop}),void 0===x.unifyVWVHBehavior||"boolean"==typeof x.unifyVWVHBehavior||d(t,{path:e+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:x.unifyVWVHBehavior}),0===Object.keys(x).length||!1===t||Object.keys(x).map(r=>{let a;if(["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(x=>r===x))return!0;let n=x[r];if(void 0===n)return!0;return d(t,{path:e+(!1===vG(a=r)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(a)?`.${r}`:`[${JSON.stringify(r)}]`),expected:"undefined",value:n,description:`The property \`${r}\` is not defined in the object type.
262
+ Please fill the \`${t.expected}\` typed value next time.`),e.push(t)),!1),((x,e,t=!0)=>("object"==typeof x&&null!==x&&!1===Array.isArray(x)||d(!0,{path:e+"",expected:"Config",value:x}))&&((x,e,t=!0)=>[void 0===x.alignMouseEventWithW3C||"boolean"==typeof x.alignMouseEventWithW3C||d(t,{path:e+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:x.alignMouseEventWithW3C}),void 0===x.disableLongpressAfterScroll||"boolean"==typeof x.disableLongpressAfterScroll||d(t,{path:e+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:x.disableLongpressAfterScroll}),void 0===x.enableA11y||"boolean"==typeof x.enableA11y||d(t,{path:e+".enableA11y",expected:"(boolean | undefined)",value:x.enableA11y}),void 0===x.enableAccessibilityElement||"boolean"==typeof x.enableAccessibilityElement||d(t,{path:e+".enableAccessibilityElement",expected:"(boolean | undefined)",value:x.enableAccessibilityElement}),void 0===x.enableCSSInheritance||"boolean"==typeof x.enableCSSInheritance||d(t,{path:e+".enableCSSInheritance",expected:"(boolean | undefined)",value:x.enableCSSInheritance}),void 0===x.enableCSSInlineVariables||"boolean"==typeof x.enableCSSInlineVariables||d(t,{path:e+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:x.enableCSSInlineVariables}),void 0===x.enableCSSRule||"boolean"==typeof x.enableCSSRule||d(t,{path:e+".enableCSSRule",expected:"(boolean | undefined)",value:x.enableCSSRule}),void 0===x.enableEndGestureAtLastFingerUp||"boolean"==typeof x.enableEndGestureAtLastFingerUp||d(t,{path:e+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:x.enableEndGestureAtLastFingerUp}),void 0===x.enableEventHandleRefactor||"boolean"==typeof x.enableEventHandleRefactor||d(t,{path:e+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:x.enableEventHandleRefactor}),void 0===x.enableEventThrough||"boolean"==typeof x.enableEventThrough||d(t,{path:e+".enableEventThrough",expected:"(boolean | undefined)",value:x.enableEventThrough}),void 0===x.enableEventThroughInheritFromPage||"boolean"==typeof x.enableEventThroughInheritFromPage||d(t,{path:e+".enableEventThroughInheritFromPage",expected:"(boolean | undefined)",value:x.enableEventThroughInheritFromPage}),void 0===x.enableFetchAPIStandardStreaming||"boolean"==typeof x.enableFetchAPIStandardStreaming||d(t,{path:e+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:x.enableFetchAPIStandardStreaming}),void 0===x.enableFixedNew||"boolean"==typeof x.enableFixedNew||d(t,{path:e+".enableFixedNew",expected:"(boolean | undefined)",value:x.enableFixedNew}),void 0===x.enableFlexBasisZeroPercent||"boolean"==typeof x.enableFlexBasisZeroPercent||d(t,{path:e+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:x.enableFlexBasisZeroPercent}),void 0===x.enableGridPlacementShorthands||"boolean"==typeof x.enableGridPlacementShorthands||d(t,{path:e+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:x.enableGridPlacementShorthands}),void 0===x.enableJsBindingApiThrowException||"boolean"==typeof x.enableJsBindingApiThrowException||d(t,{path:e+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:x.enableJsBindingApiThrowException}),void 0===x.enableLayoutOnlyEventThrough||"boolean"==typeof x.enableLayoutOnlyEventThrough||d(t,{path:e+".enableLayoutOnlyEventThrough",expected:"(boolean | undefined)",value:x.enableLayoutOnlyEventThrough}),void 0===x.enableListNewArchitecture||"boolean"==typeof x.enableListNewArchitecture||d(t,{path:e+".enableListNewArchitecture",expected:"(boolean | undefined)",value:x.enableListNewArchitecture}),void 0===x.enableMouseDragScroll||"boolean"==typeof x.enableMouseDragScroll||d(t,{path:e+".enableMouseDragScroll",expected:"(boolean | undefined)",value:x.enableMouseDragScroll}),void 0===x.enableMultiTouch||"boolean"==typeof x.enableMultiTouch||d(t,{path:e+".enableMultiTouch",expected:"(boolean | undefined)",value:x.enableMultiTouch}),void 0===x.enableNativeList||"boolean"==typeof x.enableNativeList||d(t,{path:e+".enableNativeList",expected:"(boolean | undefined)",value:x.enableNativeList}),void 0===x.enableNewGesture||"boolean"==typeof x.enableNewGesture||d(t,{path:e+".enableNewGesture",expected:"(boolean | undefined)",value:x.enableNewGesture}),void 0===x.enableNewIntersectionObserver||"boolean"==typeof x.enableNewIntersectionObserver||d(t,{path:e+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:x.enableNewIntersectionObserver}),void 0===x.enableNewTransformOrigin||"boolean"==typeof x.enableNewTransformOrigin||d(t,{path:e+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:x.enableNewTransformOrigin}),void 0===x.enableParseIntFlex||"boolean"==typeof x.enableParseIntFlex||d(t,{path:e+".enableParseIntFlex",expected:"(boolean | undefined)",value:x.enableParseIntFlex}),void 0===x.enableReloadLifecycle||"boolean"==typeof x.enableReloadLifecycle||d(t,{path:e+".enableReloadLifecycle",expected:"(boolean | undefined)",value:x.enableReloadLifecycle}),void 0===x.enableSimultaneousTap||"boolean"==typeof x.enableSimultaneousTap||d(t,{path:e+".enableSimultaneousTap",expected:"(boolean | undefined)",value:x.enableSimultaneousTap}),void 0===x.enableTextOverflow||"boolean"==typeof x.enableTextOverflow||d(t,{path:e+".enableTextOverflow",expected:"(boolean | undefined)",value:x.enableTextOverflow}),void 0===x.enableTransformedTouchPosition||"boolean"==typeof x.enableTransformedTouchPosition||d(t,{path:e+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:x.enableTransformedTouchPosition}),void 0===x.fontScaleEffectiveOnlyOnSp||"boolean"==typeof x.fontScaleEffectiveOnlyOnSp||d(t,{path:e+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:x.fontScaleEffectiveOnlyOnSp}),void 0===x.includeFontPadding||"boolean"==typeof x.includeFontPadding||d(t,{path:e+".includeFontPadding",expected:"(boolean | undefined)",value:x.includeFontPadding}),void 0===x.keyboardCallbackPassRelativeHeight||"boolean"==typeof x.keyboardCallbackPassRelativeHeight||d(t,{path:e+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:x.keyboardCallbackPassRelativeHeight}),void 0===x.longPressDuration||"number"==typeof x.longPressDuration||d(t,{path:e+".longPressDuration",expected:"(number | undefined)",value:x.longPressDuration}),void 0===x.removeDescendantSelectorScope||"boolean"==typeof x.removeDescendantSelectorScope||d(t,{path:e+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:x.removeDescendantSelectorScope}),void 0===x.tapSlop||"string"==typeof x.tapSlop||d(t,{path:e+".tapSlop",expected:"(string | undefined)",value:x.tapSlop}),void 0===x.unifyVWVHBehavior||"boolean"==typeof x.unifyVWVHBehavior||d(t,{path:e+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:x.unifyVWVHBehavior}),0===Object.keys(x).length||!1===t||Object.keys(x).map(r=>{let a;if(["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableEventThroughInheritFromPage","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableLayoutOnlyEventThrough","enableListNewArchitecture","enableMouseDragScroll","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(x=>r===x))return!0;let n=x[r];if(void 0===n)return!0;return d(t,{path:e+(!1===vK(a=r)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(a)?`.${r}`:`[${JSON.stringify(r)}]`),expected:"undefined",value:n,description:`The property \`${r}\` is not defined in the object type.
263
263
 
264
- Please remove the property next time.`})}).every(x=>x)].every(x=>x))(x,e+"",!0)||d(!0,{path:e+"",expected:"Config",value:x}))(x,"$input",!0);let t=0===v.length;return t?{success:t,data:x}:{success:t,errors:v,data:x}}return{success:!0,data:x}},{"~standard":{version:1,vendor:"typia",validate:x=>{let e=f(x);return e.success?{value:e.data}:{issues:e.errors.map(x=>({message:`expected ${x.expected}, got ${x.value}`,path:(x=>{if(!x.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(x)}`);let e=[],t="",r=rY.Start,a=5;for(;a<x.length-1;){let n=x[++a];if(r===rY.Property?"."===n||"["===n?(e.push({key:t}),r=rY.Start):a===x.length-1?(t+=n,e.push({key:t}),a++,r=rY.Start):t+=n:r===rY.StringKey?'"'===n?(e.push({key:JSON.parse(t+n)}),a+=2,r=rY.Start):"\\"===n?(t+=x[a],t+=x[++a]):t+=n:r===rY.NumberKey&&("]"===n?(e.push({key:Number.parseInt(t)}),a++,r=rY.Start):t+=n),r===rY.Start&&a<x.length-1){let e=x[a];if(t="","["===e)'"'===x[a+1]?(r=rY.StringKey,a++,t='"'):r=rY.NumberKey;else if("."===e)r=rY.Property;else throw Error("Unreachable: pointer points invalid character")}}if(r!==rY.Start)throw Error(`Failed to parse path: ${JSON.stringify(x)}`);return e})(x.path)}))}}}});function vM(x){let e=vQ(x);if(e.success)return e.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(e.errors.flatMap(({expected:x,path:e,value:t})=>{var r;return"undefined"===x?[` Unsupported configuration: \`${vK().red(e)}\``,""]:[`Invalid config on \`${vK().red(e)}\`.`,` - Expect to be ${vK().green(x)}`,` - Got: ${vK().red((r=t,Object.prototype.toString.call(r).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let vZ={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function vJ(x){return`${x??"lynx"}[Symbol.for('__LYNX_EXTERNAL_GLOBAL__')]`}class vV{options;constructor(x){for(let[e,t]of(this.options=x,Object.entries(this.options.externals)))if(!t.url&&!t.bundlePath)throw Error(`ExternalsLoadingPlugin requires \`url\` or \`bundlePath\` for external "${e}".`)}apply(x){let{RuntimeModule:e}=x.webpack,t=this.options,r=t.externals??{};class a extends e{runtimeRequirements;options;constructor(x,t){super("externals-loading-runtime",e.STAGE_TRIGGER),this.runtimeRequirements=x,this.options=t,this.runtimeRequirements=x}generate(){return this.chunk?.name&&r?this.#xF(this.options.layer):""}#xF(e){let a,n=new Map,_=new Map,A=new Set,s=new Map;if(e===t.backgroundLayer)a="background";else{if(e!==t.mainThreadLayer)return"";a="mainThread"}let i="mainThread"===a;for(let[x,e]of Object.entries(r))s.set(e.libraryName??x,e);let o=Array.from(s.entries());if(0===o.length)return"";let l=vJ(t.globalObject),c=`${l} = ${l} === undefined ? {} : ${l};`,v=`
264
+ Please remove the property next time.`})}).every(x=>x)].every(x=>x))(x,e+"",!0)||d(!0,{path:e+"",expected:"Config",value:x}))(x,"$input",!0);let t=0===v.length;return t?{success:t,data:x}:{success:t,errors:v,data:x}}return{success:!0,data:x}},{"~standard":{version:1,vendor:"typia",validate:x=>{let e=f(x);return e.success?{value:e.data}:{issues:e.errors.map(x=>({message:`expected ${x.expected}, got ${x.value}`,path:(x=>{if(!x.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(x)}`);let e=[],t="",r=rY.Start,a=5;for(;a<x.length-1;){let n=x[++a];if(r===rY.Property?"."===n||"["===n?(e.push({key:t}),r=rY.Start):a===x.length-1?(t+=n,e.push({key:t}),a++,r=rY.Start):t+=n:r===rY.StringKey?'"'===n?(e.push({key:JSON.parse(t+n)}),a+=2,r=rY.Start):"\\"===n?(t+=x[a],t+=x[++a]):t+=n:r===rY.NumberKey&&("]"===n?(e.push({key:Number.parseInt(t)}),a++,r=rY.Start):t+=n),r===rY.Start&&a<x.length-1){let e=x[a];if(t="","["===e)'"'===x[a+1]?(r=rY.StringKey,a++,t='"'):r=rY.NumberKey;else if("."===e)r=rY.Property;else throw Error("Unreachable: pointer points invalid character")}}if(r!==rY.Start)throw Error(`Failed to parse path: ${JSON.stringify(x)}`);return e})(x.path)}))}}}});function vV(x){let e=vJ(x);if(e.success)return e.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(e.errors.flatMap(({expected:x,path:e,value:t})=>{var r;return"undefined"===x?[` Unsupported configuration: \`${vZ().red(e)}\``,""]:[`Invalid config on \`${vZ().red(e)}\`.`,` - Expect to be ${vZ().green(x)}`,` - Got: ${vZ().red((r=t,Object.prototype.toString.call(r).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let vH={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function vU(x){return`${x??"lynx"}[Symbol.for('__LYNX_EXTERNAL_GLOBAL__')]`}class vY{options;constructor(x){for(let[e,t]of(this.options=x,Object.entries(this.options.externals)))if(!t.url&&!t.bundlePath)throw Error(`ExternalsLoadingPlugin requires \`url\` or \`bundlePath\` for external "${e}".`)}apply(x){let{RuntimeModule:e}=x.webpack,t=this.options,r=t.externals??{};class a extends e{runtimeRequirements;options;constructor(x,t){super("externals-loading-runtime",e.STAGE_TRIGGER),this.runtimeRequirements=x,this.options=t,this.runtimeRequirements=x}generate(){return this.chunk?.name&&r?this.#xF(this.options.layer):""}#xF(e){let a,n=new Map,_=new Map,A=new Set,s=new Map;if(e===t.backgroundLayer)a="background";else{if(e!==t.mainThreadLayer)return"";a="mainThread"}let i="mainThread"===a;for(let[x,e]of Object.entries(r))s.set(e.libraryName??x,e);let o=Array.from(s.entries());if(0===o.length)return"";let l=vU(t.globalObject),c=`${l} = ${l} === undefined ? {} : ${l};`,v=`
265
265
  function createRetryingHandler(fetchBundle, retries) {
266
266
  let cachedResponse = null
267
267
  let asyncPromise = null
@@ -360,28 +360,28 @@ function createLoadExternalSync(handler, sectionPath, timeout) {
360
360
  throw new Error('Failed to fetch external source ' + response.url + ' . The response is ' + JSON.stringify(response), { cause: response })
361
361
  }
362
362
  }
363
- `,d=new Set,f=new Map;for(let[e,r]of o){let{libraryName:s,url:i,bundlePath:o,async:l=!0,timeout:c=t.timeout??2e3,retries:v=t.retries??0}=r,b=r[a],u=c/1e3;if(!b?.sectionPath)continue;let p=s??e,m=Array.isArray(p)?p[0]:p,h=o?{...r,bundlePath:o.replace(/^\/+/,"")}:r,E=i??`bundlePath:${h.bundlePath}`,j=`${E}-${m}`;if(d.has(j))continue;d.add(j);let g=h.url?JSON.stringify(h.url):`${x.webpack.RuntimeGlobals.publicPath} + ${JSON.stringify(h.bundlePath)}`;n.set(E,`() => lynx.fetchBundle(${g}, {})`),_.set(E,Math.max(_.get(E)??0,v));let y=`${vJ(t.globalObject)}[${JSON.stringify(m)}]`,S=`${E}||${b.sectionPath}||${l}`,I=f.get(S);if(void 0!==I){A.add(`${y} = ${y} === undefined ? ${I} : ${y};`);continue}f.set(S,y);let N=[...n.keys()].indexOf(E);if(l){A.add(`${y} = ${y} === undefined ? createLoadExternalAsync(handler${N}, ${JSON.stringify(b.sectionPath)}) : ${y};`);continue}A.add(`${y} = ${y} === undefined ? createLoadExternalSync(handler${N}, ${JSON.stringify(b.sectionPath)}, ${u}) : ${y};`)}return[c,v,...[...n.entries()].map(([x,e],t)=>`const handler${t} = createRetryingHandler(${e}, ${_.get(x)??0});`),...A].join("\n")}}x.hooks.environment.tap(vV.name,()=>{x.options.externals=[...Array.isArray(x.options.externals)?x.options.externals:void 0===x.options.externals?[]:[x.options.externals],this.#xw(t.globalObject)]}),x.hooks.compilation.tap(a.name,e=>{e.hooks.additionalTreeRuntimeRequirements.tap(a.name,(t,r)=>{let n;for(let x of e.chunkGraph.getChunkModulesIterable(t))if(x.layer){n=x.layer;break}n&&(r.add(x.webpack.RuntimeGlobals.publicPath),e.addRuntimeModule(t,new a(r,{layer:n})))})})}#xw(x){let{externals:e,backgroundLayer:t,mainThreadLayer:r}=this.options,a=new Set(Object.keys(e));return({request:n,contextInfo:_},A)=>{let s=_?.issuerLayer===r?"mainThread":_?.issuerLayer===t?"background":void 0;if(n&&a.has(n)&&s&&e[n]?.[s]){let t=e[n]?.async??!0,r=e[n]?.libraryName??n,a=Array.isArray(r)?r:[r];if(t){let e=`${vJ(x)}[${JSON.stringify(a[0])}]`,t=a.slice(1).map(x=>`[${JSON.stringify(x)}]`).join("");return A(void 0,t?`Promise.resolve(${e}).then(function (m) { return m${t}; })`:e,"promise")}return A(void 0,[vJ(x),...a],void 0)}A()}}}let vH=(0,k.createRequire)(import.meta.url),vU={react:{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react":{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/internal":{libraryName:["ReactLynx","ReactInternal"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-runtime":{libraryName:["ReactLynx","ReactJSXRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXLepusDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-runtime":{libraryName:["ReactLynx","ReactJSXLepusRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/experimental/lazy/import":{libraryName:["ReactLynx","ReactLazyImport"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/legacy-react-runtime":{libraryName:["ReactLynx","ReactLegacyRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/runtime-components":{libraryName:["ReactLynx","ReactComponents"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/worklet-runtime/bindings":{libraryName:["ReactLynx","ReactWorkletRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/debug":{libraryName:["ReactLynx","ReactDebug"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/refresh":{libraryName:["ReactLynx","ReactRefresh"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},preact:{libraryName:["ReactLynx","Preact"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1}};function vY(x){return x?new Map(x instanceof Map?x:Object.entries(x)):new Map}let vz=v1();function vW(x){if(x)return!0===x?{}:x}function v0(x){return x.replace(/^\/+/,"")}function v1(){return{reactlynx:{resolveExternals:(x,e)=>{var t,r;let a;return t=vW(x),r=v2(e),a=t?.url?{url:t.url}:{bundlePath:v6(t,r)},Object.fromEntries(Object.entries(vU).map(([x,e])=>[x,{...e,...t?.async===void 0?{}:{async:t.async},...a}]))},resolveManagedAssets(x,e){let t=vW(x);if(!t||t.url)return new Map;let r=v2(e);return new Map([[v6(t,r),function(x,e,t){let r="production"===process.env.NODE_ENV?"prod":"dev",a=`${e}/${r}${t?"-web":""}`;try{return vH.resolve(a,{paths:[x]})}catch{throw Error(`external-bundle-rsbuild-plugin requires \`${a}\` when \`externalsPresets.reactlynx\` is enabled. Install a compatible \`${e}\` into your devDependencies.`)}}(e.rootPath,t.reactUmdPackageName??"@lynx-js/react-umd",r)]])}}}}function v2(x){let e=x.environmentName;return void 0!==e&&"lynx"!==e&&!e.startsWith("lynx-")}class v3{assets;constructor(x){this.assets=x}apply(x){x.hooks.thisCompilation.tap(v3.name,e=>{e.hooks.processAssets.tap({name:v3.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},()=>{let{RawSource:t}=x.webpack.sources;for(let[x,r]of this.assets)if(!e.getAsset(x)){if(!(0,r5.existsSync)(r))throw Error(`external-bundle-rsbuild-plugin could not find local bundle \`${r}\` for emitted asset \`${x}\`.`);e.emitAsset(x,new t((0,r5.readFileSync)(r),!1))}})})}}function v6(x,e){return x?.bundlePath?v0(x.bundlePath):e?"react.web.bundle":"react.lynx.bundle"}function v4(x,e){return"string"!=typeof e?e:{bundlePath:e,libraryName:x,background:{sectionPath:x},mainThread:{sectionPath:`${x}__main-thread`},async:!0}}function v5(x){return{name:"lynx:external-bundle",setup(e){let t,r=function(x){let e={...v1()};for(let[t,r]of Object.entries(x??{})){let x=vz[t];e[t]=x?function(x,e){return{extends:[...x.extends?Array.isArray(x.extends)?x.extends:[x.extends]:[],...e.extends?Array.isArray(e.extends)?e.extends:[e.extends]:[]],resolveExternals:(t,r)=>({...x.resolveExternals?.(t,r)??{},...e.resolveExternals?.(t,r)??{}}),resolveManagedAssets(t,r){let a=vY(x.resolveManagedAssets?.(t,r));for(let[x,n]of vY(e.resolveManagedAssets?.(t,r)))a.set(x,n);return a}}}(x,r):r}return e}(x.externalsPresetDefinitions),a=new Map;e.modifyRsbuildConfig((e,{mergeRsbuildConfig:r})=>(t=e.server?.base,void 0===x.externals&&void 0===x.externalsPresets)?e:r(e,{server:{setup:({server:x,action:e})=>{"dev"===e&&x.middlewares.use((x,e,t)=>{let r=x.url?a.get(x.url):void 0;if(r&&(0,r5.existsSync)(r)){e.setHeader("Content-Type","application/octet-stream"),e.setHeader("Access-Control-Allow-Origin","*");let x=(0,r5.createReadStream)(r);x.on("error",()=>{e.headersSent||(e.statusCode=404),e.end()}),x.pipe(e);return}t()})}}})),e.modifyRspackConfig((n,{environment:_})=>{let A=e.useExposed(Symbol.for("LAYERS"));if(!A)throw Error("external-bundle-rsbuild-plugin requires exposed `LAYERS`. Please install a DSL plugin, for example `pluginReactLynx` for ReactLynx.");let s=function(x,e,t){let r={},a=new Map;for(let[n,_]of Object.entries(x??{})){if(!_)continue;let x=function x(e,t,r,a,n){let _=r[e];if(!_)throw Error(`Unknown externals preset "${e}". Define it in \`externalsPresetDefinitions\` before enabling it in \`externalsPresets\`.`);if(a.includes(e))throw Error(`Circular externals preset dependency detected: ${[...a,e].join(" -> ")}`);let A={},s=new Map,i=[...a,e];for(let e of _.extends?Array.isArray(_.extends)?_.extends:[_.extends]:[]){let t=x(e,!0,r,i,n);for(let[x,e]of(Object.assign(A,t.externals),t.managedAssets))s.set(x,e)}for(let[x,e]of(Object.assign(A,_.resolveExternals?.(t,n)??{}),vY(_.resolveManagedAssets?.(t,n))))s.set(x,e);return{externals:A,managedAssets:s}}(n,_,e,[],t);for(let[e,t]of(Object.assign(r,x.externals),x.managedAssets))a.set(e,t)}return{externals:r,managedAssets:a}}(x.externalsPresets,r,{rootPath:e.context.rootPath,environmentName:_.name}),i=function(x){if(!x)return{};for(let[e,t]of Object.entries(x)){let x=v4(e,t);if(!x.url&&!x.bundlePath)throw Error(`external-bundle-rsbuild-plugin requires \`url\` or \`bundlePath\` for external "${e}".`)}return Object.fromEntries(Object.entries(x).map(([x,e])=>[x,v4(x,e)]))}(x.externals),o={...s.externals,...i},l=function(x,e,t){let r=new Map(e),a=r4.resolve(t.context.rootPath,x.externalBundleRoot??"dist-external-bundle");for(let[e,t]of Object.entries(x.externals??{})){let x=v4(e,t);!x.url&&x.bundlePath&&r.set(v0(x.bundlePath),r4.resolve(a,v0(x.bundlePath)))}return r}(x,s.managedAssets,e);for(let[x,e]of l)a.set(function(x,e){let t=x??"/",r=v0(e);if("/"===t)return`/${r}`;if(/^[a-z][a-z\d+\-.]*:/i.test(t))try{return new URL(r,t).toString()}catch{}return`${t.replace(/\/$/,"")}/${r}`}(t,x),e);return n.plugins=n.plugins||[],l.size>0&&n.plugins.push(new v3(l)),n.plugins.push(new vV({backgroundLayer:A.BACKGROUND,mainThreadLayer:A.MAIN_THREAD,externals:o,globalObject:x.globalObject,timeout:x.timeout,retries:x.retries})),n})}}}var v7={},v8={};function v9(x){var e=v8[x];if(void 0!==e)return e.exports;var t=v8[x]={exports:{}};return v7[x](t,t.exports,v9),t.exports}v9.m=v7,v9.n=x=>{var e=x&&x.__esModule?()=>x.default:()=>x;return v9.d(e,{a:e}),e},v9.d=(x,e,t)=>{var r=(e,t)=>{for(var r in e)v9.o(e,r)&&!v9.o(x,r)&&Object.defineProperty(x,r,{enumerable:!0,[t]:e[r]})};r(e,"get"),r(t,"value")},v9.add=function(x){Object.assign(v9.m,x)},v9.o=(x,e)=>Object.prototype.hasOwnProperty.call(x,e),v9.add({"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),{MAX_LENGTH:a,MAX_SAFE_INTEGER:n}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),{safeRe:_,t:A}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"),s=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"),{compareIdentifiers:i}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js");x.exports=class x{constructor(e,t){if(t=s(t),e instanceof x)if(!!t.loose===e.loose&&!!t.includePrerelease===e.includePrerelease)return e;else e=e.version;else if("string"!=typeof e)throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>a)throw TypeError(`version is longer than ${a} characters`);r("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?_[A.LOOSE]:_[A.FULL]);if(!i)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>n||this.major<0)throw TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(x=>{if(/^[0-9]+$/.test(x)){let e=+x;if(e>=0&&e<n)return e}return x}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(r("SemVer.compare",this.version,this.options,e),!(e instanceof x)){if("string"==typeof e&&e===this.version)return 0;e=new x(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return(e instanceof x||(e=new x(e,this.options)),this.major<e.major)?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:+(this.patch>e.patch)}comparePre(e){if(e instanceof x||(e=new x(e,this.options)),this.prerelease.length&&!e.prerelease.length)return -1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let x=this.prerelease[t],a=e.prerelease[t];if(r("prerelease compare",t,x,a),void 0===x&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===x)return -1;else if(x===a)continue;else return i(x,a)}while(++t)}compareBuild(e){e instanceof x||(e=new x(e,this.options));let t=0;do{let x=this.build[t],a=e.build[t];if(r("build compare",t,x,a),void 0===x&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===x)return -1;else if(x===a)continue;else return i(x,a)}while(++t)}inc(x,e,t){if(x.startsWith("pre")){if(!e&&!1===t)throw Error("invalid increment argument: identifier is empty");if(e){let x=`-${e}`.match(this.options.loose?_[A.PRERELEASELOOSE]:_[A.PRERELEASE]);if(!x||x[1]!==e)throw Error(`invalid identifier: ${e}`)}}switch(x){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",e,t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",e,t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",e,t),this.inc("pre",e,t);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",e,t),this.inc("pre",e,t);break;case"release":if(0===this.prerelease.length)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(0!==this.minor||0!==this.patch||0===this.prerelease.length)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(0!==this.patch||0===this.prerelease.length)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{let x=+!!Number(t);if(0===this.prerelease.length)this.prerelease=[x];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(e===this.prerelease.join(".")&&!1===t)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(x)}}if(e){let r=[e,x];!1===t&&(r=[e]),((x,e)=>{let t=e.split(".");if(t.length>x.length)return!1;for(let e=0;e<t.length;e++)if(0!==i(x[e],t[e]))return!1;return!0})(this.prerelease,e)?isNaN(this.prerelease[e.split(".").length])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${x}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js");x.exports=(x,e,t)=>new r(x,t).compare(new r(e,t))},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js");x.exports=(x,e,t)=>r(x,e,t)>=0},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(x){x.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||0x1fffffffffffff,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(x){x.exports="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...x)=>console.error("SEMVER",...x):()=>{}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(x){let e=/^[0-9]+$/,t=(x,t)=>{if("number"==typeof x&&"number"==typeof t)return x===t?0:x<t?-1:1;let r=e.test(x),a=e.test(t);return r&&a&&(x*=1,t*=1),x===t?0:r&&!a?-1:a&&!r?1:x<t?-1:1};x.exports={compareIdentifiers:t,rcompareIdentifiers:(x,e)=>t(e,x)}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(x){let e=Object.freeze({loose:!0}),t=Object.freeze({});x.exports=x=>x?"object"!=typeof x?e:x:t},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(x,e,t){let{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:a,MAX_LENGTH:n}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),_=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),A=(e=x.exports={}).re=[],s=e.safeRe=[],i=e.src=[],o=e.safeSrc=[],l=e.t={},c=0,v="[a-zA-Z0-9-]",d=[["\\s",1],["\\d",n],[v,a]],f=(x,e,t)=>{let r=(x=>{for(let[e,t]of d)x=x.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return x})(e),a=c++;_(x,a,e),l[x]=a,i[a]=e,o[a]=r,A[a]=new RegExp(e,t?"g":void 0),s[a]=new RegExp(r,t?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${v}*`),f("MAINVERSION",`(${i[l.NUMERICIDENTIFIER]})\\.(${i[l.NUMERICIDENTIFIER]})\\.(${i[l.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${i[l.NUMERICIDENTIFIERLOOSE]})\\.(${i[l.NUMERICIDENTIFIERLOOSE]})\\.(${i[l.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${i[l.NONNUMERICIDENTIFIER]}|${i[l.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${i[l.NONNUMERICIDENTIFIER]}|${i[l.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${i[l.PRERELEASEIDENTIFIER]}(?:\\.${i[l.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${i[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${i[l.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${v}+`),f("BUILD",`(?:\\+(${i[l.BUILDIDENTIFIER]}(?:\\.${i[l.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${i[l.MAINVERSION]}${i[l.PRERELEASE]}?${i[l.BUILD]}?`),f("FULL",`^${i[l.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${i[l.MAINVERSIONLOOSE]}${i[l.PRERELEASELOOSE]}?${i[l.BUILD]}?`),f("LOOSE",`^${i[l.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${i[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${i[l.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${i[l.XRANGEIDENTIFIER]})(?:\\.(${i[l.XRANGEIDENTIFIER]})(?:\\.(${i[l.XRANGEIDENTIFIER]})(?:${i[l.PRERELEASE]})?${i[l.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${i[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${i[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${i[l.XRANGEIDENTIFIERLOOSE]})(?:${i[l.PRERELEASELOOSE]})?${i[l.BUILD]}?)?)?`),f("XRANGE",`^${i[l.GTLT]}\\s*${i[l.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${i[l.GTLT]}\\s*${i[l.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),f("COERCE",`${i[l.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",i[l.COERCEPLAIN]+`(?:${i[l.PRERELEASE]})?`+`(?:${i[l.BUILD]})?`+"(?:$|[^\\d])"),f("COERCERTL",i[l.COERCE],!0),f("COERCERTLFULL",i[l.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${i[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",f("TILDE",`^${i[l.LONETILDE]}${i[l.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${i[l.LONETILDE]}${i[l.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${i[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",f("CARET",`^${i[l.LONECARET]}${i[l.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${i[l.LONECARET]}${i[l.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${i[l.GTLT]}\\s*(${i[l.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${i[l.GTLT]}\\s*(${i[l.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${i[l.GTLT]}\\s*(${i[l.LOOSEPLAIN]}|${i[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${i[l.XRANGEPLAIN]})\\s+-\\s+(${i[l.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${i[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${i[l.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});let dx=v9("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js");var de=v9.n(dx);let dt=Symbol.for("@lynx-js/plugin-react-alias");function dr(x,e,t){let r,a,{ResolverFactory:n}=x.experiments.resolver;return async x=>{if(r||(r={}),void 0===r[x]){if(!a){let x=new n({conditionNames:t,enablePnp:!!process.versions.pnp});a=(e,t)=>x.sync(e,t)}let _=a(e,x);if(_.error)throw Error(_.error);if(!_.path)throw Error(`Failed to resolve ${x}`);r[x]=_.path}return r[x]}}function da(x){return x?.type==="Identifier"}function dn(x){return x?.type==="StringLiteral"}function d_(x){return x?.type==="NumericLiteral"}function dA(x){return x?.type==="BooleanLiteral"}function ds(x){return x?.type==="ObjectExpression"}function di(x){return x?.type==="ArrayExpression"}function dl(x){return x?.type==="KeyValueProperty"}let dc=x=>{if(ds(x)){let e={};for(let t of x.properties){if(t?.type==="SpreadElement"||!dl(t))return null;let{key:x,value:r}=t;if(!da(x)&&!dn(x))return null;let a=x.value;ds(r)||di(r)?e[a]=dc(r):dn(r)||d_(r)||dA(r)?e[a]=r.value:da(r)&&(e[a]=r)}return e}if(di(x)){let e=[];for(let t of x.elements){if(!t||t.spread)return null;let x=t.expression;ds(x)||di(x)?e.push(dc(x)):dn(x)||d_(x)||dA(x)?e.push(x.value):da(x)&&e.push(x)}return e}},dv=I("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function dd(x,e,t){let{widgets:r,pages:a,collector:n,define:_,onDeprecatedAIMeta:A}=t,s=a[e],i=r[e],o=x;return(s||i)&&(_&&Object.keys(_).length>0&&(o=Object.keys(_).reduce((x,e)=>{let t=_[e];if("string"==typeof t)return x.replaceAll(e,t);throw Error(`define 配置项 ${e} 的值必须是字符串`)},x)),T((0,dv.parseSync)(o,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(x){if(da(x.callee)&&["defineWidget","definePage"].includes(x.callee.value)){let t=x.arguments[0]?.expression;if(ds(t)){for(let x of t.properties)if(dl(x)&&da(x.key)&&"aiMeta"===x.key.value){let t=dc(x.value);if(!t)continue;s?(A?.({kind:"page",entryName:s,filename:e}),n.addPageMeta(s,t)):i&&(A?.({kind:"widget",entryName:i,filename:e}),n.addWidgetMeta(i,t))}}}da(x.callee)&&x.callee.value in oj&&(i&&n.addWidgetMeta(i,oj[x.callee.value]),s&&n.addPageMeta(s,oj[x.callee.value]))}})),x}let df=/[/\\]/;function db(x,e){e.forEach(([e,{id:t}])=>{if(t&&df.test(t))throw Error(`入口 "${e}" 的 ${x} id "${t}" 无效:id 不能包含路径分隔符。请在 src/app.config.ts 中设置不含路径分隔符的 "id",或删除该配置以根据入口自动生成 id。`)})}async function du({pages:x,widgets:e,entries:t,collector:r,normalizedAppConfig:a,define:n}){let _=new o$,A=new Set,s={collector:_,widgets:Object.fromEntries(Object.entries(e).map(([x,e])=>[e.filename,x])),pages:Object.fromEntries(Object.entries(x).map(([x,e])=>[e.filename,x])),define:n,onDeprecatedAIMeta({kind:x,entryName:e,filename:t}){let r=`${x}:${e}:${t}`;A.has(r)||(A.add(r),oa.warn(`define${"page"===x?"Page":"Widget"}({ aiMeta }) 已弃用,入口:${e}。请改为在 src/app.config.ts 中配置该 ${x} 的元数据。源文件:${t}`))}},i=a.pages.entries,o=a.widgets.entries;await Promise.all(Object.values({...e,...x}).filter(({filename:x})=>/\.(ts|tsx|jsx|js)$/i.test(x)).map(({filename:x,isVirtualFile:e})=>{if(e){let e=s.widgets[x]??s.pages[x],r=t[e];return r?dd(r.toString(),x,s):void oa.warn("未找到虚拟文件",{file:e})}return dd(r5.readFileSync(x,"utf-8"),x,s)})).catch(x=>{oa.error("收集视图元数据失败",{error:x})});let l=_.getData(),c=oj.defineLoginPage,v=lV("",c.path),d=Object.entries(x).map(([x,e])=>{let t=l.pages[x],{web:r,...a}=i[x]??{},n=t?.path,_=e.isLoginPage||void 0!==n&&lV(x,n)===v;return[x,{id:lJ(x,e.folderName),...t,...a,..._?c:{},path:lV(x,_?c.path:e.isSpecial?n:void 0)}]}),f=[...new Set([...d.filter(([,x])=>x.path===v).map(([x])=>x),...d.filter(([,x])=>x.id===c.id).map(([x])=>x)])];if(f.length>1)throw Error(`只允许配置一个登录页面:${f.join(", ")}`);db("page",d),d.forEach(([x,e])=>{r.addPageMeta(x,e)});let b=Object.entries(e).map(([x,e])=>{let{web:t,...r}=o[x]??{};return[x,{id:lJ(x,e.folderName),...l.widgets[x],...r}]});db("widget",b),function(x){let e=new Map;x.forEach(([x,{id:t}])=>{if(!t)return;let r=e.get(t)??[];r.push(x),e.set(t,r)});let t=[...e].filter(([,x])=>x.length>1);if(0===t.length)return;let r=t.map(([x,e])=>`重复的 widget id "${x}" 被以下入口使用:
363
+ `,d=new Set,f=new Map;for(let[e,r]of o){let{libraryName:s,url:i,bundlePath:o,async:l=!0,timeout:c=t.timeout??2e3,retries:v=t.retries??0}=r,b=r[a],u=c/1e3;if(!b?.sectionPath)continue;let p=s??e,m=Array.isArray(p)?p[0]:p,h=o?{...r,bundlePath:o.replace(/^\/+/,"")}:r,E=i??`bundlePath:${h.bundlePath}`,j=`${E}-${m}`;if(d.has(j))continue;d.add(j);let g=h.url?JSON.stringify(h.url):`${x.webpack.RuntimeGlobals.publicPath} + ${JSON.stringify(h.bundlePath)}`;n.set(E,`() => lynx.fetchBundle(${g}, {})`),_.set(E,Math.max(_.get(E)??0,v));let y=`${vU(t.globalObject)}[${JSON.stringify(m)}]`,S=`${E}||${b.sectionPath}||${l}`,I=f.get(S);if(void 0!==I){A.add(`${y} = ${y} === undefined ? ${I} : ${y};`);continue}f.set(S,y);let N=[...n.keys()].indexOf(E);if(l){A.add(`${y} = ${y} === undefined ? createLoadExternalAsync(handler${N}, ${JSON.stringify(b.sectionPath)}) : ${y};`);continue}A.add(`${y} = ${y} === undefined ? createLoadExternalSync(handler${N}, ${JSON.stringify(b.sectionPath)}, ${u}) : ${y};`)}return[c,v,...[...n.entries()].map(([x,e],t)=>`const handler${t} = createRetryingHandler(${e}, ${_.get(x)??0});`),...A].join("\n")}}x.hooks.environment.tap(vY.name,()=>{x.options.externals=[...Array.isArray(x.options.externals)?x.options.externals:void 0===x.options.externals?[]:[x.options.externals],this.#xw(t.globalObject)]}),x.hooks.compilation.tap(a.name,e=>{e.hooks.additionalTreeRuntimeRequirements.tap(a.name,(t,r)=>{let n;for(let x of e.chunkGraph.getChunkModulesIterable(t))if(x.layer){n=x.layer;break}n&&(r.add(x.webpack.RuntimeGlobals.publicPath),e.addRuntimeModule(t,new a(r,{layer:n})))})})}#xw(x){let{externals:e,backgroundLayer:t,mainThreadLayer:r}=this.options,a=new Set(Object.keys(e));return({request:n,contextInfo:_},A)=>{let s=_?.issuerLayer===r?"mainThread":_?.issuerLayer===t?"background":void 0;if(n&&a.has(n)&&s&&e[n]?.[s]){let t=e[n]?.async??!0,r=e[n]?.libraryName??n,a=Array.isArray(r)?r:[r];if(t){let e=`${vU(x)}[${JSON.stringify(a[0])}]`,t=a.slice(1).map(x=>`[${JSON.stringify(x)}]`).join("");return A(void 0,t?`Promise.resolve(${e}).then(function (m) { return m${t}; })`:e,"promise")}return A(void 0,[vU(x),...a],void 0)}A()}}}let vz=(0,k.createRequire)(import.meta.url),vW={react:{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react":{libraryName:["ReactLynx","React"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/internal":{libraryName:["ReactLynx","ReactInternal"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/jsx-runtime":{libraryName:["ReactLynx","ReactJSXRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-dev-runtime":{libraryName:["ReactLynx","ReactJSXLepusDevRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/lepus/jsx-runtime":{libraryName:["ReactLynx","ReactJSXLepusRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/experimental/lazy/import":{libraryName:["ReactLynx","ReactLazyImport"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/legacy-react-runtime":{libraryName:["ReactLynx","ReactLegacyRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/runtime-components":{libraryName:["ReactLynx","ReactComponents"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/worklet-runtime/bindings":{libraryName:["ReactLynx","ReactWorkletRuntime"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/debug":{libraryName:["ReactLynx","ReactDebug"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},"@lynx-js/react/refresh":{libraryName:["ReactLynx","ReactRefresh"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1},preact:{libraryName:["ReactLynx","Preact"],background:{sectionPath:"ReactLynx"},mainThread:{sectionPath:"ReactLynx__main-thread"},async:!1}};function v0(x){return x?new Map(x instanceof Map?x:Object.entries(x)):new Map}let v1=v6();function v2(x){if(x)return!0===x?{}:x}function v3(x){return x.replace(/^\/+/,"")}function v6(){return{reactlynx:{resolveExternals:(x,e)=>{var t,r;let a;return t=v2(x),r=v4(e),a=t?.url?{url:t.url}:{bundlePath:v7(t,r)},Object.fromEntries(Object.entries(vW).map(([x,e])=>[x,{...e,...t?.async===void 0?{}:{async:t.async},...a}]))},resolveManagedAssets(x,e){let t=v2(x);if(!t||t.url)return new Map;let r=v4(e);return new Map([[v7(t,r),function(x,e,t){let r="production"===process.env.NODE_ENV?"prod":"dev",a=`${e}/${r}${t?"-web":""}`;try{return vz.resolve(a,{paths:[x]})}catch{throw Error(`external-bundle-rsbuild-plugin requires \`${a}\` when \`externalsPresets.reactlynx\` is enabled. Install a compatible \`${e}\` into your devDependencies.`)}}(e.rootPath,t.reactUmdPackageName??"@lynx-js/react-umd",r)]])}}}}function v4(x){let e=x.environmentName;return void 0!==e&&"lynx"!==e&&!e.startsWith("lynx-")}class v5{assets;constructor(x){this.assets=x}apply(x){x.hooks.thisCompilation.tap(v5.name,e=>{e.hooks.processAssets.tap({name:v5.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},()=>{let{RawSource:t}=x.webpack.sources;for(let[x,r]of this.assets)if(!e.getAsset(x)){if(!(0,r5.existsSync)(r))throw Error(`external-bundle-rsbuild-plugin could not find local bundle \`${r}\` for emitted asset \`${x}\`.`);e.emitAsset(x,new t((0,r5.readFileSync)(r),!1))}})})}}function v7(x,e){return x?.bundlePath?v3(x.bundlePath):e?"react.web.bundle":"react.lynx.bundle"}function v8(x,e){return"string"!=typeof e?e:{bundlePath:e,libraryName:x,background:{sectionPath:x},mainThread:{sectionPath:`${x}__main-thread`},async:!0}}function v9(x){return{name:"lynx:external-bundle",setup(e){let t,r=function(x){let e={...v6()};for(let[t,r]of Object.entries(x??{})){let x=v1[t];e[t]=x?function(x,e){return{extends:[...x.extends?Array.isArray(x.extends)?x.extends:[x.extends]:[],...e.extends?Array.isArray(e.extends)?e.extends:[e.extends]:[]],resolveExternals:(t,r)=>({...x.resolveExternals?.(t,r)??{},...e.resolveExternals?.(t,r)??{}}),resolveManagedAssets(t,r){let a=v0(x.resolveManagedAssets?.(t,r));for(let[x,n]of v0(e.resolveManagedAssets?.(t,r)))a.set(x,n);return a}}}(x,r):r}return e}(x.externalsPresetDefinitions),a=new Map;e.modifyRsbuildConfig((e,{mergeRsbuildConfig:r})=>(t=e.server?.base,void 0===x.externals&&void 0===x.externalsPresets)?e:r(e,{server:{setup:({server:x,action:e})=>{"dev"===e&&x.middlewares.use((x,e,t)=>{let r=x.url?a.get(x.url):void 0;if(r&&(0,r5.existsSync)(r)){e.setHeader("Content-Type","application/octet-stream"),e.setHeader("Access-Control-Allow-Origin","*");let x=(0,r5.createReadStream)(r);x.on("error",()=>{e.headersSent||(e.statusCode=404),e.end()}),x.pipe(e);return}t()})}}})),e.modifyRspackConfig((n,{environment:_})=>{let A=e.useExposed(Symbol.for("LAYERS"));if(!A)throw Error("external-bundle-rsbuild-plugin requires exposed `LAYERS`. Please install a DSL plugin, for example `pluginReactLynx` for ReactLynx.");let s=function(x,e,t){let r={},a=new Map;for(let[n,_]of Object.entries(x??{})){if(!_)continue;let x=function x(e,t,r,a,n){let _=r[e];if(!_)throw Error(`Unknown externals preset "${e}". Define it in \`externalsPresetDefinitions\` before enabling it in \`externalsPresets\`.`);if(a.includes(e))throw Error(`Circular externals preset dependency detected: ${[...a,e].join(" -> ")}`);let A={},s=new Map,i=[...a,e];for(let e of _.extends?Array.isArray(_.extends)?_.extends:[_.extends]:[]){let t=x(e,!0,r,i,n);for(let[x,e]of(Object.assign(A,t.externals),t.managedAssets))s.set(x,e)}for(let[x,e]of(Object.assign(A,_.resolveExternals?.(t,n)??{}),v0(_.resolveManagedAssets?.(t,n))))s.set(x,e);return{externals:A,managedAssets:s}}(n,_,e,[],t);for(let[e,t]of(Object.assign(r,x.externals),x.managedAssets))a.set(e,t)}return{externals:r,managedAssets:a}}(x.externalsPresets,r,{rootPath:e.context.rootPath,environmentName:_.name}),i=function(x){if(!x)return{};for(let[e,t]of Object.entries(x)){let x=v8(e,t);if(!x.url&&!x.bundlePath)throw Error(`external-bundle-rsbuild-plugin requires \`url\` or \`bundlePath\` for external "${e}".`)}return Object.fromEntries(Object.entries(x).map(([x,e])=>[x,v8(x,e)]))}(x.externals),o={...s.externals,...i},l=function(x,e,t){let r=new Map(e),a=r4.resolve(t.context.rootPath,x.externalBundleRoot??"dist-external-bundle");for(let[e,t]of Object.entries(x.externals??{})){let x=v8(e,t);!x.url&&x.bundlePath&&r.set(v3(x.bundlePath),r4.resolve(a,v3(x.bundlePath)))}return r}(x,s.managedAssets,e);for(let[x,e]of l)a.set(function(x,e){let t=x??"/",r=v3(e);if("/"===t)return`/${r}`;if(/^[a-z][a-z\d+\-.]*:/i.test(t))try{return new URL(r,t).toString()}catch{}return`${t.replace(/\/$/,"")}/${r}`}(t,x),e);return n.plugins=n.plugins||[],l.size>0&&n.plugins.push(new v5(l)),n.plugins.push(new vY({backgroundLayer:A.BACKGROUND,mainThreadLayer:A.MAIN_THREAD,externals:o,globalObject:x.globalObject,timeout:x.timeout,retries:x.retries})),n})}}}var dx={},de={};function dt(x){var e=de[x];if(void 0!==e)return e.exports;var t=de[x]={exports:{}};return dx[x](t,t.exports,dt),t.exports}dt.m=dx,dt.n=x=>{var e=x&&x.__esModule?()=>x.default:()=>x;return dt.d(e,{a:e}),e},dt.d=(x,e,t)=>{var r=(e,t)=>{for(var r in e)dt.o(e,r)&&!dt.o(x,r)&&Object.defineProperty(x,r,{enumerable:!0,[t]:e[r]})};r(e,"get"),r(t,"value")},dt.add=function(x){Object.assign(dt.m,x)},dt.o=(x,e)=>Object.prototype.hasOwnProperty.call(x,e),dt.add({"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),{MAX_LENGTH:a,MAX_SAFE_INTEGER:n}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),{safeRe:_,t:A}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"),s=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"),{compareIdentifiers:i}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js");x.exports=class x{constructor(e,t){if(t=s(t),e instanceof x)if(!!t.loose===e.loose&&!!t.includePrerelease===e.includePrerelease)return e;else e=e.version;else if("string"!=typeof e)throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>a)throw TypeError(`version is longer than ${a} characters`);r("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?_[A.LOOSE]:_[A.FULL]);if(!i)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>n||this.major<0)throw TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(x=>{if(/^[0-9]+$/.test(x)){let e=+x;if(e>=0&&e<n)return e}return x}):this.prerelease=[],this.build=i[5]?i[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(r("SemVer.compare",this.version,this.options,e),!(e instanceof x)){if("string"==typeof e&&e===this.version)return 0;e=new x(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return(e instanceof x||(e=new x(e,this.options)),this.major<e.major)?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:+(this.patch>e.patch)}comparePre(e){if(e instanceof x||(e=new x(e,this.options)),this.prerelease.length&&!e.prerelease.length)return -1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let x=this.prerelease[t],a=e.prerelease[t];if(r("prerelease compare",t,x,a),void 0===x&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===x)return -1;else if(x===a)continue;else return i(x,a)}while(++t)}compareBuild(e){e instanceof x||(e=new x(e,this.options));let t=0;do{let x=this.build[t],a=e.build[t];if(r("build compare",t,x,a),void 0===x&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===x)return -1;else if(x===a)continue;else return i(x,a)}while(++t)}inc(x,e,t){if(x.startsWith("pre")){if(!e&&!1===t)throw Error("invalid increment argument: identifier is empty");if(e){let x=`-${e}`.match(this.options.loose?_[A.PRERELEASELOOSE]:_[A.PRERELEASE]);if(!x||x[1]!==e)throw Error(`invalid identifier: ${e}`)}}switch(x){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",e,t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",e,t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",e,t),this.inc("pre",e,t);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",e,t),this.inc("pre",e,t);break;case"release":if(0===this.prerelease.length)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(0!==this.minor||0!==this.patch||0===this.prerelease.length)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(0!==this.patch||0===this.prerelease.length)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{let x=+!!Number(t);if(0===this.prerelease.length)this.prerelease=[x];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(e===this.prerelease.join(".")&&!1===t)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(x)}}if(e){let r=[e,x];!1===t&&(r=[e]),((x,e)=>{let t=e.split(".");if(t.length>x.length)return!1;for(let e=0;e<t.length;e++)if(0!==i(x[e],t[e]))return!1;return!0})(this.prerelease,e)?isNaN(this.prerelease[e.split(".").length])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${x}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js");x.exports=(x,e,t)=>new r(x,t).compare(new r(e,t))},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(x,e,t){let r=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js");x.exports=(x,e,t)=>r(x,e,t)>=0},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(x){x.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER||0x1fffffffffffff,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(x){x.exports="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...x)=>console.error("SEMVER",...x):()=>{}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(x){let e=/^[0-9]+$/,t=(x,t)=>{if("number"==typeof x&&"number"==typeof t)return x===t?0:x<t?-1:1;let r=e.test(x),a=e.test(t);return r&&a&&(x*=1,t*=1),x===t?0:r&&!a?-1:a&&!r?1:x<t?-1:1};x.exports={compareIdentifiers:t,rcompareIdentifiers:(x,e)=>t(e,x)}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(x){let e=Object.freeze({loose:!0}),t=Object.freeze({});x.exports=x=>x?"object"!=typeof x?e:x:t},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(x,e,t){let{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:a,MAX_LENGTH:n}=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),_=t("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),A=(e=x.exports={}).re=[],s=e.safeRe=[],i=e.src=[],o=e.safeSrc=[],l=e.t={},c=0,v="[a-zA-Z0-9-]",d=[["\\s",1],["\\d",n],[v,a]],f=(x,e,t)=>{let r=(x=>{for(let[e,t]of d)x=x.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return x})(e),a=c++;_(x,a,e),l[x]=a,i[a]=e,o[a]=r,A[a]=new RegExp(e,t?"g":void 0),s[a]=new RegExp(r,t?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${v}*`),f("MAINVERSION",`(${i[l.NUMERICIDENTIFIER]})\\.(${i[l.NUMERICIDENTIFIER]})\\.(${i[l.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${i[l.NUMERICIDENTIFIERLOOSE]})\\.(${i[l.NUMERICIDENTIFIERLOOSE]})\\.(${i[l.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${i[l.NONNUMERICIDENTIFIER]}|${i[l.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${i[l.NONNUMERICIDENTIFIER]}|${i[l.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${i[l.PRERELEASEIDENTIFIER]}(?:\\.${i[l.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${i[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${i[l.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${v}+`),f("BUILD",`(?:\\+(${i[l.BUILDIDENTIFIER]}(?:\\.${i[l.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${i[l.MAINVERSION]}${i[l.PRERELEASE]}?${i[l.BUILD]}?`),f("FULL",`^${i[l.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${i[l.MAINVERSIONLOOSE]}${i[l.PRERELEASELOOSE]}?${i[l.BUILD]}?`),f("LOOSE",`^${i[l.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${i[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${i[l.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${i[l.XRANGEIDENTIFIER]})(?:\\.(${i[l.XRANGEIDENTIFIER]})(?:\\.(${i[l.XRANGEIDENTIFIER]})(?:${i[l.PRERELEASE]})?${i[l.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${i[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${i[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${i[l.XRANGEIDENTIFIERLOOSE]})(?:${i[l.PRERELEASELOOSE]})?${i[l.BUILD]}?)?)?`),f("XRANGE",`^${i[l.GTLT]}\\s*${i[l.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${i[l.GTLT]}\\s*${i[l.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),f("COERCE",`${i[l.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",i[l.COERCEPLAIN]+`(?:${i[l.PRERELEASE]})?`+`(?:${i[l.BUILD]})?`+"(?:$|[^\\d])"),f("COERCERTL",i[l.COERCE],!0),f("COERCERTLFULL",i[l.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${i[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",f("TILDE",`^${i[l.LONETILDE]}${i[l.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${i[l.LONETILDE]}${i[l.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${i[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",f("CARET",`^${i[l.LONECARET]}${i[l.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${i[l.LONECARET]}${i[l.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${i[l.GTLT]}\\s*(${i[l.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${i[l.GTLT]}\\s*(${i[l.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${i[l.GTLT]}\\s*(${i[l.LOOSEPLAIN]}|${i[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${i[l.XRANGEPLAIN]})\\s+-\\s+(${i[l.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${i[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${i[l.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});let dr=dt("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js");var da=dt.n(dr);let dn=Symbol.for("@lynx-js/plugin-react-alias");function d_(x,e,t){let r,a,{ResolverFactory:n}=x.experiments.resolver;return async x=>{if(r||(r={}),void 0===r[x]){if(!a){let x=new n({conditionNames:t,enablePnp:!!process.versions.pnp});a=(e,t)=>x.sync(e,t)}let _=a(e,x);if(_.error)throw Error(_.error);if(!_.path)throw Error(`Failed to resolve ${x}`);r[x]=_.path}return r[x]}}function dA(x){return x?.type==="Identifier"}function ds(x){return x?.type==="StringLiteral"}function di(x){return x?.type==="NumericLiteral"}function dl(x){return x?.type==="BooleanLiteral"}function dc(x){return x?.type==="ObjectExpression"}function dv(x){return x?.type==="ArrayExpression"}function dd(x){return x?.type==="KeyValueProperty"}let df=x=>{if(dc(x)){let e={};for(let t of x.properties){if(t?.type==="SpreadElement"||!dd(t))return null;let{key:x,value:r}=t;if(!dA(x)&&!ds(x))return null;let a=x.value;dc(r)||dv(r)?e[a]=df(r):ds(r)||di(r)||dl(r)?e[a]=r.value:dA(r)&&(e[a]=r)}return e}if(dv(x)){let e=[];for(let t of x.elements){if(!t||t.spread)return null;let x=t.expression;dc(x)||dv(x)?e.push(df(x)):ds(x)||di(x)||dl(x)?e.push(x.value):dA(x)&&e.push(x)}return e}},db=I("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function du(x,e,t){let{widgets:r,pages:a,collector:n,define:_,onDeprecatedAIMeta:A}=t,s=a[e],i=r[e],o=x;return(s||i)&&(_&&Object.keys(_).length>0&&(o=Object.keys(_).reduce((x,e)=>{let t=_[e];if("string"==typeof t)return x.replaceAll(e,t);throw Error(`define 配置项 ${e} 的值必须是字符串`)},x)),T((0,db.parseSync)(o,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(x){if(dA(x.callee)&&["defineWidget","definePage"].includes(x.callee.value)){let t=x.arguments[0]?.expression;if(dc(t)){for(let x of t.properties)if(dd(x)&&dA(x.key)&&"aiMeta"===x.key.value){let t=df(x.value);if(!t)continue;s?(A?.({kind:"page",entryName:s,filename:e}),n.addPageMeta(s,t)):i&&(A?.({kind:"widget",entryName:i,filename:e}),n.addWidgetMeta(i,t))}}}dA(x.callee)&&x.callee.value in oj&&(i&&n.addWidgetMeta(i,oj[x.callee.value]),s&&n.addPageMeta(s,oj[x.callee.value]))}})),x}let dp=/[/\\]/;function dm(x,e){e.forEach(([e,{id:t}])=>{if(t&&dp.test(t))throw Error(`入口 "${e}" 的 ${x} id "${t}" 无效:id 不能包含路径分隔符。请在 src/app.config.ts 中设置不含路径分隔符的 "id",或删除该配置以根据入口自动生成 id。`)})}async function dh({pages:x,widgets:e,entries:t,collector:r,normalizedAppConfig:a,define:n}){let _=new o$,A=new Set,s={collector:_,widgets:Object.fromEntries(Object.entries(e).map(([x,e])=>[e.filename,x])),pages:Object.fromEntries(Object.entries(x).map(([x,e])=>[e.filename,x])),define:n,onDeprecatedAIMeta({kind:x,entryName:e,filename:t}){let r=`${x}:${e}:${t}`;A.has(r)||(A.add(r),oa.warn(`define${"page"===x?"Page":"Widget"}({ aiMeta }) 已弃用,入口:${e}。请改为在 src/app.config.ts 中配置该 ${x} 的元数据。源文件:${t}`))}},i=a.pages.entries,o=a.widgets.entries;await Promise.all(Object.values({...e,...x}).filter(({filename:x})=>/\.(ts|tsx|jsx|js)$/i.test(x)).map(({filename:x,isVirtualFile:e})=>{if(e){let e=s.widgets[x]??s.pages[x],r=t[e];return r?du(r.toString(),x,s):void oa.warn("未找到虚拟文件",{file:e})}return du(r5.readFileSync(x,"utf-8"),x,s)})).catch(x=>{oa.error("收集视图元数据失败",{error:x})});let l=_.getData(),c=oj.defineLoginPage,v=cW("",c.path),d=Object.entries(x).map(([x,e])=>{let t=l.pages[x],{web:r,...a}=i[x]??{},n=t?.path,_=e.isLoginPage||void 0!==n&&cW(x,n)===v;return[x,{id:cz(x,e.folderName),...t,...a,..._?c:{},path:cW(x,_?c.path:e.isSpecial?n:void 0)}]}),f=[...new Set([...d.filter(([,x])=>x.path===v).map(([x])=>x),...d.filter(([,x])=>x.id===c.id).map(([x])=>x)])];if(f.length>1)throw Error(`只允许配置一个登录页面:${f.join(", ")}`);dm("page",d),d.forEach(([x,e])=>{r.addPageMeta(x,e)});let b=Object.entries(e).map(([x,e])=>{let{web:t,...r}=o[x]??{};return[x,{id:cz(x,e.folderName),...l.widgets[x],...r}]});dm("widget",b),function(x){let e=new Map;x.forEach(([x,{id:t}])=>{if(!t)return;let r=e.get(t)??[];r.push(x),e.set(t,r)});let t=[...e].filter(([,x])=>x.length>1);if(0===t.length)return;let r=t.map(([x,e])=>`重复的 widget id "${x}" 被以下入口使用:
364
364
  ${e.map(x=>`- ${x}`).join("\n")}`).join("\n\n");throw Error(`${r}
365
365
 
366
- widget id 必须全局唯一,请在 src/app.config.ts 中配置不同的 "id"。`)}(b),b.forEach(([x,e])=>{r.addWidgetMeta(x,e)})}let dp=I("os"),dm=`base/${iY}`;async function dh({encryption:x}){let e=r1.mkdtempSync(r7.join(dp.tmpdir(),"doubao-keystore-")),t=r7.join(e,iY);try{let{generateKeystore:e}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),r=await e(t,{encryption:x});if(0!==r.status)throw Error(r.error_msg);return r1.readFileSync(t)}finally{r1.rmSync(e,{recursive:!0,force:!0})}}let dE=I("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40/node_modules/@byted-lynx/tasm/index.js");class dj{options;isGenerateKeystore=!1;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(dj.name,e=>{e.hooks.processAssets.tapPromise({name:dj.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let t=Date.now();try{let{RawSource:t}=x.webpack.sources,r=this.options.getAppAssetPath(),a=vp(e,iW);for(let x of[r,a].filter(x=>!!x)){let a=e.getAsset(x);if(!a)throw Error(`未生成 Worker 入口产物:${x}`);let{buffer:n,encodeOptions:_,keystoreContent:A}=await this.encode([a]);if(e.updateAsset(x,new t(n,!1)),A){let x=new t(A,!1);e.getAsset(dm)?e.updateAsset(dm,x):e.emitAsset(dm,x)}Z()&&x===r&&e.emitAsset(`${r4.dirname(x)}/tasm.json`,new t(JSON.stringify(_,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-t)}})})}async encode(x){let e={},{resolveSigningEncryptionOptions:t}=this.options;for(let t of x)t.name.endsWith(".js")&&(e[t.name.replace(/\.template\.js$/,"")]={content:t.source.source().toString()});let r={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:e},a=await t?.();if(a?.signing.enabled||a?.encryption.enabled){let{encode:x}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),e=this.options.metadata.appId,t=cz(a,{signing:{extra_config:{app_id:e,bundle_id:e}},encryption:{salt:e}}),{buffer:n,lepus_debug:_,status:A,error_msg:s}=await x(JSON.stringify(r),t);if(0!==A)throw Error(s);return!this.isGenerateKeystore&&t.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:n,encodeOptions:r,debugInfo:_,keystoreContent:await dh({encryption:{...t.encryption}})}):{buffer:n,encodeOptions:r,debugInfo:_}}let n=(0,dE.getEncodeMode)(),{buffer:_}=await n(r);return{buffer:_,encodeOptions:r}}}var dg=cU(function(x,e,t){cX(x,e,t)});function dy(x,e,r,a,n,_){let A=!1,s=_?.internal?_:void 0;return{name:dy.name,apply(_){let i=new _.webpack.experiments.VirtualModulesPlugin;i.apply(_),_.hooks.thisCompilation.tap(dy.name,()=>{Object.keys(r).forEach(x=>{i.writeModule(r[x].filename,r[x].toString())})}),_.hooks.thisCompilation.tap(dy.name,i=>{let o,l=()=>{void 0!==o&&n?.(Math.max(0,Date.now()-o))},c=x.getLynxTemplatePluginHooks(i);c.beforeEncode.tapPromise({name:dy.name,stage:1},async x=>{o??=Date.now();let e=x.chunkGroups?.find(({name:x})=>x&&Object.hasOwn(r,x))?.name;return x.encodeData.sourceContent.config=dg({},x.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0,disableQuickTracingGC:!0},s?.config,e?s?.entries?.[e]:void 0),x}),c.encode.tapPromise({name:dy.name,stage:255},async x=>{let{encodeOptions:r}=x,n=await a?.();if(n?.signing.enabled||n?.encryption.enabled){let{encode:t}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),a=e.getData(),s=function(x,e){let t=(e??"").replaceAll("\\","/"),r=t.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(r){let[,e,t]=r,a=`${e}/${t}`;return"widgets"===e?x.widgets[a]?.id:x.pages[a]?.path}let a=r4.posix.basename(t);return x.widgets[`widgets/${a}`]?.id??x.pages[`pages/${a}`]?.path}(a,x.intermediate),o=a.app.appId,c=cz(n,{signing:{extra_config:{app_id:o,bundle_id:s}},encryption:{salt:o}}),{buffer:v,lepus_debug:d,status:f,error_msg:b}=await t(JSON.stringify(r),c);if(0!==f)throw Error(b);if(!A&&c.encryption.enabled){A=!0;let x=await dh({encryption:{...c.encryption}}),e=new _.webpack.sources.RawSource(x,!1);i.getAsset(dm)?i.updateAsset(dm,e):i.emitAsset(dm,e)}return l(),{buffer:v,debugInfo:d}}let{buffer:s,lepus_debug:o}=await (t??=new S({filename:new URL("./encode-worker.js",import.meta.url).href,maxThreads:(0,ib.availableParallelism)()})).run({encodeOptions:r});return l(),{buffer:Buffer.from(s),debugInfo:o}})}),_.hooks.failed.tap(dy.name,x=>{o_.error("模板打包失败",{error:x})})}}}let dS=/^[\w+.-]+:\/\//,dI=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,dN=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function dB(x){return x.startsWith("/")}function dF(x){return/^[.?#]/.test(x)}function dw(x){let e=dI.exec(x);return dC(e[1],e[2]||"",e[3],e[4]||"",e[5]||"/",e[6]||"",e[7]||"")}function dC(x,e,t,r,a,n,_){return{scheme:x,user:e,host:t,port:r,path:a,query:n,hash:_,type:7}}function dP(x){if(x.startsWith("//")){let e=dw("http:"+x);return e.scheme="",e.type=6,e}if(dB(x)){let e=dw("http://foo.com"+x);return e.scheme="",e.host="",e.type=5,e}if(x.startsWith("file:")){let e,t;return t=(e=dN.exec(x))[2],dC("file:","",e[1]||"","",dB(t)?t:"/"+t,e[3]||"",e[4]||"")}if(dS.test(x))return dw(x);let e=dw("http://foo.com/"+x);return e.scheme="",e.host="",e.type=x?x.startsWith("?")?3:x.startsWith("#")?2:4:1,e}function dk(x,e){let t=e<=4,r=x.path.split("/"),a=1,n=0,_=!1;for(let x=1;x<r.length;x++){let e=r[x];if(!e){_=!0;continue}if(_=!1,"."!==e){if(".."===e){n?(_=!0,n--,a--):t&&(r[a++]=e);continue}r[a++]=e,n++}}let A="";for(let x=1;x<a;x++)A+="/"+r[x];A&&(!_||A.endsWith("/.."))||(A+="/"),x.path=A}function dD(x,e){for(let t=e;t<x.length;t++)if(!function(x){for(let e=1;e<x.length;e++)if(x[e][0]<x[e-1][0])return!1;return!0}(x[t]))return t;return x.length}function dL(x,e){return x[0]-e[0]}var dq=!1,dT=class{constructor(x,e){var t;let r,a,n="string"==typeof x;if(!n&&x._decodedMemo)return x;let _="string"==typeof(t=x)?JSON.parse(t):t,{version:A,file:s,names:i,sourceRoot:o,sources:l,sourcesContent:c}=_;this.version=A,this.file=s,this.names=i||[],this.sourceRoot=o,this.sources=l,this.sourcesContent=c,this.ignoreList=_.ignoreList||_.x_google_ignoreList||void 0;let v=(r=function(x){if(!x)return"";let e=x.lastIndexOf("/");return x.slice(0,e+1)}(e),a=o?o+"/":"",x=>(function(x,e){if(!x&&!e)return"";let t=dP(x),r=t.type;if(e&&7!==r){let x=dP(e),a=x.type;switch(r){case 1:t.hash=x.hash;case 2:t.query=x.query;case 3:case 4:dk(x,x.type),"/"===t.path?t.path=x.path:t.path=function(x){if(x.endsWith("/.."))return x;let e=x.lastIndexOf("/");return x.slice(0,e+1)}(x.path)+t.path;case 5:t.user=x.user,t.host=x.host,t.port=x.port;case 6:t.scheme=x.scheme}a>r&&(r=a)}dk(t,r);let a=t.query+t.hash;switch(r){case 2:case 3:return a;case 4:{let r=t.path.slice(1);if(!r)return a||".";if(dF(e||x)&&!dF(r))return"./"+r+a;return r+a}case 5:return t.path+a;default:return t.scheme+"//"+t.user+t.host+t.port+t.path+a}})(a+(x||""),r));this.resolvedSources=l.map(v);let{mappings:d}=_;if("string"==typeof d)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=function(x,e){let t=dD(x,0);if(t===x.length)return x;e||(x=x.slice());for(let a=t;a<x.length;a=dD(x,a+1)){var r;x[a]=(r=x[a],e||(r=r.slice()),r.sort(dL))}return x}(d,n);else if(_.sections)throw Error("TraceMap passed sectioned source map, please use FlattenMap export instead");else throw Error(`invalid source map: ${JSON.stringify(_)}`);this._decodedMemo={lastKey:-1,lastNeedle:-1,lastIndex:-1},this._bySources=void 0,this._bySourceMemos=void 0}};function dR(x,e,t,r){return{source:x,line:e,column:t,name:r}}let d$=new Set(["@doubao-dev/template"]),dG=new Set(["@doubao-dev/template","@byted-doubao-apps/template","@doubao-dev/components","@byted-doubao-apps/components","@doubao-dev/framework","@byted-doubao-apps/framework"]),dO=/\.(css|scss|sass|less|styl|stylus)$/i;function dX(x){let e=x.split(/[?#]/)[0];try{return(0,r5.realpathSync)(e)}catch{return r4.resolve(e)}}class dK{widgetEntryPaths;constructor(x){this.widgetEntryPaths=x}apply(x){let e=dX(x.options.context??x.context);x.hooks.thisCompilation.tap(dK.name,t=>{t.hooks.finishModules.tap(dK.name,r=>{let a=new Set(this.widgetEntryPaths.map(dX)),n=new Set,_=[],A=new Set,s=new Set,i=new Map,o=x=>{if(s.has(x))return;s.add(x);let r=x.resourceResolveData?.descriptionFileData?.name;if(r&&d$.has(r)){let t=x.resourceResolveData?.descriptionFileData?.version;if(!function(x){if("string"!=typeof x)return!1;let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(x);return!!e&&(Number(e[1])>0||Number(e[2])>=5)}(t)){let r=iG(e,dX(x.resourceResolveData?.descriptionFilePath??x.resource));i.set(r,t??"未知")}}if(!(r&&dG.has(r)))for(let e of t.moduleGraph.getOutgoingConnections(x))e.module&&o(e.module)};for(let x of r){let e=x.resource;e&&a.has(dX(e))&&o(x)}if(i.size){let e=[...new Set(i.values())].sort().join("、"),r=`@doubao-dev/template 当前版本为 ${e},请升级到 0.5.0 或更高的正式版本。`;_.push({rule_id:"template.version",severity:"warning",file:[...i.keys()].sort()[0],field:"template.version",message:r,targets:[x.options.name??"default"]});let a=new N.rspack.WebpackError(`[卡片检查] ${r}`);a.name="CardTemplateVersionWarning",t.warnings.push(a),t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[],diagnostics:_,total_count:1,truncated:!1};return}for(let x of r)for(let r of x.buildInfo?.cardDiagnostics??[]){let a=iG(e,dX(r.file)),n=r.line?`:${r.line}${r.column?`:${r.column}`:""}`:"",_="widget.root"===r.field?"":`${r.field}: `,A=new N.rspack.WebpackError(`[卡片检查] ${a}${n} ${_}${r.message}`);A.name="CardTemplateWarning",Object.assign(A,{module:x,file:`${a}${n}`}),t.warnings.push(A)}for(let s of r){let r=s.resource;if(!r||!a.has(dX(r)))continue;let i=iG(e,dX(r));A.add(i);let o=new Set,l=(a,A)=>{if(o.has(a))return;o.add(a);let s=a.resourceResolveData?.descriptionFileData?.name;if(s&&dG.has(s))return;for(let t of a.buildInfo?.cardDiagnostics??[])_.push({...t,widget:i,file:iG(e,dX(t.file)),targets:[x.options.name??"default"]});for(let x of t.moduleGraph.getOutgoingConnectionsInOrder(a))x.module&&l(x.module,x);if(!a.resource||!dO.test(a.resource.split(/[?#]/)[0]))return;let c=dX(a.resource),v=dX(r),d=`${v}:${c}`;if(n.has(d))return;n.add(d);let f=A?.originModule,b=iG(e,dX(f?.resource??c)),u=function(x){let e=x?.dependency.loc;if(!e||!("start"in e))return;let t={line:e.start.line,column:e.start.column??1},r=x?.originModule?.originalSource()?.map();if(!r)return t;let a=function(x,e){var t;let{line:r,column:a,bias:n}=e;if(--r<0)throw Error("`line` must be greater than 0 (lines start at line 1)");if(a<0)throw Error("`column` must be greater than or equal to 0 (columns start at column 0)");let _=(t=x)._decoded||(t._decoded=R(t._encoded));if(r>=_.length)return dR(null,null,null,null);let A=_[r],s=function(x,e,t,r,a){let n=function(x,e,t,r){let{lastKey:a,lastNeedle:n,lastIndex:_}=t,A=0,s=x.length-1;if(r===a){if(e===n)return dq=-1!==_&&x[_][0]===e,_;e>=n?A=-1===_?0:_:s=_}return t.lastKey=r,t.lastNeedle=e,t.lastIndex=function(x,e,t,r){for(;t<=r;){let a=t+(r-t>>1),n=x[a][0]-e;if(0===n)return dq=!0,a;n<0?t=a+1:r=a-1}return dq=!1,t-1}(x,e,A,s)}(x,r,e,t);return(dq?n=(-1===a?function(x,e,t){for(let r=t+1;r<x.length&&x[r][0]===e;t=r++);return t}:function(x,e,t){for(let r=t-1;r>=0&&x[r][0]===e;t=r--);return t})(x,r,n):-1===a&&n++,-1===n||n===x.length)?-1:n}(A,x._decodedMemo,r,a,n||1);if(-1===s)return dR(null,null,null,null);let i=A[s];if(1===i.length)return dR(null,null,null,null);let{names:o,resolvedSources:l}=x;return dR(l[i[1]],i[2]+1,i[3],5===i.length?o[i[4]]:null)}(new dT({...r,version:3}),{line:t.line,column:Math.max(0,t.column-1)});return null!==a.line&&null!==a.column?{line:a.line,column:a.column+1}:void 0}(A),p=u?.line,m=u?.column,h=p?`:${p}:${m}`:"",E="卡片不支持引入自定义样式文件,请使用模板提供的样式。";_.push({rule_id:"template.stylesheet",severity:"warning",widget:i,file:b,...p?{line:p,column:m}:{},field:"widget.styles",message:E,targets:[x.options.name??"default"]});let j=new N.rspack.WebpackError(`[卡片检查] ${b}${h} ${E}`);j.name="CardStyleWarning",Object.assign(j,{module:f??a,file:`${b}${h}`}),t.warnings.push(j)};l(s)}t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[...A],diagnostics:_,total_count:_.length,truncated:!1}})})}}class dQ{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return dQ._instance??=new dQ}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=x=>{let e=x.toString("utf-8");this.listeners.some(x=>x.run(e))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(x,e,t=0){let r=x=>()=>{let e=this.listeners.findIndex(e=>e.run===x);e>-1&&(this.listeners.splice(e,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(e){let x=this.listeners.find(x=>x.tag===e);if(x)return r(x.run)}return this.listeners.push({run:x,tag:e,priority:t,index:this.nextIndex++}),this.listeners.sort((x,e)=>x.priority-e.priority||x.index-e.index),this.start(),r(x)}}function dM(x){if(!(x instanceof Error&&"ExitPromptError"===x.name))throw x}function dZ(x){dQ.instance.stop(),x().catch(dM).finally(()=>dQ.instance.start())}$||q.env.TERM_PROGRAM;let dJ=!$&&"win32"===q.platform;!$&&(q.env.TERM?.startsWith("screen")||q.env.TERM?.startsWith("tmux")||q.env.TMUX),$||q.cwd;let dV=(x=1)=>"\x1b["+x+"A";function dH(x,e,t=!1){let r;for(let n of x){var a;if(a=n.family,"IPv4"===e?"IPv4"===a||4===a:"IPv6"===e?"IPv6"===a||6===a:a===e){if(t&&n.address.startsWith("127."))continue;if("IPv6"!==e||0===n.scopeid)return n;r||(r=n)}}return r}(()=>{if($||!dJ)return;let x=ib.release().split("."),e=Number(x[0]);return x[2]})();let dU=I("node:net"),dY=I("node:util"),dz=(0,dY.debuglog)("detect-port");class dW extends Error{constructor(x){super("The IP address is not available on this machine",x),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}}async function d0(x,e,t){return x>=e&&(dz("port: %s >= maxPort: %s, give up and use random port",x,e),x=0,e=0),await d1(x,e,t)}async function d1(x,e,t){if(t)try{return await d2(x,t)}catch(r){if("EADDRNOTAVAIL"===r.code)throw new dW({cause:r});return await d0(++x,e,t)}try{await d2(x)}catch(r){if(0===x)throw r;return await d0(++x,e,t)}try{await d2(x,"0.0.0.0")}catch(r){return await d0(++x,e,t)}try{await d2(x,"127.0.0.1")}catch(r){return await d0(++x,e,t)}try{await d2(x,"localhost")}catch(r){if("EADDRNOTAVAIL"!==r.code)return await d0(++x,e,t)}try{let e;return await d2(x,(e=function(x,e){let t,r,a=ib.networkInterfaces(),n=!e;if(e=e||(t="eth",r=ib.platform(),"darwin"===r?t="en":"win32"===r&&(t=void 0),t),x=x||"IPv4",e)for(let t=-1;t<8;t++){let r=a[e+(t>=0?t:"")];if(r){let e=dH(r,x);if(e)return e}}if(n)for(let e in a){let t=a[e];if(t){let e=dH(t,x,!0);if(e)return e}}}("IPv4",void 0),e?.address))}catch(r){return await d0(++x,e,t)}}function d2(x,e){let t=(0,dU.createServer)();return new Promise((r,a)=>{t.once("error",n=>(dz("listen %s:%s error: %s",e,x,n),t.close(),"ENOTFOUND"===n.code)?(dz("ignore dns ENOTFOUND error, get free %s:%s",e,x),r(x)):a(n)),dz("try listen %d on %s",x,e),t.listen(x,e,()=>(dz("get free %s:%s",e,x=t.address().port),t.close(),r(x)))})}(0,dY.debuglog)("detect-port:wait-port");let d3=function(x,e){let t="";x&&"object"==typeof x?(t=x.hostname,e=x.callback,x=x.port):"function"==typeof x&&(e=x,x=void 0);let r=(x=parseInt(x)||0)+10;return(r>65535&&(r=65535),dz("detect free port between [%s, %s)",x,r),"function"==typeof e)?d1(x,r,t).then(x=>e(null,x)).catch(e):d1(x,r,t)},d6=K.child("simulator"),d4=I("node:http"),d5={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},d7=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),d8=new Set([...d7,"cookie","host","origin","referer"]),d9=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,fx="X-DBX-Sandbox-Session-ID",fe="x-tt-logid";function ft(x){try{return new URL(x.url??"/","http://localhost")}catch{return}}function fr(x){if(!x)throw Error("url 必须为非空字符串");let e=new URL(x);if("http:"!==e.protocol&&"https:"!==e.protocol)throw Error(`不支持的请求协议:${e.protocol}`);return e}function fa(x,e,t={}){let r={};for(let[e,t]of Object.entries(x))void 0===t||d8.has(e.toLowerCase())||(r[e]=t);return{...r,...t,host:e.host}}function fn(x,e=[]){let t={};for(let[e,r]of Object.entries(x))void 0===r||d7.has(e.toLowerCase())||(t[e]=r);if(e.length>0){let x=new Set(String(t["access-control-expose-headers"]??"").split(",").map(x=>x.trim().toLowerCase()).filter(Boolean));for(let t of e)x.add(t.toLowerCase());t["access-control-expose-headers"]=[...x].join(", ")}return t}function f_(x,e=[]){let t=fn(Object.fromEntries(x),e);return delete t["content-encoding"],delete t["content-length"],t}function fA(x,e={}){Object.entries({...d5,...e}).forEach(([e,t])=>{void 0!==t&&x.setHeader(e,t)})}function fs(x,e,t,r){fA(x,r),x.writeHead(e,{"Content-Type":"text/plain; charset=utf-8"}),x.end(t)}function fi(x,e,t,r){let a=JSON.stringify(t);fA(x,r),x.writeHead(e,{"Content-Length":Buffer.byteLength(a),"Content-Type":"application/json; charset=utf-8"}),x.end(a)}function fo(x,e,t){return new Promise((r,a)=>{let n=[],_=0,A=!1;x.on("data",r=>{if(A)return;let s=Uint8Array.from(Buffer.isBuffer(r)?r:Buffer.from(r));if((_+=s.byteLength)>t){A=!0,x.pause(),e.shouldKeepAlive=!1,e.setHeader("Connection","close");let t=()=>{x.destroyed||x.destroy()};e.once("finish",t),e.once("close",t),a(Error("Request body is too large"));return}n.push(s)}),x.once("end",()=>{if(A)return;A=!0;let x=new Uint8Array(_),e=0;for(let t of n)x.set(t,e),e+=t.byteLength;r(x)}),x.once("aborted",()=>{A||(A=!0,a(Error("Request aborted")))}),x.once("error",x=>{A||(A=!0,a(x))})})}function fl(x,e,t){return fo(x,e,t).then(x=>Buffer.from(x).toString("utf8"))}function fc(x){return x.arrayBuffer().then(x=>Buffer.from(x))}function fv(x){return Object.entries(x).filter(([,x])=>void 0!==x).map(([x,e])=>{let t=d9.test(x)?"[REDACTED]":Array.isArray(e)?e.join(", "):e;return` ${x}: ${t}`}).join("\n")}function fd(x){return("string"==typeof x||void 0===x?x:x.toString("utf8"))||"(no content)"}function ff({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){Z()&&d6.info(`${x} ${_.pathname}${_.search} ${(n>=500?Y.red:n>=400?Y.yellow:Y.green)(String(n))}
366
+ widget id 必须全局唯一,请在 src/app.config.ts 中配置不同的 "id"。`)}(b),b.forEach(([x,e])=>{r.addWidgetMeta(x,e)})}let dE=I("os"),dj=`base/${iY}`;async function dg({encryption:x}){let e=r1.mkdtempSync(r7.join(dE.tmpdir(),"doubao-keystore-")),t=r7.join(e,iY);try{let{generateKeystore:e}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),r=await e(t,{encryption:x});if(0!==r.status)throw Error(r.error_msg);return r1.readFileSync(t)}finally{r1.rmSync(e,{recursive:!0,force:!0})}}let dy=I("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40/node_modules/@byted-lynx/tasm/index.js");class dS{options;isGenerateKeystore=!1;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(dS.name,e=>{e.hooks.processAssets.tapPromise({name:dS.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let t=Date.now();try{let{RawSource:t}=x.webpack.sources,r=this.options.getAppAssetPath(),a=vE(e,iW);for(let x of[r,a].filter(x=>!!x)){let a=e.getAsset(x);if(!a)throw Error(`未生成 Worker 入口产物:${x}`);let{buffer:n,encodeOptions:_,keystoreContent:A}=await this.encode([a]);if(e.updateAsset(x,new t(n,!1)),A){let x=new t(A,!1);e.getAsset(dj)?e.updateAsset(dj,x):e.emitAsset(dj,x)}Z()&&x===r&&e.emitAsset(`${r4.dirname(x)}/tasm.json`,new t(JSON.stringify(_,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-t)}})})}async encode(x){let e={},{resolveSigningEncryptionOptions:t}=this.options;for(let t of x)t.name.endsWith(".js")&&(e[t.name.replace(/\.template\.js$/,"")]={content:t.source.source().toString()});let r={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:e},a=await t?.();if(a?.signing.enabled||a?.encryption.enabled){let{encode:x}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),e=this.options.metadata.appId,t=c2(a,{signing:{extra_config:{app_id:e,bundle_id:e}},encryption:{salt:e}}),{buffer:n,lepus_debug:_,status:A,error_msg:s}=await x(JSON.stringify(r),t);if(0!==A)throw Error(s);return!this.isGenerateKeystore&&t.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:n,encodeOptions:r,debugInfo:_,keystoreContent:await dg({encryption:{...t.encryption}})}):{buffer:n,encodeOptions:r,debugInfo:_}}let n=(0,dy.getEncodeMode)(),{buffer:_}=await n(r);return{buffer:_,encodeOptions:r}}}function dI(x,e,r,a,n,_){let A=!1,s=_?.internal?_:void 0;return{name:dI.name,apply(_){let i=new _.webpack.experiments.VirtualModulesPlugin;i.apply(_),_.hooks.thisCompilation.tap(dI.name,()=>{Object.keys(r).forEach(x=>{i.writeModule(r[x].filename,r[x].toString())})}),_.hooks.thisCompilation.tap(dI.name,i=>{let o,l=()=>{void 0!==o&&n?.(Math.max(0,Date.now()-o))},c=x.getLynxTemplatePluginHooks(i);c.beforeEncode.tapPromise({name:dI.name,stage:1},async x=>{o??=Date.now();let e=x.chunkGroups?.find(({name:x})=>x&&Object.hasOwn(r,x))?.name;return x.encodeData.sourceContent.config=cV({},x.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0,disableQuickTracingGC:!0},s?.config,e?s?.entries?.[e]:void 0),x}),c.encode.tapPromise({name:dI.name,stage:255},async x=>{let{encodeOptions:r}=x,n=await a?.();if(n?.signing.enabled||n?.encryption.enabled){let{encode:t}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),a=e.getData(),s=function(x,e){let t=(e??"").replaceAll("\\","/"),r=t.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(r){let[,e,t]=r,a=`${e}/${t}`;return"widgets"===e?x.widgets[a]?.id:x.pages[a]?.path}let a=r4.posix.basename(t);return x.widgets[`widgets/${a}`]?.id??x.pages[`pages/${a}`]?.path}(a,x.intermediate),o=a.app.appId,c=c2(n,{signing:{extra_config:{app_id:o,bundle_id:s}},encryption:{salt:o}}),{buffer:v,lepus_debug:d,status:f,error_msg:b}=await t(JSON.stringify(r),c);if(0!==f)throw Error(b);if(!A&&c.encryption.enabled){A=!0;let x=await dg({encryption:{...c.encryption}}),e=new _.webpack.sources.RawSource(x,!1);i.getAsset(dj)?i.updateAsset(dj,e):i.emitAsset(dj,e)}return l(),{buffer:v,debugInfo:d}}let{buffer:s,lepus_debug:o}=await (t??=new S({filename:new URL("./encode-worker.js",import.meta.url).href,maxThreads:(0,ib.availableParallelism)()})).run({encodeOptions:r});return l(),{buffer:Buffer.from(s),debugInfo:o}})}),_.hooks.failed.tap(dI.name,x=>{o_.error("模板打包失败",{error:x})})}}}let dN=/^[\w+.-]+:\/\//,dB=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,dF=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function dw(x){return x.startsWith("/")}function dC(x){return/^[.?#]/.test(x)}function dP(x){let e=dB.exec(x);return dk(e[1],e[2]||"",e[3],e[4]||"",e[5]||"/",e[6]||"",e[7]||"")}function dk(x,e,t,r,a,n,_){return{scheme:x,user:e,host:t,port:r,path:a,query:n,hash:_,type:7}}function dD(x){if(x.startsWith("//")){let e=dP("http:"+x);return e.scheme="",e.type=6,e}if(dw(x)){let e=dP("http://foo.com"+x);return e.scheme="",e.host="",e.type=5,e}if(x.startsWith("file:")){let e,t;return t=(e=dF.exec(x))[2],dk("file:","",e[1]||"","",dw(t)?t:"/"+t,e[3]||"",e[4]||"")}if(dN.test(x))return dP(x);let e=dP("http://foo.com/"+x);return e.scheme="",e.host="",e.type=x?x.startsWith("?")?3:x.startsWith("#")?2:4:1,e}function dL(x,e){let t=e<=4,r=x.path.split("/"),a=1,n=0,_=!1;for(let x=1;x<r.length;x++){let e=r[x];if(!e){_=!0;continue}if(_=!1,"."!==e){if(".."===e){n?(_=!0,n--,a--):t&&(r[a++]=e);continue}r[a++]=e,n++}}let A="";for(let x=1;x<a;x++)A+="/"+r[x];A&&(!_||A.endsWith("/.."))||(A+="/"),x.path=A}function dq(x,e){for(let t=e;t<x.length;t++)if(!function(x){for(let e=1;e<x.length;e++)if(x[e][0]<x[e-1][0])return!1;return!0}(x[t]))return t;return x.length}function dT(x,e){return x[0]-e[0]}var dR=!1,d$=class{constructor(x,e){var t;let r,a,n="string"==typeof x;if(!n&&x._decodedMemo)return x;let _="string"==typeof(t=x)?JSON.parse(t):t,{version:A,file:s,names:i,sourceRoot:o,sources:l,sourcesContent:c}=_;this.version=A,this.file=s,this.names=i||[],this.sourceRoot=o,this.sources=l,this.sourcesContent=c,this.ignoreList=_.ignoreList||_.x_google_ignoreList||void 0;let v=(r=function(x){if(!x)return"";let e=x.lastIndexOf("/");return x.slice(0,e+1)}(e),a=o?o+"/":"",x=>(function(x,e){if(!x&&!e)return"";let t=dD(x),r=t.type;if(e&&7!==r){let x=dD(e),a=x.type;switch(r){case 1:t.hash=x.hash;case 2:t.query=x.query;case 3:case 4:dL(x,x.type),"/"===t.path?t.path=x.path:t.path=function(x){if(x.endsWith("/.."))return x;let e=x.lastIndexOf("/");return x.slice(0,e+1)}(x.path)+t.path;case 5:t.user=x.user,t.host=x.host,t.port=x.port;case 6:t.scheme=x.scheme}a>r&&(r=a)}dL(t,r);let a=t.query+t.hash;switch(r){case 2:case 3:return a;case 4:{let r=t.path.slice(1);if(!r)return a||".";if(dC(e||x)&&!dC(r))return"./"+r+a;return r+a}case 5:return t.path+a;default:return t.scheme+"//"+t.user+t.host+t.port+t.path+a}})(a+(x||""),r));this.resolvedSources=l.map(v);let{mappings:d}=_;if("string"==typeof d)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=function(x,e){let t=dq(x,0);if(t===x.length)return x;e||(x=x.slice());for(let a=t;a<x.length;a=dq(x,a+1)){var r;x[a]=(r=x[a],e||(r=r.slice()),r.sort(dT))}return x}(d,n);else if(_.sections)throw Error("TraceMap passed sectioned source map, please use FlattenMap export instead");else throw Error(`invalid source map: ${JSON.stringify(_)}`);this._decodedMemo={lastKey:-1,lastNeedle:-1,lastIndex:-1},this._bySources=void 0,this._bySourceMemos=void 0}};function dG(x,e,t,r){return{source:x,line:e,column:t,name:r}}let dO=new Set(["@doubao-dev/template"]),dX=new Set(["@doubao-dev/template","@byted-doubao-apps/template","@doubao-dev/components","@byted-doubao-apps/components","@doubao-dev/framework","@byted-doubao-apps/framework"]),dK=/\.(css|scss|sass|less|styl|stylus)$/i;function dQ(x){let e=x.split(/[?#]/)[0];try{return(0,r5.realpathSync)(e)}catch{return r4.resolve(e)}}class dM{widgetEntryPaths;constructor(x){this.widgetEntryPaths=x}apply(x){let e=dQ(x.options.context??x.context);x.hooks.thisCompilation.tap(dM.name,t=>{t.hooks.finishModules.tap(dM.name,r=>{let a=new Set(this.widgetEntryPaths.map(dQ)),n=new Set,_=[],A=new Set,s=new Set,i=new Map,o=x=>{if(s.has(x))return;s.add(x);let r=x.resourceResolveData?.descriptionFileData?.name;if(r&&dO.has(r)){let t=x.resourceResolveData?.descriptionFileData?.version;if(!function(x){if("string"!=typeof x)return!1;let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(x);return!!e&&(Number(e[1])>0||Number(e[2])>=5)}(t)){let r=iG(e,dQ(x.resourceResolveData?.descriptionFilePath??x.resource));i.set(r,t??"未知")}}if(!(r&&dX.has(r)))for(let e of t.moduleGraph.getOutgoingConnections(x))e.module&&o(e.module)};for(let x of r){let e=x.resource;e&&a.has(dQ(e))&&o(x)}if(i.size){let e=[...new Set(i.values())].sort().join("、"),r=`@doubao-dev/template 当前版本为 ${e},请升级到 0.5.0 或更高的正式版本。`;_.push({rule_id:"template.version",severity:"warning",file:[...i.keys()].sort()[0],field:"template.version",message:r,targets:[x.options.name??"default"]});let a=new N.rspack.WebpackError(`[卡片检查] ${r}`);a.name="CardTemplateVersionWarning",t.warnings.push(a),t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[],diagnostics:_,total_count:1,truncated:!1};return}for(let x of r)for(let r of x.buildInfo?.cardDiagnostics??[]){let a=iG(e,dQ(r.file)),n=r.line?`:${r.line}${r.column?`:${r.column}`:""}`:"",_="widget.root"===r.field?"":`${r.field}: `,A=new N.rspack.WebpackError(`[卡片检查] ${a}${n} ${_}${r.message}`);A.name="CardTemplateWarning",Object.assign(A,{module:x,file:`${a}${n}`}),t.warnings.push(A)}for(let s of r){let r=s.resource;if(!r||!a.has(dQ(r)))continue;let i=iG(e,dQ(r));A.add(i);let o=new Set,l=(a,A)=>{if(o.has(a))return;o.add(a);let s=a.resourceResolveData?.descriptionFileData?.name;if(s&&dX.has(s))return;for(let t of a.buildInfo?.cardDiagnostics??[])_.push({...t,widget:i,file:iG(e,dQ(t.file)),targets:[x.options.name??"default"]});for(let x of t.moduleGraph.getOutgoingConnectionsInOrder(a))x.module&&l(x.module,x);if(!a.resource||!dK.test(a.resource.split(/[?#]/)[0]))return;let c=dQ(a.resource),v=dQ(r),d=`${v}:${c}`;if(n.has(d))return;n.add(d);let f=A?.originModule,b=iG(e,dQ(f?.resource??c)),u=function(x){let e=x?.dependency.loc;if(!e||!("start"in e))return;let t={line:e.start.line,column:e.start.column??1},r=x?.originModule?.originalSource()?.map();if(!r)return t;let a=function(x,e){var t;let{line:r,column:a,bias:n}=e;if(--r<0)throw Error("`line` must be greater than 0 (lines start at line 1)");if(a<0)throw Error("`column` must be greater than or equal to 0 (columns start at column 0)");let _=(t=x)._decoded||(t._decoded=R(t._encoded));if(r>=_.length)return dG(null,null,null,null);let A=_[r],s=function(x,e,t,r,a){let n=function(x,e,t,r){let{lastKey:a,lastNeedle:n,lastIndex:_}=t,A=0,s=x.length-1;if(r===a){if(e===n)return dR=-1!==_&&x[_][0]===e,_;e>=n?A=-1===_?0:_:s=_}return t.lastKey=r,t.lastNeedle=e,t.lastIndex=function(x,e,t,r){for(;t<=r;){let a=t+(r-t>>1),n=x[a][0]-e;if(0===n)return dR=!0,a;n<0?t=a+1:r=a-1}return dR=!1,t-1}(x,e,A,s)}(x,r,e,t);return(dR?n=(-1===a?function(x,e,t){for(let r=t+1;r<x.length&&x[r][0]===e;t=r++);return t}:function(x,e,t){for(let r=t-1;r>=0&&x[r][0]===e;t=r--);return t})(x,r,n):-1===a&&n++,-1===n||n===x.length)?-1:n}(A,x._decodedMemo,r,a,n||1);if(-1===s)return dG(null,null,null,null);let i=A[s];if(1===i.length)return dG(null,null,null,null);let{names:o,resolvedSources:l}=x;return dG(l[i[1]],i[2]+1,i[3],5===i.length?o[i[4]]:null)}(new d$({...r,version:3}),{line:t.line,column:Math.max(0,t.column-1)});return null!==a.line&&null!==a.column?{line:a.line,column:a.column+1}:void 0}(A),p=u?.line,m=u?.column,h=p?`:${p}:${m}`:"",E="卡片不支持引入自定义样式文件,请使用模板提供的样式。";_.push({rule_id:"template.stylesheet",severity:"warning",widget:i,file:b,...p?{line:p,column:m}:{},field:"widget.styles",message:E,targets:[x.options.name??"default"]});let j=new N.rspack.WebpackError(`[卡片检查] ${b}${h} ${E}`);j.name="CardStyleWarning",Object.assign(j,{module:f??a,file:`${b}${h}`}),t.warnings.push(j)};l(s)}t.cardCheck={schema_version:1,rules_version:"1",execution_status:"completed",coverage:"partial",checked_widgets:[...A],diagnostics:_,total_count:_.length,truncated:!1}})})}}class dZ{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return dZ._instance??=new dZ}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=x=>{let e=x.toString("utf-8");this.listeners.some(x=>x.run(e))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(x,e,t=0){let r=x=>()=>{let e=this.listeners.findIndex(e=>e.run===x);e>-1&&(this.listeners.splice(e,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(e){let x=this.listeners.find(x=>x.tag===e);if(x)return r(x.run)}return this.listeners.push({run:x,tag:e,priority:t,index:this.nextIndex++}),this.listeners.sort((x,e)=>x.priority-e.priority||x.index-e.index),this.start(),r(x)}}function dJ(x){if(!(x instanceof Error&&"ExitPromptError"===x.name))throw x}function dV(x){dZ.instance.stop(),x().catch(dJ).finally(()=>dZ.instance.start())}$||q.env.TERM_PROGRAM;let dH=!$&&"win32"===q.platform;!$&&(q.env.TERM?.startsWith("screen")||q.env.TERM?.startsWith("tmux")||q.env.TMUX),$||q.cwd;let dU=(x=1)=>"\x1b["+x+"A";function dY(x,e,t=!1){let r;for(let n of x){var a;if(a=n.family,"IPv4"===e?"IPv4"===a||4===a:"IPv6"===e?"IPv6"===a||6===a:a===e){if(t&&n.address.startsWith("127."))continue;if("IPv6"!==e||0===n.scopeid)return n;r||(r=n)}}return r}(()=>{if($||!dH)return;let x=ib.release().split("."),e=Number(x[0]);return x[2]})();let dz=I("node:net"),dW=I("node:util"),d0=(0,dW.debuglog)("detect-port");class d1 extends Error{constructor(x){super("The IP address is not available on this machine",x),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}}async function d2(x,e,t){return x>=e&&(d0("port: %s >= maxPort: %s, give up and use random port",x,e),x=0,e=0),await d3(x,e,t)}async function d3(x,e,t){if(t)try{return await d6(x,t)}catch(r){if("EADDRNOTAVAIL"===r.code)throw new d1({cause:r});return await d2(++x,e,t)}try{await d6(x)}catch(r){if(0===x)throw r;return await d2(++x,e,t)}try{await d6(x,"0.0.0.0")}catch(r){return await d2(++x,e,t)}try{await d6(x,"127.0.0.1")}catch(r){return await d2(++x,e,t)}try{await d6(x,"localhost")}catch(r){if("EADDRNOTAVAIL"!==r.code)return await d2(++x,e,t)}try{let e;return await d6(x,(e=function(x,e){let t,r,a=ib.networkInterfaces(),n=!e;if(e=e||(t="eth",r=ib.platform(),"darwin"===r?t="en":"win32"===r&&(t=void 0),t),x=x||"IPv4",e)for(let t=-1;t<8;t++){let r=a[e+(t>=0?t:"")];if(r){let e=dY(r,x);if(e)return e}}if(n)for(let e in a){let t=a[e];if(t){let e=dY(t,x,!0);if(e)return e}}}("IPv4",void 0),e?.address))}catch(r){return await d2(++x,e,t)}}function d6(x,e){let t=(0,dz.createServer)();return new Promise((r,a)=>{t.once("error",n=>(d0("listen %s:%s error: %s",e,x,n),t.close(),"ENOTFOUND"===n.code)?(d0("ignore dns ENOTFOUND error, get free %s:%s",e,x),r(x)):a(n)),d0("try listen %d on %s",x,e),t.listen(x,e,()=>(d0("get free %s:%s",e,x=t.address().port),t.close(),r(x)))})}(0,dW.debuglog)("detect-port:wait-port");let d4=function(x,e){let t="";x&&"object"==typeof x?(t=x.hostname,e=x.callback,x=x.port):"function"==typeof x&&(e=x,x=void 0);let r=(x=parseInt(x)||0)+10;return(r>65535&&(r=65535),d0("detect free port between [%s, %s)",x,r),"function"==typeof e)?d3(x,r,t).then(x=>e(null,x)).catch(e):d3(x,r,t)},d5=K.child("simulator"),d7=I("node:http"),d8={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},d9=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),fx=new Set([...d9,"cookie","host","origin","referer"]),fe=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,ft="X-DBX-Sandbox-Session-ID",fr="x-tt-logid";function fa(x){try{return new URL(x.url??"/","http://localhost")}catch{return}}function fn(x){if(!x)throw Error("url 必须为非空字符串");let e=new URL(x);if("http:"!==e.protocol&&"https:"!==e.protocol)throw Error(`不支持的请求协议:${e.protocol}`);return e}function f_(x,e,t={}){let r={};for(let[e,t]of Object.entries(x))void 0===t||fx.has(e.toLowerCase())||(r[e]=t);return{...r,...t,host:e.host}}function fA(x,e=[]){let t={};for(let[e,r]of Object.entries(x))void 0===r||d9.has(e.toLowerCase())||(t[e]=r);if(e.length>0){let x=new Set(String(t["access-control-expose-headers"]??"").split(",").map(x=>x.trim().toLowerCase()).filter(Boolean));for(let t of e)x.add(t.toLowerCase());t["access-control-expose-headers"]=[...x].join(", ")}return t}function fs(x,e=[]){let t=fA(Object.fromEntries(x),e);return delete t["content-encoding"],delete t["content-length"],t}function fi(x,e={}){Object.entries({...d8,...e}).forEach(([e,t])=>{void 0!==t&&x.setHeader(e,t)})}function fo(x,e,t,r){fi(x,r),x.writeHead(e,{"Content-Type":"text/plain; charset=utf-8"}),x.end(t)}function fl(x,e,t,r){let a=JSON.stringify(t);fi(x,r),x.writeHead(e,{"Content-Length":Buffer.byteLength(a),"Content-Type":"application/json; charset=utf-8"}),x.end(a)}function fc(x,e,t){return new Promise((r,a)=>{let n=[],_=0,A=!1;x.on("data",r=>{if(A)return;let s=Uint8Array.from(Buffer.isBuffer(r)?r:Buffer.from(r));if((_+=s.byteLength)>t){A=!0,x.pause(),e.shouldKeepAlive=!1,e.setHeader("Connection","close");let t=()=>{x.destroyed||x.destroy()};e.once("finish",t),e.once("close",t),a(Error("Request body is too large"));return}n.push(s)}),x.once("end",()=>{if(A)return;A=!0;let x=new Uint8Array(_),e=0;for(let t of n)x.set(t,e),e+=t.byteLength;r(x)}),x.once("aborted",()=>{A||(A=!0,a(Error("Request aborted")))}),x.once("error",x=>{A||(A=!0,a(x))})})}function fv(x,e,t){return fc(x,e,t).then(x=>Buffer.from(x).toString("utf8"))}function fd(x){return x.arrayBuffer().then(x=>Buffer.from(x))}function ff(x){return Object.entries(x).filter(([,x])=>void 0!==x).map(([x,e])=>{let t=fe.test(x)?"[REDACTED]":Array.isArray(e)?e.join(", "):e;return` ${x}: ${t}`}).join("\n")}function fb(x){return("string"==typeof x||void 0===x?x:x.toString("utf8"))||"(no content)"}function fu({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){Z()&&d5.info(`${x} ${_.pathname}${_.search} ${(n>=500?Y.red:n>=400?Y.yellow:Y.green)(String(n))}
367
367
  Request headers:
368
- ${fv(t)}
369
- Request body: ${fd(e)}
368
+ ${ff(t)}
369
+ Request body: ${fb(e)}
370
370
 
371
371
  Response headers:
372
- ${fv(Object.fromEntries(a))}
373
- Response body: ${fd(r)}`)}function fb(x,e){let t=new AbortController,r=()=>t.abort();return x.once("aborted",r),e.once("close",()=>{x.off("aborted",r),e.writableEnded||r()}),(x.aborted||e.destroyed)&&r(),t.signal}function fu(x,e,t){let r,a=("https:"===t.targetUrl.protocol?B:d4).request(t.targetUrl,{headers:t.requestHeaders,method:x.method},x=>{(r=x,e.destroyed||e.writableEnded)?x.destroy():(fA(e,t.commonHeaders),e.writeHead(x.statusCode??500,t.createResponseHeaders?.(x.headers)??fn(x.headers)),x.pipe(e))}),n=()=>{a.destroy(),r?.destroy()};a.once("error",x=>{if(!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(x);fs(e,502,`${t.errorMessage}: ${x.message}`,t.commonHeaders)}}),x.once("aborted",()=>{n()}),e.once("close",()=>{e.writableEnded||n()}),x.pipe(a)}async function fp(x,e,t){let r=e.find(({match:e})=>"string"==typeof e?x.url.pathname===e:e(x.url));await (r?.handle??t)(x)}function fm(x,e){return(t,r)=>{let a=ft(t);a?fp({request:t,response:r,url:a},x,e).catch(x=>(function(x,e){if(d6.error("处理 Web SDK 调试器请求失败",{error:e}),!x.destroyed&&!x.writableEnded){if(x.headersSent)return void x.destroy(e instanceof Error?e:void 0);fs(x,500,"Internal server error")}})(r,x)):fs(r,400,"Bad request")}}let fh=I("../../../node_modules/.pnpm/undici@6.29.0/node_modules/undici/index.js"),fE={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},fj={"http:":"80","https:":"443"},fg=new Map;function fy(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function fS(x){let e=x.startsWith("/")?x:`/${x}`;return"/app_developer"===e||e.startsWith("/app_developer/")}async function fI(x,e={}){let t=function(x){var e,t;let r="string"==typeof x?new URL(x):x;if(function(x){let e=fF(["NO_PROXY","no_proxy"]);if(!e)return!1;let t=fw(x.hostname),r=x.port||fj[x.protocol]||"";for(let x of e.split(",")){let e=function(x){let e=x.trim().toLowerCase();if(!e)return{host:""};if((e=e.replace(/^[a-z][a-z\d+.-]*:\/\//,"").split("/")[0]).startsWith("[")){let x=e.indexOf("]");if(-1!==x)return{host:fw(e.slice(0,x+1)),port:":"===e[x+1]?e.slice(x+2):void 0}}let t=e.indexOf(":")===e.lastIndexOf(":")?e.match(/:(\d+)$/):void 0;return{host:fw(t?e.slice(0,-t[0].length):e),port:t?.[1]}}(x);if(e.host&&(!e.port||e.port===r)){if("*"===e.host)return!0;if(e.host.startsWith("*.")){let x=e.host.slice(1);if(t.endsWith(x))return!0;continue}if(e.host.startsWith(".")){if(t.endsWith(e.host))return!0;continue}if(t===e.host)return!0}}return!1}(r))return;let a="https:"===(e=r.protocol)?fF(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===e?fF(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!a)return;let n=(t=a,/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`http://${t}`),_=fg.get(n);return _||(_=new fh.kT(n),fg.set(n,_)),_}(x),r=t?{...e,dispatcher:t}:e;return await fetch(x,r)}async function fN({internal:x,domainId:e,path:t,query:r,method:a="GET",body:n,headers:_,signal:A,auth:s=!0}){let i={method:a,body:n,headers:{...fy(),..._}};A&&(i.signal=A);let o=function({internal:x,domainId:e,path:t,query:r}){let a=t.startsWith("/")?t:`/${t}`,n=new URLSearchParams;for(let[x,e]of Object.entries(r||{}))null!=e&&n.append(x,e.toString());let _=n.toString(),A=_?`${a.includes("?")?"&":"?"}${_}`:"",s=fS(a)?oI:e?fE[e]:x?fE["sso-internal"]:fE["sms-external"];return`https://${s}${a}${A}`}({internal:x,domainId:e,path:t,query:r}),l=new Headers(i.headers);if(!s||!fS(t)||l.has("Authorization")||l.has("X-Developer-Open-Build-Token"))return await fI(o,i);let c=new URL(o).origin,v=z(fI,{baseUrl:c,allowedOrigins:[c]});try{return await v(o,i)}catch(x){if(!(x instanceof W||x instanceof U))throw x;throw Error(x instanceof U?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function fB(x){let e=await fN(x),t=e.headers.get("x-tt-logid")||"";if(!e.ok){let x=await e.text();throw Error(JSON.stringify({code:e.status,message:"HTTP 请求失败",data:x,log_id:t}))}let r=await e.json();if(0!==r.code)throw Error(JSON.stringify({...r,log_id:t}));return{...r,log_id:t}}function fF(x){for(let e of x){let x=process.env[e]?.trim();if(x)return x}}function fw(x){return x.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let fC="/__mcp_proxy";var fP=Object.create,fk=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,fL=Object.getOwnPropertyNames,fq=Object.getPrototypeOf,fT=Object.prototype.hasOwnProperty,fR=(x,e)=>()=>(e||x((e={exports:{}}).exports,e),e.exports),f$=(x,e,t)=>(t=null!=x?fP(fq(x)):{},((x,e,t)=>{if(e&&"object"==typeof e||"function"==typeof e)for(var r,a=fL(e),n=0,_=a.length;n<_;n++)r=a[n],fT.call(x,r)||void 0===r||fk(x,r,{get:(x=>e[x]).bind(null,r),enumerable:!(t=fD(e,r))||t.enumerable});return x})(!e&&x&&x.__esModule?t:fk(t,"default",{value:x,enumerable:!0}),x));let fG=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),fO=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),fX=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),fK=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]),fQ=Symbol.for("mcp.sdk.errorBrands");function fM(x,e){let t=new Set,r=e;for(;"function"==typeof r;){let x=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,"mcpBrand")&&"string"==typeof x&&t.add(x),r=Object.getPrototypeOf(r)}0!==t.size&&Object.defineProperty(x,fQ,{value:t,enumerable:!1,configurable:!0})}function fZ(x,e){try{if("object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(x,"mcpBrand")&&"string"==typeof x.mcpBrand&&Object.prototype.hasOwnProperty.call(e,fQ)){let t=e[fQ];if(t&&"function"==typeof t.has&&t.has(x.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(x,e)}(class x extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](x){return fZ(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fZ(this,x)}constructor(x,e,t){super(e),this.code=x,this.errorUri=t,this.name="OAuthError",fM(this,new.target)}toResponseObject(){let x={error:this.code,error_description:this.message};return this.errorUri&&(x.error_uri=this.errorUri),x}static fromResponse(e){return new x(e.error,e.error_description??e.error,e.error_uri)}});let fJ=((rX={}).NotConnected="NOT_CONNECTED",rX.AlreadyConnected="ALREADY_CONNECTED",rX.NotInitialized="NOT_INITIALIZED",rX.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",rX.RequestTimeout="REQUEST_TIMEOUT",rX.ConnectionClosed="CONNECTION_CLOSED",rX.SendFailed="SEND_FAILED",rX.InvalidResult="INVALID_RESULT",rX.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",rX.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",rX.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",rX.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",rX.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",rX.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",rX.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",rX.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",rX.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",rX.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",rX.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",rX);var fV=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](x){return fZ(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fZ(this,x)}constructor(x,e,t){super(e),this.code=x,this.data=t,this.name="SdkError",fM(this,new.target)}};(class extends fV{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(x,e,t){super(x,e,t),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}});let fH={};function fU(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function fY(x,e){let t={};for(let[r,a]of Object.entries(x)){if(void 0===a)continue;let x=void 0===e?void 0:e[r];if(void 0===x){t[r]=a;continue}if(fU(a)&&fU(x)){let e={};for(let[t,n]of Object.entries(a))void 0!==n&&void 0===x[t]&&("elicitation"!==r||"form"!==t||void 0!==x.form||void 0!==x.url)&&(e[t]=n);Object.keys(e).length>0&&(t[r]=e)}}return Object.keys(t).length>0?t:void 0}let fz="2026-07-28",fW=[fz];function f0(x){return x.filter(x=>x>=fz)}function f1(x){let e=x.structuredContent;return void 0===e||!("object"!=typeof e||null===e||Array.isArray(e))||x.content?.some(x=>"text"===x.type)?x:{...x,content:[...x.content??[],{type:"text",text:JSON.stringify(e)}]}}let f2=["task","inputRequests","requestState"];function f3(x){return null===x||"object"!=typeof x||Array.isArray(x)||void 0!==x.content||f2.some(e=>e in x)?x:{...x,content:[]}}function f6(){let x,e,t,a,n,_,A,s,i,o,l,c,v,d,f,b,u,p,m,h,E,j,g,y,S,I,N,B,F,w,C,P,k,D,L,q,T,R,$,G,O,X,K,Q,M,Z,J,V,H,U,Y,z,W,xx,xe,xt,xr,xa,xn,x_,xA,xs,xi,xo,xl,xc,xv,xd,xf,xb,xu,xp,xm,xh,xE,xj,xg,xy,xS,xI,xN,xB,xF,xw,xC,xP,xk,xD,xL,xq,xT,xR,x$,xG,xO,xX,xK,xQ,xM,xZ,xJ,xV,xH,xU,xY,xz,xW,x2,x3,x6,x5,x7,x8,x9,ex,et,er,ea,en,e_,ei,eo,el,ec,ev,ed,ef,eb,eu,ep,em,eh,eE,ej,eg,ey,eS,eI,eN,eB;return r??=(x=es(()=>ee([ra(),eD(),eY(),tw(),e6(ra(),x),rc(x)])),e=e6(ra(),x),t=ee([ra(),eD().int()]),a=ra(),n=tM({ttl:eD().optional()}),_=tM({taskId:ra()}),i=(s=tM({_meta:(A=x0({progressToken:t.optional(),"io.modelcontextprotocol/related-task":_.optional()})).optional()})).extend({task:n.optional()}),o=tM({method:ra(),params:s.loose().optional()}),l=tM({_meta:A.optional()}),c=tM({method:ra(),params:l.loose().optional()}),v=x0({_meta:A.optional()}),d=ee([ra(),eD().int()]),f=v.strict(),b=l.extend({requestId:d.optional(),reason:ra().optional()}),u=c.extend({method:rl("notifications/cancelled"),params:b}),p=tM({src:ra(),mimeType:ra().optional(),sizes:rc(ra()).optional(),theme:x1(["light","dark"]).optional()}),m=tM({icons:rc(p).optional()}),E=(h=tM({name:ra(),title:ra().optional()})).extend({...h.shape,...m.shape,version:ra(),websiteUrl:ra().optional(),description:ra().optional()}),j=tU(tM({applyDefaults:eY().optional()}),e),g=t0(x=>x&&"object"==typeof x&&!Array.isArray(x)&&0===Object.keys(x).length?{form:{}}:x,tU(tM({form:j.optional(),url:e.optional()}),e.optional())),y=x0({list:e.optional(),cancel:e.optional(),requests:x0({sampling:x0({createMessage:e.optional()}).optional(),elicitation:x0({create:e.optional()}).optional()}).optional()}),S=x0({list:e.optional(),cancel:e.optional(),requests:x0({tools:x0({call:e.optional()}).optional()}).optional()}),I=tM({experimental:e6(ra(),e).optional(),sampling:tM({context:e.optional(),tools:e.optional()}).optional(),elicitation:g.optional(),roots:tM({listChanged:eY().optional()}).optional(),tasks:y.optional(),extensions:e6(ra(),e).optional()}),N=s.extend({protocolVersion:ra(),capabilities:I,clientInfo:E}),B=o.extend({method:rl("initialize"),params:N}),F=tM({experimental:e6(ra(),e).optional(),logging:e.optional(),completions:e.optional(),prompts:tM({listChanged:eY().optional()}).optional(),resources:tM({subscribe:eY().optional(),listChanged:eY().optional()}).optional(),tools:tM({listChanged:eY().optional()}).optional(),tasks:S.optional(),extensions:e6(ra(),e).optional()}),w=v.extend({protocolVersion:ra(),capabilities:F,serverInfo:E,instructions:ra().optional()}),C=c.extend({method:rl("notifications/initialized"),params:l.optional()}),P=o.extend({method:rl("ping"),params:s.optional()}),k=tM({progress:eD(),total:eA(eD()),message:eA(ra())}),D=tM({...l.shape,...k.shape,progressToken:t}),L=c.extend({method:rl("notifications/progress"),params:D}),q=s.extend({cursor:a.optional()}),T=o.extend({params:q.optional()}),R=v.extend({nextCursor:a.optional()}),G=($=tM({uri:ra(),mimeType:eA(ra()),_meta:e6(ra(),x4()).optional()})).extend({text:ra()}),O=ra().refine(x=>{try{return atob(x),!0}catch{return!1}},{message:"Invalid Base64 string"}),X=$.extend({blob:O}),Q=tM({audience:rc(K=x1(["user","assistant"])).optional(),priority:eD().min(0).max(1).optional(),lastModified:rn({offset:!0}).optional()}),M=tM({...h.shape,...m.shape,uri:ra(),description:eA(ra()),mimeType:eA(ra()),size:eA(eD()),annotations:Q.optional(),_meta:eA(x0({}))}),Z=tM({...h.shape,...m.shape,uriTemplate:ra(),description:eA(ra()),mimeType:eA(ra()),annotations:Q.optional(),_meta:eA(x0({}))}),J=T.extend({method:rl("resources/list")}),V=R.extend({resources:rc(M)}),H=T.extend({method:rl("resources/templates/list")}),U=R.extend({resourceTemplates:rc(Z)}),Y=s.extend({uri:ra()}),z=o.extend({method:rl("resources/read"),params:Y}),W=v.extend({contents:rc(ee([G,X]))}),xx=c.extend({method:rl("notifications/resources/list_changed"),params:l.optional()}),xe=o.extend({method:rl("resources/subscribe"),params:Y}),xt=o.extend({method:rl("resources/unsubscribe"),params:Y}),xr=l.extend({uri:ra()}),xa=c.extend({method:rl("notifications/resources/updated"),params:xr}),xn=tM({name:ra(),description:eA(ra()),required:eA(eY())}),x_=tM({...h.shape,...m.shape,description:eA(ra()),arguments:eA(rc(xn)),_meta:eA(x0({}))}),xA=T.extend({method:rl("prompts/list")}),xs=R.extend({prompts:rc(x_)}),xi=s.extend({name:ra(),arguments:e6(ra(),ra()).optional()}),xo=o.extend({method:rl("prompts/get"),params:xi}),xl=tM({type:rl("text"),text:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xc=tM({type:rl("image"),data:O,mimeType:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xv=tM({type:rl("audio"),data:O,mimeType:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xd=tM({type:rl("tool_use"),name:ra(),id:ra(),input:e6(ra(),x4()),_meta:e6(ra(),x4()).optional()}),xf=tM({type:rl("resource"),resource:ee([G,X]),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xp=tM({role:K,content:xu=ee([xl,xc,xv,xb=M.extend({type:rl("resource_link")}),xf])}),xm=v.extend({description:ra().optional(),messages:rc(xp)}),xh=c.extend({method:rl("notifications/prompts/list_changed"),params:l.optional()}),xE=tM({title:ra().optional(),readOnlyHint:eY().optional(),destructiveHint:eY().optional(),idempotentHint:eY().optional(),openWorldHint:eY().optional()}),xj=tM({taskSupport:x1(["required","optional","forbidden"]).optional()}),xg=tM({...h.shape,...m.shape,description:ra().optional(),inputSchema:tM({type:rl("object"),properties:e6(ra(),x).optional(),required:rc(ra()).optional()}).catchall(x4()),outputSchema:tM({type:rl("object"),properties:e6(ra(),x).optional(),required:rc(ra()).optional()}).catchall(x4()).optional(),annotations:xE.optional(),execution:xj.optional(),_meta:e6(ra(),x4()).optional()}),xy=T.extend({method:rl("tools/list")}),xS=R.extend({tools:rc(xg)}),xI=v.extend({content:rc(xu),structuredContent:e6(ra(),x4()).optional(),isError:eY().optional()}),xN=i.extend({name:ra(),arguments:e6(ra(),x4()).optional()}),xB=o.extend({method:rl("tools/call"),params:xN}),xF=c.extend({method:rl("notifications/tools/list_changed"),params:l.optional()}),xw=x1(["debug","info","notice","warning","error","critical","alert","emergency"]),xC=s.extend({level:xw}),xP=o.extend({method:rl("logging/setLevel"),params:xC}),xk=l.extend({level:xw,logger:ra().optional(),data:x4()}),xD=c.extend({method:rl("notifications/message"),params:xk}),xL=tM({name:ra().optional()}),xq=tM({hints:rc(xL).optional(),costPriority:eD().min(0).max(1).optional(),speedPriority:eD().min(0).max(1).optional(),intelligencePriority:eD().min(0).max(1).optional()}),xT=tM({mode:x1(["auto","required","none"]).optional()}),xR=tM({type:rl("tool_result"),toolUseId:ra().describe("The unique identifier for the corresponding tool call."),content:rc(xu),structuredContent:tM({}).loose().optional(),isError:eY().optional(),_meta:e6(ra(),x4()).optional()}),x$=e9("type",[xl,xc,xv]),xO=tM({role:K,content:ee([xG=e9("type",[xl,xc,xv,xd,xR]),rc(xG)]),_meta:e6(ra(),x4()).optional()}),xX=i.extend({messages:rc(xO),modelPreferences:xq.optional(),systemPrompt:ra().optional(),includeContext:x1(["none","thisServer","allServers"]).optional(),temperature:eD().optional(),maxTokens:eD().int(),stopSequences:rc(ra()).optional(),metadata:e.optional(),tools:rc(xg).optional(),toolChoice:xT.optional()}),xK=o.extend({method:rl("sampling/createMessage"),params:xX}),xQ=v.extend({model:ra(),stopReason:eA(x1(["endTurn","stopSequence","maxTokens"]).or(ra())),role:K,content:x$}),xM=v.extend({model:ra(),stopReason:eA(x1(["endTurn","stopSequence","maxTokens","toolUse"]).or(ra())),role:K,content:ee([xG,rc(xG)])}),xZ=tM({type:rl("boolean"),title:ra().optional(),description:ra().optional(),default:eY().optional()}),xJ=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),minLength:eD().optional(),maxLength:eD().optional(),format:x1(["email","uri","date","date-time"]).optional(),default:ra().optional()}),xV=tM({type:x1(["number","integer"]),title:ra().optional(),description:ra().optional(),minimum:eD().optional(),maximum:eD().optional(),default:eD().optional()}),xH=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),default:ra().optional()}),xU=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),oneOf:rc(tM({const:ra(),title:ra()})),default:ra().optional()}),xY=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),enumNames:rc(ra()).optional(),default:ra().optional()}),xz=ee([xH,xU]),xW=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({type:rl("string"),enum:rc(ra())}),default:rc(ra()).optional()}),x3=ee([xW,x2=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({anyOf:rc(tM({const:ra(),title:ra()}))}),default:rc(ra()).optional()})]),x6=ee([xY,xz,x3]),x5=ee([x6,xZ,xJ,xV]),x7=i.extend({mode:rl("form").optional(),message:ra(),requestedSchema:tM({type:rl("object"),properties:e6(ra(),x5),required:rc(ra()).optional()}).catchall(x4())}),x9=ee([x7,x8=i.extend({mode:rl("url"),message:ra(),elicitationId:ra(),url:ra().url()})]),ex=o.extend({method:rl("elicitation/create"),params:x9}),et=l.extend({elicitationId:ra()}),er=c.extend({method:rl("notifications/elicitation/complete"),params:et}),ea=v.extend({action:x1(["accept","decline","cancel"]),content:t0(x=>null===x?void 0:x,e6(ra(),ee([ra(),eD(),eY(),rc(ra())])).optional())}),en=tM({type:rl("ref/resource"),uri:ra()}),e_=tM({type:rl("ref/prompt"),name:ra()}),ei=s.extend({ref:ee([e_,en]),argument:tM({name:ra(),value:ra()}),context:tM({arguments:e6(ra(),ra()).optional()}).optional()}),eo=o.extend({method:rl("completion/complete"),params:ei}),el=v.extend({completion:x0({values:rc(ra()).max(100),total:eA(eD().int()),hasMore:eA(eY())})}),ec=tM({uri:ra().startsWith("file://"),name:ra().optional(),_meta:e6(ra(),x4()).optional()}),ev=o.extend({method:rl("roots/list"),params:s.optional()}),ed=v.extend({roots:rc(ec)}),ef=c.extend({method:rl("notifications/roots/list_changed"),params:l.optional()}),eb=x0({ttl:eD().optional(),pollInterval:eD().optional()}),eu=x1(["working","input_required","completed","failed","cancelled"]),ep=tM({taskId:ra(),status:eu,ttl:ee([eD(),tw()]),createdAt:ra(),lastUpdatedAt:ra(),pollInterval:eA(eD()),statusMessage:eA(ra())}),em=v.extend({task:ep}),eh=l.merge(ep),eE=c.extend({method:rl("notifications/tasks/status"),params:eh}),ej=o.extend({method:rl("tasks/get"),params:s.extend({taskId:ra()})}),eg=v.merge(ep),ey=o.extend({method:rl("tasks/result"),params:s.extend({taskId:ra()})}),eS=v.loose(),eI=T.extend({method:rl("tasks/list")}),eN=R.extend({tasks:rc(ep)}),eB=o.extend({method:rl("tasks/cancel"),params:s.extend({taskId:ra()})}),{JSONValueSchema:x,JSONObjectSchema:e,ProgressTokenSchema:t,CursorSchema:a,TaskMetadataSchema:n,RelatedTaskMetadataSchema:_,RequestMetaSchema:A,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:i,RequestSchema:o,NotificationsParamsSchema:l,NotificationSchema:c,ResultSchema:v,RequestIdSchema:d,EmptyResultSchema:f,CancelledNotificationParamsSchema:b,CancelledNotificationSchema:u,IconSchema:p,IconsSchema:m,BaseMetadataSchema:h,ImplementationSchema:E,ClientTasksCapabilitySchema:y,ServerTasksCapabilitySchema:S,ClientCapabilitiesSchema:I,InitializeRequestParamsSchema:N,InitializeRequestSchema:B,ServerCapabilitiesSchema:F,InitializeResultSchema:w,InitializedNotificationSchema:C,PingRequestSchema:P,ProgressSchema:k,ProgressNotificationParamsSchema:D,ProgressNotificationSchema:L,PaginatedRequestParamsSchema:q,PaginatedRequestSchema:T,PaginatedResultSchema:R,ResourceContentsSchema:$,TextResourceContentsSchema:G,BlobResourceContentsSchema:X,RoleSchema:K,AnnotationsSchema:Q,ResourceSchema:M,ResourceTemplateSchema:Z,ListResourcesRequestSchema:J,ListResourcesResultSchema:V,ListResourceTemplatesRequestSchema:H,ListResourceTemplatesResultSchema:U,ResourceRequestParamsSchema:Y,ReadResourceRequestParamsSchema:Y,ReadResourceRequestSchema:z,ReadResourceResultSchema:W,ResourceListChangedNotificationSchema:xx,SubscribeRequestParamsSchema:Y,SubscribeRequestSchema:xe,UnsubscribeRequestParamsSchema:Y,UnsubscribeRequestSchema:xt,ResourceUpdatedNotificationParamsSchema:xr,ResourceUpdatedNotificationSchema:xa,PromptArgumentSchema:xn,PromptSchema:x_,ListPromptsRequestSchema:xA,ListPromptsResultSchema:xs,GetPromptRequestParamsSchema:xi,GetPromptRequestSchema:xo,TextContentSchema:xl,ImageContentSchema:xc,AudioContentSchema:xv,ToolUseContentSchema:xd,EmbeddedResourceSchema:xf,ResourceLinkSchema:xb,ContentBlockSchema:xu,PromptMessageSchema:xp,GetPromptResultSchema:xm,PromptListChangedNotificationSchema:xh,ToolAnnotationsSchema:xE,ToolExecutionSchema:xj,ToolSchema:xg,ListToolsRequestSchema:xy,ListToolsResultSchema:xS,CallToolResultSchema:xI,CallToolRequestParamsSchema:xN,CallToolRequestSchema:xB,ToolListChangedNotificationSchema:xF,LoggingLevelSchema:xw,SetLevelRequestParamsSchema:xC,SetLevelRequestSchema:xP,LoggingMessageNotificationParamsSchema:xk,LoggingMessageNotificationSchema:xD,ModelHintSchema:xL,ModelPreferencesSchema:xq,ToolChoiceSchema:xT,ToolResultContentSchema:xR,SamplingContentSchema:x$,SamplingMessageContentBlockSchema:xG,SamplingMessageSchema:xO,CreateMessageRequestParamsSchema:xX,CreateMessageRequestSchema:xK,CreateMessageResultSchema:xQ,CreateMessageResultWithToolsSchema:xM,BooleanSchemaSchema:xZ,StringSchemaSchema:xJ,NumberSchemaSchema:xV,UntitledSingleSelectEnumSchemaSchema:xH,TitledSingleSelectEnumSchemaSchema:xU,LegacyTitledEnumSchemaSchema:xY,SingleSelectEnumSchemaSchema:xz,UntitledMultiSelectEnumSchemaSchema:xW,TitledMultiSelectEnumSchemaSchema:x2,MultiSelectEnumSchemaSchema:x3,EnumSchemaSchema:x6,PrimitiveSchemaDefinitionSchema:x5,ElicitRequestFormParamsSchema:x7,ElicitRequestURLParamsSchema:x8,ElicitRequestParamsSchema:x9,ElicitRequestSchema:ex,ElicitationCompleteNotificationParamsSchema:et,ElicitationCompleteNotificationSchema:er,ElicitResultSchema:ea,ResourceTemplateReferenceSchema:en,PromptReferenceSchema:e_,CompleteRequestParamsSchema:ei,CompleteRequestSchema:eo,CompleteResultSchema:el,RootSchema:ec,ListRootsRequestSchema:ev,ListRootsResultSchema:ed,RootsListChangedNotificationSchema:ef,TaskCreationParamsSchema:eb,TaskStatusSchema:eu,TaskSchema:ep,CreateTaskResultSchema:em,TaskStatusNotificationParamsSchema:eh,TaskStatusNotificationSchema:eE,GetTaskRequestSchema:ej,GetTaskResultSchema:eg,GetTaskPayloadRequestSchema:ey,GetTaskPayloadResultSchema:eS,ListTasksRequestSchema:eI,ListTasksResultSchema:eN,CancelTaskRequestSchema:eB,CancelTaskResultSchema:v.merge(ep),ClientRequestSchema:ee([P,B,eo,xP,xo,xA,J,H,z,xe,xt,xB,xy,ej,ey,eI,eB]),ClientNotificationSchema:ee([u,L,C,ef,eE]),ClientResultSchema:ee([f,xQ,xM,ea,ed,eg,eN,em]),ServerRequestSchema:ee([P,xK,ex,ev,ej,ey,eI,eB]),ServerNotificationSchema:ee([u,L,xD,xa,xx,xF,xh,eE,er]),ServerResultSchema:ee([f,w,el,xm,xs,V,U,W,xI,xS,eg,eN,em]),CallToolResultWireSchema:x4().superRefine((x,e)=>{if(!("object"!=typeof x||null===x||Array.isArray(x))&&void 0===x.content){for(let t of f2)if(t in x)return void e.addIssue({code:"custom",message:`content is required when the body carries '${t}' — another result family cannot default into an empty tools/call success`})}}).transform(f3).pipe(xI)})}function f4(x){return"object"!==x.type}let f5=new Set(["const","enum","default","examples"]),f7=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function f8(x){return void 0!==x&&!("string"==typeof x&&x.startsWith("#"))}let f9={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},bx={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},be={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};function bt(){if(a)return a;let x=f6();return a={requestSchemas:{ping:x.PingRequestSchema,initialize:x.InitializeRequestSchema,"completion/complete":x.CompleteRequestSchema,"logging/setLevel":x.SetLevelRequestSchema,"prompts/get":x.GetPromptRequestSchema,"prompts/list":x.ListPromptsRequestSchema,"resources/list":x.ListResourcesRequestSchema,"resources/templates/list":x.ListResourceTemplatesRequestSchema,"resources/read":x.ReadResourceRequestSchema,"resources/subscribe":x.SubscribeRequestSchema,"resources/unsubscribe":x.UnsubscribeRequestSchema,"tools/call":x.CallToolRequestSchema,"tools/list":x.ListToolsRequestSchema,"tasks/get":x.GetTaskRequestSchema,"tasks/result":x.GetTaskPayloadRequestSchema,"tasks/list":x.ListTasksRequestSchema,"tasks/cancel":x.CancelTaskRequestSchema,"sampling/createMessage":x.CreateMessageRequestSchema,"elicitation/create":x.ElicitRequestSchema,"roots/list":x.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":x.CancelledNotificationSchema,"notifications/progress":x.ProgressNotificationSchema,"notifications/initialized":x.InitializedNotificationSchema,"notifications/roots/list_changed":x.RootsListChangedNotificationSchema,"notifications/tasks/status":x.TaskStatusNotificationSchema,"notifications/message":x.LoggingMessageNotificationSchema,"notifications/resources/updated":x.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":x.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":x.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":x.PromptListChangedNotificationSchema,"notifications/elicitation/complete":x.ElicitationCompleteNotificationSchema},resultSchemas:{ping:x.EmptyResultSchema,initialize:x.InitializeResultSchema,"completion/complete":x.CompleteResultSchema,"logging/setLevel":x.EmptyResultSchema,"prompts/get":x.GetPromptResultSchema,"prompts/list":x.ListPromptsResultSchema,"resources/list":x.ListResourcesResultSchema,"resources/templates/list":x.ListResourceTemplatesResultSchema,"resources/read":x.ReadResourceResultSchema,"resources/subscribe":x.EmptyResultSchema,"resources/unsubscribe":x.EmptyResultSchema,"tools/call":x.CallToolResultWireSchema,"tools/list":x.ListToolsResultSchema,"sampling/createMessage":x.CreateMessageResultWithToolsSchema,"elicitation/create":x.ElicitResultSchema,"roots/list":x.ListRootsResultSchema}}}function br(x){return Object.prototype.hasOwnProperty.call(f9,x)}function ba(x){return Object.prototype.hasOwnProperty.call(bx,x)}function bn(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function b_(x,e){if(void 0===x)return{ok:!1,reason:"not-in-era"};let t=x.safeParse(e);return t.success?{ok:!0,value:t.data}:{ok:!1,reason:"invalid",message:String(t.error)}}Object.keys(f9),Object.keys(bx);let bA={ok:!1,reason:"not-in-era"};function bs(x){return bn(x)&&bn(x.outputSchema)&&f4(x.outputSchema)}let bi={era:"2025-11-25",hasRequestMethod:br,hasNotificationMethod:ba,validateRequest:(x,e)=>b_(br(x)?bt().requestSchemas[x]:void 0,e),validateResult:(x,e)=>b_(Object.prototype.hasOwnProperty.call(be,x)?bt().resultSchemas[x]:void 0,e),validateNotification:(x,e)=>b_(ba(x)?bt().notificationSchemas[x]:void 0,e),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bA,validateInputResponse:()=>bA,samplingResultVariant:(x,e)=>{let t=f6();return b_(x?t.CreateMessageResultWithToolsSchema:t.CreateMessageResultSchema,e)},outboundEnvelope:x=>void 0,validateEnvelopeMeta:x=>[],projectCallToolResult(x,e){let t=f1(x),r=t.structuredContent;if(void 0===r)return t;let a="object"!=typeof r||null===r||Array.isArray(r),n=void 0!==e&&f4(e);return a||n?{...t,structuredContent:{result:r}}:t},decodeResult(x,e){if(bn(e)&&"resultType"in e){let x={...e};return delete x.resultType,{kind:"complete",result:x}}return{kind:"complete",result:e}},encodeResult(x,e){if("tools/list"!==x)return e;let t=e.tools;return Array.isArray(t)&&t.some(x=>bs(x))?{...e,tools:t.map(x=>bs(x)?{...x,outputSchema:function(x){var e;let t="string"==typeof x.$schema?x.$schema:void 0;if(f8(x.$id))return{...void 0!==t&&{$schema:t},type:"object",properties:{result:x},required:["result"]};let r="string"==typeof(e=x.$schema)&&fO.has(e.replace(/#$/,""))&&!0!==x.$recursiveAnchor,a=(x,e)=>{if(Array.isArray(x))return x.map(x=>a(x,!1));if(null===x||"object"!=typeof x||!e&&f8(x.$id))return x;let t={},n=!1;for(let[_,A]of Object.entries(x))e?t[_]=a(A,!1):("$ref"===_||"$dynamicRef"===_)&&"string"==typeof A?t[_]="#"===A?"#/properties/result":A.startsWith("#/")?`#/properties/result${A.slice(1)}`:A:"$recursiveRef"===_&&"#"===A&&r?n=!0:f5.has(_)?t[_]=A:f7.has(_)?t[_]=a(A,!0):t[_]=a(A,!1);return n&&("$ref"in t?t.allOf=[...Array.isArray(t.allOf)?t.allOf:[],{$ref:"#/properties/result"}]:t.$ref="#/properties/result"),t};return{...void 0!==t&&{$schema:t},type:"object",properties:{result:a(x,!1)},required:["result"]}}(x.outputSchema)}:x)}:e},encodeErrorCode:x=>-32002===x?-32602:x,checkInboundEnvelope:x=>void 0};function bo(){return n??=function(){let x=es(()=>ee([ra(),eD(),eY(),tw(),e6(ra(),x),rc(x)])),e=e6(ra(),x),t=ee([ra(),eD().int()]),r=ra(),a=ee([ra(),eD().int()]),n=x1(["user","assistant"]),_=x1(["debug","info","notice","warning","error","critical","alert","emergency"]),A=ra().refine(x=>{try{return atob(x),!0}catch{return!1}},{message:"Invalid Base64 string"}),s=tM({ttl:eD().optional()}),i=tM({taskId:ra()}),o=x0({progressToken:t.optional(),"io.modelcontextprotocol/related-task":i.optional()}),l=tM({_meta:o.optional()}),c=l.extend({task:s.optional()}),v=tM({_meta:o.optional()}),d=tM({method:ra(),params:v.loose().optional()}),f=tM({src:ra(),mimeType:ra().optional(),sizes:rc(ra()).optional(),theme:x1(["light","dark"]).optional()}),b=tM({icons:rc(f).optional()}),u=tM({name:ra(),title:ra().optional()}),p=u.extend({...u.shape,...b.shape,version:ra(),websiteUrl:ra().optional(),description:ra().optional()}),m=tU(tM({applyDefaults:eY().optional()}),e),h=t0(x=>x&&"object"==typeof x&&!Array.isArray(x)&&0===Object.keys(x).length?{form:{}}:x,tU(tM({form:m.optional(),url:e.optional()}),e.optional())),E=x0({list:e.optional(),cancel:e.optional(),requests:x0({sampling:x0({createMessage:e.optional()}).optional(),elicitation:x0({create:e.optional()}).optional()}).optional()}),j=x0({list:e.optional(),cancel:e.optional(),requests:x0({tools:x0({call:e.optional()}).optional()}).optional()}),g=tM({experimental:e6(ra(),e).optional(),sampling:tM({context:e.optional(),tools:e.optional()}).optional(),elicitation:h.optional(),roots:tM({listChanged:eY().optional()}).optional(),tasks:E.optional(),extensions:e6(ra(),e).optional()}),y=tM({experimental:e6(ra(),e).optional(),logging:e.optional(),completions:e.optional(),prompts:tM({listChanged:eY().optional()}).optional(),resources:tM({subscribe:eY().optional(),listChanged:eY().optional()}).optional(),tools:tM({listChanged:eY().optional()}).optional(),tasks:j.optional(),extensions:e6(ra(),e).optional()}),S=tM({progress:eD(),total:eA(eD()),message:eA(ra())}),I=tM({...v.shape,...S.shape,progressToken:t}),N=d.extend({method:rl("notifications/progress"),params:I}),B=v.extend({level:_,logger:ra().optional(),data:x4()}),F=d.extend({method:rl("notifications/message"),params:B}),w=tM({uri:ra(),mimeType:eA(ra()),_meta:e6(ra(),x4()).optional()}),C=w.extend({text:ra()}),P=w.extend({blob:A}),k=tM({audience:rc(n).optional(),priority:eD().min(0).max(1).optional(),lastModified:rn({offset:!0}).optional()}),D=tM({...u.shape,...b.shape,uri:ra(),description:eA(ra()),mimeType:eA(ra()),size:eA(eD()),annotations:k.optional(),_meta:eA(x0({}))}),L=tM({...u.shape,...b.shape,uriTemplate:ra(),description:eA(ra()),mimeType:eA(ra()),annotations:k.optional(),_meta:eA(x0({}))}),q=d.extend({method:rl("notifications/resources/list_changed"),params:v.optional()}),T=v.extend({uri:ra()}),R=d.extend({method:rl("notifications/resources/updated"),params:T}),$=tM({name:ra(),description:eA(ra()),required:eA(eY())}),G=tM({...u.shape,...b.shape,description:eA(ra()),arguments:eA(rc($)),_meta:eA(x0({}))}),O=d.extend({method:rl("notifications/prompts/list_changed"),params:v.optional()}),X=tM({type:rl("text"),text:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),K=tM({type:rl("image"),data:A,mimeType:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),Q=tM({type:rl("audio"),data:A,mimeType:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),M=tM({type:rl("tool_use"),name:ra(),id:ra(),input:e6(ra(),x4()),_meta:e6(ra(),x4()).optional()}),Z=tM({type:rl("resource"),resource:ee([C,P]),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),J=D.extend({type:rl("resource_link")}),V=ee([X,K,Q,J,Z]),H=tM({role:n,content:V}),U=tM({title:ra().optional(),readOnlyHint:eY().optional(),destructiveHint:eY().optional(),idempotentHint:eY().optional(),openWorldHint:eY().optional()}),Y=d.extend({method:rl("notifications/tools/list_changed"),params:v.optional()}),z=tM({name:ra().optional()}),W=tM({hints:rc(z).optional(),costPriority:eD().min(0).max(1).optional(),speedPriority:eD().min(0).max(1).optional(),intelligencePriority:eD().min(0).max(1).optional()}),xx=tM({mode:x1(["auto","required","none"]).optional()}),xe=tM({type:rl("boolean"),title:ra().optional(),description:ra().optional(),default:eY().optional()}),xt=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),minLength:eD().optional(),maxLength:eD().optional(),format:x1(["email","uri","date","date-time"]).optional(),default:ra().optional()}),xr=tM({type:x1(["number","integer"]),title:ra().optional(),description:ra().optional(),minimum:eD().optional(),maximum:eD().optional(),default:eD().optional()}),xa=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),default:ra().optional()}),xn=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),oneOf:rc(tM({const:ra(),title:ra()})),default:ra().optional()}),x_=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),enumNames:rc(ra()).optional(),default:ra().optional()}),xA=ee([xa,xn]),xs=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({type:rl("string"),enum:rc(ra())}),default:rc(ra()).optional()}),xi=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({anyOf:rc(tM({const:ra(),title:ra()}))}),default:rc(ra()).optional()}),xo=ee([xs,xi]),xc=ee([x_,xA,xo]),xv=ee([xc,xe,xt,xr]),xd=c.extend({mode:rl("form").optional(),message:ra(),requestedSchema:tM({type:rl("object"),properties:e6(ra(),xv),required:rc(ra()).optional()}).catchall(x4())}),xf=tM({type:rl("ref/resource"),uri:ra()}),xb=tM({type:rl("ref/prompt"),name:ra()}),xu=tM({uri:ra().startsWith("file://"),name:ra().optional(),_meta:e6(ra(),x4()).optional()}),xp=g.shape,xm=tM({experimental:xp.experimental,sampling:xp.sampling,elicitation:xp.elicitation,roots:xp.roots,extensions:xp.extensions}),xE=y.shape,xj=tM({experimental:xE.experimental,logging:xE.logging,completions:xE.completions,prompts:xE.prompts,resources:xE.resources,tools:xE.tools,extensions:xE.extensions}),xg=x0({progressToken:t.optional(),[xl]:ra(),[xh]:p.optional(),[ef]:xm,[t$]:_.optional()}),xy=tM({...u.shape,...b.shape,description:ra().optional(),inputSchema:x0({$schema:ra().optional(),type:rl("object")}),outputSchema:x0({$schema:ra().optional()}).optional(),annotations:U.optional(),_meta:e6(ra(),x4()).optional()}),xS=tM({type:rl("tool_result"),toolUseId:ra(),content:rc(V),structuredContent:x4().optional(),isError:eY().optional(),_meta:e6(ra(),x4()).optional()}),xI=ee([X,K,Q,M,xS]),xN=tM({role:n,content:ee([xI,rc(xI)]),_meta:e6(ra(),x4()).optional()}),xB=ra(),xF=x0({[tS]:p.optional().catch(void 0)}),xw=xF.optional();function xC(x){return x0({_meta:xw,resultType:xB.default("complete"),...x})}let xP=xC({}),xk=xC({nextCursor:r.optional()}),xD=xC({content:rc(V),structuredContent:x4().optional(),isError:eY().optional()}),xL=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),tools:rc(xy),nextCursor:r.optional()}),xq=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),prompts:rc(G),nextCursor:r.optional()}),xT=xC({description:ra().optional(),messages:rc(H)}),xR=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resources:rc(D),nextCursor:r.optional()}),x$=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resourceTemplates:rc(L),nextCursor:r.optional()}),xG=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),contents:rc(ee([C,P]))}),xO=xC({completion:tM({values:rc(ra()).max(100),total:eD().int().optional(),hasMore:eY().optional()}).loose()}),xX=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"])}),xK=xC({ttlMs:eD().int().min(0).catch(0),cacheScope:x1(["public","private"]).catch("private"),supportedVersions:rc(ra()),capabilities:xj,instructions:ra().optional()}),xQ=tM({messages:rc(xN),modelPreferences:W.optional(),systemPrompt:ra().optional(),includeContext:x1(["none","thisServer","allServers"]).optional(),temperature:eD().optional(),maxTokens:eD().int(),stopSequences:rc(ra()).optional(),metadata:e.optional(),tools:rc(xy).optional(),toolChoice:xx.optional()}),xM=tM({method:rl("sampling/createMessage"),params:xQ}),xZ=tM({method:rl("roots/list"),params:tM({_meta:e6(ra(),x4()).optional()}).optional()}),xJ=tM({...xN.shape,model:ra(),stopReason:ra().optional()}),xV=tM({roots:rc(xu)}),xH=tM({action:x1(["accept","decline","cancel"]),content:e6(ra(),ee([ra(),eD(),eY(),rc(ra())])).optional()}),xU=tM({mode:rl("url"),message:ra(),url:ra().url()}),xY=ee([xd,xU]),xz=tM({method:rl("elicitation/create"),params:xY}),xW=ee([xM,xZ,xz]),x2=ee([xJ,xV,xH]),x3=e6(ra(),xW),x6=e6(ra(),x2),x5=xC({inputRequests:x3.optional(),requestState:ra().optional()}),x7={inputResponses:x6.optional(),requestState:ra().optional()},x8=tM({_meta:xg,...x7}),x9=x0({progressToken:t.optional()});function ex(x,e){return tM({method:rl(x),params:tM({_meta:xg,...e})})}function et(x,e){return tM({method:rl(x),params:tM({_meta:x9.optional(),...e}).optional()})}let er={name:ra(),arguments:e6(ra(),x4()).optional(),...x7},ea={cursor:r.optional()},en=ex("tools/call",er),e_=ex("tools/list",ea),ei=ex("prompts/list",ea),eo=ex("prompts/get",{name:ra(),arguments:e6(ra(),ra()).optional(),...x7}),el=ex("resources/list",ea),ec=ex("resources/templates/list",ea),ev=ex("resources/read",{uri:ra(),...x7}),ed={ref:ee([xb,xf]),argument:tM({name:ra(),value:ra()}),context:tM({arguments:e6(ra(),ra()).optional()}).optional()},eb=ex("completion/complete",ed),eu=ex("server/discover",{}),ep=tM({toolsListChanged:eY().optional(),promptsListChanged:eY().optional(),resourcesListChanged:eY().optional(),resourceSubscriptions:rc(ra()).optional()}),em={notifications:ep},eh=ex("subscriptions/listen",em),eE=xF.extend({"io.modelcontextprotocol/subscriptionId":a}),ej=x0({_meta:eE,resultType:xB.default("complete")}),eg={"tools/call":et("tools/call",er),"tools/list":et("tools/list",ea),"prompts/get":et("prompts/get",{name:ra(),arguments:e6(ra(),ra()).optional()}),"prompts/list":et("prompts/list",ea),"resources/list":et("resources/list",ea),"resources/templates/list":et("resources/templates/list",ea),"resources/read":et("resources/read",{uri:ra()}),"completion/complete":et("completion/complete",ed),"server/discover":et("server/discover",{}),"subscriptions/listen":et("subscriptions/listen",em)};function ey(x){return x0({_meta:xw,...x})}let eS={"tools/call":ey({content:rc(V),structuredContent:x4().optional(),isError:eY().optional()}),"tools/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),tools:rc(xy),nextCursor:r.optional()}),"prompts/get":ey({description:ra().optional(),messages:rc(H)}),"prompts/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),prompts:rc(G),nextCursor:r.optional()}),"resources/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resources:rc(D),nextCursor:r.optional()}),"resources/templates/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resourceTemplates:rc(L),nextCursor:r.optional()}),"resources/read":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),contents:rc(ee([C,P]))}),"completion/complete":ey({completion:tM({values:rc(ra()).max(100),total:eD().int().optional(),hasMore:eY().optional()}).loose()}),"server/discover":ey({ttlMs:eD().int().min(0).catch(0),cacheScope:x1(["public","private"]).catch("private"),supportedVersions:rc(ra()),capabilities:xj,instructions:ra().optional()}),"subscriptions/listen":ey({})},eI=x0({"io.modelcontextprotocol/subscriptionId":a.optional()}),eN=tM({method:rl("notifications/subscriptions/acknowledged"),params:tM({_meta:eI.optional(),notifications:ep})}),eB=tM({_meta:eI.optional(),requestId:a,reason:ra().optional()}),eF=tM({method:rl("notifications/cancelled"),params:eB}),ew=x=>tM({jsonrpc:rl("2.0"),id:ee([ra(),eD().int()]),result:x}).strict();return{JSONValueSchema:x,JSONObjectSchema:e,ProgressTokenSchema:t,CursorSchema:r,RequestIdSchema:a,RoleSchema:n,LoggingLevelSchema:_,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:o,BaseRequestParamsSchema:l,TaskAugmentedRequestParamsSchema:c,NotificationsParamsSchema:v,NotificationSchema:d,IconSchema:f,IconsSchema:b,BaseMetadataSchema:u,ImplementationSchema:p,ClientTasksCapabilitySchema:E,ServerTasksCapabilitySchema:j,ClientCapabilitiesSchema:g,ServerCapabilitiesSchema:y,ProgressSchema:S,ProgressNotificationParamsSchema:I,ProgressNotificationSchema:N,LoggingMessageNotificationParamsSchema:B,LoggingMessageNotificationSchema:F,ResourceContentsSchema:w,TextResourceContentsSchema:C,BlobResourceContentsSchema:P,AnnotationsSchema:k,ResourceSchema:D,ResourceTemplateSchema:L,ResourceListChangedNotificationSchema:q,ResourceUpdatedNotificationParamsSchema:T,ResourceUpdatedNotificationSchema:R,PromptArgumentSchema:$,PromptSchema:G,PromptListChangedNotificationSchema:O,TextContentSchema:X,ImageContentSchema:K,AudioContentSchema:Q,ToolUseContentSchema:M,EmbeddedResourceSchema:Z,ResourceLinkSchema:J,ContentBlockSchema:V,PromptMessageSchema:H,ToolAnnotationsSchema:U,ToolListChangedNotificationSchema:Y,ModelHintSchema:z,ModelPreferencesSchema:W,ToolChoiceSchema:xx,BooleanSchemaSchema:xe,StringSchemaSchema:xt,NumberSchemaSchema:xr,UntitledSingleSelectEnumSchemaSchema:xa,TitledSingleSelectEnumSchemaSchema:xn,LegacyTitledEnumSchemaSchema:x_,SingleSelectEnumSchemaSchema:xA,UntitledMultiSelectEnumSchemaSchema:xs,TitledMultiSelectEnumSchemaSchema:xi,MultiSelectEnumSchemaSchema:xo,EnumSchemaSchema:xc,PrimitiveSchemaDefinitionSchema:xv,ElicitRequestFormParamsSchema:xd,ResourceTemplateReferenceSchema:xf,PromptReferenceSchema:xb,RootSchema:xu,ClientCapabilities2026Schema:xm,ServerCapabilities2026Schema:xj,RequestMetaEnvelopeSchema:xg,ToolSchema:xy,ToolResultContentSchema:xS,SamplingMessageContentBlockSchema:xI,SamplingMessageSchema:xN,ResultTypeSchema:xB,ResultMetaSchema:xF,ResultSchema:xP,PaginatedResultSchema:xk,CallToolResultSchema:xD,ListToolsResultSchema:xL,ListPromptsResultSchema:xq,GetPromptResultSchema:xT,ListResourcesResultSchema:xR,ListResourceTemplatesResultSchema:x$,ReadResourceResultSchema:xG,CompleteResultSchema:xO,CacheableResultSchema:xX,DiscoverResultSchema:xK,CreateMessageRequestParamsSchema:xQ,CreateMessageRequestSchema:xM,ListRootsRequestSchema:xZ,CreateMessageResultSchema:xJ,ListRootsResultSchema:xV,ElicitResultSchema:xH,ElicitRequestURLParamsSchema:xU,ElicitRequestParamsSchema:xY,ElicitRequestSchema:xz,InputRequestSchema:xW,InputResponseSchema:x2,InputRequestsSchema:x3,InputResponsesSchema:x6,InputRequiredResultSchema:x5,InputResponseRequestParamsSchema:x8,CallToolRequestSchema:en,ListToolsRequestSchema:e_,ListPromptsRequestSchema:ei,GetPromptRequestSchema:eo,ListResourcesRequestSchema:el,ListResourceTemplatesRequestSchema:ec,ReadResourceRequestSchema:ev,CompleteRequestSchema:eb,DiscoverRequestSchema:eu,SubscriptionFilterSchema:ep,SubscriptionsListenRequestSchema:eh,SubscriptionsListenResultMetaSchema:eE,SubscriptionsListenResultSchema:ej,dispatchRequestSchemas:eg,dispatchResultSchemas:eS,NotificationMetaSchema:eI,SubscriptionsAcknowledgedNotificationSchema:eN,CancelledNotificationParamsSchema:eB,CancelledNotificationSchema:eF,notificationSchemas2026:{"notifications/cancelled":eF,"notifications/progress":N,"notifications/message":F,"notifications/resources/updated":R,"notifications/resources/list_changed":q,"notifications/tools/list_changed":Y,"notifications/prompts/list_changed":O,"notifications/subscriptions/acknowledged":eN},JSONRPCResultResponseSchema:ew(xP),CallToolResultResponseSchema:ew(ee([xD,x5])),ListToolsResultResponseSchema:ew(xL),ListPromptsResultResponseSchema:ew(xq),GetPromptResultResponseSchema:ew(ee([xT,x5])),ListResourcesResultResponseSchema:ew(xR),ListResourceTemplatesResultResponseSchema:ew(x$),ReadResourceResultResponseSchema:ew(ee([xG,x5])),CompleteResultResponseSchema:ew(xO),DiscoverResultResponseSchema:ew(xK)}}()}let bl=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"],bc=Symbol("modelcontextprotocol.resultCacheHintFallback");function bv(x,e){if(void 0===e)return x;let t=x[bc];if(void 0===t)return{...x,[bc]:e};let r={},a=t.ttlMs??e.ttlMs;void 0!==a&&(r.ttlMs=a);let n=t.cacheScope??e.cacheScope;return void 0!==n&&(r.cacheScope=n),{...x,[bc]:r}}function bd(x){return"number"==typeof x&&Number.isSafeInteger(x)&&x>=0}function bf(x){return"public"===x||"private"===x}function bb(x,e){if(void 0!==x.ttlMs&&!bd(x.ttlMs))throw RangeError(`Invalid cache hint for ${e}: ttlMs must be a non-negative safe integer (got ${String(x.ttlMs)})`);if(void 0!==x.cacheScope&&!bf(x.cacheScope))throw RangeError(`Invalid cache hint for ${e}: cacheScope must be 'public' or 'private' (got ${String(x.cacheScope)})`)}let bu=((rK={})[rK.ParseError=-32700]="ParseError",rK[rK.InvalidRequest=-32600]="InvalidRequest",rK[rK.MethodNotFound=-32601]="MethodNotFound",rK[rK.InvalidParams=-32602]="InvalidParams",rK[rK.InternalError=-32603]="InternalError",rK[rK.ResourceNotFound=-32002]="ResourceNotFound",rK[rK.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",rK[rK.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",rK[rK.UrlElicitationRequired=-32042]="UrlElicitationRequired",rK);var bp=class x extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](x){return fZ(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fZ(this,x)}constructor(x,e,t){super(e),this.code=x,this.data=t,this.name="ProtocolError",fM(this,new.target)}static fromError(e,t,r){return e===bu.UrlElicitationRequired&&r&&r.elicitations?new bh(r.elicitations,t):e===bu.UnsupportedProtocolVersion&&r&&Array.isArray(r.supported)&&"string"==typeof r.requested?new bE({supported:r.supported,requested:r.requested},t):(e===bu.InvalidParams||e===bu.ResourceNotFound)&&"string"==typeof r?.uri&&(e===bu.ResourceNotFound||1===Object.keys(r).length)?new bm(r.uri,t):e===bu.MissingRequiredClientCapability&&r&&null!==r.requiredCapabilities&&"object"==typeof r.requiredCapabilities&&!Array.isArray(r.requiredCapabilities)?new bj({requiredCapabilities:r.requiredCapabilities},t):new x(e,t,r)}},bm=class extends bp{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(x,e=`Resource not found: ${x}`){super(bu.InvalidParams,e,{uri:x})}get uri(){return this.data.uri}},bh=class extends bp{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(x,e=`URL elicitation${x.length>1?"s":""} required`){super(bu.UrlElicitationRequired,e,{elicitations:x})}get elicitations(){return this.data?.elicitations??[]}},bE=class extends bp{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(x,e=`Unsupported protocol version: ${x.requested}`){super(bu.UnsupportedProtocolVersion,e,x)}get supported(){return this.data.supported}get requested(){return this.data.requested}},bj=class extends bp{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(x,e=`Missing required client capabilities: ${Object.keys(x.requiredCapabilities).join(", ")}`){super(bu.MissingRequiredClientCapability,e,x)}get requiredCapabilities(){return this.data.requiredCapabilities}};let bg=["tools/call","prompts/get","resources/read"],by=["elicitation/create","sampling/createMessage","roots/list"];function bS(){if(_)return _;let x=bo();return _={request:{"elicitation/create":tM({method:rl("elicitation/create"),params:x.ElicitRequestParamsSchema}),"sampling/createMessage":tM({method:rl("sampling/createMessage"),params:x.CreateMessageRequestParamsSchema}),"roots/list":tM({method:rl("roots/list"),params:x0({}).optional()})},response:{"elicitation/create":x.ElicitResultSchema,"sampling/createMessage":x.CreateMessageResultSchema,"roots/list":x.ListRootsResultSchema}}}function bI(x){return by.includes(x)}function bN(x){return bI(x)?bS().request[x]:void 0}let bB={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},bF={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function bw(x){return Object.prototype.hasOwnProperty.call(bB,x)}function bC(x){return Object.prototype.hasOwnProperty.call(bF,x)}function bP(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function bk(x,e){if(void 0===x)return{ok:!1,reason:"not-in-era"};let t=x.safeParse(e);return t.success?{ok:!0,value:t.data}:{ok:!1,reason:"invalid",message:String(t.error)}}Object.keys(bB),Object.keys(bF);let bD={ok:!1,reason:"not-in-era"},bL=[xl,ef],bq={era:"2026-07-28",hasRequestMethod:bw,hasNotificationMethod:bC,hasInputRequestMethod:x=>void 0!==bN(x),validateRequest:(x,e)=>bk(bw(x)?bo().dispatchRequestSchemas[x]:void 0,e),validateResult:(x,e)=>bk(Object.prototype.hasOwnProperty.call(bB,x)?bo().dispatchResultSchemas[x]:void 0,e),validateNotification:(x,e)=>bk(bC(x)?bo().notificationSchemas2026[x]:void 0,e),validateInputRequest:(x,e)=>bk(bN(x),e),validateInputResponse:(x,e)=>bk(bI(x)?bS().response[x]:void 0,e),samplingResultVariant:()=>bD,outboundEnvelope:x=>({[xl]:x.protocolVersion,[xh]:x.clientInfo,[ef]:x.clientCapabilities,...void 0!==x.logLevel&&{[t$]:x.logLevel}}),validateEnvelopeMeta(x){let e=[];for(let t of bL)t in x||e.push({key:t,problem:"missing"});let t=bo().RequestMetaEnvelopeSchema.safeParse(x);if(!t.success)for(let x of t.error.issues){let t=x.path.map(String),r=t.length>0?t.join("."):"_meta";1===t.length&&e.some(x=>x.key===r&&"missing"===x.problem)||e.push({key:r,problem:x.message})}return e},projectCallToolResult:x=>f1(x),inputRequestSchema:bN,decodeResult(x,e){if(!bP(e))return{kind:"invalid",error:new fV(fJ.InvalidResult,`Invalid result for ${x}: not an object`,{method:x})};let t=e.resultType;if(void 0===t)return{kind:"invalid",error:new fV(fJ.InvalidResult,`Invalid result for ${x}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:x,violation:"missing-resultType"})};if("string"!=typeof t)return{kind:"invalid",error:new fV(fJ.InvalidResult,`Invalid result for ${x}: non-string resultType`,{method:x,resultType:t})};if("input_required"===t){let t=e.inputRequests,r=bP(t)?t:{},a=e.requestState;return 0===Object.keys(r).length&&"string"!=typeof a?{kind:"invalid",error:new fV(fJ.InvalidResult,`Invalid result for ${x}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:x,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:r,..."string"==typeof a&&{requestState:a}}}if("complete"!==t)return{kind:"invalid",error:new fV(fJ.UnsupportedResultType,`Unsupported result type '${t}' for ${x}`,{resultType:t,method:x})};let r=function(){if(A)return A;let x=bo();return A={"tools/call":x.CallToolResultSchema,"tools/list":x.ListToolsResultSchema,"prompts/get":x.GetPromptResultSchema,"prompts/list":x.ListPromptsResultSchema,"resources/list":x.ListResourcesResultSchema,"resources/templates/list":x.ListResourceTemplatesResultSchema,"resources/read":x.ReadResourceResultSchema,"completion/complete":x.CompleteResultSchema,"server/discover":x.DiscoverResultSchema}}(),a=Object.hasOwn(r,x)?r[x]:void 0;if(void 0!==a){let t=a.safeParse(e);if(!t.success)return{kind:"invalid",error:new fV(fJ.InvalidResult,`Invalid result for ${x}: ${t.error}`,{method:x})}}let n={...e};return delete n.resultType,{kind:"complete",result:n}},encodeResult:(x,e,t)=>(function(x,e){if(void 0===e)return x;let t=x._meta;return void 0===t?{...x,_meta:{[tS]:e}}:null===t||"object"!=typeof t||Array.isArray(t)||void 0!==t[tS]?x:{...x,_meta:{...t,[tS]:e}}})(function(x,e){var t,r;let a=e[bc];if("complete"!==e.resultType||!bl.includes(x)){let x;return void 0===a?e:(x={...e},delete x[bc],x)}let n=bd(e.ttlMs)?e.ttlMs:void 0!==(t=a)&&bd(t.ttlMs)?t.ttlMs:0,_=bf(e.cacheScope)?e.cacheScope:void 0!==(r=a)&&bf(r.cacheScope)?r.cacheScope:"private",A={...e,ttlMs:n,cacheScope:_};return delete A[bc],A}(x,function(x,e){let t=e.resultType;if(void 0===t)return{...e,resultType:"complete"};if("complete"===t||bg.includes(x))return e;throw new bp(bu.InternalError,`Handler for ${x} returned resultType '${String(t)}', but results of ${x} only support 'complete' on protocol revision 2026-07-28`)}(x,function(x,e){let t=e,r=!1,a=()=>(r||(t={...t},r=!0),t),n=e.tools;"tools/list"===x&&Array.isArray(n)&&n.some(x=>bP(x)&&"execution"in x)&&(a().tools=n.map(x=>{if(!bP(x)||!("execution"in x))return x;let e={...x};return delete e.execution,e}));let _=e.capabilities;if(bP(_)&&"tasks"in _){let x={..._};delete x.tasks,a().capabilities=x}return t}(x,e))),t),encodeErrorCode:x=>-32002===x?-32602:x,checkInboundEnvelope(x){if(void 0===x.envelope)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let e=bo().RequestMetaEnvelopeSchema.safeParse(x.envelope);if(!e.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${e.error.issues.map(x=>x.message).join("; ")}`}},bT="2026-07-28";function bR(x){return void 0!==x&&x>=fz?bq:bi}function b$(x){return void 0!==x.revision?bR(x.revision).era:"modern"===x.era?bq.era:bi.era}function bG(x){return bX.some(e=>e.hasRequestMethod(x))}function bO(x){return bX.some(e=>e.hasNotificationMethod(x))}let bX=[bi,bq];function bK(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function bQ(x){if(!bK(x))return;let e=x._meta;return bK(e)?e:void 0}function bM(x){let e=bQ(x);return void 0!==e&&xl in e}function bZ(x){let e=bQ(x)?.[xl];return"string"==typeof e?e:void 0}function bJ(x){return bR(bT).validateEnvelopeMeta(x)}var bV=(x=>{let e={};for(var t in x)fk(e,t,{get:x[t],enumerable:!0});return e})({AnnotationsSchema:()=>ro,AudioContentSchema:()=>tx,BaseMetadataSchema:()=>tI,BaseRequestParamsSchema:()=>et,BlobResourceContentsSchema:()=>eB,BooleanSchemaSchema:()=>ed,CallToolRequestParamsSchema:()=>tZ,CallToolRequestSchema:()=>tW,CallToolResultSchema:()=>eu,CancelTaskRequestSchema:()=>xm,CancelTaskResultSchema:()=>e5,CancelledNotificationParamsSchema:()=>rf,CancelledNotificationSchema:()=>ej,ClientCapabilitiesSchema:()=>xB,ClientNotificationSchema:()=>tv,ClientRequestSchema:()=>eK,ClientResultSchema:()=>xc,ClientTasksCapabilitySchema:()=>th,CompatibilityCallToolResultSchema:()=>tb,CompleteRequestParamsSchema:()=>rb,CompleteRequestSchema:()=>xS,CompleteResultSchema:()=>xy,ContentBlockSchema:()=>rs,CreateMessageRequestParamsSchema:()=>xn,CreateMessageRequestSchema:()=>eI,CreateMessageResultSchema:()=>xM,CreateMessageResultWithToolsSchema:()=>xJ,CreateTaskResultSchema:()=>x9,CursorSchema:()=>xV,DiscoverRequestSchema:()=>xI,DiscoverResultSchema:()=>xu,ElicitRequestFormParamsSchema:()=>eb,ElicitRequestParamsSchema:()=>e3,ElicitRequestSchema:()=>e4,ElicitRequestURLParamsSchema:()=>e1,ElicitResultSchema:()=>xK,ElicitationCompleteNotificationParamsSchema:()=>tF,ElicitationCompleteNotificationSchema:()=>ri,EmbeddedResourceSchema:()=>ey,EmptyResultSchema:()=>xC,EnumSchemaSchema:()=>te,GetPromptRequestParamsSchema:()=>tC,GetPromptRequestSchema:()=>rx,GetPromptResultSchema:()=>ts,GetTaskPayloadRequestSchema:()=>ty,GetTaskPayloadResultSchema:()=>xN,GetTaskRequestSchema:()=>e_,GetTaskResultSchema:()=>rd,IconSchema:()=>xY,IconsSchema:()=>e7,ImageContentSchema:()=>ez,ImplementationSchema:()=>tu,InitializeRequestParamsSchema:()=>e8,InitializeRequestSchema:()=>x_,InitializeResultSchema:()=>eT,InitializedNotificationSchema:()=>eG,JSONArraySchema:()=>ep,JSONObjectSchema:()=>xE,JSONRPCErrorResponseSchema:()=>xL,JSONRPCMessageSchema:()=>ei,JSONRPCNotificationSchema:()=>xk,JSONRPCRequestSchema:()=>eE,JSONRPCResponseSchema:()=>eL,JSONRPCResultResponseSchema:()=>eS,JSONValueSchema:()=>tk,LegacyTitledEnumSchemaSchema:()=>er,ListChangedOptionsBaseSchema:()=>xR,ListPromptsRequestSchema:()=>rj,ListPromptsResultSchema:()=>tt,ListResourceTemplatesRequestSchema:()=>tP,ListResourceTemplatesResultSchema:()=>tN,ListResourcesRequestSchema:()=>tA,ListResourcesResultSchema:()=>xA,ListRootsRequestSchema:()=>t4,ListRootsResultSchema:()=>ta,ListTasksRequestSchema:()=>x6,ListTasksResultSchema:()=>t7,ListToolsRequestSchema:()=>rA,ListToolsResultSchema:()=>tV,LoggingLevelSchema:()=>tc,LoggingMessageNotificationParamsSchema:()=>xs,LoggingMessageNotificationSchema:()=>tQ,ModelHintSchema:()=>tp,ModelPreferencesSchema:()=>xP,MultiSelectEnumSchemaSchema:()=>eO,NotificationSchema:()=>e$,NotificationsParamsSchema:()=>tn,NumberSchemaSchema:()=>e0,PaginatedRequestParamsSchema:()=>tf,PaginatedRequestSchema:()=>ex,PaginatedResultSchema:()=>eJ,PingRequestSchema:()=>ru,PrimitiveSchemaDefinitionSchema:()=>ti,ProgressNotificationParamsSchema:()=>en,ProgressNotificationSchema:()=>xv,ProgressSchema:()=>xj,ProgressTokenSchema:()=>tm,PromptArgumentSchema:()=>xi,PromptListChangedNotificationSchema:()=>ev,PromptMessageSchema:()=>xD,PromptReferenceSchema:()=>xz,PromptSchema:()=>to,ReadResourceRequestParamsSchema:()=>xX,ReadResourceRequestSchema:()=>t9,ReadResourceResultSchema:()=>e2,RelatedTaskMetadataSchema:()=>tl,RequestIdSchema:()=>rp,RequestMetaSchema:()=>t5,RequestSchema:()=>eq,ResourceContentsSchema:()=>el,ResourceLinkSchema:()=>xZ,ResourceListChangedNotificationSchema:()=>t6,ResourceRequestParamsSchema:()=>rm,ResourceSchema:()=>x7,ResourceTemplateReferenceSchema:()=>x5,ResourceTemplateSchema:()=>xg,ResourceUpdatedNotificationParamsSchema:()=>xW,ResourceUpdatedNotificationSchema:()=>tG,ResultMetaObjectSchema:()=>tK,ResultSchema:()=>eN,RoleSchema:()=>eQ,RootSchema:()=>re,RootsListChangedNotificationSchema:()=>eF,SamplingContentSchema:()=>eU,SamplingMessageContentBlockSchema:()=>t_,SamplingMessageSchema:()=>ew,ServerCapabilitiesSchema:()=>rh,ServerNotificationSchema:()=>eC,ServerRequestSchema:()=>eg,ServerResultSchema:()=>em,ServerTasksCapabilitySchema:()=>eX,SetLevelRequestParamsSchema:()=>xT,SetLevelRequestSchema:()=>ec,SingleSelectEnumSchemaSchema:()=>xo,StringSchemaSchema:()=>ek,SubscribeRequestParamsSchema:()=>eP,SubscribeRequestSchema:()=>tD,SubscriptionFilterSchema:()=>eR,SubscriptionsAcknowledgedNotificationParamsSchema:()=>tB,SubscriptionsAcknowledgedNotificationSchema:()=>tE,SubscriptionsListenRequestParamsSchema:()=>tR,SubscriptionsListenRequestSchema:()=>rt,SubscriptionsListenResultMetaSchema:()=>tL,SubscriptionsListenResultSchema:()=>xb,TaskAugmentedRequestParamsSchema:()=>tj,TaskCreationParamsSchema:()=>tH,TaskMetadataSchema:()=>xO,TaskSchema:()=>xH,TaskStatusNotificationParamsSchema:()=>xq,TaskStatusNotificationSchema:()=>xp,TaskStatusSchema:()=>tq,TextContentSchema:()=>tY,TextResourceContentsSchema:()=>x$,TitledMultiSelectEnumSchemaSchema:()=>xd,TitledSingleSelectEnumSchemaSchema:()=>ea,ToolAnnotationsSchema:()=>tT,ToolChoiceSchema:()=>eM,ToolExecutionSchema:()=>xU,ToolListChangedNotificationSchema:()=>tr,ToolResultContentSchema:()=>xG,ToolSchema:()=>eZ,ToolUseContentSchema:()=>t2,UnsubscribeRequestParamsSchema:()=>tg,UnsubscribeRequestSchema:()=>tX,UntitledMultiSelectEnumSchemaSchema:()=>rE,UntitledSingleSelectEnumSchemaSchema:()=>eV});let bH=x=>eE.safeParse(x).success,bU=x=>xk.safeParse(x).success,bY=x=>eS.safeParse(x).success,bz=x=>xL.safeParse(x).success,bW=x=>"object"==typeof x&&null!==x&&!Array.isArray(x)&&"input_required"===x.resultType,b0="x-mcp-header",b1=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,b2=new Set(["string","integer","boolean","number"]);function b3(x){let e=[],t=new Map,r=(x,a,n)=>{if(null===x||"object"!=typeof x)return;if(b0 in x){if(!n||0===a.length)return`${b5(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let r=x[b0];if("string"!=typeof r||0===r.length)return`${b5(a)}: x-mcp-header MUST be a non-empty string`;if(!b1.test(r))return`${b5(a)}: x-mcp-header '${r}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let _="string"==typeof x.type?x.type:void 0;if(void 0===_||!b2.has(_))return`${b5(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${_??"<none>"}`;let A=r.toLowerCase(),s=t.get(A);if(void 0!==s)return`x-mcp-header '${r}' is not case-insensitively unique (also declared as '${s}')`;t.set(A,r),e.push({path:a,headerName:r,type:_})}let _=x.properties;if(null!==_&&"object"==typeof _)for(let[x,e]of Object.entries(_)){let t=r(e,[...a,x],n);if(void 0!==t)return t}for(let e of b6){let t=x[e];if(void 0!==t)for(let x of Array.isArray(t)?t:null!==t&&"object"==typeof t&&b4.has(e)?Object.values(t):[t]){let t=r(x,[...a,`<${e}>`],!1);if(void 0!==t)return t}}},a=r(x,[],!0);return void 0===a?{valid:!0,declarations:e}:{valid:!1,reason:a}}let b6=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],b4=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function b5(x){return 0===x.length?"<root>":x.join(".")}let b7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,b8=/^-?\d+(\.\d+)?$/;function b9(x){if(!(x.startsWith("=?base64?")&&x.endsWith("?=")))return x;let e=x.slice(9,x.length-2);if(b7.test(e))try{let x=atob(e),t=new Uint8Array(x.length);for(let e=0;e<x.length;e++)t[e]=x.codePointAt(e);return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}function ux(x,e,t){return{kind:"reject",rung:"param-header-validation",cell:x,httpStatus:400,code:ue,message:`Bad Request: the request headers and body disagree: ${t}`,data:{mismatch:{header:e,body:t}},settled:!0}}let ue=-32020;bu.InvalidRequest,bu.UnsupportedProtocolVersion,bu.InvalidParams,bu.MethodNotFound,bu.InvalidParams,bu.MissingRequiredClientCapability;let ut={[bu.ParseError]:400,[bu.InvalidRequest]:400,[bu.MethodNotFound]:404,[bu.UnsupportedProtocolVersion]:400,[bu.MissingRequiredClientCapability]:400,[ue]:400};function ur(x,e,t,r,a){return{kind:"reject",rung:x,cell:e,httpStatus:t,code:r.code,message:r.message,...void 0!==r.data&&{data:r.data},settled:a}}function ua(x,e,t,r="era-classification"){return ur(r,x,400,new bp(ue,`Bad Request: the request headers and body disagree: ${t}`,{mismatch:{header:e,body:t}}),!0)}let un={"tools/call":"name","prompts/get":"name","resources/read":"uri"};function u_(x){let e=0;for(;e<x.length;){let t=x.codePointAt(e);if(9!==t&&32!==t)break;e+=1}let t=x.length;for(;t>e;){let e=x.codePointAt(t-1);if(9!==e&&32!==e)break;t-=1}return 0===e&&t===x.length?x:x.slice(e,t)}function uA(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function us(x){return void 0===x?{era:"modern"}:{era:x>=fz?"modern":"legacy",revision:x}}function ui(x){return new Set(x.flatMap(x=>Object.keys(x.shape)))}function uo(x){if(null==x)return!1;let e=typeof x;return("object"===e||"function"===e)&&"~standard"in x&&"function"==typeof x["~standard"]?.validate}let ul=!1,uc="draft-2020-12";function uv(x,e="input"){let t,r=x["~standard"];if(r.jsonSchema)t=r.jsonSchema[e]({target:uc});else if("zod"===r.vendor){if(!("_zod"in x))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");ul||(ul=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),t=t8(x,{target:uc,io:e})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if("output"===e)return void 0!==t.type||!function x(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(e=>null!==e&&"object"==typeof e&&("object"===e.type||x(e)))}return!1}(t)?t:{type:"object",...t};if(void 0!==t.type&&"object"!==t.type)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(t.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...t}}async function ud(x,e){let t=await x["~standard"].validate(e);return t.issues&&t.issues.length>0?{success:!1,error:t.issues.map(x=>x.path?.length?`${x.path.map(x=>String("object"==typeof x?x.key:x)).join(".")}: ${x.message}`:x.message).join(", ")}:{success:!0,data:t.value}}let uf=/\\\.\\d\{(\d+)\}/;function ub(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}let uu=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function up(x){return uu.has(x)||x.startsWith("x-")}let um=new Set(["$schema",...Object.keys(eb.shape.requestedSchema.shape)]),uh={string:ui([ek,eV,ea,er]),number:ui([e0]),integer:ui([e0]),boolean:ui([ed]),array:ui([rE,xd])},uE=new Set(ek.shape.format.unwrap().options);Object.assign(function(x){let e=void 0!==x.inputRequests&&Object.keys(x.inputRequests).length>0,t="string"==typeof x.requestState;if(!e&&!t)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...void 0!==x.inputRequests&&{inputRequests:x.inputRequests},...void 0!==x.requestState&&{requestState:x.requestState}}},{elicit(x){try{return{method:"elicitation/create",params:function(x){var e;if(!uo(x.requestedSchema))return{...x,mode:"form",requestedSchema:x.requestedSchema};let t=x.requestedSchema["~standard"].vendor,r=function(x,e){let t={},r=[];for(let[a,n]of Object.entries(x))"properties"===a&&ub(n)?t[a]=Object.fromEntries(Object.entries(n).map(([x,t])=>[x,function(x,e,t,r){if(!ub(x))return x;let a="string"==typeof x.type&&Object.hasOwn(uh,x.type)?uh[x.type]:void 0;if(void 0===a)return x;let n={};for(let[A,s]of Object.entries(x))if(a.has(A)||up(A))n[A]=s;else if("pattern"===A&&"string"===x.type&&"string"==typeof x.format)if(uE.has(x.format)){var _;"string"==typeof s&&(_=x.format,"zod"!==t||(function(x,e){let t;switch(x){case"email":t=[tJ()];break;case"uri":t=[td()];break;case"date":t=[eh()];break;case"date-time":let r,a;r=uf.exec(e),a=[void 0,-1,0],r&&a.push(Number(r[1])),t=[!1,!0].flatMap(x=>[!1,!0].flatMap(e=>a.map(t=>rn({local:x,offset:e,precision:t}))))}return new Set(t.map(x=>{let e;return e=t8(x,{target:uc,io:"input"}),"string"==typeof e.pattern?e.pattern:void 0}).filter(x=>void 0!==x))})(_,s).has(s))||r.push(`${e}.${A}`)}else n[A]=s;else r.push(`${e}.${A}`);return n}(t,`properties.${x}`,e,r)])):um.has(a)?t[a]=n:up(a)||r.push(a);if(r.length>0)throw new bp(bu.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(", ")}`);return t}(function(x){try{return uv(x,"input")}catch(e){let x=e instanceof Error?e.message:String(e);throw new bp(bu.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${x}`)}}(x.requestedSchema),t),a=(e=eb.shape.requestedSchema,rr(e,r));if(!a.success)throw new bp(bu.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${function(x,e){if(!ub(x.properties))return e;let t=Object.entries(x.properties).filter(([,x])=>!rr(ti,x).success).map(([x])=>`properties.${x}`);return t.length>0?t.join(", "):e}(r,a.error.message)}`);let n=function x(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,a)=>x(e,t[a],`${r}[${a}]`)):ub(e)&&ub(t)?Object.entries(e).flatMap(([e,a])=>{let n=r?`${r}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?x(a,t[e],n):up(e)?[]:[n]}):[]}(r,a.data);if(n.length>0)throw new bp(bu.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let _=(a.data.required??[]).filter(x=>!Object.prototype.hasOwnProperty.call(a.data.properties,x));if(_.length>0)throw new bp(bu.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${_.join(", ")}`);return{...x,mode:"form",requestedSchema:a.data}}(x)}}catch(x){throw x instanceof bp?TypeError(x.message,{cause:x}):x}},elicitUrl:x=>({method:"elicitation/create",params:{...x,mode:"url"}}),createMessage:x=>({method:"sampling/createMessage",params:x}),listRoots:()=>({method:"roots/list"})});let uj={},ug={};function uy(x,e){let t=x.slice(0,-6);uj[t]=e,ug[t]=x=>e.safeParse(x).success}for(let x of["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"])uy(x,bV[x]);for(let[x,e]of Object.entries({IdJagTokenExchangeResponseSchema:tz,OAuthClientInformationFullSchema:x3,OAuthClientInformationSchema:eW,OAuthClientMetadataSchema:xF,OAuthClientRegistrationErrorSchema:eH,OAuthErrorResponseSchema:xw,OAuthMetadataSchema:t1,OAuthProtectedResourceMetadataSchema:r_,OAuthTokenRevocationRequestSchema:x8,OAuthTokensSchema:rv,OpenIdProviderDiscoveryMetadataSchema:xf,OpenIdProviderMetadataSchema:eo}))uy(x,e);Object.freeze(uj);let uS=Object.freeze(ug),uI=[xl,xh,ef,t$],uN=["inputResponses","requestState"];function uB(x,e){let t=x.params;if(!uk(t))return{message:x,lifted:{}};let r=t._meta,a=uk(r)?uI.filter(x=>x in r):[],n="request"===e?uN.filter(x=>x in t):[];if(0===a.length&&0===n.length)return{message:x,lifted:{}};let _={},A={...t};if(a.length>0&&uk(r)){let x={},e={...r};for(let t of a)x[t]=r[t],delete e[t];_.envelope=x,Object.keys(e).length>0?A._meta=e:delete A._meta}for(let x of n)"inputResponses"===x&&(_.inputResponses=A[x]),"requestState"===x&&(_.requestState=A[x]),delete A[x];return{message:{...x,params:A},lifted:_}}function uF(x,e){let t=x.validateResult(e,void 0);if(t.ok||"not-in-era"!==t.reason)return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(t){let r=x.validateResult(e,t);return r.ok?{value:r.value}:{issues:[{message:"invalid"===r.reason?r.message:`not-in-era: ${e}`}]}}}}}let uw=(rQ=void 0,()=>rQ);function uC(x,e){return{...x,mcpReq:{...x.mcpReq,requestState:()=>e}}}var uP=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{s=(x,e)=>{x._negotiatedProtocolVersion=e}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(x){this._options=x,this._supportedProtocolVersions=x?.supportedProtocolVersions??tO,this.setNotificationHandler("notifications/cancelled",x=>{this._oncancel(x)}),this.setNotificationHandler("notifications/progress",x=>{this._onprogress(x)}),this.setRequestHandler("ping",x=>({}))}_shouldDropInbound(x){}_outboundMetaEnvelope(){}_envelopeOutbound(x){let e=this._outboundMetaEnvelope();if(void 0===e)return x;let t=x.params??{};return{...x,params:{...t,_meta:{...e,...t._meta}}}}_resolveNonCompleteResult(x,e){return Promise.reject(new fV(fJ.UnsupportedResultType,`Unsupported result type '${x.kind}' for ${e.request.method}`,{resultType:x.kind,method:e.request.method}))}_getRequestHandler(x){return this._requestHandlers.get(x)}async _oncancel(x){x.params.requestId&&this._requestHandlerAbortControllers.get(x.params.requestId)?.abort(x.params.reason)}_setupTimeout(x,e,t,r,a=!1){this._timeoutInfo.set(x,{timeoutId:setTimeout(r,e),startTime:Date.now(),timeout:e,maxTotalTimeout:t,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(x){let e=this._timeoutInfo.get(x);if(!e)return!1;let t=Date.now()-e.startTime;if(e.maxTotalTimeout&&t>=e.maxTotalTimeout)throw this._timeoutInfo.delete(x),new fV(fJ.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:e.maxTotalTimeout,totalElapsed:t});return clearTimeout(e.timeoutId),e.timeoutId=setTimeout(e.onTimeout,e.timeout),!0}_cleanupTimeout(x){let e=this._timeoutInfo.get(x);e&&(clearTimeout(e.timeoutId),this._timeoutInfo.delete(x))}async connect(x){this._transport=x;let e=this.transport?.onclose;this._transport.onclose=()=>{try{e?.()}finally{this._onclose()}};let t=this.transport?.onerror;this._transport.onerror=x=>{t?.(x),this._onerror(x)};let r=this._transport?.onmessage;this._transport.onmessage=(x,e)=>{r?.(x,e),bY(x)||bz(x)?this._onresponse(x):bH(x)?this._onrequest(x,e):bU(x)?this._onnotification(x,e):this._onerror(Error(`Unknown message type: ${JSON.stringify(x)}`))},x.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let x=this._responseHandlers;for(let x of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._timeoutInfo.values()))clearTimeout(x.timeoutId);this._timeoutInfo.clear();let e=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let t=new fV(fJ.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let e of x.values())e(t);for(let x of e.values())x.abort(t)}}_onerror(x){this.onerror?.(x)}_onnotification(x,e){let{message:t}=uB(x,"notification"),r=this._negotiatedWireCodec();if(e?.classification===void 0&&"drop"===this._shouldDropInbound(x))return;if(e?.classification!==void 0){let x=b$(e.classification);if(x!==r.era)return void this._onerror(Error(`Era mismatch on inbound notification '${t.method}': classified as ${x} but this instance serves ${r.era}`))}if(bO(t.method)&&!r.hasNotificationMethod(t.method))return;let a=this._notificationHandlers.get(t.method),n=this.fallbackNotificationHandler;(void 0!==a||void 0!==n)&&Promise.resolve().then(()=>void 0===a?n(t):a(t,r)).catch(x=>this._onerror(Error(`Uncaught error in notification handler: ${x}`)))}_onrequest(x,e){var t;let{message:r,lifted:a}=uB(x,"request"),n=this._negotiatedWireCodec();if(e?.classification===void 0&&"drop"===this._shouldDropInbound(x))return void this._onerror(Error(`Dropped inbound request '${x.method}': not servable on this connection's protocol era`));let _=this._transport,A=(x,e,t)=>{let a={jsonrpc:"2.0",id:r.id,error:{code:x,message:e,...void 0!==t&&{data:t}}};_?.send(a).catch(x=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(e?.classification!==void 0){let x=b$(e.classification);if(x!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${x} but this instance serves ${n.era}`));let t=e.classification.revision??x;A(bu.UnsupportedProtocolVersion,`Unsupported protocol version: ${t}`,{supported:this._supportedProtocolVersions,requested:t});return}}if(bG(r.method)&&!n.hasRequestMethod(r.method))return void A(bu.MethodNotFound,"Method not found");let s=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(void 0===s)return void A(bu.MethodNotFound,"Method not found");let i=n.checkInboundEnvelope(a);if(void 0!==i)return void A(bu.InvalidParams,i);let o=(x,e)=>this._notificationViaCodec(this._resolveOutboundCodec(x.method),x,{...e,relatedRequestId:r.id}),l=(x,e,t)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(x.method),x,e,{...t,relatedRequestId:r.id}),c=new AbortController;this._requestHandlerAbortControllers.set(r.id,c);let v=void 0===a.inputResponses?void 0:function(x){let e={},t=[];if(!uD(x))return{accepted:e,droppedKeys:t};for(let[r,a]of Object.entries(x)){if(!uD(a)||"method"in a||"result"in a){t.push(r);continue}e[r]=a}return{accepted:e,droppedKeys:t}}(a.inputResponses),d={sessionId:_?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...void 0!==a.envelope&&{envelope:a.envelope},...void 0!==v&&{inputResponses:v.accepted},...void 0!==v&&v.droppedKeys.length>0&&{droppedInputResponseKeys:v.droppedKeys},requestState:void 0===a.requestState?uw:(t=a.requestState,()=>t),signal:c.signal,send:(x,e,t)=>{let r=this._resolveOutboundCodec(x.method);if(this._assertOutboundRequestInEra(r,x.method),uo(e))return l(x,e,t);let a=uF(r,x.method);if(void 0===a)throw TypeError(`'${x.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return l(x,a,e)},notify:o},http:e?.authInfo?{authInfo:e.authInfo}:void 0},f=this.buildContext(d,e);Promise.resolve().then(()=>s(r,f)).then(async x=>{let e;if(c.signal.aborted)return;try{e=n.encodeResult(r.method,x,this._outboundServerInfo())}catch(x){this._onerror(Error(`Failed to encode result for ${r.method}: ${x}`)),A(bu.InternalError,"Internal error");return}let t={result:e,jsonrpc:"2.0",id:r.id};await _?.send(t)},async x=>{if(c.signal.aborted)return;let e=Number.isSafeInteger(x.code)?x.code:bu.InternalError,t={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(e),message:x.message??"Internal error",...void 0!==x.data&&{data:x.data}}};await _?.send(t)}).catch(x=>this._onerror(Error(`Failed to send response: ${x}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===c&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(x){let{progressToken:e,...t}=x.params,r=Number(e),a=this._progressHandlers.get(r);if(!a)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(x)}`));let n=this._responseHandlers.get(r),_=this._timeoutInfo.get(r);if(_&&n&&_.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(x){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),n(x);return}a(t)}_onresponse(x){let e=Number(x.id),t=this._responseHandlers.get(e);void 0===t?this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(x)}`)):(this._responseHandlers.delete(e),this._cleanupTimeout(e),this._progressHandlers.delete(e),t(bY(x)?x:bp.fromError(x.error.code,x.error.message,x.error.data)))}get transport(){return this._transport}async close(){await this._transport?.close()}request(x,e,t){let r=this._resolveOutboundCodec(x.method);if(this._assertOutboundRequestInEra(r,x.method),uo(e))return this._requestWithSchemaViaCodec(r,x,e,t);let a=uF(r,x.method);if(void 0===a)throw TypeError(`'${x.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,x,a,e)}_negotiatedWireCodec(){return bR(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(x){if(void 0===this._negotiatedProtocolVersion){let e=function(x){switch(x){case"initialize":case"notifications/initialized":return bR(void 0);case"server/discover":return bR(bT);default:return}}(x);if(e)return e}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(x,e){if(bG(e)&&!x.hasRequestMethod(e))throw new fV(fJ.MethodNotSupportedByProtocolVersion,`Method '${e}' is not supported by the negotiated protocol version (wire era ${x.era})`,{method:e,era:x.era})}_requestWithSchema(x,e,t){let r=this._resolveOutboundCodec(x.method);return this._assertOutboundRequestInEra(r,x.method),this._requestWithSchemaViaCodec(r,x,e,t)}_requestWithSchemaViaCodec(x,e,t,r){let a,n,{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s,headers:i}=r??{},o=Date.now();return new Promise((l,c)=>{let v=x=>{c(x)};if(!this._transport)return void v(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(x){v(x);return}if(r?.signal?.aborted){let x=r.signal.reason;throw x instanceof fV?x:new fV(fJ.RequestTimeout,String(x))}let d=x.era===bT&&!0===this._transport.hasPerRequestStream?new AbortController:void 0,f=this._requestMessageId++;n=f;let b={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),b.params={...e.params,_meta:{...e.params?._meta,progressToken:f}});let u=this._envelopeOutbound(b),p=!1,m=x=>{p||(this._progressHandlers.delete(f),void 0===d?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(x)}}),{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s}).catch(x=>this._onerror(Error(`Failed to send cancellation: ${x}`))):d.abort(),c(x instanceof fV?x:new fV(fJ.RequestTimeout,String(x))))};this._responseHandlers.set(f,a=>{let n;if(!r?.signal?.aborted){if(p=!0,a instanceof Error)return c(a);try{n=x.decodeResult(e.method,a.result)}catch(x){return c(x instanceof Error?x:Error(String(x)))}if("invalid"===n.kind)return c(n.error);if("input_required"===n.kind){var _;return r?.allowInputRequired===!0?l({resultType:"input_required",inputRequests:(_=n).inputRequests,...void 0!==_.requestState&&{requestState:_.requestState}}):l(this._resolveNonCompleteResult(n,{codec:x,request:e,resultSchema:t,options:r,flowStartedAt:o,retry:(r,a)=>this._requestWithSchemaViaCodec(x,void 0===r?{method:e.method}:{method:e.method,params:r},t,a)}))}ud(t,n.result).then(x=>{x.success?l(x.data):c(new fV(fJ.InvalidResult,`Invalid result for ${e.method}: ${x.error}`))},c)}}),a=()=>m(r?.signal?.reason),r?.signal?.addEventListener("abort",a,{once:!0});let h=r?.timeout??6e4;this._setupTimeout(f,h,r?.maxTotalTimeout,()=>m(new fV(fJ.RequestTimeout,"Request timed out",{timeout:h})),r?.resetTimeoutOnProgress??!1),this._transport.send(u,{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s,headers:i,requestSignal:d?.signal}).catch(x=>{this._progressHandlers.delete(f),c(x)})}).finally(()=>{a&&r?.signal?.removeEventListener("abort",a),void 0!==n&&(this._responseHandlers.delete(n),this._cleanupTimeout(n))})}async notification(x,e){return this._notificationViaCodec(this._resolveOutboundCodec(x.method),x,e)}async _notificationViaCodec(x,e,t){if(!this._transport)throw new fV(fJ.NotConnected,"Not connected");if(bO(e.method)&&!x.hasNotificationMethod(e.method))throw new fV(fJ.MethodNotSupportedByProtocolVersion,`Notification '${e.method}' is not supported by the negotiated protocol version (wire era ${x.era})`,{method:e.method,era:x.era});this.assertNotificationCapability(e.method);let r=this._envelopeOutbound({jsonrpc:"2.0",...e});if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(r,t).catch(x=>this._onerror(x))});return}await this._transport.send(r,t)}setRequestHandler(x,e,t){let r;if(this.assertRequestHandlerCapability(x),"function"==typeof e){if(!bG(x))throw TypeError(`'${x}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(t,r)=>{let a=this._negotiatedWireCodec(),n=a.validateRequest(x,t);if(n.ok||"not-in-era"!==n.reason||(n=a.validateInputRequest(x,t)),!n.ok){if("not-in-era"===n.reason)throw new bp(bu.InternalError,`No wire schema for ${x} in the resolved era`);throw Error(n.message)}return Promise.resolve(e(n.value,r))}}else if(t)r=async(r,a)=>{let n=await ud(e.params,{...r.params});if(!n.success)throw new bp(bu.InvalidParams,`Invalid params for ${x}: ${n.error}`);return t(n.data,a)};else throw TypeError("setRequestHandler: handler is required");this._requestHandlers.set(x,this._wrapHandler(x,r))}_wrapHandler(x,e){return e}_outboundServerInfo(){}removeRequestHandler(x){this._requestHandlers.delete(x)}assertCanSetRequestHandler(x){if(this._requestHandlers.has(x))throw Error(`A request handler for ${x} already exists, which would be overridden`)}setNotificationHandler(x,e,t){if("function"==typeof e){if(!bO(x))throw TypeError(`'${x}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(x,(t,r)=>{let a=r.validateNotification(x,t);if(!a.ok){if("not-in-era"===a.reason)throw new bp(bu.InternalError,`No wire schema for ${x} in the resolved era`);throw Error(a.message)}return Promise.resolve(e(a.value))});return}if(!t)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(x,async r=>{let a=await ud(e.params,{...r.params});if(!a.success)throw new bp(bu.InvalidParams,`Invalid params for notification ${x}: ${a.error}`);await t(a.data,r)})}removeNotificationHandler(x){this._notificationHandlers.delete(x)}};function uk(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function uD(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}var uL=f$(fR(x=>{var e=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,t=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function a(x){this.parameters=Object.create(null),this.type=x}x.parse=function(x){if(!x)throw TypeError("argument string is required");var n,_,A,s="object"==typeof x?function(x){var e;if("function"==typeof x.getHeader?e=x.getHeader("content-type"):"object"==typeof x.headers&&(e=x.headers&&x.headers["content-type"]),"string"!=typeof e)throw TypeError("content-type header is missing from object");return e}(x):x;if("string"!=typeof s)throw TypeError("argument string is required to be a string");var i=s.indexOf(";"),o=-1!==i?s.slice(0,i).trim():s.trim();if(!r.test(o))throw TypeError("invalid media type");var l=new a(o.toLowerCase());if(-1!==i){for(e.lastIndex=i;_=e.exec(s);){if(_.index!==i)throw TypeError("invalid parameter format");i+=_[0].length,n=_[1].toLowerCase(),34===(A=_[2]).charCodeAt(0)&&-1!==(A=A.slice(1,-1)).indexOf("\\")&&(A=A.replace(t,"$1")),l.parameters[n]=A}if(i!==s.length)throw TypeError("invalid parameter format")}return l}})(),1);function uq(x){if(x)try{return uL.parse(x).type}catch{let e=(x.split(";",1)[0]??"").trim().toLowerCase();if(""===e||x.slice(e.length).includes(","))return;return e}}function uT(x){return"application/json"===x||"application/json"===uq(x)}let uR=/^[A-Za-z0-9._-]{1,128}$/;function u$(x){let e=function(x){let e=[];if(0===x.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(x.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${x.length})`]};if(x.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),x.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(x.startsWith("-")||x.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(x.startsWith(".")||x.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!uR.test(x)){let t=[...x].filter(x=>!/[A-Za-z0-9._-]/.test(x)).filter((x,e,t)=>t.indexOf(x)===e);return e.push(`Tool name contains invalid characters: ${t.map(x=>`"${x}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}(x);var t=e.warnings;if(t.length>0){for(let e of(console.warn(`Tool name validation warning for "${x}":`),t))console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return e.isValid}function uG(x){if(void 0!==x){if(function(x){if("object"!=typeof x||null===x||uo(x))return!1;let e=Object.getPrototypeOf(x);return(e===Object.prototype||null===e)&&Object.values(x).every(x=>"object"==typeof x&&null!==x&&"_zod"in x)}(x))return tM(x);if("object"==typeof x&&null!==x&&!uo(x)&&Object.values(x).some(x=>"object"==typeof x&&null!==x&&!("_zod"in x)&&"_def"in x&&"string"==typeof x._def?.typeName))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!uo(x))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return x}}var uO=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.regexpCode=x.getEsmExportName=x.getProperty=x.safeStringify=x.stringify=x.strConcat=x.addCodeArg=x.str=x._=x.nil=x._Code=x.Name=x.IDENTIFIER=x._CodeOrName=void 0;var e=class{};x._CodeOrName=e,x.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var t=class extends e{constructor(e){if(super(),!x.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};x.Name=t;var r=class extends e{constructor(x){super(),this._items="string"==typeof x?[x]:x}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let x=this._items[0];return""===x||'""'===x}get str(){var x;return null!=(x=this._str)?x:this._str=this._items.reduce((x,e)=>`${x}${e}`,"")}get names(){var x;return null!=(x=this._names)?x:this._names=this._items.reduce((x,e)=>(e instanceof t&&(x[e.str]=(x[e.str]||0)+1),x),{})}};function a(x,...e){let t=[x[0]],n=0;for(;n<e.length;)A(t,e[n]),t.push(x[++n]);return new r(t)}x._Code=r,x.nil=new r(""),x._=a;let n=new r("+");function _(x,...e){let a=[s(x[0])],i=0;for(;i<e.length;)a.push(n),A(a,e[i]),a.push(n,s(x[++i]));return function(x){let e=1;for(;e<x.length-1;){if(x[e]===n){var r,a;let n=(r=x[e-1],'""'===(a=x[e+1])?r:'""'===r?a:"string"==typeof r?a instanceof t||'"'!==r[r.length-1]?void 0:"string"!=typeof a?`${r.slice(0,-1)}${a}"`:'"'===a[0]?r.slice(0,-1)+a.slice(1):void 0:"string"!=typeof a||'"'!==a[0]||r instanceof t?void 0:`"${r}${a.slice(1)}`);if(void 0!==n){x.splice(e-1,3,n);continue}x[e++]="+"}e++}}(a),new r(a)}function A(x,e){var a;e instanceof r?x.push(...e._items):e instanceof t?x.push(e):x.push("number"==typeof(a=e)||"boolean"==typeof a||null===a?a:s(Array.isArray(a)?a.join(","):a))}function s(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}x.str=_,x.addCodeArg=A,x.strConcat=function(x,e){return e.emptyStr()?x:x.emptyStr()?e:_`${x}${e}`},x.stringify=function(x){return new r(s(x))},x.safeStringify=s,x.getProperty=function(e){return"string"==typeof e&&x.IDENTIFIER.test(e)?new r(`.${e}`):a`[${e}]`},x.getEsmExportName=function(e){if("string"==typeof e&&x.IDENTIFIER.test(e))return new r(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},x.regexpCode=function(x){return new r(x.toString())}}),uX=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.ValueScope=x.ValueScopeName=x.Scope=x.varKinds=x.UsedValueState=void 0;let e=uO();var t,r,a=class extends Error{constructor(x){super(`CodeGen: "code" for ${x} not defined`),this.value=x.value}};(t=r||(x.UsedValueState=r={}))[t.Started=0]="Started",t[t.Completed=1]="Completed",x.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};var n=class{constructor({prefixes:x,parent:e}={}){this._names={},this._prefixes=x,this._parent=e}toName(x){return x instanceof e.Name?x:this.name(x)}name(x){return new e.Name(this._newName(x))}_newName(x){let e=this._names[x]||this._nameGroup(x);return`${x}${e.index++}`}_nameGroup(x){var e,t;if((null==(t=null==(e=this._parent)?void 0:e._prefixes)?void 0:t.has(x))||this._prefixes&&!this._prefixes.has(x))throw Error(`CodeGen: prefix "${x}" is not allowed in this scope`);return this._names[x]={prefix:x,index:0}}};x.Scope=n;var _=class extends e.Name{constructor(x,e){super(e),this.prefix=x}setValue(x,{property:t,itemIndex:r}){this.value=x,this.scopePath=(0,e._)`.${new e.Name(t)}[${r}]`}};x.ValueScopeName=_;let A=(0,e._)`\n`;var s=class extends n{constructor(x){super(x),this._values={},this._scope=x.scope,this.opts={...x,_n:x.lines?A:e.nil}}get(){return this._scope}name(x){return new _(x,this._newName(x))}value(x,e){var t;if(void 0===e.ref)throw Error("CodeGen: ref must be passed in value");let r=this.toName(x),{prefix:a}=r,n=null!=(t=e.key)?t:e.ref,_=this._values[a];if(_){let x=_.get(n);if(x)return x}else _=this._values[a]=new Map;_.set(n,r);let A=this._scope[a]||(this._scope[a]=[]),s=A.length;return A[s]=e.ref,r.setValue(e,{property:a,itemIndex:s}),r}getValue(x,e){let t=this._values[x];if(t)return t.get(e)}scopeRefs(x,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw Error(`CodeGen: name "${t}" has no value`);return(0,e._)`${x}${t.scopePath}`})}scopeCode(x=this._values,e,t){return this._reduceValues(x,x=>{if(void 0===x.value)throw Error(`CodeGen: name "${x}" has no value`);return x.value.code},e,t)}_reduceValues(t,n,_={},A){let s=e.nil;for(let i in t){let o=t[i];if(!o)continue;let l=_[i]=_[i]||new Map;o.forEach(t=>{if(l.has(t))return;l.set(t,r.Started);let _=n(t);if(_){let r=this.opts.es5?x.varKinds.var:x.varKinds.const;s=(0,e._)`${s}${r} ${t} = ${_};${this.opts._n}`}else if(_=null==A?void 0:A(t))s=(0,e._)`${s}${_}${this.opts._n}`;else throw new a(t);l.set(t,r.Completed)})}return s}};x.ValueScope=s}),uK=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.or=x.and=x.not=x.CodeGen=x.operators=x.varKinds=x.ValueScopeName=x.ValueScope=x.Scope=x.Name=x.regexpCode=x.stringify=x.getProperty=x.nil=x.strConcat=x.str=x._=void 0;let e=uO(),t=uX();var r=uO();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return r.Name}});var a=uX();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),x.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};var n=class{optimizeNodes(){return this}optimizeNames(x,e){return this}},_=class extends n{constructor(x,e,t){super(),this.varKind=x,this.name=e,this.rhs=t}render({es5:x,_n:e}){let r=x?t.varKinds.var:this.varKind,a=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${a};`+e}optimizeNames(x,e){if(x[this.name.str])return this.rhs&&(this.rhs=w(this.rhs,x,e)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}},A=class extends n{constructor(x,e,t){super(),this.lhs=x,this.rhs=e,this.sideEffects=t}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,t){if(!(this.lhs instanceof e.Name)||x[this.lhs.str]||this.sideEffects)return this.rhs=w(this.rhs,x,t),this}get names(){return F(this.lhs instanceof e.Name?{}:{...this.lhs.names},this.rhs)}},s=class extends A{constructor(x,e,t,r){super(x,t,r),this.op=e}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}},i=class extends n{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}},o=class extends n{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}},l=class extends n{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}},c=class extends n{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,e){return this.code=w(this.code,x,e),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}},v=class extends n{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((e,t)=>e+t.render(x),"")}optimizeNodes(){let{nodes:x}=this,e=x.length;for(;e--;){let t=x[e].optimizeNodes();Array.isArray(t)?x.splice(e,1,...t):t?x[e]=t:x.splice(e,1)}return x.length>0?this:void 0}optimizeNames(x,e){let{nodes:t}=this,r=t.length;for(;r--;){let a=t[r];a.optimizeNames(x,e)||(function(x,e){for(let t in e)x[t]=(x[t]||0)-(e[t]||0)}(x,a.names),t.splice(r,1))}return t.length>0?this:void 0}get names(){return this.nodes.reduce((x,e)=>B(x,e.names),{})}},d=class extends v{render(x){return"{"+x._n+super.render(x)+"}"+x._n}},f=class extends v{},b=class extends d{};b.kind="else";var u=class x extends d{constructor(x,e){super(e),this.condition=x}render(x){let e=`if(${this.condition})`+super.render(x);return this.else&&(e+="else "+this.else.render(x)),e}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){let x=t.optimizeNodes();t=this.else=Array.isArray(x)?new b(x):x}return t?!1===e?t instanceof x?t:t.nodes:this.nodes.length?this:new x(C(e),t instanceof x?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(x,e){var t;if(this.else=null==(t=this.else)?void 0:t.optimizeNames(x,e),super.optimizeNames(x,e)||this.else)return this.condition=w(this.condition,x,e),this}get names(){let x=super.names;return F(x,this.condition),this.else&&B(x,this.else.names),x}};u.kind="if";var p=class extends d{};p.kind="for";var m=class extends p{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,e){if(super.optimizeNames(x,e))return this.iteration=w(this.iteration,x,e),this}get names(){return B(super.names,this.iteration.names)}},h=class extends p{constructor(x,e,t,r){super(),this.varKind=x,this.name=e,this.from=t,this.to=r}render(x){let e=x.es5?t.varKinds.var:this.varKind,{name:r,from:a,to:n}=this;return`for(${e} ${r}=${a}; ${r}<${n}; ${r}++)`+super.render(x)}get names(){return F(F(super.names,this.from),this.to)}},E=class extends p{constructor(x,e,t,r){super(),this.loop=x,this.varKind=e,this.name=t,this.iterable=r}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,e){if(super.optimizeNames(x,e))return this.iterable=w(this.iterable,x,e),this}get names(){return B(super.names,this.iterable.names)}},j=class extends d{constructor(x,e,t){super(),this.name=x,this.args=e,this.async=t}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}};j.kind="func";var g=class extends v{render(x){return"return "+super.render(x)}};g.kind="return";var y=class extends d{render(x){let e="try"+super.render(x);return this.catch&&(e+=this.catch.render(x)),this.finally&&(e+=this.finally.render(x)),e}optimizeNodes(){var x,e;return super.optimizeNodes(),null==(x=this.catch)||x.optimizeNodes(),null==(e=this.finally)||e.optimizeNodes(),this}optimizeNames(x,e){var t,r;return super.optimizeNames(x,e),null==(t=this.catch)||t.optimizeNames(x,e),null==(r=this.finally)||r.optimizeNames(x,e),this}get names(){let x=super.names;return this.catch&&B(x,this.catch.names),this.finally&&B(x,this.finally.names),x}},S=class extends d{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}};S.kind="catch";var I=class extends d{render(x){return"finally"+super.render(x)}};I.kind="finally";var N=class{constructor(x,e={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...e,_n:e.lines?"\n":""},this._extScope=x,this._scope=new t.Scope({parent:x}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,e){let t=this._extScope.value(x,e);return(this._values[t.prefix]||(this._values[t.prefix]=new Set)).add(t),t}getScopeValue(x,e){return this._extScope.getValue(x,e)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,e,t,r){let a=this._scope.toName(e);return void 0!==t&&r&&(this._constants[a.str]=t),this._leafNode(new _(x,a,t)),a}const(x,e,r){return this._def(t.varKinds.const,x,e,r)}let(x,e,r){return this._def(t.varKinds.let,x,e,r)}var(x,e,r){return this._def(t.varKinds.var,x,e,r)}assign(x,e,t){return this._leafNode(new A(x,e,t))}add(e,t){return this._leafNode(new s(e,x.operators.ADD,t))}code(x){return"function"==typeof x?x():x!==e.nil&&this._leafNode(new c(x)),this}object(...x){let t=["{"];for(let[r,a]of x)t.length>1&&t.push(","),t.push(r),(r!==a||this.opts.es5)&&(t.push(":"),(0,e.addCodeArg)(t,a));return t.push("}"),new e._Code(t)}if(x,e,t){if(this._blockNode(new u(x)),e&&t)this.code(e).else().code(t).endIf();else if(e)this.code(e).endIf();else if(t)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new u(x))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(u,b)}_for(x,e){return this._blockNode(x),e&&this.code(e).endFor(),this}for(x,e){return this._for(new m(x),e)}forRange(x,e,r,a,n=this.opts.es5?t.varKinds.var:t.varKinds.let){let _=this._scope.toName(x);return this._for(new h(n,_,e,r),()=>a(_))}forOf(x,r,a,n=t.varKinds.const){let _=this._scope.toName(x);if(this.opts.es5){let x=r instanceof e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,e._)`${x}.length`,t=>{this.var(_,(0,e._)`${x}[${t}]`),a(_)})}return this._for(new E("of",n,_,r),()=>a(_))}forIn(x,r,a,n=this.opts.es5?t.varKinds.var:t.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,e._)`Object.keys(${r})`,a);let _=this._scope.toName(x);return this._for(new E("in",n,_,r),()=>a(_))}endFor(){return this._endBlockNode(p)}label(x){return this._leafNode(new i(x))}break(x){return this._leafNode(new o(x))}return(x){let e=new g;if(this._blockNode(e),this.code(x),1!==e.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(g)}try(x,e,t){if(!e&&!t)throw Error('CodeGen: "try" without "catch" and "finally"');let r=new y;if(this._blockNode(r),this.code(x),e){let x=this.name("e");this._currNode=r.catch=new S(x),e(x)}return t&&(this._currNode=r.finally=new I,this.code(t)),this._endBlockNode(S,I)}throw(x){return this._leafNode(new l(x))}block(x,e){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(e),this}endBlock(x){let e=this._blockStarts.pop();if(void 0===e)throw Error("CodeGen: not in self-balancing block");let t=this._nodes.length-e;if(t<0||void 0!==x&&t!==x)throw Error(`CodeGen: wrong number of nodes: ${t} vs ${x} expected`);return this._nodes.length=e,this}func(x,t=e.nil,r,a){return this._blockNode(new j(x,t,r)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,e){let t=this._currNode;if(t instanceof x||e&&t instanceof e)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${e?`${x.kind}/${e.kind}`:x.kind}"`)}_elseNode(x){let e=this._currNode;if(!(e instanceof u))throw Error('CodeGen: "else" without "if"');return this._currNode=e.else=x,this}get _root(){return this._nodes[0]}get _currNode(){let x=this._nodes;return x[x.length-1]}set _currNode(x){let e=this._nodes;e[e.length-1]=x}};function B(x,e){for(let t in e)x[t]=(x[t]||0)+(e[t]||0);return x}function F(x,t){return t instanceof e._CodeOrName?B(x,t.names):x}function w(x,t,r){var a;if(x instanceof e.Name)return n(x);if(!((a=x)instanceof e._Code&&a._items.some(x=>x instanceof e.Name&&1===t[x.str]&&void 0!==r[x.str])))return x;return new e._Code(x._items.reduce((x,t)=>(t instanceof e.Name&&(t=n(t)),t instanceof e._Code?x.push(...t._items):x.push(t),x),[]));function n(x){let e=r[x.str];return void 0===e||1!==t[x.str]?x:(delete t[x.str],e)}}function C(x){return"boolean"==typeof x||"number"==typeof x||null===x?!x:(0,e._)`!${L(x)}`}x.CodeGen=N,x.not=C;let P=D(x.operators.AND);x.and=function(...x){return x.reduce(P)};let k=D(x.operators.OR);function D(x){return(t,r)=>t===e.nil?r:r===e.nil?t:(0,e._)`${L(t)} ${x} ${L(r)}`}function L(x){return x instanceof e.Name?x:(0,e._)`(${x})`}x.or=function(...x){return x.reduce(k)}}),uQ=fR(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.checkStrictMode=x.getErrorPath=x.Type=x.useFunc=x.setEvaluated=x.evaluatedPropsToName=x.mergeEvaluated=x.eachItem=x.unescapeJsonPointer=x.escapeJsonPointer=x.escapeFragment=x.unescapeFragment=x.schemaRefOrVal=x.schemaHasRulesButRef=x.schemaHasRules=x.checkUnknownRules=x.alwaysValidSchema=x.toHash=void 0;let r=uK(),a=uO();function n(x,e=x.schema){let{opts:t,self:r}=x;if(!t.strictSchema||"boolean"==typeof e)return;let a=r.RULES.keywords;for(let t in e)a[t]||v(x,`unknown keyword: "${t}"`)}function _(x,e){if("boolean"==typeof x)return!x;for(let t in x)if(e[t])return!0;return!1}function A(x){return"number"==typeof x?`${x}`:x.replace(/~/g,"~0").replace(/\//g,"~1")}function s(x){return x.replace(/~1/g,"/").replace(/~0/g,"~")}function i({mergeNames:x,mergeToName:e,mergeValues:t,resultToName:a}){return(n,_,A,s)=>{let i=void 0===A?_:A instanceof r.Name?(_ instanceof r.Name?x(n,_,A):e(n,_,A),A):_ instanceof r.Name?(e(n,A,_),_):t(_,A);return s!==r.Name||i instanceof r.Name?i:a(n,i)}}function o(x,e){if(!0===e)return x.var("props",!0);let t=x.var("props",(0,r._)`{}`);return void 0!==e&&l(x,t,e),t}function l(x,e,t){Object.keys(t).forEach(t=>x.assign((0,r._)`${e}${(0,r.getProperty)(t)}`,!0))}x.toHash=function(x){let e={};for(let t of x)e[t]=!0;return e},x.alwaysValidSchema=function(x,e){return"boolean"==typeof e?e:0===Object.keys(e).length||(n(x,e),!_(e,x.self.RULES.all))},x.checkUnknownRules=n,x.schemaHasRules=_,x.schemaHasRulesButRef=function(x,e){if("boolean"==typeof x)return!x;for(let t in x)if("$ref"!==t&&e.all[t])return!0;return!1},x.schemaRefOrVal=function({topSchemaRef:x,schemaPath:e},t,a,n){if(!n){if("number"==typeof t||"boolean"==typeof t)return t;if("string"==typeof t)return(0,r._)`${t}`}return(0,r._)`${x}${e}${(0,r.getProperty)(a)}`},x.unescapeFragment=function(x){return s(decodeURIComponent(x))},x.escapeFragment=function(x){return encodeURIComponent(A(x))},x.escapeJsonPointer=A,x.unescapeJsonPointer=s,x.eachItem=function(x,e){if(Array.isArray(x))for(let t of x)e(t);else e(x)},x.mergeEvaluated={props:i({mergeNames:(x,e,t)=>x.if((0,r._)`${t} !== true && ${e} !== undefined`,()=>{x.if((0,r._)`${e} === true`,()=>x.assign(t,!0),()=>x.assign(t,(0,r._)`${t} || {}`).code((0,r._)`Object.assign(${t}, ${e})`))}),mergeToName:(x,e,t)=>x.if((0,r._)`${t} !== true`,()=>{!0===e?x.assign(t,!0):(x.assign(t,(0,r._)`${t} || {}`),l(x,t,e))}),mergeValues:(x,e)=>!0===x||{...x,...e},resultToName:o}),items:i({mergeNames:(x,e,t)=>x.if((0,r._)`${t} !== true && ${e} !== undefined`,()=>x.assign(t,(0,r._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(x,e,t)=>x.if((0,r._)`${t} !== true`,()=>x.assign(t,!0===e||(0,r._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(x,e)=>!0===x||Math.max(x,e),resultToName:(x,e)=>x.var("items",e)})},x.evaluatedPropsToName=o,x.setEvaluated=l;let c={};function v(x,e,t=x.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,!0===t)throw Error(e);x.self.logger.warn(e)}}x.useFunc=function(x,e){return x.scopeValue("func",{ref:e,code:c[e.code]||(c[e.code]=new a._Code(e.code))})},(t=e||(x.Type=e={}))[t.Num=0]="Num",t[t.Str=1]="Str",x.getErrorPath=function(x,t,a){if(x instanceof r.Name){let n=t===e.Num;return a?n?(0,r._)`"[" + ${x} + "]"`:(0,r._)`"['" + ${x} + "']"`:n?(0,r._)`"/" + ${x}`:(0,r._)`"/" + ${x}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return a?(0,r.getProperty)(x).toString():"/"+A(x)},x.checkStrictMode=v}),uM=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK();x.default={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")}}),uZ=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.extendErrors=x.resetErrorsCount=x.reportExtraError=x.reportError=x.keyword$DataError=x.keywordError=void 0;let e=uK(),t=uQ(),r=uM();function a(x,t){let a=x.const("err",t);x.if((0,e._)`${r.default.vErrors} === null`,()=>x.assign(r.default.vErrors,(0,e._)`[${a}]`),(0,e._)`${r.default.vErrors}.push(${a})`),x.code((0,e._)`${r.default.errors}++`)}function n(x,t){let{gen:r,validateName:a,schemaEnv:n}=x;n.$async?r.throw((0,e._)`new ${x.ValidationError}(${t})`):(r.assign((0,e._)`${a}.errors`,t),r.return(!1))}x.keywordError={message:({keyword:x})=>(0,e.str)`must pass "${x}" keyword validation`},x.keyword$DataError={message:({keyword:x,schemaType:t})=>t?(0,e.str)`"${x}" keyword must be ${t} ($data)`:(0,e.str)`"${x}" keyword is invalid ($data)`},x.reportError=function(t,r=x.keywordError,_,s){let{it:i}=t,{gen:o,compositeRule:l,allErrors:c}=i,v=A(t,r,_);(null!=s?s:l||c)?a(o,v):n(i,(0,e._)`[${v}]`)},x.reportExtraError=function(e,t=x.keywordError,_){let{it:s}=e,{gen:i,compositeRule:o,allErrors:l}=s;a(i,A(e,t,_)),o||l||n(s,r.default.vErrors)},x.resetErrorsCount=function(x,t){x.assign(r.default.errors,t),x.if((0,e._)`${r.default.vErrors} !== null`,()=>x.if(t,()=>x.assign((0,e._)`${r.default.vErrors}.length`,t),()=>x.assign(r.default.vErrors,null)))},x.extendErrors=function({gen:x,keyword:t,schemaValue:a,data:n,errsCount:_,it:A}){if(void 0===_)throw Error("ajv implementation error");let s=x.name("err");x.forRange("i",_,r.default.errors,_=>{x.const(s,(0,e._)`${r.default.vErrors}[${_}]`),x.if((0,e._)`${s}.instancePath === undefined`,()=>x.assign((0,e._)`${s}.instancePath`,(0,e.strConcat)(r.default.instancePath,A.errorPath))),x.assign((0,e._)`${s}.schemaPath`,(0,e.str)`${A.errSchemaPath}/${t}`),A.opts.verbose&&(x.assign((0,e._)`${s}.schema`,a),x.assign((0,e._)`${s}.data`,n))})};let _={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function A(x,a,n){let{createErrors:A}=x.it;return!1===A?(0,e._)`{}`:function(x,a,n={}){let{gen:A,it:s}=x,i=[function({errorPath:x},{instancePath:a}){let n=a?(0,e.str)`${x}${(0,t.getErrorPath)(a,t.Type.Str)}`:x;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,n)]}(s,n),function({keyword:x,it:{errSchemaPath:r}},{schemaPath:a,parentSchema:n}){let A=n?r:(0,e.str)`${r}/${x}`;return a&&(A=(0,e.str)`${A}${(0,t.getErrorPath)(a,t.Type.Str)}`),[_.schemaPath,A]}(x,n)];return function(x,{params:t,message:a},n){let{keyword:A,data:s,schemaValue:i,it:o}=x,{opts:l,propertyName:c,topSchemaRef:v,schemaPath:d}=o;n.push([_.keyword,A],[_.params,"function"==typeof t?t(x):t||(0,e._)`{}`]),l.messages&&n.push([_.message,"function"==typeof a?a(x):a]),l.verbose&&n.push([_.schema,i],[_.parentSchema,(0,e._)`${v}${d}`],[r.default.data,s]),c&&n.push([_.propertyName,c])}(x,a,i),A.object(...i)}(x,a,n)}}),uJ=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.boolOrEmptySchema=x.topBoolOrEmptySchema=void 0;let e=uZ(),t=uK(),r=uM(),a={message:"boolean schema is false"};function n(x,t){let{gen:r,data:n}=x;(0,e.reportError)({gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:x},a,void 0,t)}x.topBoolOrEmptySchema=function(x){let{gen:e,schema:a,validateName:_}=x;!1===a?n(x,!1):"object"==typeof a&&!0===a.$async?e.return(r.default.data):(e.assign((0,t._)`${_}.errors`,null),e.return(!0))},x.boolOrEmptySchema=function(x,e){let{gen:t,schema:r}=x;!1===r?(t.var(e,!1),n(x)):t.var(e,!0)}}),uV=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getRules=x.isJSONType=void 0;let e=new Set(["string","number","integer","boolean","null","object","array"]);x.isJSONType=function(x){return"string"==typeof x&&e.has(x)},x.getRules=function(){let x={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...x,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},x.number,x.string,x.array,x.object],post:{rules:[]},all:{},keywords:{}}}}),uH=fR(x=>{function e(x,e){return e.rules.some(e=>t(x,e))}function t(x,e){var t;return void 0!==x[e.keyword]||(null==(t=e.definition.implements)?void 0:t.some(e=>void 0!==x[e]))}Object.defineProperty(x,"__esModule",{value:!0}),x.shouldUseRule=x.shouldUseGroup=x.schemaHasRulesForType=void 0,x.schemaHasRulesForType=function({schema:x,self:t},r){let a=t.RULES.types[r];return a&&!0!==a&&e(x,a)},x.shouldUseGroup=e,x.shouldUseRule=t}),uU=fR(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.reportTypeError=x.checkDataTypes=x.checkDataType=x.coerceAndCheckDataType=x.getJSONTypes=x.getSchemaTypes=x.DataType=void 0;let r=uV(),a=uH(),n=uZ(),_=uK(),A=uQ();function s(x){let e=Array.isArray(x)?x:x?[x]:[];if(e.every(r.isJSONType))return e;throw Error("type must be JSONType or JSONType[]: "+e.join(","))}(t=e||(x.DataType=e={}))[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong",x.getSchemaTypes=function(x){let e=s(x.type);if(e.includes("null")){if(!1===x.nullable)throw Error("type: null contradicts nullable: false")}else{if(!e.length&&void 0!==x.nullable)throw Error('"nullable" cannot be used without "type"');!0===x.nullable&&e.push("null")}return e},x.getJSONTypes=s,x.coerceAndCheckDataType=function(x,t){var r,n;let{gen:A,data:s,opts:o}=x,c=(r=t,(n=o.coerceTypes)?r.filter(x=>i.has(x)||"array"===n&&"array"===x):[]),d=t.length>0&&!(0===c.length&&1===t.length&&(0,a.schemaHasRulesForType)(x,t[0]));if(d){let r=l(t,s,o.strictNumbers,e.Wrong);A.if(r,()=>{c.length?function(x,e,t){let{gen:r,data:a,opts:n}=x,A=r.let("dataType",(0,_._)`typeof ${a}`),s=r.let("coerced",(0,_._)`undefined`);for(let x of("array"===n.coerceTypes&&r.if((0,_._)`${A} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,_._)`${a}[0]`).assign(A,(0,_._)`typeof ${a}`).if(l(e,a,n.strictNumbers),()=>r.assign(s,a))),r.if((0,_._)`${s} !== undefined`),t))(i.has(x)||"array"===x&&"array"===n.coerceTypes)&&function(x){switch(x){case"string":r.elseIf((0,_._)`${A} == "number" || ${A} == "boolean"`).assign(s,(0,_._)`"" + ${a}`).elseIf((0,_._)`${a} === null`).assign(s,(0,_._)`""`);return;case"number":r.elseIf((0,_._)`${A} == "boolean" || ${a} === null
372
+ ${ff(Object.fromEntries(a))}
373
+ Response body: ${fb(r)}`)}function fp(x,e){let t=new AbortController,r=()=>t.abort();return x.once("aborted",r),e.once("close",()=>{x.off("aborted",r),e.writableEnded||r()}),(x.aborted||e.destroyed)&&r(),t.signal}function fm(x,e,t){let r,a=("https:"===t.targetUrl.protocol?B:d7).request(t.targetUrl,{headers:t.requestHeaders,method:x.method},x=>{(r=x,e.destroyed||e.writableEnded)?x.destroy():(fi(e,t.commonHeaders),e.writeHead(x.statusCode??500,t.createResponseHeaders?.(x.headers)??fA(x.headers)),x.pipe(e))}),n=()=>{a.destroy(),r?.destroy()};a.once("error",x=>{if(!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(x);fo(e,502,`${t.errorMessage}: ${x.message}`,t.commonHeaders)}}),x.once("aborted",()=>{n()}),e.once("close",()=>{e.writableEnded||n()}),x.pipe(a)}async function fh(x,e,t){let r=e.find(({match:e})=>"string"==typeof e?x.url.pathname===e:e(x.url));await (r?.handle??t)(x)}function fE(x,e){return(t,r)=>{let a=fa(t);a?fh({request:t,response:r,url:a},x,e).catch(x=>(function(x,e){if(d5.error("处理 Web SDK 调试器请求失败",{error:e}),!x.destroyed&&!x.writableEnded){if(x.headersSent)return void x.destroy(e instanceof Error?e:void 0);fo(x,500,"Internal server error")}})(r,x)):fo(r,400,"Bad request")}}let fj=I("../../../node_modules/.pnpm/undici@6.29.0/node_modules/undici/index.js"),fg={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},fy={"http:":"80","https:":"443"},fS=new Map;function fI(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function fN(x){let e=x.startsWith("/")?x:`/${x}`;return"/app_developer"===e||e.startsWith("/app_developer/")}async function fB(x,e={}){let t=function(x){var e,t;let r="string"==typeof x?new URL(x):x;if(function(x){let e=fC(["NO_PROXY","no_proxy"]);if(!e)return!1;let t=fP(x.hostname),r=x.port||fy[x.protocol]||"";for(let x of e.split(",")){let e=function(x){let e=x.trim().toLowerCase();if(!e)return{host:""};if((e=e.replace(/^[a-z][a-z\d+.-]*:\/\//,"").split("/")[0]).startsWith("[")){let x=e.indexOf("]");if(-1!==x)return{host:fP(e.slice(0,x+1)),port:":"===e[x+1]?e.slice(x+2):void 0}}let t=e.indexOf(":")===e.lastIndexOf(":")?e.match(/:(\d+)$/):void 0;return{host:fP(t?e.slice(0,-t[0].length):e),port:t?.[1]}}(x);if(e.host&&(!e.port||e.port===r)){if("*"===e.host)return!0;if(e.host.startsWith("*.")){let x=e.host.slice(1);if(t.endsWith(x))return!0;continue}if(e.host.startsWith(".")){if(t.endsWith(e.host))return!0;continue}if(t===e.host)return!0}}return!1}(r))return;let a="https:"===(e=r.protocol)?fC(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===e?fC(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!a)return;let n=(t=a,/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`http://${t}`),_=fS.get(n);return _||(_=new fj.kT(n),fS.set(n,_)),_}(x),r=t?{...e,dispatcher:t}:e;return await fetch(x,r)}async function fF({internal:x,domainId:e,path:t,query:r,method:a="GET",body:n,headers:_,signal:A,auth:s=!0}){let i={method:a,body:n,headers:{...fI(),..._}};A&&(i.signal=A);let o=function({internal:x,domainId:e,path:t,query:r}){let a=t.startsWith("/")?t:`/${t}`,n=new URLSearchParams;for(let[x,e]of Object.entries(r||{}))null!=e&&n.append(x,e.toString());let _=n.toString(),A=_?`${a.includes("?")?"&":"?"}${_}`:"",s=fN(a)?oI:e?fg[e]:x?fg["sso-internal"]:fg["sms-external"];return`https://${s}${a}${A}`}({internal:x,domainId:e,path:t,query:r}),l=new Headers(i.headers);if(!s||!fN(t)||l.has("Authorization")||l.has("X-Developer-Open-Build-Token"))return await fB(o,i);let c=new URL(o).origin,v=z(fB,{baseUrl:c,allowedOrigins:[c]});try{return await v(o,i)}catch(x){if(!(x instanceof W||x instanceof U))throw x;throw Error(x instanceof U?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function fw(x){let e=await fF(x),t=e.headers.get("x-tt-logid")||"";if(!e.ok){let x=await e.text();throw Error(JSON.stringify({code:e.status,message:"HTTP 请求失败",data:x,log_id:t}))}let r=await e.json();if(0!==r.code)throw Error(JSON.stringify({...r,log_id:t}));return{...r,log_id:t}}function fC(x){for(let e of x){let x=process.env[e]?.trim();if(x)return x}}function fP(x){return x.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let fk="/__mcp_proxy";var fD=Object.create,fL=Object.defineProperty,fq=Object.getOwnPropertyDescriptor,fT=Object.getOwnPropertyNames,fR=Object.getPrototypeOf,f$=Object.prototype.hasOwnProperty,fG=(x,e)=>()=>(e||x((e={exports:{}}).exports,e),e.exports),fO=(x,e,t)=>(t=null!=x?fD(fR(x)):{},((x,e,t)=>{if(e&&"object"==typeof e||"function"==typeof e)for(var r,a=fT(e),n=0,_=a.length;n<_;n++)r=a[n],f$.call(x,r)||void 0===r||fL(x,r,{get:(x=>e[x]).bind(null,r),enumerable:!(t=fq(e,r))||t.enumerable});return x})(!e&&x&&x.__esModule?t:fL(t,"default",{value:x,enumerable:!0}),x));let fX=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),fK=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),fQ=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),fM=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]),fZ=Symbol.for("mcp.sdk.errorBrands");function fJ(x,e){let t=new Set,r=e;for(;"function"==typeof r;){let x=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,"mcpBrand")&&"string"==typeof x&&t.add(x),r=Object.getPrototypeOf(r)}0!==t.size&&Object.defineProperty(x,fZ,{value:t,enumerable:!1,configurable:!0})}function fV(x,e){try{if("object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(x,"mcpBrand")&&"string"==typeof x.mcpBrand&&Object.prototype.hasOwnProperty.call(e,fZ)){let t=e[fZ];if(t&&"function"==typeof t.has&&t.has(x.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(x,e)}(class x extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](x){return fV(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fV(this,x)}constructor(x,e,t){super(e),this.code=x,this.errorUri=t,this.name="OAuthError",fJ(this,new.target)}toResponseObject(){let x={error:this.code,error_description:this.message};return this.errorUri&&(x.error_uri=this.errorUri),x}static fromResponse(e){return new x(e.error,e.error_description??e.error,e.error_uri)}});let fH=((rX={}).NotConnected="NOT_CONNECTED",rX.AlreadyConnected="ALREADY_CONNECTED",rX.NotInitialized="NOT_INITIALIZED",rX.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",rX.RequestTimeout="REQUEST_TIMEOUT",rX.ConnectionClosed="CONNECTION_CLOSED",rX.SendFailed="SEND_FAILED",rX.InvalidResult="INVALID_RESULT",rX.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",rX.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",rX.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",rX.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",rX.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",rX.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",rX.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",rX.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",rX.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",rX.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",rX.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",rX);var fU=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](x){return fV(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fV(this,x)}constructor(x,e,t){super(e),this.code=x,this.data=t,this.name="SdkError",fJ(this,new.target)}};(class extends fU{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(x,e,t){super(x,e,t),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}});let fY={};function fz(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function fW(x,e){let t={};for(let[r,a]of Object.entries(x)){if(void 0===a)continue;let x=void 0===e?void 0:e[r];if(void 0===x){t[r]=a;continue}if(fz(a)&&fz(x)){let e={};for(let[t,n]of Object.entries(a))void 0!==n&&void 0===x[t]&&("elicitation"!==r||"form"!==t||void 0!==x.form||void 0!==x.url)&&(e[t]=n);Object.keys(e).length>0&&(t[r]=e)}}return Object.keys(t).length>0?t:void 0}let f0="2026-07-28",f1=[f0];function f2(x){return x.filter(x=>x>=f0)}function f3(x){let e=x.structuredContent;return void 0===e||!("object"!=typeof e||null===e||Array.isArray(e))||x.content?.some(x=>"text"===x.type)?x:{...x,content:[...x.content??[],{type:"text",text:JSON.stringify(e)}]}}let f6=["task","inputRequests","requestState"];function f4(x){return null===x||"object"!=typeof x||Array.isArray(x)||void 0!==x.content||f6.some(e=>e in x)?x:{...x,content:[]}}function f5(){let x,e,t,a,n,_,A,s,i,o,l,c,v,d,f,b,u,p,m,h,E,j,g,y,S,I,N,B,F,w,C,P,k,D,L,q,T,R,$,G,O,X,K,Q,M,Z,J,V,H,U,Y,z,W,xx,xe,xt,xr,xa,xn,x_,xA,xs,xi,xo,xl,xc,xv,xd,xf,xb,xu,xp,xm,xh,xE,xj,xg,xy,xS,xI,xN,xB,xF,xw,xC,xP,xk,xD,xL,xq,xT,xR,x$,xG,xO,xX,xK,xQ,xM,xZ,xJ,xV,xH,xU,xY,xz,xW,x2,x3,x6,x5,x7,x8,x9,ex,et,er,ea,en,e_,ei,eo,el,ec,ev,ed,ef,eb,eu,ep,em,eh,eE,ej,eg,ey,eS,eI,eN,eB;return r??=(x=es(()=>ee([ra(),eD(),eY(),tw(),e6(ra(),x),rc(x)])),e=e6(ra(),x),t=ee([ra(),eD().int()]),a=ra(),n=tM({ttl:eD().optional()}),_=tM({taskId:ra()}),i=(s=tM({_meta:(A=x0({progressToken:t.optional(),"io.modelcontextprotocol/related-task":_.optional()})).optional()})).extend({task:n.optional()}),o=tM({method:ra(),params:s.loose().optional()}),l=tM({_meta:A.optional()}),c=tM({method:ra(),params:l.loose().optional()}),v=x0({_meta:A.optional()}),d=ee([ra(),eD().int()]),f=v.strict(),b=l.extend({requestId:d.optional(),reason:ra().optional()}),u=c.extend({method:rl("notifications/cancelled"),params:b}),p=tM({src:ra(),mimeType:ra().optional(),sizes:rc(ra()).optional(),theme:x1(["light","dark"]).optional()}),m=tM({icons:rc(p).optional()}),E=(h=tM({name:ra(),title:ra().optional()})).extend({...h.shape,...m.shape,version:ra(),websiteUrl:ra().optional(),description:ra().optional()}),j=tU(tM({applyDefaults:eY().optional()}),e),g=t0(x=>x&&"object"==typeof x&&!Array.isArray(x)&&0===Object.keys(x).length?{form:{}}:x,tU(tM({form:j.optional(),url:e.optional()}),e.optional())),y=x0({list:e.optional(),cancel:e.optional(),requests:x0({sampling:x0({createMessage:e.optional()}).optional(),elicitation:x0({create:e.optional()}).optional()}).optional()}),S=x0({list:e.optional(),cancel:e.optional(),requests:x0({tools:x0({call:e.optional()}).optional()}).optional()}),I=tM({experimental:e6(ra(),e).optional(),sampling:tM({context:e.optional(),tools:e.optional()}).optional(),elicitation:g.optional(),roots:tM({listChanged:eY().optional()}).optional(),tasks:y.optional(),extensions:e6(ra(),e).optional()}),N=s.extend({protocolVersion:ra(),capabilities:I,clientInfo:E}),B=o.extend({method:rl("initialize"),params:N}),F=tM({experimental:e6(ra(),e).optional(),logging:e.optional(),completions:e.optional(),prompts:tM({listChanged:eY().optional()}).optional(),resources:tM({subscribe:eY().optional(),listChanged:eY().optional()}).optional(),tools:tM({listChanged:eY().optional()}).optional(),tasks:S.optional(),extensions:e6(ra(),e).optional()}),w=v.extend({protocolVersion:ra(),capabilities:F,serverInfo:E,instructions:ra().optional()}),C=c.extend({method:rl("notifications/initialized"),params:l.optional()}),P=o.extend({method:rl("ping"),params:s.optional()}),k=tM({progress:eD(),total:eA(eD()),message:eA(ra())}),D=tM({...l.shape,...k.shape,progressToken:t}),L=c.extend({method:rl("notifications/progress"),params:D}),q=s.extend({cursor:a.optional()}),T=o.extend({params:q.optional()}),R=v.extend({nextCursor:a.optional()}),G=($=tM({uri:ra(),mimeType:eA(ra()),_meta:e6(ra(),x4()).optional()})).extend({text:ra()}),O=ra().refine(x=>{try{return atob(x),!0}catch{return!1}},{message:"Invalid Base64 string"}),X=$.extend({blob:O}),Q=tM({audience:rc(K=x1(["user","assistant"])).optional(),priority:eD().min(0).max(1).optional(),lastModified:rn({offset:!0}).optional()}),M=tM({...h.shape,...m.shape,uri:ra(),description:eA(ra()),mimeType:eA(ra()),size:eA(eD()),annotations:Q.optional(),_meta:eA(x0({}))}),Z=tM({...h.shape,...m.shape,uriTemplate:ra(),description:eA(ra()),mimeType:eA(ra()),annotations:Q.optional(),_meta:eA(x0({}))}),J=T.extend({method:rl("resources/list")}),V=R.extend({resources:rc(M)}),H=T.extend({method:rl("resources/templates/list")}),U=R.extend({resourceTemplates:rc(Z)}),Y=s.extend({uri:ra()}),z=o.extend({method:rl("resources/read"),params:Y}),W=v.extend({contents:rc(ee([G,X]))}),xx=c.extend({method:rl("notifications/resources/list_changed"),params:l.optional()}),xe=o.extend({method:rl("resources/subscribe"),params:Y}),xt=o.extend({method:rl("resources/unsubscribe"),params:Y}),xr=l.extend({uri:ra()}),xa=c.extend({method:rl("notifications/resources/updated"),params:xr}),xn=tM({name:ra(),description:eA(ra()),required:eA(eY())}),x_=tM({...h.shape,...m.shape,description:eA(ra()),arguments:eA(rc(xn)),_meta:eA(x0({}))}),xA=T.extend({method:rl("prompts/list")}),xs=R.extend({prompts:rc(x_)}),xi=s.extend({name:ra(),arguments:e6(ra(),ra()).optional()}),xo=o.extend({method:rl("prompts/get"),params:xi}),xl=tM({type:rl("text"),text:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xc=tM({type:rl("image"),data:O,mimeType:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xv=tM({type:rl("audio"),data:O,mimeType:ra(),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xd=tM({type:rl("tool_use"),name:ra(),id:ra(),input:e6(ra(),x4()),_meta:e6(ra(),x4()).optional()}),xf=tM({type:rl("resource"),resource:ee([G,X]),annotations:Q.optional(),_meta:e6(ra(),x4()).optional()}),xp=tM({role:K,content:xu=ee([xl,xc,xv,xb=M.extend({type:rl("resource_link")}),xf])}),xm=v.extend({description:ra().optional(),messages:rc(xp)}),xh=c.extend({method:rl("notifications/prompts/list_changed"),params:l.optional()}),xE=tM({title:ra().optional(),readOnlyHint:eY().optional(),destructiveHint:eY().optional(),idempotentHint:eY().optional(),openWorldHint:eY().optional()}),xj=tM({taskSupport:x1(["required","optional","forbidden"]).optional()}),xg=tM({...h.shape,...m.shape,description:ra().optional(),inputSchema:tM({type:rl("object"),properties:e6(ra(),x).optional(),required:rc(ra()).optional()}).catchall(x4()),outputSchema:tM({type:rl("object"),properties:e6(ra(),x).optional(),required:rc(ra()).optional()}).catchall(x4()).optional(),annotations:xE.optional(),execution:xj.optional(),_meta:e6(ra(),x4()).optional()}),xy=T.extend({method:rl("tools/list")}),xS=R.extend({tools:rc(xg)}),xI=v.extend({content:rc(xu),structuredContent:e6(ra(),x4()).optional(),isError:eY().optional()}),xN=i.extend({name:ra(),arguments:e6(ra(),x4()).optional()}),xB=o.extend({method:rl("tools/call"),params:xN}),xF=c.extend({method:rl("notifications/tools/list_changed"),params:l.optional()}),xw=x1(["debug","info","notice","warning","error","critical","alert","emergency"]),xC=s.extend({level:xw}),xP=o.extend({method:rl("logging/setLevel"),params:xC}),xk=l.extend({level:xw,logger:ra().optional(),data:x4()}),xD=c.extend({method:rl("notifications/message"),params:xk}),xL=tM({name:ra().optional()}),xq=tM({hints:rc(xL).optional(),costPriority:eD().min(0).max(1).optional(),speedPriority:eD().min(0).max(1).optional(),intelligencePriority:eD().min(0).max(1).optional()}),xT=tM({mode:x1(["auto","required","none"]).optional()}),xR=tM({type:rl("tool_result"),toolUseId:ra().describe("The unique identifier for the corresponding tool call."),content:rc(xu),structuredContent:tM({}).loose().optional(),isError:eY().optional(),_meta:e6(ra(),x4()).optional()}),x$=e9("type",[xl,xc,xv]),xO=tM({role:K,content:ee([xG=e9("type",[xl,xc,xv,xd,xR]),rc(xG)]),_meta:e6(ra(),x4()).optional()}),xX=i.extend({messages:rc(xO),modelPreferences:xq.optional(),systemPrompt:ra().optional(),includeContext:x1(["none","thisServer","allServers"]).optional(),temperature:eD().optional(),maxTokens:eD().int(),stopSequences:rc(ra()).optional(),metadata:e.optional(),tools:rc(xg).optional(),toolChoice:xT.optional()}),xK=o.extend({method:rl("sampling/createMessage"),params:xX}),xQ=v.extend({model:ra(),stopReason:eA(x1(["endTurn","stopSequence","maxTokens"]).or(ra())),role:K,content:x$}),xM=v.extend({model:ra(),stopReason:eA(x1(["endTurn","stopSequence","maxTokens","toolUse"]).or(ra())),role:K,content:ee([xG,rc(xG)])}),xZ=tM({type:rl("boolean"),title:ra().optional(),description:ra().optional(),default:eY().optional()}),xJ=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),minLength:eD().optional(),maxLength:eD().optional(),format:x1(["email","uri","date","date-time"]).optional(),default:ra().optional()}),xV=tM({type:x1(["number","integer"]),title:ra().optional(),description:ra().optional(),minimum:eD().optional(),maximum:eD().optional(),default:eD().optional()}),xH=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),default:ra().optional()}),xU=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),oneOf:rc(tM({const:ra(),title:ra()})),default:ra().optional()}),xY=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),enumNames:rc(ra()).optional(),default:ra().optional()}),xz=ee([xH,xU]),xW=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({type:rl("string"),enum:rc(ra())}),default:rc(ra()).optional()}),x3=ee([xW,x2=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({anyOf:rc(tM({const:ra(),title:ra()}))}),default:rc(ra()).optional()})]),x6=ee([xY,xz,x3]),x5=ee([x6,xZ,xJ,xV]),x7=i.extend({mode:rl("form").optional(),message:ra(),requestedSchema:tM({type:rl("object"),properties:e6(ra(),x5),required:rc(ra()).optional()}).catchall(x4())}),x9=ee([x7,x8=i.extend({mode:rl("url"),message:ra(),elicitationId:ra(),url:ra().url()})]),ex=o.extend({method:rl("elicitation/create"),params:x9}),et=l.extend({elicitationId:ra()}),er=c.extend({method:rl("notifications/elicitation/complete"),params:et}),ea=v.extend({action:x1(["accept","decline","cancel"]),content:t0(x=>null===x?void 0:x,e6(ra(),ee([ra(),eD(),eY(),rc(ra())])).optional())}),en=tM({type:rl("ref/resource"),uri:ra()}),e_=tM({type:rl("ref/prompt"),name:ra()}),ei=s.extend({ref:ee([e_,en]),argument:tM({name:ra(),value:ra()}),context:tM({arguments:e6(ra(),ra()).optional()}).optional()}),eo=o.extend({method:rl("completion/complete"),params:ei}),el=v.extend({completion:x0({values:rc(ra()).max(100),total:eA(eD().int()),hasMore:eA(eY())})}),ec=tM({uri:ra().startsWith("file://"),name:ra().optional(),_meta:e6(ra(),x4()).optional()}),ev=o.extend({method:rl("roots/list"),params:s.optional()}),ed=v.extend({roots:rc(ec)}),ef=c.extend({method:rl("notifications/roots/list_changed"),params:l.optional()}),eb=x0({ttl:eD().optional(),pollInterval:eD().optional()}),eu=x1(["working","input_required","completed","failed","cancelled"]),ep=tM({taskId:ra(),status:eu,ttl:ee([eD(),tw()]),createdAt:ra(),lastUpdatedAt:ra(),pollInterval:eA(eD()),statusMessage:eA(ra())}),em=v.extend({task:ep}),eh=l.merge(ep),eE=c.extend({method:rl("notifications/tasks/status"),params:eh}),ej=o.extend({method:rl("tasks/get"),params:s.extend({taskId:ra()})}),eg=v.merge(ep),ey=o.extend({method:rl("tasks/result"),params:s.extend({taskId:ra()})}),eS=v.loose(),eI=T.extend({method:rl("tasks/list")}),eN=R.extend({tasks:rc(ep)}),eB=o.extend({method:rl("tasks/cancel"),params:s.extend({taskId:ra()})}),{JSONValueSchema:x,JSONObjectSchema:e,ProgressTokenSchema:t,CursorSchema:a,TaskMetadataSchema:n,RelatedTaskMetadataSchema:_,RequestMetaSchema:A,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:i,RequestSchema:o,NotificationsParamsSchema:l,NotificationSchema:c,ResultSchema:v,RequestIdSchema:d,EmptyResultSchema:f,CancelledNotificationParamsSchema:b,CancelledNotificationSchema:u,IconSchema:p,IconsSchema:m,BaseMetadataSchema:h,ImplementationSchema:E,ClientTasksCapabilitySchema:y,ServerTasksCapabilitySchema:S,ClientCapabilitiesSchema:I,InitializeRequestParamsSchema:N,InitializeRequestSchema:B,ServerCapabilitiesSchema:F,InitializeResultSchema:w,InitializedNotificationSchema:C,PingRequestSchema:P,ProgressSchema:k,ProgressNotificationParamsSchema:D,ProgressNotificationSchema:L,PaginatedRequestParamsSchema:q,PaginatedRequestSchema:T,PaginatedResultSchema:R,ResourceContentsSchema:$,TextResourceContentsSchema:G,BlobResourceContentsSchema:X,RoleSchema:K,AnnotationsSchema:Q,ResourceSchema:M,ResourceTemplateSchema:Z,ListResourcesRequestSchema:J,ListResourcesResultSchema:V,ListResourceTemplatesRequestSchema:H,ListResourceTemplatesResultSchema:U,ResourceRequestParamsSchema:Y,ReadResourceRequestParamsSchema:Y,ReadResourceRequestSchema:z,ReadResourceResultSchema:W,ResourceListChangedNotificationSchema:xx,SubscribeRequestParamsSchema:Y,SubscribeRequestSchema:xe,UnsubscribeRequestParamsSchema:Y,UnsubscribeRequestSchema:xt,ResourceUpdatedNotificationParamsSchema:xr,ResourceUpdatedNotificationSchema:xa,PromptArgumentSchema:xn,PromptSchema:x_,ListPromptsRequestSchema:xA,ListPromptsResultSchema:xs,GetPromptRequestParamsSchema:xi,GetPromptRequestSchema:xo,TextContentSchema:xl,ImageContentSchema:xc,AudioContentSchema:xv,ToolUseContentSchema:xd,EmbeddedResourceSchema:xf,ResourceLinkSchema:xb,ContentBlockSchema:xu,PromptMessageSchema:xp,GetPromptResultSchema:xm,PromptListChangedNotificationSchema:xh,ToolAnnotationsSchema:xE,ToolExecutionSchema:xj,ToolSchema:xg,ListToolsRequestSchema:xy,ListToolsResultSchema:xS,CallToolResultSchema:xI,CallToolRequestParamsSchema:xN,CallToolRequestSchema:xB,ToolListChangedNotificationSchema:xF,LoggingLevelSchema:xw,SetLevelRequestParamsSchema:xC,SetLevelRequestSchema:xP,LoggingMessageNotificationParamsSchema:xk,LoggingMessageNotificationSchema:xD,ModelHintSchema:xL,ModelPreferencesSchema:xq,ToolChoiceSchema:xT,ToolResultContentSchema:xR,SamplingContentSchema:x$,SamplingMessageContentBlockSchema:xG,SamplingMessageSchema:xO,CreateMessageRequestParamsSchema:xX,CreateMessageRequestSchema:xK,CreateMessageResultSchema:xQ,CreateMessageResultWithToolsSchema:xM,BooleanSchemaSchema:xZ,StringSchemaSchema:xJ,NumberSchemaSchema:xV,UntitledSingleSelectEnumSchemaSchema:xH,TitledSingleSelectEnumSchemaSchema:xU,LegacyTitledEnumSchemaSchema:xY,SingleSelectEnumSchemaSchema:xz,UntitledMultiSelectEnumSchemaSchema:xW,TitledMultiSelectEnumSchemaSchema:x2,MultiSelectEnumSchemaSchema:x3,EnumSchemaSchema:x6,PrimitiveSchemaDefinitionSchema:x5,ElicitRequestFormParamsSchema:x7,ElicitRequestURLParamsSchema:x8,ElicitRequestParamsSchema:x9,ElicitRequestSchema:ex,ElicitationCompleteNotificationParamsSchema:et,ElicitationCompleteNotificationSchema:er,ElicitResultSchema:ea,ResourceTemplateReferenceSchema:en,PromptReferenceSchema:e_,CompleteRequestParamsSchema:ei,CompleteRequestSchema:eo,CompleteResultSchema:el,RootSchema:ec,ListRootsRequestSchema:ev,ListRootsResultSchema:ed,RootsListChangedNotificationSchema:ef,TaskCreationParamsSchema:eb,TaskStatusSchema:eu,TaskSchema:ep,CreateTaskResultSchema:em,TaskStatusNotificationParamsSchema:eh,TaskStatusNotificationSchema:eE,GetTaskRequestSchema:ej,GetTaskResultSchema:eg,GetTaskPayloadRequestSchema:ey,GetTaskPayloadResultSchema:eS,ListTasksRequestSchema:eI,ListTasksResultSchema:eN,CancelTaskRequestSchema:eB,CancelTaskResultSchema:v.merge(ep),ClientRequestSchema:ee([P,B,eo,xP,xo,xA,J,H,z,xe,xt,xB,xy,ej,ey,eI,eB]),ClientNotificationSchema:ee([u,L,C,ef,eE]),ClientResultSchema:ee([f,xQ,xM,ea,ed,eg,eN,em]),ServerRequestSchema:ee([P,xK,ex,ev,ej,ey,eI,eB]),ServerNotificationSchema:ee([u,L,xD,xa,xx,xF,xh,eE,er]),ServerResultSchema:ee([f,w,el,xm,xs,V,U,W,xI,xS,eg,eN,em]),CallToolResultWireSchema:x4().superRefine((x,e)=>{if(!("object"!=typeof x||null===x||Array.isArray(x))&&void 0===x.content){for(let t of f6)if(t in x)return void e.addIssue({code:"custom",message:`content is required when the body carries '${t}' — another result family cannot default into an empty tools/call success`})}}).transform(f4).pipe(xI)})}function f7(x){return"object"!==x.type}let f8=new Set(["const","enum","default","examples"]),f9=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function bx(x){return void 0!==x&&!("string"==typeof x&&x.startsWith("#"))}let be={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},bt={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},br={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};function ba(){if(a)return a;let x=f5();return a={requestSchemas:{ping:x.PingRequestSchema,initialize:x.InitializeRequestSchema,"completion/complete":x.CompleteRequestSchema,"logging/setLevel":x.SetLevelRequestSchema,"prompts/get":x.GetPromptRequestSchema,"prompts/list":x.ListPromptsRequestSchema,"resources/list":x.ListResourcesRequestSchema,"resources/templates/list":x.ListResourceTemplatesRequestSchema,"resources/read":x.ReadResourceRequestSchema,"resources/subscribe":x.SubscribeRequestSchema,"resources/unsubscribe":x.UnsubscribeRequestSchema,"tools/call":x.CallToolRequestSchema,"tools/list":x.ListToolsRequestSchema,"tasks/get":x.GetTaskRequestSchema,"tasks/result":x.GetTaskPayloadRequestSchema,"tasks/list":x.ListTasksRequestSchema,"tasks/cancel":x.CancelTaskRequestSchema,"sampling/createMessage":x.CreateMessageRequestSchema,"elicitation/create":x.ElicitRequestSchema,"roots/list":x.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":x.CancelledNotificationSchema,"notifications/progress":x.ProgressNotificationSchema,"notifications/initialized":x.InitializedNotificationSchema,"notifications/roots/list_changed":x.RootsListChangedNotificationSchema,"notifications/tasks/status":x.TaskStatusNotificationSchema,"notifications/message":x.LoggingMessageNotificationSchema,"notifications/resources/updated":x.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":x.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":x.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":x.PromptListChangedNotificationSchema,"notifications/elicitation/complete":x.ElicitationCompleteNotificationSchema},resultSchemas:{ping:x.EmptyResultSchema,initialize:x.InitializeResultSchema,"completion/complete":x.CompleteResultSchema,"logging/setLevel":x.EmptyResultSchema,"prompts/get":x.GetPromptResultSchema,"prompts/list":x.ListPromptsResultSchema,"resources/list":x.ListResourcesResultSchema,"resources/templates/list":x.ListResourceTemplatesResultSchema,"resources/read":x.ReadResourceResultSchema,"resources/subscribe":x.EmptyResultSchema,"resources/unsubscribe":x.EmptyResultSchema,"tools/call":x.CallToolResultWireSchema,"tools/list":x.ListToolsResultSchema,"sampling/createMessage":x.CreateMessageResultWithToolsSchema,"elicitation/create":x.ElicitResultSchema,"roots/list":x.ListRootsResultSchema}}}function bn(x){return Object.prototype.hasOwnProperty.call(be,x)}function b_(x){return Object.prototype.hasOwnProperty.call(bt,x)}function bA(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function bs(x,e){if(void 0===x)return{ok:!1,reason:"not-in-era"};let t=x.safeParse(e);return t.success?{ok:!0,value:t.data}:{ok:!1,reason:"invalid",message:String(t.error)}}Object.keys(be),Object.keys(bt);let bi={ok:!1,reason:"not-in-era"};function bo(x){return bA(x)&&bA(x.outputSchema)&&f7(x.outputSchema)}let bl={era:"2025-11-25",hasRequestMethod:bn,hasNotificationMethod:b_,validateRequest:(x,e)=>bs(bn(x)?ba().requestSchemas[x]:void 0,e),validateResult:(x,e)=>bs(Object.prototype.hasOwnProperty.call(br,x)?ba().resultSchemas[x]:void 0,e),validateNotification:(x,e)=>bs(b_(x)?ba().notificationSchemas[x]:void 0,e),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bi,validateInputResponse:()=>bi,samplingResultVariant:(x,e)=>{let t=f5();return bs(x?t.CreateMessageResultWithToolsSchema:t.CreateMessageResultSchema,e)},outboundEnvelope:x=>void 0,validateEnvelopeMeta:x=>[],projectCallToolResult(x,e){let t=f3(x),r=t.structuredContent;if(void 0===r)return t;let a="object"!=typeof r||null===r||Array.isArray(r),n=void 0!==e&&f7(e);return a||n?{...t,structuredContent:{result:r}}:t},decodeResult(x,e){if(bA(e)&&"resultType"in e){let x={...e};return delete x.resultType,{kind:"complete",result:x}}return{kind:"complete",result:e}},encodeResult(x,e){if("tools/list"!==x)return e;let t=e.tools;return Array.isArray(t)&&t.some(x=>bo(x))?{...e,tools:t.map(x=>bo(x)?{...x,outputSchema:function(x){var e;let t="string"==typeof x.$schema?x.$schema:void 0;if(bx(x.$id))return{...void 0!==t&&{$schema:t},type:"object",properties:{result:x},required:["result"]};let r="string"==typeof(e=x.$schema)&&fK.has(e.replace(/#$/,""))&&!0!==x.$recursiveAnchor,a=(x,e)=>{if(Array.isArray(x))return x.map(x=>a(x,!1));if(null===x||"object"!=typeof x||!e&&bx(x.$id))return x;let t={},n=!1;for(let[_,A]of Object.entries(x))e?t[_]=a(A,!1):("$ref"===_||"$dynamicRef"===_)&&"string"==typeof A?t[_]="#"===A?"#/properties/result":A.startsWith("#/")?`#/properties/result${A.slice(1)}`:A:"$recursiveRef"===_&&"#"===A&&r?n=!0:f8.has(_)?t[_]=A:f9.has(_)?t[_]=a(A,!0):t[_]=a(A,!1);return n&&("$ref"in t?t.allOf=[...Array.isArray(t.allOf)?t.allOf:[],{$ref:"#/properties/result"}]:t.$ref="#/properties/result"),t};return{...void 0!==t&&{$schema:t},type:"object",properties:{result:a(x,!1)},required:["result"]}}(x.outputSchema)}:x)}:e},encodeErrorCode:x=>-32002===x?-32602:x,checkInboundEnvelope:x=>void 0};function bc(){return n??=function(){let x=es(()=>ee([ra(),eD(),eY(),tw(),e6(ra(),x),rc(x)])),e=e6(ra(),x),t=ee([ra(),eD().int()]),r=ra(),a=ee([ra(),eD().int()]),n=x1(["user","assistant"]),_=x1(["debug","info","notice","warning","error","critical","alert","emergency"]),A=ra().refine(x=>{try{return atob(x),!0}catch{return!1}},{message:"Invalid Base64 string"}),s=tM({ttl:eD().optional()}),i=tM({taskId:ra()}),o=x0({progressToken:t.optional(),"io.modelcontextprotocol/related-task":i.optional()}),l=tM({_meta:o.optional()}),c=l.extend({task:s.optional()}),v=tM({_meta:o.optional()}),d=tM({method:ra(),params:v.loose().optional()}),f=tM({src:ra(),mimeType:ra().optional(),sizes:rc(ra()).optional(),theme:x1(["light","dark"]).optional()}),b=tM({icons:rc(f).optional()}),u=tM({name:ra(),title:ra().optional()}),p=u.extend({...u.shape,...b.shape,version:ra(),websiteUrl:ra().optional(),description:ra().optional()}),m=tU(tM({applyDefaults:eY().optional()}),e),h=t0(x=>x&&"object"==typeof x&&!Array.isArray(x)&&0===Object.keys(x).length?{form:{}}:x,tU(tM({form:m.optional(),url:e.optional()}),e.optional())),E=x0({list:e.optional(),cancel:e.optional(),requests:x0({sampling:x0({createMessage:e.optional()}).optional(),elicitation:x0({create:e.optional()}).optional()}).optional()}),j=x0({list:e.optional(),cancel:e.optional(),requests:x0({tools:x0({call:e.optional()}).optional()}).optional()}),g=tM({experimental:e6(ra(),e).optional(),sampling:tM({context:e.optional(),tools:e.optional()}).optional(),elicitation:h.optional(),roots:tM({listChanged:eY().optional()}).optional(),tasks:E.optional(),extensions:e6(ra(),e).optional()}),y=tM({experimental:e6(ra(),e).optional(),logging:e.optional(),completions:e.optional(),prompts:tM({listChanged:eY().optional()}).optional(),resources:tM({subscribe:eY().optional(),listChanged:eY().optional()}).optional(),tools:tM({listChanged:eY().optional()}).optional(),tasks:j.optional(),extensions:e6(ra(),e).optional()}),S=tM({progress:eD(),total:eA(eD()),message:eA(ra())}),I=tM({...v.shape,...S.shape,progressToken:t}),N=d.extend({method:rl("notifications/progress"),params:I}),B=v.extend({level:_,logger:ra().optional(),data:x4()}),F=d.extend({method:rl("notifications/message"),params:B}),w=tM({uri:ra(),mimeType:eA(ra()),_meta:e6(ra(),x4()).optional()}),C=w.extend({text:ra()}),P=w.extend({blob:A}),k=tM({audience:rc(n).optional(),priority:eD().min(0).max(1).optional(),lastModified:rn({offset:!0}).optional()}),D=tM({...u.shape,...b.shape,uri:ra(),description:eA(ra()),mimeType:eA(ra()),size:eA(eD()),annotations:k.optional(),_meta:eA(x0({}))}),L=tM({...u.shape,...b.shape,uriTemplate:ra(),description:eA(ra()),mimeType:eA(ra()),annotations:k.optional(),_meta:eA(x0({}))}),q=d.extend({method:rl("notifications/resources/list_changed"),params:v.optional()}),T=v.extend({uri:ra()}),R=d.extend({method:rl("notifications/resources/updated"),params:T}),$=tM({name:ra(),description:eA(ra()),required:eA(eY())}),G=tM({...u.shape,...b.shape,description:eA(ra()),arguments:eA(rc($)),_meta:eA(x0({}))}),O=d.extend({method:rl("notifications/prompts/list_changed"),params:v.optional()}),X=tM({type:rl("text"),text:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),K=tM({type:rl("image"),data:A,mimeType:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),Q=tM({type:rl("audio"),data:A,mimeType:ra(),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),M=tM({type:rl("tool_use"),name:ra(),id:ra(),input:e6(ra(),x4()),_meta:e6(ra(),x4()).optional()}),Z=tM({type:rl("resource"),resource:ee([C,P]),annotations:k.optional(),_meta:e6(ra(),x4()).optional()}),J=D.extend({type:rl("resource_link")}),V=ee([X,K,Q,J,Z]),H=tM({role:n,content:V}),U=tM({title:ra().optional(),readOnlyHint:eY().optional(),destructiveHint:eY().optional(),idempotentHint:eY().optional(),openWorldHint:eY().optional()}),Y=d.extend({method:rl("notifications/tools/list_changed"),params:v.optional()}),z=tM({name:ra().optional()}),W=tM({hints:rc(z).optional(),costPriority:eD().min(0).max(1).optional(),speedPriority:eD().min(0).max(1).optional(),intelligencePriority:eD().min(0).max(1).optional()}),xx=tM({mode:x1(["auto","required","none"]).optional()}),xe=tM({type:rl("boolean"),title:ra().optional(),description:ra().optional(),default:eY().optional()}),xt=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),minLength:eD().optional(),maxLength:eD().optional(),format:x1(["email","uri","date","date-time"]).optional(),default:ra().optional()}),xr=tM({type:x1(["number","integer"]),title:ra().optional(),description:ra().optional(),minimum:eD().optional(),maximum:eD().optional(),default:eD().optional()}),xa=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),default:ra().optional()}),xn=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),oneOf:rc(tM({const:ra(),title:ra()})),default:ra().optional()}),x_=tM({type:rl("string"),title:ra().optional(),description:ra().optional(),enum:rc(ra()),enumNames:rc(ra()).optional(),default:ra().optional()}),xA=ee([xa,xn]),xs=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({type:rl("string"),enum:rc(ra())}),default:rc(ra()).optional()}),xi=tM({type:rl("array"),title:ra().optional(),description:ra().optional(),minItems:eD().optional(),maxItems:eD().optional(),items:tM({anyOf:rc(tM({const:ra(),title:ra()}))}),default:rc(ra()).optional()}),xo=ee([xs,xi]),xc=ee([x_,xA,xo]),xv=ee([xc,xe,xt,xr]),xd=c.extend({mode:rl("form").optional(),message:ra(),requestedSchema:tM({type:rl("object"),properties:e6(ra(),xv),required:rc(ra()).optional()}).catchall(x4())}),xf=tM({type:rl("ref/resource"),uri:ra()}),xb=tM({type:rl("ref/prompt"),name:ra()}),xu=tM({uri:ra().startsWith("file://"),name:ra().optional(),_meta:e6(ra(),x4()).optional()}),xp=g.shape,xm=tM({experimental:xp.experimental,sampling:xp.sampling,elicitation:xp.elicitation,roots:xp.roots,extensions:xp.extensions}),xE=y.shape,xj=tM({experimental:xE.experimental,logging:xE.logging,completions:xE.completions,prompts:xE.prompts,resources:xE.resources,tools:xE.tools,extensions:xE.extensions}),xg=x0({progressToken:t.optional(),[xl]:ra(),[xh]:p.optional(),[ef]:xm,[t$]:_.optional()}),xy=tM({...u.shape,...b.shape,description:ra().optional(),inputSchema:x0({$schema:ra().optional(),type:rl("object")}),outputSchema:x0({$schema:ra().optional()}).optional(),annotations:U.optional(),_meta:e6(ra(),x4()).optional()}),xS=tM({type:rl("tool_result"),toolUseId:ra(),content:rc(V),structuredContent:x4().optional(),isError:eY().optional(),_meta:e6(ra(),x4()).optional()}),xI=ee([X,K,Q,M,xS]),xN=tM({role:n,content:ee([xI,rc(xI)]),_meta:e6(ra(),x4()).optional()}),xB=ra(),xF=x0({[tS]:p.optional().catch(void 0)}),xw=xF.optional();function xC(x){return x0({_meta:xw,resultType:xB.default("complete"),...x})}let xP=xC({}),xk=xC({nextCursor:r.optional()}),xD=xC({content:rc(V),structuredContent:x4().optional(),isError:eY().optional()}),xL=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),tools:rc(xy),nextCursor:r.optional()}),xq=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),prompts:rc(G),nextCursor:r.optional()}),xT=xC({description:ra().optional(),messages:rc(H)}),xR=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resources:rc(D),nextCursor:r.optional()}),x$=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resourceTemplates:rc(L),nextCursor:r.optional()}),xG=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),contents:rc(ee([C,P]))}),xO=xC({completion:tM({values:rc(ra()).max(100),total:eD().int().optional(),hasMore:eY().optional()}).loose()}),xX=xC({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"])}),xK=xC({ttlMs:eD().int().min(0).catch(0),cacheScope:x1(["public","private"]).catch("private"),supportedVersions:rc(ra()),capabilities:xj,instructions:ra().optional()}),xQ=tM({messages:rc(xN),modelPreferences:W.optional(),systemPrompt:ra().optional(),includeContext:x1(["none","thisServer","allServers"]).optional(),temperature:eD().optional(),maxTokens:eD().int(),stopSequences:rc(ra()).optional(),metadata:e.optional(),tools:rc(xy).optional(),toolChoice:xx.optional()}),xM=tM({method:rl("sampling/createMessage"),params:xQ}),xZ=tM({method:rl("roots/list"),params:tM({_meta:e6(ra(),x4()).optional()}).optional()}),xJ=tM({...xN.shape,model:ra(),stopReason:ra().optional()}),xV=tM({roots:rc(xu)}),xH=tM({action:x1(["accept","decline","cancel"]),content:e6(ra(),ee([ra(),eD(),eY(),rc(ra())])).optional()}),xU=tM({mode:rl("url"),message:ra(),url:ra().url()}),xY=ee([xd,xU]),xz=tM({method:rl("elicitation/create"),params:xY}),xW=ee([xM,xZ,xz]),x2=ee([xJ,xV,xH]),x3=e6(ra(),xW),x6=e6(ra(),x2),x5=xC({inputRequests:x3.optional(),requestState:ra().optional()}),x7={inputResponses:x6.optional(),requestState:ra().optional()},x8=tM({_meta:xg,...x7}),x9=x0({progressToken:t.optional()});function ex(x,e){return tM({method:rl(x),params:tM({_meta:xg,...e})})}function et(x,e){return tM({method:rl(x),params:tM({_meta:x9.optional(),...e}).optional()})}let er={name:ra(),arguments:e6(ra(),x4()).optional(),...x7},ea={cursor:r.optional()},en=ex("tools/call",er),e_=ex("tools/list",ea),ei=ex("prompts/list",ea),eo=ex("prompts/get",{name:ra(),arguments:e6(ra(),ra()).optional(),...x7}),el=ex("resources/list",ea),ec=ex("resources/templates/list",ea),ev=ex("resources/read",{uri:ra(),...x7}),ed={ref:ee([xb,xf]),argument:tM({name:ra(),value:ra()}),context:tM({arguments:e6(ra(),ra()).optional()}).optional()},eb=ex("completion/complete",ed),eu=ex("server/discover",{}),ep=tM({toolsListChanged:eY().optional(),promptsListChanged:eY().optional(),resourcesListChanged:eY().optional(),resourceSubscriptions:rc(ra()).optional()}),em={notifications:ep},eh=ex("subscriptions/listen",em),eE=xF.extend({"io.modelcontextprotocol/subscriptionId":a}),ej=x0({_meta:eE,resultType:xB.default("complete")}),eg={"tools/call":et("tools/call",er),"tools/list":et("tools/list",ea),"prompts/get":et("prompts/get",{name:ra(),arguments:e6(ra(),ra()).optional()}),"prompts/list":et("prompts/list",ea),"resources/list":et("resources/list",ea),"resources/templates/list":et("resources/templates/list",ea),"resources/read":et("resources/read",{uri:ra()}),"completion/complete":et("completion/complete",ed),"server/discover":et("server/discover",{}),"subscriptions/listen":et("subscriptions/listen",em)};function ey(x){return x0({_meta:xw,...x})}let eS={"tools/call":ey({content:rc(V),structuredContent:x4().optional(),isError:eY().optional()}),"tools/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),tools:rc(xy),nextCursor:r.optional()}),"prompts/get":ey({description:ra().optional(),messages:rc(H)}),"prompts/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),prompts:rc(G),nextCursor:r.optional()}),"resources/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resources:rc(D),nextCursor:r.optional()}),"resources/templates/list":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),resourceTemplates:rc(L),nextCursor:r.optional()}),"resources/read":ey({ttlMs:eD().int().min(0),cacheScope:x1(["public","private"]),contents:rc(ee([C,P]))}),"completion/complete":ey({completion:tM({values:rc(ra()).max(100),total:eD().int().optional(),hasMore:eY().optional()}).loose()}),"server/discover":ey({ttlMs:eD().int().min(0).catch(0),cacheScope:x1(["public","private"]).catch("private"),supportedVersions:rc(ra()),capabilities:xj,instructions:ra().optional()}),"subscriptions/listen":ey({})},eI=x0({"io.modelcontextprotocol/subscriptionId":a.optional()}),eN=tM({method:rl("notifications/subscriptions/acknowledged"),params:tM({_meta:eI.optional(),notifications:ep})}),eB=tM({_meta:eI.optional(),requestId:a,reason:ra().optional()}),eF=tM({method:rl("notifications/cancelled"),params:eB}),ew=x=>tM({jsonrpc:rl("2.0"),id:ee([ra(),eD().int()]),result:x}).strict();return{JSONValueSchema:x,JSONObjectSchema:e,ProgressTokenSchema:t,CursorSchema:r,RequestIdSchema:a,RoleSchema:n,LoggingLevelSchema:_,TaskMetadataSchema:s,RelatedTaskMetadataSchema:i,RequestMetaSchema:o,BaseRequestParamsSchema:l,TaskAugmentedRequestParamsSchema:c,NotificationsParamsSchema:v,NotificationSchema:d,IconSchema:f,IconsSchema:b,BaseMetadataSchema:u,ImplementationSchema:p,ClientTasksCapabilitySchema:E,ServerTasksCapabilitySchema:j,ClientCapabilitiesSchema:g,ServerCapabilitiesSchema:y,ProgressSchema:S,ProgressNotificationParamsSchema:I,ProgressNotificationSchema:N,LoggingMessageNotificationParamsSchema:B,LoggingMessageNotificationSchema:F,ResourceContentsSchema:w,TextResourceContentsSchema:C,BlobResourceContentsSchema:P,AnnotationsSchema:k,ResourceSchema:D,ResourceTemplateSchema:L,ResourceListChangedNotificationSchema:q,ResourceUpdatedNotificationParamsSchema:T,ResourceUpdatedNotificationSchema:R,PromptArgumentSchema:$,PromptSchema:G,PromptListChangedNotificationSchema:O,TextContentSchema:X,ImageContentSchema:K,AudioContentSchema:Q,ToolUseContentSchema:M,EmbeddedResourceSchema:Z,ResourceLinkSchema:J,ContentBlockSchema:V,PromptMessageSchema:H,ToolAnnotationsSchema:U,ToolListChangedNotificationSchema:Y,ModelHintSchema:z,ModelPreferencesSchema:W,ToolChoiceSchema:xx,BooleanSchemaSchema:xe,StringSchemaSchema:xt,NumberSchemaSchema:xr,UntitledSingleSelectEnumSchemaSchema:xa,TitledSingleSelectEnumSchemaSchema:xn,LegacyTitledEnumSchemaSchema:x_,SingleSelectEnumSchemaSchema:xA,UntitledMultiSelectEnumSchemaSchema:xs,TitledMultiSelectEnumSchemaSchema:xi,MultiSelectEnumSchemaSchema:xo,EnumSchemaSchema:xc,PrimitiveSchemaDefinitionSchema:xv,ElicitRequestFormParamsSchema:xd,ResourceTemplateReferenceSchema:xf,PromptReferenceSchema:xb,RootSchema:xu,ClientCapabilities2026Schema:xm,ServerCapabilities2026Schema:xj,RequestMetaEnvelopeSchema:xg,ToolSchema:xy,ToolResultContentSchema:xS,SamplingMessageContentBlockSchema:xI,SamplingMessageSchema:xN,ResultTypeSchema:xB,ResultMetaSchema:xF,ResultSchema:xP,PaginatedResultSchema:xk,CallToolResultSchema:xD,ListToolsResultSchema:xL,ListPromptsResultSchema:xq,GetPromptResultSchema:xT,ListResourcesResultSchema:xR,ListResourceTemplatesResultSchema:x$,ReadResourceResultSchema:xG,CompleteResultSchema:xO,CacheableResultSchema:xX,DiscoverResultSchema:xK,CreateMessageRequestParamsSchema:xQ,CreateMessageRequestSchema:xM,ListRootsRequestSchema:xZ,CreateMessageResultSchema:xJ,ListRootsResultSchema:xV,ElicitResultSchema:xH,ElicitRequestURLParamsSchema:xU,ElicitRequestParamsSchema:xY,ElicitRequestSchema:xz,InputRequestSchema:xW,InputResponseSchema:x2,InputRequestsSchema:x3,InputResponsesSchema:x6,InputRequiredResultSchema:x5,InputResponseRequestParamsSchema:x8,CallToolRequestSchema:en,ListToolsRequestSchema:e_,ListPromptsRequestSchema:ei,GetPromptRequestSchema:eo,ListResourcesRequestSchema:el,ListResourceTemplatesRequestSchema:ec,ReadResourceRequestSchema:ev,CompleteRequestSchema:eb,DiscoverRequestSchema:eu,SubscriptionFilterSchema:ep,SubscriptionsListenRequestSchema:eh,SubscriptionsListenResultMetaSchema:eE,SubscriptionsListenResultSchema:ej,dispatchRequestSchemas:eg,dispatchResultSchemas:eS,NotificationMetaSchema:eI,SubscriptionsAcknowledgedNotificationSchema:eN,CancelledNotificationParamsSchema:eB,CancelledNotificationSchema:eF,notificationSchemas2026:{"notifications/cancelled":eF,"notifications/progress":N,"notifications/message":F,"notifications/resources/updated":R,"notifications/resources/list_changed":q,"notifications/tools/list_changed":Y,"notifications/prompts/list_changed":O,"notifications/subscriptions/acknowledged":eN},JSONRPCResultResponseSchema:ew(xP),CallToolResultResponseSchema:ew(ee([xD,x5])),ListToolsResultResponseSchema:ew(xL),ListPromptsResultResponseSchema:ew(xq),GetPromptResultResponseSchema:ew(ee([xT,x5])),ListResourcesResultResponseSchema:ew(xR),ListResourceTemplatesResultResponseSchema:ew(x$),ReadResourceResultResponseSchema:ew(ee([xG,x5])),CompleteResultResponseSchema:ew(xO),DiscoverResultResponseSchema:ew(xK)}}()}let bv=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"],bd=Symbol("modelcontextprotocol.resultCacheHintFallback");function bf(x,e){if(void 0===e)return x;let t=x[bd];if(void 0===t)return{...x,[bd]:e};let r={},a=t.ttlMs??e.ttlMs;void 0!==a&&(r.ttlMs=a);let n=t.cacheScope??e.cacheScope;return void 0!==n&&(r.cacheScope=n),{...x,[bd]:r}}function bb(x){return"number"==typeof x&&Number.isSafeInteger(x)&&x>=0}function bu(x){return"public"===x||"private"===x}function bp(x,e){if(void 0!==x.ttlMs&&!bb(x.ttlMs))throw RangeError(`Invalid cache hint for ${e}: ttlMs must be a non-negative safe integer (got ${String(x.ttlMs)})`);if(void 0!==x.cacheScope&&!bu(x.cacheScope))throw RangeError(`Invalid cache hint for ${e}: cacheScope must be 'public' or 'private' (got ${String(x.cacheScope)})`)}let bm=((rK={})[rK.ParseError=-32700]="ParseError",rK[rK.InvalidRequest=-32600]="InvalidRequest",rK[rK.MethodNotFound=-32601]="MethodNotFound",rK[rK.InvalidParams=-32602]="InvalidParams",rK[rK.InternalError=-32603]="InternalError",rK[rK.ResourceNotFound=-32002]="ResourceNotFound",rK[rK.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",rK[rK.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",rK[rK.UrlElicitationRequired=-32042]="UrlElicitationRequired",rK);var bh=class x extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](x){return fV(this,x)}static isInstance(x){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return fV(this,x)}constructor(x,e,t){super(e),this.code=x,this.data=t,this.name="ProtocolError",fJ(this,new.target)}static fromError(e,t,r){return e===bm.UrlElicitationRequired&&r&&r.elicitations?new bj(r.elicitations,t):e===bm.UnsupportedProtocolVersion&&r&&Array.isArray(r.supported)&&"string"==typeof r.requested?new bg({supported:r.supported,requested:r.requested},t):(e===bm.InvalidParams||e===bm.ResourceNotFound)&&"string"==typeof r?.uri&&(e===bm.ResourceNotFound||1===Object.keys(r).length)?new bE(r.uri,t):e===bm.MissingRequiredClientCapability&&r&&null!==r.requiredCapabilities&&"object"==typeof r.requiredCapabilities&&!Array.isArray(r.requiredCapabilities)?new by({requiredCapabilities:r.requiredCapabilities},t):new x(e,t,r)}},bE=class extends bh{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(x,e=`Resource not found: ${x}`){super(bm.InvalidParams,e,{uri:x})}get uri(){return this.data.uri}},bj=class extends bh{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(x,e=`URL elicitation${x.length>1?"s":""} required`){super(bm.UrlElicitationRequired,e,{elicitations:x})}get elicitations(){return this.data?.elicitations??[]}},bg=class extends bh{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(x,e=`Unsupported protocol version: ${x.requested}`){super(bm.UnsupportedProtocolVersion,e,x)}get supported(){return this.data.supported}get requested(){return this.data.requested}},by=class extends bh{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(x,e=`Missing required client capabilities: ${Object.keys(x.requiredCapabilities).join(", ")}`){super(bm.MissingRequiredClientCapability,e,x)}get requiredCapabilities(){return this.data.requiredCapabilities}};let bS=["tools/call","prompts/get","resources/read"],bI=["elicitation/create","sampling/createMessage","roots/list"];function bN(){if(_)return _;let x=bc();return _={request:{"elicitation/create":tM({method:rl("elicitation/create"),params:x.ElicitRequestParamsSchema}),"sampling/createMessage":tM({method:rl("sampling/createMessage"),params:x.CreateMessageRequestParamsSchema}),"roots/list":tM({method:rl("roots/list"),params:x0({}).optional()})},response:{"elicitation/create":x.ElicitResultSchema,"sampling/createMessage":x.CreateMessageResultSchema,"roots/list":x.ListRootsResultSchema}}}function bB(x){return bI.includes(x)}function bF(x){return bB(x)?bN().request[x]:void 0}let bw={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},bC={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function bP(x){return Object.prototype.hasOwnProperty.call(bw,x)}function bk(x){return Object.prototype.hasOwnProperty.call(bC,x)}function bD(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function bL(x,e){if(void 0===x)return{ok:!1,reason:"not-in-era"};let t=x.safeParse(e);return t.success?{ok:!0,value:t.data}:{ok:!1,reason:"invalid",message:String(t.error)}}Object.keys(bw),Object.keys(bC);let bq={ok:!1,reason:"not-in-era"},bT=[xl,ef],bR={era:"2026-07-28",hasRequestMethod:bP,hasNotificationMethod:bk,hasInputRequestMethod:x=>void 0!==bF(x),validateRequest:(x,e)=>bL(bP(x)?bc().dispatchRequestSchemas[x]:void 0,e),validateResult:(x,e)=>bL(Object.prototype.hasOwnProperty.call(bw,x)?bc().dispatchResultSchemas[x]:void 0,e),validateNotification:(x,e)=>bL(bk(x)?bc().notificationSchemas2026[x]:void 0,e),validateInputRequest:(x,e)=>bL(bF(x),e),validateInputResponse:(x,e)=>bL(bB(x)?bN().response[x]:void 0,e),samplingResultVariant:()=>bq,outboundEnvelope:x=>({[xl]:x.protocolVersion,[xh]:x.clientInfo,[ef]:x.clientCapabilities,...void 0!==x.logLevel&&{[t$]:x.logLevel}}),validateEnvelopeMeta(x){let e=[];for(let t of bT)t in x||e.push({key:t,problem:"missing"});let t=bc().RequestMetaEnvelopeSchema.safeParse(x);if(!t.success)for(let x of t.error.issues){let t=x.path.map(String),r=t.length>0?t.join("."):"_meta";1===t.length&&e.some(x=>x.key===r&&"missing"===x.problem)||e.push({key:r,problem:x.message})}return e},projectCallToolResult:x=>f3(x),inputRequestSchema:bF,decodeResult(x,e){if(!bD(e))return{kind:"invalid",error:new fU(fH.InvalidResult,`Invalid result for ${x}: not an object`,{method:x})};let t=e.resultType;if(void 0===t)return{kind:"invalid",error:new fU(fH.InvalidResult,`Invalid result for ${x}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:x,violation:"missing-resultType"})};if("string"!=typeof t)return{kind:"invalid",error:new fU(fH.InvalidResult,`Invalid result for ${x}: non-string resultType`,{method:x,resultType:t})};if("input_required"===t){let t=e.inputRequests,r=bD(t)?t:{},a=e.requestState;return 0===Object.keys(r).length&&"string"!=typeof a?{kind:"invalid",error:new fU(fH.InvalidResult,`Invalid result for ${x}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:x,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:r,..."string"==typeof a&&{requestState:a}}}if("complete"!==t)return{kind:"invalid",error:new fU(fH.UnsupportedResultType,`Unsupported result type '${t}' for ${x}`,{resultType:t,method:x})};let r=function(){if(A)return A;let x=bc();return A={"tools/call":x.CallToolResultSchema,"tools/list":x.ListToolsResultSchema,"prompts/get":x.GetPromptResultSchema,"prompts/list":x.ListPromptsResultSchema,"resources/list":x.ListResourcesResultSchema,"resources/templates/list":x.ListResourceTemplatesResultSchema,"resources/read":x.ReadResourceResultSchema,"completion/complete":x.CompleteResultSchema,"server/discover":x.DiscoverResultSchema}}(),a=Object.hasOwn(r,x)?r[x]:void 0;if(void 0!==a){let t=a.safeParse(e);if(!t.success)return{kind:"invalid",error:new fU(fH.InvalidResult,`Invalid result for ${x}: ${t.error}`,{method:x})}}let n={...e};return delete n.resultType,{kind:"complete",result:n}},encodeResult:(x,e,t)=>(function(x,e){if(void 0===e)return x;let t=x._meta;return void 0===t?{...x,_meta:{[tS]:e}}:null===t||"object"!=typeof t||Array.isArray(t)||void 0!==t[tS]?x:{...x,_meta:{...t,[tS]:e}}})(function(x,e){var t,r;let a=e[bd];if("complete"!==e.resultType||!bv.includes(x)){let x;return void 0===a?e:(x={...e},delete x[bd],x)}let n=bb(e.ttlMs)?e.ttlMs:void 0!==(t=a)&&bb(t.ttlMs)?t.ttlMs:0,_=bu(e.cacheScope)?e.cacheScope:void 0!==(r=a)&&bu(r.cacheScope)?r.cacheScope:"private",A={...e,ttlMs:n,cacheScope:_};return delete A[bd],A}(x,function(x,e){let t=e.resultType;if(void 0===t)return{...e,resultType:"complete"};if("complete"===t||bS.includes(x))return e;throw new bh(bm.InternalError,`Handler for ${x} returned resultType '${String(t)}', but results of ${x} only support 'complete' on protocol revision 2026-07-28`)}(x,function(x,e){let t=e,r=!1,a=()=>(r||(t={...t},r=!0),t),n=e.tools;"tools/list"===x&&Array.isArray(n)&&n.some(x=>bD(x)&&"execution"in x)&&(a().tools=n.map(x=>{if(!bD(x)||!("execution"in x))return x;let e={...x};return delete e.execution,e}));let _=e.capabilities;if(bD(_)&&"tasks"in _){let x={..._};delete x.tasks,a().capabilities=x}return t}(x,e))),t),encodeErrorCode:x=>-32002===x?-32602:x,checkInboundEnvelope(x){if(void 0===x.envelope)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let e=bc().RequestMetaEnvelopeSchema.safeParse(x.envelope);if(!e.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${e.error.issues.map(x=>x.message).join("; ")}`}},b$="2026-07-28";function bG(x){return void 0!==x&&x>=f0?bR:bl}function bO(x){return void 0!==x.revision?bG(x.revision).era:"modern"===x.era?bR.era:bl.era}function bX(x){return bQ.some(e=>e.hasRequestMethod(x))}function bK(x){return bQ.some(e=>e.hasNotificationMethod(x))}let bQ=[bl,bR];function bM(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function bZ(x){if(!bM(x))return;let e=x._meta;return bM(e)?e:void 0}function bJ(x){let e=bZ(x);return void 0!==e&&xl in e}function bV(x){let e=bZ(x)?.[xl];return"string"==typeof e?e:void 0}function bH(x){return bG(b$).validateEnvelopeMeta(x)}var bU=(x=>{let e={};for(var t in x)fL(e,t,{get:x[t],enumerable:!0});return e})({AnnotationsSchema:()=>ro,AudioContentSchema:()=>tx,BaseMetadataSchema:()=>tI,BaseRequestParamsSchema:()=>et,BlobResourceContentsSchema:()=>eB,BooleanSchemaSchema:()=>ed,CallToolRequestParamsSchema:()=>tZ,CallToolRequestSchema:()=>tW,CallToolResultSchema:()=>eu,CancelTaskRequestSchema:()=>xm,CancelTaskResultSchema:()=>e5,CancelledNotificationParamsSchema:()=>rf,CancelledNotificationSchema:()=>ej,ClientCapabilitiesSchema:()=>xB,ClientNotificationSchema:()=>tv,ClientRequestSchema:()=>eK,ClientResultSchema:()=>xc,ClientTasksCapabilitySchema:()=>th,CompatibilityCallToolResultSchema:()=>tb,CompleteRequestParamsSchema:()=>rb,CompleteRequestSchema:()=>xS,CompleteResultSchema:()=>xy,ContentBlockSchema:()=>rs,CreateMessageRequestParamsSchema:()=>xn,CreateMessageRequestSchema:()=>eI,CreateMessageResultSchema:()=>xM,CreateMessageResultWithToolsSchema:()=>xJ,CreateTaskResultSchema:()=>x9,CursorSchema:()=>xV,DiscoverRequestSchema:()=>xI,DiscoverResultSchema:()=>xu,ElicitRequestFormParamsSchema:()=>eb,ElicitRequestParamsSchema:()=>e3,ElicitRequestSchema:()=>e4,ElicitRequestURLParamsSchema:()=>e1,ElicitResultSchema:()=>xK,ElicitationCompleteNotificationParamsSchema:()=>tF,ElicitationCompleteNotificationSchema:()=>ri,EmbeddedResourceSchema:()=>ey,EmptyResultSchema:()=>xC,EnumSchemaSchema:()=>te,GetPromptRequestParamsSchema:()=>tC,GetPromptRequestSchema:()=>rx,GetPromptResultSchema:()=>ts,GetTaskPayloadRequestSchema:()=>ty,GetTaskPayloadResultSchema:()=>xN,GetTaskRequestSchema:()=>e_,GetTaskResultSchema:()=>rd,IconSchema:()=>xY,IconsSchema:()=>e7,ImageContentSchema:()=>ez,ImplementationSchema:()=>tu,InitializeRequestParamsSchema:()=>e8,InitializeRequestSchema:()=>x_,InitializeResultSchema:()=>eT,InitializedNotificationSchema:()=>eG,JSONArraySchema:()=>ep,JSONObjectSchema:()=>xE,JSONRPCErrorResponseSchema:()=>xL,JSONRPCMessageSchema:()=>ei,JSONRPCNotificationSchema:()=>xk,JSONRPCRequestSchema:()=>eE,JSONRPCResponseSchema:()=>eL,JSONRPCResultResponseSchema:()=>eS,JSONValueSchema:()=>tk,LegacyTitledEnumSchemaSchema:()=>er,ListChangedOptionsBaseSchema:()=>xR,ListPromptsRequestSchema:()=>rj,ListPromptsResultSchema:()=>tt,ListResourceTemplatesRequestSchema:()=>tP,ListResourceTemplatesResultSchema:()=>tN,ListResourcesRequestSchema:()=>tA,ListResourcesResultSchema:()=>xA,ListRootsRequestSchema:()=>t4,ListRootsResultSchema:()=>ta,ListTasksRequestSchema:()=>x6,ListTasksResultSchema:()=>t7,ListToolsRequestSchema:()=>rA,ListToolsResultSchema:()=>tV,LoggingLevelSchema:()=>tc,LoggingMessageNotificationParamsSchema:()=>xs,LoggingMessageNotificationSchema:()=>tQ,ModelHintSchema:()=>tp,ModelPreferencesSchema:()=>xP,MultiSelectEnumSchemaSchema:()=>eO,NotificationSchema:()=>e$,NotificationsParamsSchema:()=>tn,NumberSchemaSchema:()=>e0,PaginatedRequestParamsSchema:()=>tf,PaginatedRequestSchema:()=>ex,PaginatedResultSchema:()=>eJ,PingRequestSchema:()=>ru,PrimitiveSchemaDefinitionSchema:()=>ti,ProgressNotificationParamsSchema:()=>en,ProgressNotificationSchema:()=>xv,ProgressSchema:()=>xj,ProgressTokenSchema:()=>tm,PromptArgumentSchema:()=>xi,PromptListChangedNotificationSchema:()=>ev,PromptMessageSchema:()=>xD,PromptReferenceSchema:()=>xz,PromptSchema:()=>to,ReadResourceRequestParamsSchema:()=>xX,ReadResourceRequestSchema:()=>t9,ReadResourceResultSchema:()=>e2,RelatedTaskMetadataSchema:()=>tl,RequestIdSchema:()=>rp,RequestMetaSchema:()=>t5,RequestSchema:()=>eq,ResourceContentsSchema:()=>el,ResourceLinkSchema:()=>xZ,ResourceListChangedNotificationSchema:()=>t6,ResourceRequestParamsSchema:()=>rm,ResourceSchema:()=>x7,ResourceTemplateReferenceSchema:()=>x5,ResourceTemplateSchema:()=>xg,ResourceUpdatedNotificationParamsSchema:()=>xW,ResourceUpdatedNotificationSchema:()=>tG,ResultMetaObjectSchema:()=>tK,ResultSchema:()=>eN,RoleSchema:()=>eQ,RootSchema:()=>re,RootsListChangedNotificationSchema:()=>eF,SamplingContentSchema:()=>eU,SamplingMessageContentBlockSchema:()=>t_,SamplingMessageSchema:()=>ew,ServerCapabilitiesSchema:()=>rh,ServerNotificationSchema:()=>eC,ServerRequestSchema:()=>eg,ServerResultSchema:()=>em,ServerTasksCapabilitySchema:()=>eX,SetLevelRequestParamsSchema:()=>xT,SetLevelRequestSchema:()=>ec,SingleSelectEnumSchemaSchema:()=>xo,StringSchemaSchema:()=>ek,SubscribeRequestParamsSchema:()=>eP,SubscribeRequestSchema:()=>tD,SubscriptionFilterSchema:()=>eR,SubscriptionsAcknowledgedNotificationParamsSchema:()=>tB,SubscriptionsAcknowledgedNotificationSchema:()=>tE,SubscriptionsListenRequestParamsSchema:()=>tR,SubscriptionsListenRequestSchema:()=>rt,SubscriptionsListenResultMetaSchema:()=>tL,SubscriptionsListenResultSchema:()=>xb,TaskAugmentedRequestParamsSchema:()=>tj,TaskCreationParamsSchema:()=>tH,TaskMetadataSchema:()=>xO,TaskSchema:()=>xH,TaskStatusNotificationParamsSchema:()=>xq,TaskStatusNotificationSchema:()=>xp,TaskStatusSchema:()=>tq,TextContentSchema:()=>tY,TextResourceContentsSchema:()=>x$,TitledMultiSelectEnumSchemaSchema:()=>xd,TitledSingleSelectEnumSchemaSchema:()=>ea,ToolAnnotationsSchema:()=>tT,ToolChoiceSchema:()=>eM,ToolExecutionSchema:()=>xU,ToolListChangedNotificationSchema:()=>tr,ToolResultContentSchema:()=>xG,ToolSchema:()=>eZ,ToolUseContentSchema:()=>t2,UnsubscribeRequestParamsSchema:()=>tg,UnsubscribeRequestSchema:()=>tX,UntitledMultiSelectEnumSchemaSchema:()=>rE,UntitledSingleSelectEnumSchemaSchema:()=>eV});let bY=x=>eE.safeParse(x).success,bz=x=>xk.safeParse(x).success,bW=x=>eS.safeParse(x).success,b0=x=>xL.safeParse(x).success,b1=x=>"object"==typeof x&&null!==x&&!Array.isArray(x)&&"input_required"===x.resultType,b2="x-mcp-header",b3=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,b6=new Set(["string","integer","boolean","number"]);function b4(x){let e=[],t=new Map,r=(x,a,n)=>{if(null===x||"object"!=typeof x)return;if(b2 in x){if(!n||0===a.length)return`${b8(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let r=x[b2];if("string"!=typeof r||0===r.length)return`${b8(a)}: x-mcp-header MUST be a non-empty string`;if(!b3.test(r))return`${b8(a)}: x-mcp-header '${r}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let _="string"==typeof x.type?x.type:void 0;if(void 0===_||!b6.has(_))return`${b8(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${_??"<none>"}`;let A=r.toLowerCase(),s=t.get(A);if(void 0!==s)return`x-mcp-header '${r}' is not case-insensitively unique (also declared as '${s}')`;t.set(A,r),e.push({path:a,headerName:r,type:_})}let _=x.properties;if(null!==_&&"object"==typeof _)for(let[x,e]of Object.entries(_)){let t=r(e,[...a,x],n);if(void 0!==t)return t}for(let e of b5){let t=x[e];if(void 0!==t)for(let x of Array.isArray(t)?t:null!==t&&"object"==typeof t&&b7.has(e)?Object.values(t):[t]){let t=r(x,[...a,`<${e}>`],!1);if(void 0!==t)return t}}},a=r(x,[],!0);return void 0===a?{valid:!0,declarations:e}:{valid:!1,reason:a}}let b5=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],b7=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function b8(x){return 0===x.length?"<root>":x.join(".")}let b9=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ux=/^-?\d+(\.\d+)?$/;function ue(x){if(!(x.startsWith("=?base64?")&&x.endsWith("?=")))return x;let e=x.slice(9,x.length-2);if(b9.test(e))try{let x=atob(e),t=new Uint8Array(x.length);for(let e=0;e<x.length;e++)t[e]=x.codePointAt(e);return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return}}function ut(x,e,t){return{kind:"reject",rung:"param-header-validation",cell:x,httpStatus:400,code:ur,message:`Bad Request: the request headers and body disagree: ${t}`,data:{mismatch:{header:e,body:t}},settled:!0}}let ur=-32020;bm.InvalidRequest,bm.UnsupportedProtocolVersion,bm.InvalidParams,bm.MethodNotFound,bm.InvalidParams,bm.MissingRequiredClientCapability;let ua={[bm.ParseError]:400,[bm.InvalidRequest]:400,[bm.MethodNotFound]:404,[bm.UnsupportedProtocolVersion]:400,[bm.MissingRequiredClientCapability]:400,[ur]:400};function un(x,e,t,r,a){return{kind:"reject",rung:x,cell:e,httpStatus:t,code:r.code,message:r.message,...void 0!==r.data&&{data:r.data},settled:a}}function u_(x,e,t,r="era-classification"){return un(r,x,400,new bh(ur,`Bad Request: the request headers and body disagree: ${t}`,{mismatch:{header:e,body:t}}),!0)}let uA={"tools/call":"name","prompts/get":"name","resources/read":"uri"};function us(x){let e=0;for(;e<x.length;){let t=x.codePointAt(e);if(9!==t&&32!==t)break;e+=1}let t=x.length;for(;t>e;){let e=x.codePointAt(t-1);if(9!==e&&32!==e)break;t-=1}return 0===e&&t===x.length?x:x.slice(e,t)}function ui(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function uo(x){return void 0===x?{era:"modern"}:{era:x>=f0?"modern":"legacy",revision:x}}function ul(x){return new Set(x.flatMap(x=>Object.keys(x.shape)))}function uc(x){if(null==x)return!1;let e=typeof x;return("object"===e||"function"===e)&&"~standard"in x&&"function"==typeof x["~standard"]?.validate}let uv=!1,ud="draft-2020-12";function uf(x,e="input"){let t,r=x["~standard"];if(r.jsonSchema)t=r.jsonSchema[e]({target:ud});else if("zod"===r.vendor){if(!("_zod"in x))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");uv||(uv=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),t=t8(x,{target:ud,io:e})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if("output"===e)return void 0!==t.type||!function x(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(e=>null!==e&&"object"==typeof e&&("object"===e.type||x(e)))}return!1}(t)?t:{type:"object",...t};if(void 0!==t.type&&"object"!==t.type)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(t.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...t}}async function ub(x,e){let t=await x["~standard"].validate(e);return t.issues&&t.issues.length>0?{success:!1,error:t.issues.map(x=>x.path?.length?`${x.path.map(x=>String("object"==typeof x?x.key:x)).join(".")}: ${x.message}`:x.message).join(", ")}:{success:!0,data:t.value}}let uu=/\\\.\\d\{(\d+)\}/;function up(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}let um=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function uh(x){return um.has(x)||x.startsWith("x-")}let uE=new Set(["$schema",...Object.keys(eb.shape.requestedSchema.shape)]),uj={string:ul([ek,eV,ea,er]),number:ul([e0]),integer:ul([e0]),boolean:ul([ed]),array:ul([rE,xd])},ug=new Set(ek.shape.format.unwrap().options);Object.assign(function(x){let e=void 0!==x.inputRequests&&Object.keys(x.inputRequests).length>0,t="string"==typeof x.requestState;if(!e&&!t)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...void 0!==x.inputRequests&&{inputRequests:x.inputRequests},...void 0!==x.requestState&&{requestState:x.requestState}}},{elicit(x){try{return{method:"elicitation/create",params:function(x){var e;if(!uc(x.requestedSchema))return{...x,mode:"form",requestedSchema:x.requestedSchema};let t=x.requestedSchema["~standard"].vendor,r=function(x,e){let t={},r=[];for(let[a,n]of Object.entries(x))"properties"===a&&up(n)?t[a]=Object.fromEntries(Object.entries(n).map(([x,t])=>[x,function(x,e,t,r){if(!up(x))return x;let a="string"==typeof x.type&&Object.hasOwn(uj,x.type)?uj[x.type]:void 0;if(void 0===a)return x;let n={};for(let[A,s]of Object.entries(x))if(a.has(A)||uh(A))n[A]=s;else if("pattern"===A&&"string"===x.type&&"string"==typeof x.format)if(ug.has(x.format)){var _;"string"==typeof s&&(_=x.format,"zod"!==t||(function(x,e){let t;switch(x){case"email":t=[tJ()];break;case"uri":t=[td()];break;case"date":t=[eh()];break;case"date-time":let r,a;r=uu.exec(e),a=[void 0,-1,0],r&&a.push(Number(r[1])),t=[!1,!0].flatMap(x=>[!1,!0].flatMap(e=>a.map(t=>rn({local:x,offset:e,precision:t}))))}return new Set(t.map(x=>{let e;return e=t8(x,{target:ud,io:"input"}),"string"==typeof e.pattern?e.pattern:void 0}).filter(x=>void 0!==x))})(_,s).has(s))||r.push(`${e}.${A}`)}else n[A]=s;else r.push(`${e}.${A}`);return n}(t,`properties.${x}`,e,r)])):uE.has(a)?t[a]=n:uh(a)||r.push(a);if(r.length>0)throw new bh(bm.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(", ")}`);return t}(function(x){try{return uf(x,"input")}catch(e){let x=e instanceof Error?e.message:String(e);throw new bh(bm.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${x}`)}}(x.requestedSchema),t),a=(e=eb.shape.requestedSchema,rr(e,r));if(!a.success)throw new bh(bm.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${function(x,e){if(!up(x.properties))return e;let t=Object.entries(x.properties).filter(([,x])=>!rr(ti,x).success).map(([x])=>`properties.${x}`);return t.length>0?t.join(", "):e}(r,a.error.message)}`);let n=function x(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,a)=>x(e,t[a],`${r}[${a}]`)):up(e)&&up(t)?Object.entries(e).flatMap(([e,a])=>{let n=r?`${r}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?x(a,t[e],n):uh(e)?[]:[n]}):[]}(r,a.data);if(n.length>0)throw new bh(bm.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let _=(a.data.required??[]).filter(x=>!Object.prototype.hasOwnProperty.call(a.data.properties,x));if(_.length>0)throw new bh(bm.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${_.join(", ")}`);return{...x,mode:"form",requestedSchema:a.data}}(x)}}catch(x){throw x instanceof bh?TypeError(x.message,{cause:x}):x}},elicitUrl:x=>({method:"elicitation/create",params:{...x,mode:"url"}}),createMessage:x=>({method:"sampling/createMessage",params:x}),listRoots:()=>({method:"roots/list"})});let uy={},uS={};function uI(x,e){let t=x.slice(0,-6);uy[t]=e,uS[t]=x=>e.safeParse(x).success}for(let x of["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"])uI(x,bU[x]);for(let[x,e]of Object.entries({IdJagTokenExchangeResponseSchema:tz,OAuthClientInformationFullSchema:x3,OAuthClientInformationSchema:eW,OAuthClientMetadataSchema:xF,OAuthClientRegistrationErrorSchema:eH,OAuthErrorResponseSchema:xw,OAuthMetadataSchema:t1,OAuthProtectedResourceMetadataSchema:r_,OAuthTokenRevocationRequestSchema:x8,OAuthTokensSchema:rv,OpenIdProviderDiscoveryMetadataSchema:xf,OpenIdProviderMetadataSchema:eo}))uI(x,e);Object.freeze(uy);let uN=Object.freeze(uS),uB=[xl,xh,ef,t$],uF=["inputResponses","requestState"];function uw(x,e){let t=x.params;if(!uL(t))return{message:x,lifted:{}};let r=t._meta,a=uL(r)?uB.filter(x=>x in r):[],n="request"===e?uF.filter(x=>x in t):[];if(0===a.length&&0===n.length)return{message:x,lifted:{}};let _={},A={...t};if(a.length>0&&uL(r)){let x={},e={...r};for(let t of a)x[t]=r[t],delete e[t];_.envelope=x,Object.keys(e).length>0?A._meta=e:delete A._meta}for(let x of n)"inputResponses"===x&&(_.inputResponses=A[x]),"requestState"===x&&(_.requestState=A[x]),delete A[x];return{message:{...x,params:A},lifted:_}}function uC(x,e){let t=x.validateResult(e,void 0);if(t.ok||"not-in-era"!==t.reason)return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(t){let r=x.validateResult(e,t);return r.ok?{value:r.value}:{issues:[{message:"invalid"===r.reason?r.message:`not-in-era: ${e}`}]}}}}}let uP=(rQ=void 0,()=>rQ);function uk(x,e){return{...x,mcpReq:{...x.mcpReq,requestState:()=>e}}}var uD=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{s=(x,e)=>{x._negotiatedProtocolVersion=e}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(x){this._options=x,this._supportedProtocolVersions=x?.supportedProtocolVersions??tO,this.setNotificationHandler("notifications/cancelled",x=>{this._oncancel(x)}),this.setNotificationHandler("notifications/progress",x=>{this._onprogress(x)}),this.setRequestHandler("ping",x=>({}))}_shouldDropInbound(x){}_outboundMetaEnvelope(){}_envelopeOutbound(x){let e=this._outboundMetaEnvelope();if(void 0===e)return x;let t=x.params??{};return{...x,params:{...t,_meta:{...e,...t._meta}}}}_resolveNonCompleteResult(x,e){return Promise.reject(new fU(fH.UnsupportedResultType,`Unsupported result type '${x.kind}' for ${e.request.method}`,{resultType:x.kind,method:e.request.method}))}_getRequestHandler(x){return this._requestHandlers.get(x)}async _oncancel(x){x.params.requestId&&this._requestHandlerAbortControllers.get(x.params.requestId)?.abort(x.params.reason)}_setupTimeout(x,e,t,r,a=!1){this._timeoutInfo.set(x,{timeoutId:setTimeout(r,e),startTime:Date.now(),timeout:e,maxTotalTimeout:t,resetTimeoutOnProgress:a,onTimeout:r})}_resetTimeout(x){let e=this._timeoutInfo.get(x);if(!e)return!1;let t=Date.now()-e.startTime;if(e.maxTotalTimeout&&t>=e.maxTotalTimeout)throw this._timeoutInfo.delete(x),new fU(fH.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:e.maxTotalTimeout,totalElapsed:t});return clearTimeout(e.timeoutId),e.timeoutId=setTimeout(e.onTimeout,e.timeout),!0}_cleanupTimeout(x){let e=this._timeoutInfo.get(x);e&&(clearTimeout(e.timeoutId),this._timeoutInfo.delete(x))}async connect(x){this._transport=x;let e=this.transport?.onclose;this._transport.onclose=()=>{try{e?.()}finally{this._onclose()}};let t=this.transport?.onerror;this._transport.onerror=x=>{t?.(x),this._onerror(x)};let r=this._transport?.onmessage;this._transport.onmessage=(x,e)=>{r?.(x,e),bW(x)||b0(x)?this._onresponse(x):bY(x)?this._onrequest(x,e):bz(x)?this._onnotification(x,e):this._onerror(Error(`Unknown message type: ${JSON.stringify(x)}`))},x.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let x=this._responseHandlers;for(let x of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._timeoutInfo.values()))clearTimeout(x.timeoutId);this._timeoutInfo.clear();let e=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let t=new fU(fH.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let e of x.values())e(t);for(let x of e.values())x.abort(t)}}_onerror(x){this.onerror?.(x)}_onnotification(x,e){let{message:t}=uw(x,"notification"),r=this._negotiatedWireCodec();if(e?.classification===void 0&&"drop"===this._shouldDropInbound(x))return;if(e?.classification!==void 0){let x=bO(e.classification);if(x!==r.era)return void this._onerror(Error(`Era mismatch on inbound notification '${t.method}': classified as ${x} but this instance serves ${r.era}`))}if(bK(t.method)&&!r.hasNotificationMethod(t.method))return;let a=this._notificationHandlers.get(t.method),n=this.fallbackNotificationHandler;(void 0!==a||void 0!==n)&&Promise.resolve().then(()=>void 0===a?n(t):a(t,r)).catch(x=>this._onerror(Error(`Uncaught error in notification handler: ${x}`)))}_onrequest(x,e){var t;let{message:r,lifted:a}=uw(x,"request"),n=this._negotiatedWireCodec();if(e?.classification===void 0&&"drop"===this._shouldDropInbound(x))return void this._onerror(Error(`Dropped inbound request '${x.method}': not servable on this connection's protocol era`));let _=this._transport,A=(x,e,t)=>{let a={jsonrpc:"2.0",id:r.id,error:{code:x,message:e,...void 0!==t&&{data:t}}};_?.send(a).catch(x=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(e?.classification!==void 0){let x=bO(e.classification);if(x!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${x} but this instance serves ${n.era}`));let t=e.classification.revision??x;A(bm.UnsupportedProtocolVersion,`Unsupported protocol version: ${t}`,{supported:this._supportedProtocolVersions,requested:t});return}}if(bX(r.method)&&!n.hasRequestMethod(r.method))return void A(bm.MethodNotFound,"Method not found");let s=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(void 0===s)return void A(bm.MethodNotFound,"Method not found");let i=n.checkInboundEnvelope(a);if(void 0!==i)return void A(bm.InvalidParams,i);let o=(x,e)=>this._notificationViaCodec(this._resolveOutboundCodec(x.method),x,{...e,relatedRequestId:r.id}),l=(x,e,t)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(x.method),x,e,{...t,relatedRequestId:r.id}),c=new AbortController;this._requestHandlerAbortControllers.set(r.id,c);let v=void 0===a.inputResponses?void 0:function(x){let e={},t=[];if(!uq(x))return{accepted:e,droppedKeys:t};for(let[r,a]of Object.entries(x)){if(!uq(a)||"method"in a||"result"in a){t.push(r);continue}e[r]=a}return{accepted:e,droppedKeys:t}}(a.inputResponses),d={sessionId:_?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...void 0!==a.envelope&&{envelope:a.envelope},...void 0!==v&&{inputResponses:v.accepted},...void 0!==v&&v.droppedKeys.length>0&&{droppedInputResponseKeys:v.droppedKeys},requestState:void 0===a.requestState?uP:(t=a.requestState,()=>t),signal:c.signal,send:(x,e,t)=>{let r=this._resolveOutboundCodec(x.method);if(this._assertOutboundRequestInEra(r,x.method),uc(e))return l(x,e,t);let a=uC(r,x.method);if(void 0===a)throw TypeError(`'${x.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return l(x,a,e)},notify:o},http:e?.authInfo?{authInfo:e.authInfo}:void 0},f=this.buildContext(d,e);Promise.resolve().then(()=>s(r,f)).then(async x=>{let e;if(c.signal.aborted)return;try{e=n.encodeResult(r.method,x,this._outboundServerInfo())}catch(x){this._onerror(Error(`Failed to encode result for ${r.method}: ${x}`)),A(bm.InternalError,"Internal error");return}let t={result:e,jsonrpc:"2.0",id:r.id};await _?.send(t)},async x=>{if(c.signal.aborted)return;let e=Number.isSafeInteger(x.code)?x.code:bm.InternalError,t={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(e),message:x.message??"Internal error",...void 0!==x.data&&{data:x.data}}};await _?.send(t)}).catch(x=>this._onerror(Error(`Failed to send response: ${x}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===c&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(x){let{progressToken:e,...t}=x.params,r=Number(e),a=this._progressHandlers.get(r);if(!a)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(x)}`));let n=this._responseHandlers.get(r),_=this._timeoutInfo.get(r);if(_&&n&&_.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(x){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),n(x);return}a(t)}_onresponse(x){let e=Number(x.id),t=this._responseHandlers.get(e);void 0===t?this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(x)}`)):(this._responseHandlers.delete(e),this._cleanupTimeout(e),this._progressHandlers.delete(e),t(bW(x)?x:bh.fromError(x.error.code,x.error.message,x.error.data)))}get transport(){return this._transport}async close(){await this._transport?.close()}request(x,e,t){let r=this._resolveOutboundCodec(x.method);if(this._assertOutboundRequestInEra(r,x.method),uc(e))return this._requestWithSchemaViaCodec(r,x,e,t);let a=uC(r,x.method);if(void 0===a)throw TypeError(`'${x.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,x,a,e)}_negotiatedWireCodec(){return bG(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(x){if(void 0===this._negotiatedProtocolVersion){let e=function(x){switch(x){case"initialize":case"notifications/initialized":return bG(void 0);case"server/discover":return bG(b$);default:return}}(x);if(e)return e}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(x,e){if(bX(e)&&!x.hasRequestMethod(e))throw new fU(fH.MethodNotSupportedByProtocolVersion,`Method '${e}' is not supported by the negotiated protocol version (wire era ${x.era})`,{method:e,era:x.era})}_requestWithSchema(x,e,t){let r=this._resolveOutboundCodec(x.method);return this._assertOutboundRequestInEra(r,x.method),this._requestWithSchemaViaCodec(r,x,e,t)}_requestWithSchemaViaCodec(x,e,t,r){let a,n,{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s,headers:i}=r??{},o=Date.now();return new Promise((l,c)=>{let v=x=>{c(x)};if(!this._transport)return void v(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(x){v(x);return}if(r?.signal?.aborted){let x=r.signal.reason;throw x instanceof fU?x:new fU(fH.RequestTimeout,String(x))}let d=x.era===b$&&!0===this._transport.hasPerRequestStream?new AbortController:void 0,f=this._requestMessageId++;n=f;let b={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.onprogress),b.params={...e.params,_meta:{...e.params?._meta,progressToken:f}});let u=this._envelopeOutbound(b),p=!1,m=x=>{p||(this._progressHandlers.delete(f),void 0===d?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(x)}}),{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s}).catch(x=>this._onerror(Error(`Failed to send cancellation: ${x}`))):d.abort(),c(x instanceof fU?x:new fU(fH.RequestTimeout,String(x))))};this._responseHandlers.set(f,a=>{let n;if(!r?.signal?.aborted){if(p=!0,a instanceof Error)return c(a);try{n=x.decodeResult(e.method,a.result)}catch(x){return c(x instanceof Error?x:Error(String(x)))}if("invalid"===n.kind)return c(n.error);if("input_required"===n.kind){var _;return r?.allowInputRequired===!0?l({resultType:"input_required",inputRequests:(_=n).inputRequests,...void 0!==_.requestState&&{requestState:_.requestState}}):l(this._resolveNonCompleteResult(n,{codec:x,request:e,resultSchema:t,options:r,flowStartedAt:o,retry:(r,a)=>this._requestWithSchemaViaCodec(x,void 0===r?{method:e.method}:{method:e.method,params:r},t,a)}))}ub(t,n.result).then(x=>{x.success?l(x.data):c(new fU(fH.InvalidResult,`Invalid result for ${e.method}: ${x.error}`))},c)}}),a=()=>m(r?.signal?.reason),r?.signal?.addEventListener("abort",a,{once:!0});let h=r?.timeout??6e4;this._setupTimeout(f,h,r?.maxTotalTimeout,()=>m(new fU(fH.RequestTimeout,"Request timed out",{timeout:h})),r?.resetTimeoutOnProgress??!1),this._transport.send(u,{relatedRequestId:_,resumptionToken:A,onresumptiontoken:s,headers:i,requestSignal:d?.signal}).catch(x=>{this._progressHandlers.delete(f),c(x)})}).finally(()=>{a&&r?.signal?.removeEventListener("abort",a),void 0!==n&&(this._responseHandlers.delete(n),this._cleanupTimeout(n))})}async notification(x,e){return this._notificationViaCodec(this._resolveOutboundCodec(x.method),x,e)}async _notificationViaCodec(x,e,t){if(!this._transport)throw new fU(fH.NotConnected,"Not connected");if(bK(e.method)&&!x.hasNotificationMethod(e.method))throw new fU(fH.MethodNotSupportedByProtocolVersion,`Notification '${e.method}' is not supported by the negotiated protocol version (wire era ${x.era})`,{method:e.method,era:x.era});this.assertNotificationCapability(e.method);let r=this._envelopeOutbound({jsonrpc:"2.0",...e});if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(r,t).catch(x=>this._onerror(x))});return}await this._transport.send(r,t)}setRequestHandler(x,e,t){let r;if(this.assertRequestHandlerCapability(x),"function"==typeof e){if(!bX(x))throw TypeError(`'${x}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(t,r)=>{let a=this._negotiatedWireCodec(),n=a.validateRequest(x,t);if(n.ok||"not-in-era"!==n.reason||(n=a.validateInputRequest(x,t)),!n.ok){if("not-in-era"===n.reason)throw new bh(bm.InternalError,`No wire schema for ${x} in the resolved era`);throw Error(n.message)}return Promise.resolve(e(n.value,r))}}else if(t)r=async(r,a)=>{let n=await ub(e.params,{...r.params});if(!n.success)throw new bh(bm.InvalidParams,`Invalid params for ${x}: ${n.error}`);return t(n.data,a)};else throw TypeError("setRequestHandler: handler is required");this._requestHandlers.set(x,this._wrapHandler(x,r))}_wrapHandler(x,e){return e}_outboundServerInfo(){}removeRequestHandler(x){this._requestHandlers.delete(x)}assertCanSetRequestHandler(x){if(this._requestHandlers.has(x))throw Error(`A request handler for ${x} already exists, which would be overridden`)}setNotificationHandler(x,e,t){if("function"==typeof e){if(!bK(x))throw TypeError(`'${x}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(x,(t,r)=>{let a=r.validateNotification(x,t);if(!a.ok){if("not-in-era"===a.reason)throw new bh(bm.InternalError,`No wire schema for ${x} in the resolved era`);throw Error(a.message)}return Promise.resolve(e(a.value))});return}if(!t)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(x,async r=>{let a=await ub(e.params,{...r.params});if(!a.success)throw new bh(bm.InvalidParams,`Invalid params for notification ${x}: ${a.error}`);await t(a.data,r)})}removeNotificationHandler(x){this._notificationHandlers.delete(x)}};function uL(x){return null!==x&&"object"==typeof x&&!Array.isArray(x)}function uq(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}var uT=fO(fG(x=>{var e=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,t=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function a(x){this.parameters=Object.create(null),this.type=x}x.parse=function(x){if(!x)throw TypeError("argument string is required");var n,_,A,s="object"==typeof x?function(x){var e;if("function"==typeof x.getHeader?e=x.getHeader("content-type"):"object"==typeof x.headers&&(e=x.headers&&x.headers["content-type"]),"string"!=typeof e)throw TypeError("content-type header is missing from object");return e}(x):x;if("string"!=typeof s)throw TypeError("argument string is required to be a string");var i=s.indexOf(";"),o=-1!==i?s.slice(0,i).trim():s.trim();if(!r.test(o))throw TypeError("invalid media type");var l=new a(o.toLowerCase());if(-1!==i){for(e.lastIndex=i;_=e.exec(s);){if(_.index!==i)throw TypeError("invalid parameter format");i+=_[0].length,n=_[1].toLowerCase(),34===(A=_[2]).charCodeAt(0)&&-1!==(A=A.slice(1,-1)).indexOf("\\")&&(A=A.replace(t,"$1")),l.parameters[n]=A}if(i!==s.length)throw TypeError("invalid parameter format")}return l}})(),1);function uR(x){if(x)try{return uT.parse(x).type}catch{let e=(x.split(";",1)[0]??"").trim().toLowerCase();if(""===e||x.slice(e.length).includes(","))return;return e}}function u$(x){return"application/json"===x||"application/json"===uR(x)}let uG=/^[A-Za-z0-9._-]{1,128}$/;function uO(x){let e=function(x){let e=[];if(0===x.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(x.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${x.length})`]};if(x.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),x.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(x.startsWith("-")||x.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(x.startsWith(".")||x.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!uG.test(x)){let t=[...x].filter(x=>!/[A-Za-z0-9._-]/.test(x)).filter((x,e,t)=>t.indexOf(x)===e);return e.push(`Tool name contains invalid characters: ${t.map(x=>`"${x}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}(x);var t=e.warnings;if(t.length>0){for(let e of(console.warn(`Tool name validation warning for "${x}":`),t))console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return e.isValid}function uX(x){if(void 0!==x){if(function(x){if("object"!=typeof x||null===x||uc(x))return!1;let e=Object.getPrototypeOf(x);return(e===Object.prototype||null===e)&&Object.values(x).every(x=>"object"==typeof x&&null!==x&&"_zod"in x)}(x))return tM(x);if("object"==typeof x&&null!==x&&!uc(x)&&Object.values(x).some(x=>"object"==typeof x&&null!==x&&!("_zod"in x)&&"_def"in x&&"string"==typeof x._def?.typeName))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!uc(x))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return x}}var uK=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.regexpCode=x.getEsmExportName=x.getProperty=x.safeStringify=x.stringify=x.strConcat=x.addCodeArg=x.str=x._=x.nil=x._Code=x.Name=x.IDENTIFIER=x._CodeOrName=void 0;var e=class{};x._CodeOrName=e,x.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var t=class extends e{constructor(e){if(super(),!x.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};x.Name=t;var r=class extends e{constructor(x){super(),this._items="string"==typeof x?[x]:x}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let x=this._items[0];return""===x||'""'===x}get str(){var x;return null!=(x=this._str)?x:this._str=this._items.reduce((x,e)=>`${x}${e}`,"")}get names(){var x;return null!=(x=this._names)?x:this._names=this._items.reduce((x,e)=>(e instanceof t&&(x[e.str]=(x[e.str]||0)+1),x),{})}};function a(x,...e){let t=[x[0]],n=0;for(;n<e.length;)A(t,e[n]),t.push(x[++n]);return new r(t)}x._Code=r,x.nil=new r(""),x._=a;let n=new r("+");function _(x,...e){let a=[s(x[0])],i=0;for(;i<e.length;)a.push(n),A(a,e[i]),a.push(n,s(x[++i]));return function(x){let e=1;for(;e<x.length-1;){if(x[e]===n){var r,a;let n=(r=x[e-1],'""'===(a=x[e+1])?r:'""'===r?a:"string"==typeof r?a instanceof t||'"'!==r[r.length-1]?void 0:"string"!=typeof a?`${r.slice(0,-1)}${a}"`:'"'===a[0]?r.slice(0,-1)+a.slice(1):void 0:"string"!=typeof a||'"'!==a[0]||r instanceof t?void 0:`"${r}${a.slice(1)}`);if(void 0!==n){x.splice(e-1,3,n);continue}x[e++]="+"}e++}}(a),new r(a)}function A(x,e){var a;e instanceof r?x.push(...e._items):e instanceof t?x.push(e):x.push("number"==typeof(a=e)||"boolean"==typeof a||null===a?a:s(Array.isArray(a)?a.join(","):a))}function s(x){return JSON.stringify(x).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}x.str=_,x.addCodeArg=A,x.strConcat=function(x,e){return e.emptyStr()?x:x.emptyStr()?e:_`${x}${e}`},x.stringify=function(x){return new r(s(x))},x.safeStringify=s,x.getProperty=function(e){return"string"==typeof e&&x.IDENTIFIER.test(e)?new r(`.${e}`):a`[${e}]`},x.getEsmExportName=function(e){if("string"==typeof e&&x.IDENTIFIER.test(e))return new r(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},x.regexpCode=function(x){return new r(x.toString())}}),uQ=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.ValueScope=x.ValueScopeName=x.Scope=x.varKinds=x.UsedValueState=void 0;let e=uK();var t,r,a=class extends Error{constructor(x){super(`CodeGen: "code" for ${x} not defined`),this.value=x.value}};(t=r||(x.UsedValueState=r={}))[t.Started=0]="Started",t[t.Completed=1]="Completed",x.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};var n=class{constructor({prefixes:x,parent:e}={}){this._names={},this._prefixes=x,this._parent=e}toName(x){return x instanceof e.Name?x:this.name(x)}name(x){return new e.Name(this._newName(x))}_newName(x){let e=this._names[x]||this._nameGroup(x);return`${x}${e.index++}`}_nameGroup(x){var e,t;if((null==(t=null==(e=this._parent)?void 0:e._prefixes)?void 0:t.has(x))||this._prefixes&&!this._prefixes.has(x))throw Error(`CodeGen: prefix "${x}" is not allowed in this scope`);return this._names[x]={prefix:x,index:0}}};x.Scope=n;var _=class extends e.Name{constructor(x,e){super(e),this.prefix=x}setValue(x,{property:t,itemIndex:r}){this.value=x,this.scopePath=(0,e._)`.${new e.Name(t)}[${r}]`}};x.ValueScopeName=_;let A=(0,e._)`\n`;var s=class extends n{constructor(x){super(x),this._values={},this._scope=x.scope,this.opts={...x,_n:x.lines?A:e.nil}}get(){return this._scope}name(x){return new _(x,this._newName(x))}value(x,e){var t;if(void 0===e.ref)throw Error("CodeGen: ref must be passed in value");let r=this.toName(x),{prefix:a}=r,n=null!=(t=e.key)?t:e.ref,_=this._values[a];if(_){let x=_.get(n);if(x)return x}else _=this._values[a]=new Map;_.set(n,r);let A=this._scope[a]||(this._scope[a]=[]),s=A.length;return A[s]=e.ref,r.setValue(e,{property:a,itemIndex:s}),r}getValue(x,e){let t=this._values[x];if(t)return t.get(e)}scopeRefs(x,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw Error(`CodeGen: name "${t}" has no value`);return(0,e._)`${x}${t.scopePath}`})}scopeCode(x=this._values,e,t){return this._reduceValues(x,x=>{if(void 0===x.value)throw Error(`CodeGen: name "${x}" has no value`);return x.value.code},e,t)}_reduceValues(t,n,_={},A){let s=e.nil;for(let i in t){let o=t[i];if(!o)continue;let l=_[i]=_[i]||new Map;o.forEach(t=>{if(l.has(t))return;l.set(t,r.Started);let _=n(t);if(_){let r=this.opts.es5?x.varKinds.var:x.varKinds.const;s=(0,e._)`${s}${r} ${t} = ${_};${this.opts._n}`}else if(_=null==A?void 0:A(t))s=(0,e._)`${s}${_}${this.opts._n}`;else throw new a(t);l.set(t,r.Completed)})}return s}};x.ValueScope=s}),uM=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.or=x.and=x.not=x.CodeGen=x.operators=x.varKinds=x.ValueScopeName=x.ValueScope=x.Scope=x.Name=x.regexpCode=x.stringify=x.getProperty=x.nil=x.strConcat=x.str=x._=void 0;let e=uK(),t=uQ();var r=uK();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return r.Name}});var a=uQ();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),x.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};var n=class{optimizeNodes(){return this}optimizeNames(x,e){return this}},_=class extends n{constructor(x,e,t){super(),this.varKind=x,this.name=e,this.rhs=t}render({es5:x,_n:e}){let r=x?t.varKinds.var:this.varKind,a=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${a};`+e}optimizeNames(x,e){if(x[this.name.str])return this.rhs&&(this.rhs=w(this.rhs,x,e)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}},A=class extends n{constructor(x,e,t){super(),this.lhs=x,this.rhs=e,this.sideEffects=t}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,t){if(!(this.lhs instanceof e.Name)||x[this.lhs.str]||this.sideEffects)return this.rhs=w(this.rhs,x,t),this}get names(){return F(this.lhs instanceof e.Name?{}:{...this.lhs.names},this.rhs)}},s=class extends A{constructor(x,e,t,r){super(x,t,r),this.op=e}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}},i=class extends n{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}},o=class extends n{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}},l=class extends n{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}},c=class extends n{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,e){return this.code=w(this.code,x,e),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}},v=class extends n{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((e,t)=>e+t.render(x),"")}optimizeNodes(){let{nodes:x}=this,e=x.length;for(;e--;){let t=x[e].optimizeNodes();Array.isArray(t)?x.splice(e,1,...t):t?x[e]=t:x.splice(e,1)}return x.length>0?this:void 0}optimizeNames(x,e){let{nodes:t}=this,r=t.length;for(;r--;){let a=t[r];a.optimizeNames(x,e)||(function(x,e){for(let t in e)x[t]=(x[t]||0)-(e[t]||0)}(x,a.names),t.splice(r,1))}return t.length>0?this:void 0}get names(){return this.nodes.reduce((x,e)=>B(x,e.names),{})}},d=class extends v{render(x){return"{"+x._n+super.render(x)+"}"+x._n}},f=class extends v{},b=class extends d{};b.kind="else";var u=class x extends d{constructor(x,e){super(e),this.condition=x}render(x){let e=`if(${this.condition})`+super.render(x);return this.else&&(e+="else "+this.else.render(x)),e}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){let x=t.optimizeNodes();t=this.else=Array.isArray(x)?new b(x):x}return t?!1===e?t instanceof x?t:t.nodes:this.nodes.length?this:new x(C(e),t instanceof x?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(x,e){var t;if(this.else=null==(t=this.else)?void 0:t.optimizeNames(x,e),super.optimizeNames(x,e)||this.else)return this.condition=w(this.condition,x,e),this}get names(){let x=super.names;return F(x,this.condition),this.else&&B(x,this.else.names),x}};u.kind="if";var p=class extends d{};p.kind="for";var m=class extends p{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,e){if(super.optimizeNames(x,e))return this.iteration=w(this.iteration,x,e),this}get names(){return B(super.names,this.iteration.names)}},h=class extends p{constructor(x,e,t,r){super(),this.varKind=x,this.name=e,this.from=t,this.to=r}render(x){let e=x.es5?t.varKinds.var:this.varKind,{name:r,from:a,to:n}=this;return`for(${e} ${r}=${a}; ${r}<${n}; ${r}++)`+super.render(x)}get names(){return F(F(super.names,this.from),this.to)}},E=class extends p{constructor(x,e,t,r){super(),this.loop=x,this.varKind=e,this.name=t,this.iterable=r}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,e){if(super.optimizeNames(x,e))return this.iterable=w(this.iterable,x,e),this}get names(){return B(super.names,this.iterable.names)}},j=class extends d{constructor(x,e,t){super(),this.name=x,this.args=e,this.async=t}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}};j.kind="func";var g=class extends v{render(x){return"return "+super.render(x)}};g.kind="return";var y=class extends d{render(x){let e="try"+super.render(x);return this.catch&&(e+=this.catch.render(x)),this.finally&&(e+=this.finally.render(x)),e}optimizeNodes(){var x,e;return super.optimizeNodes(),null==(x=this.catch)||x.optimizeNodes(),null==(e=this.finally)||e.optimizeNodes(),this}optimizeNames(x,e){var t,r;return super.optimizeNames(x,e),null==(t=this.catch)||t.optimizeNames(x,e),null==(r=this.finally)||r.optimizeNames(x,e),this}get names(){let x=super.names;return this.catch&&B(x,this.catch.names),this.finally&&B(x,this.finally.names),x}},S=class extends d{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}};S.kind="catch";var I=class extends d{render(x){return"finally"+super.render(x)}};I.kind="finally";var N=class{constructor(x,e={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...e,_n:e.lines?"\n":""},this._extScope=x,this._scope=new t.Scope({parent:x}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,e){let t=this._extScope.value(x,e);return(this._values[t.prefix]||(this._values[t.prefix]=new Set)).add(t),t}getScopeValue(x,e){return this._extScope.getValue(x,e)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,e,t,r){let a=this._scope.toName(e);return void 0!==t&&r&&(this._constants[a.str]=t),this._leafNode(new _(x,a,t)),a}const(x,e,r){return this._def(t.varKinds.const,x,e,r)}let(x,e,r){return this._def(t.varKinds.let,x,e,r)}var(x,e,r){return this._def(t.varKinds.var,x,e,r)}assign(x,e,t){return this._leafNode(new A(x,e,t))}add(e,t){return this._leafNode(new s(e,x.operators.ADD,t))}code(x){return"function"==typeof x?x():x!==e.nil&&this._leafNode(new c(x)),this}object(...x){let t=["{"];for(let[r,a]of x)t.length>1&&t.push(","),t.push(r),(r!==a||this.opts.es5)&&(t.push(":"),(0,e.addCodeArg)(t,a));return t.push("}"),new e._Code(t)}if(x,e,t){if(this._blockNode(new u(x)),e&&t)this.code(e).else().code(t).endIf();else if(e)this.code(e).endIf();else if(t)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new u(x))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(u,b)}_for(x,e){return this._blockNode(x),e&&this.code(e).endFor(),this}for(x,e){return this._for(new m(x),e)}forRange(x,e,r,a,n=this.opts.es5?t.varKinds.var:t.varKinds.let){let _=this._scope.toName(x);return this._for(new h(n,_,e,r),()=>a(_))}forOf(x,r,a,n=t.varKinds.const){let _=this._scope.toName(x);if(this.opts.es5){let x=r instanceof e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,e._)`${x}.length`,t=>{this.var(_,(0,e._)`${x}[${t}]`),a(_)})}return this._for(new E("of",n,_,r),()=>a(_))}forIn(x,r,a,n=this.opts.es5?t.varKinds.var:t.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,e._)`Object.keys(${r})`,a);let _=this._scope.toName(x);return this._for(new E("in",n,_,r),()=>a(_))}endFor(){return this._endBlockNode(p)}label(x){return this._leafNode(new i(x))}break(x){return this._leafNode(new o(x))}return(x){let e=new g;if(this._blockNode(e),this.code(x),1!==e.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(g)}try(x,e,t){if(!e&&!t)throw Error('CodeGen: "try" without "catch" and "finally"');let r=new y;if(this._blockNode(r),this.code(x),e){let x=this.name("e");this._currNode=r.catch=new S(x),e(x)}return t&&(this._currNode=r.finally=new I,this.code(t)),this._endBlockNode(S,I)}throw(x){return this._leafNode(new l(x))}block(x,e){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(e),this}endBlock(x){let e=this._blockStarts.pop();if(void 0===e)throw Error("CodeGen: not in self-balancing block");let t=this._nodes.length-e;if(t<0||void 0!==x&&t!==x)throw Error(`CodeGen: wrong number of nodes: ${t} vs ${x} expected`);return this._nodes.length=e,this}func(x,t=e.nil,r,a){return this._blockNode(new j(x,t,r)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,e){let t=this._currNode;if(t instanceof x||e&&t instanceof e)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${e?`${x.kind}/${e.kind}`:x.kind}"`)}_elseNode(x){let e=this._currNode;if(!(e instanceof u))throw Error('CodeGen: "else" without "if"');return this._currNode=e.else=x,this}get _root(){return this._nodes[0]}get _currNode(){let x=this._nodes;return x[x.length-1]}set _currNode(x){let e=this._nodes;e[e.length-1]=x}};function B(x,e){for(let t in e)x[t]=(x[t]||0)+(e[t]||0);return x}function F(x,t){return t instanceof e._CodeOrName?B(x,t.names):x}function w(x,t,r){var a;if(x instanceof e.Name)return n(x);if(!((a=x)instanceof e._Code&&a._items.some(x=>x instanceof e.Name&&1===t[x.str]&&void 0!==r[x.str])))return x;return new e._Code(x._items.reduce((x,t)=>(t instanceof e.Name&&(t=n(t)),t instanceof e._Code?x.push(...t._items):x.push(t),x),[]));function n(x){let e=r[x.str];return void 0===e||1!==t[x.str]?x:(delete t[x.str],e)}}function C(x){return"boolean"==typeof x||"number"==typeof x||null===x?!x:(0,e._)`!${L(x)}`}x.CodeGen=N,x.not=C;let P=D(x.operators.AND);x.and=function(...x){return x.reduce(P)};let k=D(x.operators.OR);function D(x){return(t,r)=>t===e.nil?r:r===e.nil?t:(0,e._)`${L(t)} ${x} ${L(r)}`}function L(x){return x instanceof e.Name?x:(0,e._)`(${x})`}x.or=function(...x){return x.reduce(k)}}),uZ=fG(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.checkStrictMode=x.getErrorPath=x.Type=x.useFunc=x.setEvaluated=x.evaluatedPropsToName=x.mergeEvaluated=x.eachItem=x.unescapeJsonPointer=x.escapeJsonPointer=x.escapeFragment=x.unescapeFragment=x.schemaRefOrVal=x.schemaHasRulesButRef=x.schemaHasRules=x.checkUnknownRules=x.alwaysValidSchema=x.toHash=void 0;let r=uM(),a=uK();function n(x,e=x.schema){let{opts:t,self:r}=x;if(!t.strictSchema||"boolean"==typeof e)return;let a=r.RULES.keywords;for(let t in e)a[t]||v(x,`unknown keyword: "${t}"`)}function _(x,e){if("boolean"==typeof x)return!x;for(let t in x)if(e[t])return!0;return!1}function A(x){return"number"==typeof x?`${x}`:x.replace(/~/g,"~0").replace(/\//g,"~1")}function s(x){return x.replace(/~1/g,"/").replace(/~0/g,"~")}function i({mergeNames:x,mergeToName:e,mergeValues:t,resultToName:a}){return(n,_,A,s)=>{let i=void 0===A?_:A instanceof r.Name?(_ instanceof r.Name?x(n,_,A):e(n,_,A),A):_ instanceof r.Name?(e(n,A,_),_):t(_,A);return s!==r.Name||i instanceof r.Name?i:a(n,i)}}function o(x,e){if(!0===e)return x.var("props",!0);let t=x.var("props",(0,r._)`{}`);return void 0!==e&&l(x,t,e),t}function l(x,e,t){Object.keys(t).forEach(t=>x.assign((0,r._)`${e}${(0,r.getProperty)(t)}`,!0))}x.toHash=function(x){let e={};for(let t of x)e[t]=!0;return e},x.alwaysValidSchema=function(x,e){return"boolean"==typeof e?e:0===Object.keys(e).length||(n(x,e),!_(e,x.self.RULES.all))},x.checkUnknownRules=n,x.schemaHasRules=_,x.schemaHasRulesButRef=function(x,e){if("boolean"==typeof x)return!x;for(let t in x)if("$ref"!==t&&e.all[t])return!0;return!1},x.schemaRefOrVal=function({topSchemaRef:x,schemaPath:e},t,a,n){if(!n){if("number"==typeof t||"boolean"==typeof t)return t;if("string"==typeof t)return(0,r._)`${t}`}return(0,r._)`${x}${e}${(0,r.getProperty)(a)}`},x.unescapeFragment=function(x){return s(decodeURIComponent(x))},x.escapeFragment=function(x){return encodeURIComponent(A(x))},x.escapeJsonPointer=A,x.unescapeJsonPointer=s,x.eachItem=function(x,e){if(Array.isArray(x))for(let t of x)e(t);else e(x)},x.mergeEvaluated={props:i({mergeNames:(x,e,t)=>x.if((0,r._)`${t} !== true && ${e} !== undefined`,()=>{x.if((0,r._)`${e} === true`,()=>x.assign(t,!0),()=>x.assign(t,(0,r._)`${t} || {}`).code((0,r._)`Object.assign(${t}, ${e})`))}),mergeToName:(x,e,t)=>x.if((0,r._)`${t} !== true`,()=>{!0===e?x.assign(t,!0):(x.assign(t,(0,r._)`${t} || {}`),l(x,t,e))}),mergeValues:(x,e)=>!0===x||{...x,...e},resultToName:o}),items:i({mergeNames:(x,e,t)=>x.if((0,r._)`${t} !== true && ${e} !== undefined`,()=>x.assign(t,(0,r._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(x,e,t)=>x.if((0,r._)`${t} !== true`,()=>x.assign(t,!0===e||(0,r._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(x,e)=>!0===x||Math.max(x,e),resultToName:(x,e)=>x.var("items",e)})},x.evaluatedPropsToName=o,x.setEvaluated=l;let c={};function v(x,e,t=x.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,!0===t)throw Error(e);x.self.logger.warn(e)}}x.useFunc=function(x,e){return x.scopeValue("func",{ref:e,code:c[e.code]||(c[e.code]=new a._Code(e.code))})},(t=e||(x.Type=e={}))[t.Num=0]="Num",t[t.Str=1]="Str",x.getErrorPath=function(x,t,a){if(x instanceof r.Name){let n=t===e.Num;return a?n?(0,r._)`"[" + ${x} + "]"`:(0,r._)`"['" + ${x} + "']"`:n?(0,r._)`"/" + ${x}`:(0,r._)`"/" + ${x}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return a?(0,r.getProperty)(x).toString():"/"+A(x)},x.checkStrictMode=v}),uJ=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM();x.default={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")}}),uV=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.extendErrors=x.resetErrorsCount=x.reportExtraError=x.reportError=x.keyword$DataError=x.keywordError=void 0;let e=uM(),t=uZ(),r=uJ();function a(x,t){let a=x.const("err",t);x.if((0,e._)`${r.default.vErrors} === null`,()=>x.assign(r.default.vErrors,(0,e._)`[${a}]`),(0,e._)`${r.default.vErrors}.push(${a})`),x.code((0,e._)`${r.default.errors}++`)}function n(x,t){let{gen:r,validateName:a,schemaEnv:n}=x;n.$async?r.throw((0,e._)`new ${x.ValidationError}(${t})`):(r.assign((0,e._)`${a}.errors`,t),r.return(!1))}x.keywordError={message:({keyword:x})=>(0,e.str)`must pass "${x}" keyword validation`},x.keyword$DataError={message:({keyword:x,schemaType:t})=>t?(0,e.str)`"${x}" keyword must be ${t} ($data)`:(0,e.str)`"${x}" keyword is invalid ($data)`},x.reportError=function(t,r=x.keywordError,_,s){let{it:i}=t,{gen:o,compositeRule:l,allErrors:c}=i,v=A(t,r,_);(null!=s?s:l||c)?a(o,v):n(i,(0,e._)`[${v}]`)},x.reportExtraError=function(e,t=x.keywordError,_){let{it:s}=e,{gen:i,compositeRule:o,allErrors:l}=s;a(i,A(e,t,_)),o||l||n(s,r.default.vErrors)},x.resetErrorsCount=function(x,t){x.assign(r.default.errors,t),x.if((0,e._)`${r.default.vErrors} !== null`,()=>x.if(t,()=>x.assign((0,e._)`${r.default.vErrors}.length`,t),()=>x.assign(r.default.vErrors,null)))},x.extendErrors=function({gen:x,keyword:t,schemaValue:a,data:n,errsCount:_,it:A}){if(void 0===_)throw Error("ajv implementation error");let s=x.name("err");x.forRange("i",_,r.default.errors,_=>{x.const(s,(0,e._)`${r.default.vErrors}[${_}]`),x.if((0,e._)`${s}.instancePath === undefined`,()=>x.assign((0,e._)`${s}.instancePath`,(0,e.strConcat)(r.default.instancePath,A.errorPath))),x.assign((0,e._)`${s}.schemaPath`,(0,e.str)`${A.errSchemaPath}/${t}`),A.opts.verbose&&(x.assign((0,e._)`${s}.schema`,a),x.assign((0,e._)`${s}.data`,n))})};let _={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function A(x,a,n){let{createErrors:A}=x.it;return!1===A?(0,e._)`{}`:function(x,a,n={}){let{gen:A,it:s}=x,i=[function({errorPath:x},{instancePath:a}){let n=a?(0,e.str)`${x}${(0,t.getErrorPath)(a,t.Type.Str)}`:x;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,n)]}(s,n),function({keyword:x,it:{errSchemaPath:r}},{schemaPath:a,parentSchema:n}){let A=n?r:(0,e.str)`${r}/${x}`;return a&&(A=(0,e.str)`${A}${(0,t.getErrorPath)(a,t.Type.Str)}`),[_.schemaPath,A]}(x,n)];return function(x,{params:t,message:a},n){let{keyword:A,data:s,schemaValue:i,it:o}=x,{opts:l,propertyName:c,topSchemaRef:v,schemaPath:d}=o;n.push([_.keyword,A],[_.params,"function"==typeof t?t(x):t||(0,e._)`{}`]),l.messages&&n.push([_.message,"function"==typeof a?a(x):a]),l.verbose&&n.push([_.schema,i],[_.parentSchema,(0,e._)`${v}${d}`],[r.default.data,s]),c&&n.push([_.propertyName,c])}(x,a,i),A.object(...i)}(x,a,n)}}),uH=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.boolOrEmptySchema=x.topBoolOrEmptySchema=void 0;let e=uV(),t=uM(),r=uJ(),a={message:"boolean schema is false"};function n(x,t){let{gen:r,data:n}=x;(0,e.reportError)({gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:x},a,void 0,t)}x.topBoolOrEmptySchema=function(x){let{gen:e,schema:a,validateName:_}=x;!1===a?n(x,!1):"object"==typeof a&&!0===a.$async?e.return(r.default.data):(e.assign((0,t._)`${_}.errors`,null),e.return(!0))},x.boolOrEmptySchema=function(x,e){let{gen:t,schema:r}=x;!1===r?(t.var(e,!1),n(x)):t.var(e,!0)}}),uU=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getRules=x.isJSONType=void 0;let e=new Set(["string","number","integer","boolean","null","object","array"]);x.isJSONType=function(x){return"string"==typeof x&&e.has(x)},x.getRules=function(){let x={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...x,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},x.number,x.string,x.array,x.object],post:{rules:[]},all:{},keywords:{}}}}),uY=fG(x=>{function e(x,e){return e.rules.some(e=>t(x,e))}function t(x,e){var t;return void 0!==x[e.keyword]||(null==(t=e.definition.implements)?void 0:t.some(e=>void 0!==x[e]))}Object.defineProperty(x,"__esModule",{value:!0}),x.shouldUseRule=x.shouldUseGroup=x.schemaHasRulesForType=void 0,x.schemaHasRulesForType=function({schema:x,self:t},r){let a=t.RULES.types[r];return a&&!0!==a&&e(x,a)},x.shouldUseGroup=e,x.shouldUseRule=t}),uz=fG(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.reportTypeError=x.checkDataTypes=x.checkDataType=x.coerceAndCheckDataType=x.getJSONTypes=x.getSchemaTypes=x.DataType=void 0;let r=uU(),a=uY(),n=uV(),_=uM(),A=uZ();function s(x){let e=Array.isArray(x)?x:x?[x]:[];if(e.every(r.isJSONType))return e;throw Error("type must be JSONType or JSONType[]: "+e.join(","))}(t=e||(x.DataType=e={}))[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong",x.getSchemaTypes=function(x){let e=s(x.type);if(e.includes("null")){if(!1===x.nullable)throw Error("type: null contradicts nullable: false")}else{if(!e.length&&void 0!==x.nullable)throw Error('"nullable" cannot be used without "type"');!0===x.nullable&&e.push("null")}return e},x.getJSONTypes=s,x.coerceAndCheckDataType=function(x,t){var r,n;let{gen:A,data:s,opts:o}=x,c=(r=t,(n=o.coerceTypes)?r.filter(x=>i.has(x)||"array"===n&&"array"===x):[]),d=t.length>0&&!(0===c.length&&1===t.length&&(0,a.schemaHasRulesForType)(x,t[0]));if(d){let r=l(t,s,o.strictNumbers,e.Wrong);A.if(r,()=>{c.length?function(x,e,t){let{gen:r,data:a,opts:n}=x,A=r.let("dataType",(0,_._)`typeof ${a}`),s=r.let("coerced",(0,_._)`undefined`);for(let x of("array"===n.coerceTypes&&r.if((0,_._)`${A} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,_._)`${a}[0]`).assign(A,(0,_._)`typeof ${a}`).if(l(e,a,n.strictNumbers),()=>r.assign(s,a))),r.if((0,_._)`${s} !== undefined`),t))(i.has(x)||"array"===x&&"array"===n.coerceTypes)&&function(x){switch(x){case"string":r.elseIf((0,_._)`${A} == "number" || ${A} == "boolean"`).assign(s,(0,_._)`"" + ${a}`).elseIf((0,_._)`${a} === null`).assign(s,(0,_._)`""`);return;case"number":r.elseIf((0,_._)`${A} == "boolean" || ${a} === null
374
374
  || (${A} == "string" && ${a} && ${a} == +${a})`).assign(s,(0,_._)`+${a}`);return;case"integer":r.elseIf((0,_._)`${A} === "boolean" || ${a} === null
375
375
  || (${A} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(s,(0,_._)`+${a}`);return;case"boolean":r.elseIf((0,_._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(s,!1).elseIf((0,_._)`${a} === "true" || ${a} === 1`).assign(s,!0);return;case"null":r.elseIf((0,_._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(s,null);return;case"array":r.elseIf((0,_._)`${A} === "string" || ${A} === "number"
376
- || ${A} === "boolean" || ${a} === null`).assign(s,(0,_._)`[${a}]`)}}(x);r.else(),v(x),r.endIf(),r.if((0,_._)`${s} !== undefined`,()=>{r.assign(a,s),function({gen:x,parentData:e,parentDataProperty:t},r){x.if((0,_._)`${e} !== undefined`,()=>x.assign((0,_._)`${e}[${t}]`,r))}(x,s)})}(x,t,c):v(x)})}return d};let i=new Set(["string","number","integer","boolean","null"]);function o(x,t,r,a=e.Correct){let n,A=a===e.Correct?_.operators.EQ:_.operators.NEQ;switch(x){case"null":return(0,_._)`${t} ${A} null`;case"array":n=(0,_._)`Array.isArray(${t})`;break;case"object":n=(0,_._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":n=s((0,_._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":n=s();break;default:return(0,_._)`typeof ${t} ${A} ${x}`}return a===e.Correct?n:(0,_.not)(n);function s(x=_.nil){return(0,_.and)((0,_._)`typeof ${t} == "number"`,x,r?(0,_._)`isFinite(${t})`:_.nil)}}function l(x,e,t,r){let a;if(1===x.length)return o(x[0],e,t,r);let n=(0,A.toHash)(x);if(n.array&&n.object){let x=(0,_._)`typeof ${e} != "object"`;a=n.null?x:(0,_._)`!${e} || ${x}`,delete n.null,delete n.array,delete n.object}else a=_.nil;for(let x in n.number&&delete n.integer,n)a=(0,_.and)(a,o(x,e,t,r));return a}x.checkDataType=o,x.checkDataTypes=l;let c={message:({schema:x})=>`must be ${x}`,params:({schema:x,schemaValue:e})=>"string"==typeof x?(0,_._)`{type: ${x}}`:(0,_._)`{type: ${e}}`};function v(x){let e=function(x){let{gen:e,data:t,schema:r}=x,a=(0,A.schemaRefOrVal)(x,r,"type");return{gen:e,keyword:"type",data:t,schema:r.type,schemaCode:a,schemaValue:a,parentSchema:r,params:{},it:x}}(x);(0,n.reportError)(e,c)}x.reportTypeError=v}),uY=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.assignDefaults=void 0;let e=uK(),t=uQ();function r(x,r,a){let{gen:n,compositeRule:_,data:A,opts:s}=x;if(void 0===a)return;let i=(0,e._)`${A}${(0,e.getProperty)(r)}`;if(_)return void(0,t.checkStrictMode)(x,`default is ignored for: ${i}`);let o=(0,e._)`${i} === undefined`;"empty"===s.useDefaults&&(o=(0,e._)`${o} || ${i} === null || ${i} === ""`),n.if(o,(0,e._)`${i} = ${(0,e.stringify)(a)}`)}x.assignDefaults=function(x,e){let{properties:t,items:a}=x.schema;if("object"===e&&t)for(let e in t)r(x,e,t[e].default);else"array"===e&&Array.isArray(a)&&a.forEach((e,t)=>r(x,t,e.default))}}),uz=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateUnion=x.validateArray=x.usePattern=x.callValidateCode=x.schemaProperties=x.allSchemaProperties=x.noPropertyInData=x.propertyInData=x.isOwnProperty=x.hasPropFunc=x.reportMissingProp=x.checkMissingProp=x.checkReportMissingProp=void 0;let e=uK(),t=uQ(),r=uM(),a=uQ();function n(x){return x.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}function _(x,t,r){return(0,e._)`${n(x)}.call(${t}, ${r})`}function A(x,t,r,a){let n=(0,e._)`${t}${(0,e.getProperty)(r)} === undefined`;return a?(0,e.or)(n,(0,e.not)(_(x,t,r))):n}function s(x){return x?Object.keys(x).filter(x=>"__proto__"!==x):[]}x.checkReportMissingProp=function(x,t){let{gen:r,data:a,it:n}=x;r.if(A(r,a,t,n.opts.ownProperties),()=>{x.setParams({missingProperty:(0,e._)`${t}`},!0),x.error()})},x.checkMissingProp=function({gen:x,data:t,it:{opts:r}},a,n){return(0,e.or)(...a.map(a=>(0,e.and)(A(x,t,a,r.ownProperties),(0,e._)`${n} = ${a}`)))},x.reportMissingProp=function(x,e){x.setParams({missingProperty:e},!0),x.error()},x.hasPropFunc=n,x.isOwnProperty=_,x.propertyInData=function(x,t,r,a){let n=(0,e._)`${t}${(0,e.getProperty)(r)} !== undefined`;return a?(0,e._)`${n} && ${_(x,t,r)}`:n},x.noPropertyInData=A,x.allSchemaProperties=s,x.schemaProperties=function(x,e){return s(e).filter(r=>!(0,t.alwaysValidSchema)(x,e[r]))},x.callValidateCode=function({schemaCode:x,data:t,it:{gen:a,topSchemaRef:n,schemaPath:_,errorPath:A},it:s},i,o,l){let c=l?(0,e._)`${x}, ${t}, ${n}${_}`:t,v=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,A)],[r.default.parentData,s.parentData],[r.default.parentDataProperty,s.parentDataProperty],[r.default.rootData,r.default.rootData]];s.opts.dynamicRef&&v.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let d=(0,e._)`${c}, ${a.object(...v)}`;return o!==e.nil?(0,e._)`${i}.call(${o}, ${d})`:(0,e._)`${i}(${d})`};let i=(0,e._)`new RegExp`;x.usePattern=function({gen:x,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:_}=t.code,A=_(r,n);return x.scopeValue("pattern",{key:A.toString(),ref:A,code:(0,e._)`${"new RegExp"===_.code?i:(0,a.useFunc)(x,_)}(${r}, ${n})`})},x.validateArray=function(x){let{gen:r,data:a,keyword:n,it:_}=x,A=r.name("valid");if(_.allErrors){let x=r.let("valid",!0);return s(()=>r.assign(x,!1)),x}return r.var(A,!0),s(()=>r.break()),A;function s(_){let s=r.const("len",(0,e._)`${a}.length`);r.forRange("i",0,s,a=>{x.subschema({keyword:n,dataProp:a,dataPropType:t.Type.Num},A),r.if((0,e.not)(A),_)})}},x.validateUnion=function(x){let{gen:r,schema:a,keyword:n,it:_}=x;if(!Array.isArray(a))throw Error("ajv implementation error");if(a.some(x=>(0,t.alwaysValidSchema)(_,x))&&!_.opts.unevaluated)return;let A=r.let("valid",!1),s=r.name("_valid");r.block(()=>a.forEach((t,a)=>{let _=x.subschema({keyword:n,schemaProp:a,compositeRule:!0},s);r.assign(A,(0,e._)`${A} || ${s}`),x.mergeValidEvaluated(_,s)||r.if((0,e.not)(A))})),x.result(A,()=>x.reset(),()=>x.error(!0))}}),uW=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateKeywordUsage=x.validSchemaType=x.funcKeywordCode=x.macroKeywordCode=void 0;let e=uK(),t=uM(),r=uz(),a=uZ();function n(x){let{gen:t,data:r,it:a}=x;t.if(a.parentData,()=>t.assign(r,(0,e._)`${a.parentData}[${a.parentDataProperty}]`))}function _(x,t,r){if(void 0===r)throw Error(`keyword "${t}" failed to compile`);return x.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,e.stringify)(r)})}x.macroKeywordCode=function(x,t){let{gen:r,keyword:a,schema:n,parentSchema:A,it:s}=x,i=t.macro.call(s.self,n,A,s),o=_(r,a,i);!1!==s.opts.validateSchema&&s.self.validateSchema(i,!0);let l=r.name("valid");x.subschema({schema:i,schemaPath:e.nil,errSchemaPath:`${s.errSchemaPath}/${a}`,topSchemaRef:o,compositeRule:!0},l),x.pass(l,()=>x.error(!0))},x.funcKeywordCode=function(x,A){var s;let{gen:i,keyword:o,schema:l,parentSchema:c,$data:v,it:d}=x;!function({schemaEnv:x},e){if(e.async&&!x.$async)throw Error("async keyword in sync schema")}(d,A);let f=_(i,o,!v&&A.compile?A.compile.call(d.self,l,c,d):A.validate),b=i.let("valid");function u(a=A.async?(0,e._)`await `:e.nil){let n=d.opts.passContext?t.default.this:t.default.self,_=!("compile"in A&&!v||!1===A.schema);i.assign(b,(0,e._)`${a}${(0,r.callValidateCode)(x,f,n,_)}`,A.modifying)}function p(x){var t;i.if((0,e.not)(null!=(t=A.valid)?t:b),x)}x.block$data(b,function(){if(!1===A.errors)u(),A.modifying&&n(x),p(()=>x.error());else{let r,_,s=A.async?(r=i.let("ruleErrs",null),i.try(()=>u((0,e._)`await `),x=>i.assign(b,!1).if((0,e._)`${x} instanceof ${d.ValidationError}`,()=>i.assign(r,(0,e._)`${x}.errors`),()=>i.throw(x))),r):(_=(0,e._)`${f}.errors`,i.assign(_,null),u(e.nil),_);A.modifying&&n(x),p(()=>(function(x,r){let{gen:n}=x;n.if((0,e._)`Array.isArray(${r})`,()=>{n.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${r} : ${t.default.vErrors}.concat(${r})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,a.extendErrors)(x)},()=>x.error())})(x,s))}}),x.ok(null!=(s=A.valid)?s:b)},x.validSchemaType=function(x,e,t=!1){return!e.length||e.some(e=>"array"===e?Array.isArray(x):"object"===e?x&&"object"==typeof x&&!Array.isArray(x):typeof x==e||t&&void 0===x)},x.validateKeywordUsage=function({schema:x,opts:e,self:t,errSchemaPath:r},a,n){if(Array.isArray(a.keyword)?!a.keyword.includes(n):a.keyword!==n)throw Error("ajv implementation error");let _=a.dependencies;if(null==_?void 0:_.some(e=>!Object.prototype.hasOwnProperty.call(x,e)))throw Error(`parent schema must have dependencies of ${n}: ${_.join(",")}`);if(a.validateSchema&&!a.validateSchema(x[n])){let x=`keyword "${n}" value is invalid at path "${r}": `+t.errorsText(a.validateSchema.errors);if("log"===e.validateSchema)t.logger.error(x);else throw Error(x)}}}),u0=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.extendSubschemaMode=x.extendSubschemaData=x.getSubschema=void 0;let e=uK(),t=uQ();x.getSubschema=function(x,{keyword:r,schemaProp:a,schema:n,schemaPath:_,errSchemaPath:A,topSchemaRef:s}){if(void 0!==r&&void 0!==n)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){let n=x.schema[r];return void 0===a?{schema:n,schemaPath:(0,e._)`${x.schemaPath}${(0,e.getProperty)(r)}`,errSchemaPath:`${x.errSchemaPath}/${r}`}:{schema:n[a],schemaPath:(0,e._)`${x.schemaPath}${(0,e.getProperty)(r)}${(0,e.getProperty)(a)}`,errSchemaPath:`${x.errSchemaPath}/${r}/${(0,t.escapeFragment)(a)}`}}if(void 0!==n){if(void 0===_||void 0===A||void 0===s)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:_,topSchemaRef:s,errSchemaPath:A}}throw Error('either "keyword" or "schema" must be passed')},x.extendSubschemaData=function(x,r,{dataProp:a,dataPropType:n,data:_,dataTypes:A,propertyName:s}){if(void 0!==_&&void 0!==a)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=r;if(void 0!==a){let{errorPath:_,dataPathArr:A,opts:s}=r;o(i.let("data",(0,e._)`${r.data}${(0,e.getProperty)(a)}`,!0)),x.errorPath=(0,e.str)`${_}${(0,t.getErrorPath)(a,n,s.jsPropertySyntax)}`,x.parentDataProperty=(0,e._)`${a}`,x.dataPathArr=[...A,x.parentDataProperty]}function o(e){x.data=e,x.dataLevel=r.dataLevel+1,x.dataTypes=[],r.definedProperties=new Set,x.parentData=r.data,x.dataNames=[...r.dataNames,e]}void 0!==_&&(o(_ instanceof e.Name?_:i.let("data",_,!0)),void 0!==s&&(x.propertyName=s)),A&&(x.dataTypes=A)},x.extendSubschemaMode=function(x,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:a,allErrors:n}){void 0!==r&&(x.compositeRule=r),void 0!==a&&(x.createErrors=a),void 0!==n&&(x.allErrors=n),x.jtdDiscriminator=e,x.jtdMetadata=t}}),u1=fR((x,e)=>{e.exports=function x(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;if(Array.isArray(e)){if((r=e.length)!=t.length)return!1;for(a=r;0!=a--;)if(!x(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if((r=(n=Object.keys(e)).length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var r,a,n,_=n[a];if(!x(e[_],t[_]))return!1}return!0}return e!=e&&t!=t}}),u2=fR((x,e)=>{var t=e.exports=function(x,e,r){"function"==typeof e&&(r=e,e={});var a="function"==typeof(r=e.cb||r)?r:r.pre||function(){};!function x(e,r,a,n,_,A,s,i,o,l){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var c in r(n,_,A,s,i,o,l),n){var v=n[c];if(Array.isArray(v)){if(c in t.arrayKeywords)for(var d=0;d<v.length;d++)x(e,r,a,v[d],_+"/"+c+"/"+d,A,_,c,n,d)}else if(c in t.propsKeywords){if(v&&"object"==typeof v)for(var f in v)x(e,r,a,v[f],_+"/"+c+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),A,_,c,n,f)}else(c in t.keywords||e.allKeys&&!(c in t.skipKeywords))&&x(e,r,a,v,_+"/"+c,A,_,c,n)}a(n,_,A,s,i,o,l)}}(e,a,r.post||function(){},x,"",x)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}}),u3=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getSchemaRefs=x.resolveUrl=x.normalizeId=x._getFullPath=x.getFullPath=x.inlineRef=void 0;let e=uQ(),t=u1(),r=u2(),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);x.inlineRef=function(x,t=!0){return"boolean"==typeof x||(!0===t?!function x(e){for(let t in e){if(n.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(x)||"object"==typeof r&&x(r))return!0}return!1}(x):!!t&&function x(t){let r=0;for(let n in t)if("$ref"===n||(r++,!a.has(n)&&("object"==typeof t[n]&&(0,e.eachItem)(t[n],e=>r+=x(e)),r===1/0)))return 1/0;return r}(x)<=t)};let n=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _(x,e="",t){return!1!==t&&(e=i(e)),A(x,x.parse(e))}function A(x,e){return x.serialize(e).split("#")[0]+"#"}x.getFullPath=_,x._getFullPath=A;let s=/#\/?$/;function i(x){return x?x.replace(s,""):""}x.normalizeId=i,x.resolveUrl=function(x,e,t){return t=i(t),x.resolve(e,t)};let o=/^[a-z_][-a-z0-9._]*$/i;x.getSchemaRefs=function(x,e){if("boolean"==typeof x)return{};let{schemaId:a,uriResolver:n}=this.opts,A=i(x[a]||e),s={"":A},l=_(n,A,!1),c={},v=new Set;return r(x,{allKeys:!0},(x,e,t,r)=>{if(void 0===r)return;let n=l+e,_=s[r];function A(e){let t=this.opts.uriResolver.resolve;if(e=i(_?t(_,e):e),v.has(e))throw f(e);v.add(e);let r=this.refs[e];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?d(x,r.schema,e):e!==i(n)&&("#"===e[0]?(d(x,c[e],e),c[e]=x):this.refs[e]=n),e}function b(x){if("string"==typeof x){if(!o.test(x))throw Error(`invalid anchor "${x}"`);A.call(this,`#${x}`)}}"string"==typeof x[a]&&(_=A.call(this,x[a])),b.call(this,x.$anchor),b.call(this,x.$dynamicAnchor),s[e]=_}),c;function d(x,e,r){if(void 0!==e&&!t(x,e))throw f(r)}function f(x){return Error(`reference "${x}" resolves to more than one schema`)}}}),u6=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getData=x.KeywordCxt=x.validateFunctionCode=void 0;let e=uJ(),t=uU(),r=uH(),a=uU(),n=uY(),_=uW(),A=u0(),s=uK(),i=uM(),o=u3(),l=uQ(),c=uZ();function v({gen:x,validateName:e,schema:t,schemaEnv:r,opts:a},n){var _;a.code.es5?x.func(e,(0,s._)`${i.default.data}, ${i.default.valCxt}`,r.$async,()=>{var e,r;x.code((0,s._)`"use strict"; ${d(t,a)}`),e=x,r=a,e.if(i.default.valCxt,()=>{e.var(i.default.instancePath,(0,s._)`${i.default.valCxt}.${i.default.instancePath}`),e.var(i.default.parentData,(0,s._)`${i.default.valCxt}.${i.default.parentData}`),e.var(i.default.parentDataProperty,(0,s._)`${i.default.valCxt}.${i.default.parentDataProperty}`),e.var(i.default.rootData,(0,s._)`${i.default.valCxt}.${i.default.rootData}`),r.dynamicRef&&e.var(i.default.dynamicAnchors,(0,s._)`${i.default.valCxt}.${i.default.dynamicAnchors}`)},()=>{e.var(i.default.instancePath,(0,s._)`""`),e.var(i.default.parentData,(0,s._)`undefined`),e.var(i.default.parentDataProperty,(0,s._)`undefined`),e.var(i.default.rootData,i.default.data),r.dynamicRef&&e.var(i.default.dynamicAnchors,(0,s._)`{}`)}),x.code(n)}):x.func(e,(0,s._)`${i.default.data}, ${(_=a,(0,s._)`{${i.default.instancePath}="", ${i.default.parentData}, ${i.default.parentDataProperty}, ${i.default.rootData}=${i.default.data}${_.dynamicRef?(0,s._)`, ${i.default.dynamicAnchors}={}`:s.nil}}={}`)}`,r.$async,()=>x.code(d(t,a)).code(n))}function d(x,e){let t="object"==typeof x&&x[e.schemaId];return t&&(e.code.source||e.code.process)?(0,s._)`/*# sourceURL=${t} */`:s.nil}function f({schema:x,self:e}){if("boolean"==typeof x)return!x;for(let t in x)if(e.RULES.all[t])return!0;return!1}function b(x){return"boolean"!=typeof x.schema}function u(x){(0,l.checkUnknownRules)(x),function(x){let{schema:e,errSchemaPath:t,opts:r,self:a}=x;e.$ref&&r.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(e,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}(x)}function p(x,e){if(x.opts.jtd)return h(x,[],!1,e);let r=(0,t.getSchemaTypes)(x.schema);h(x,r,!(0,t.coerceAndCheckDataType)(x,r),e)}function m({gen:x,schemaEnv:e,schema:t,errSchemaPath:r,opts:a}){let n=t.$comment;if(!0===a.$comment)x.code((0,s._)`${i.default.self}.logger.log(${n})`);else if("function"==typeof a.$comment){let t=(0,s.str)`${r}/$comment`,a=x.scopeValue("root",{ref:e.root});x.code((0,s._)`${i.default.self}.opts.$comment(${n}, ${t}, ${a}.schema)`)}}function h(x,e,t,n){var _,A,o,c;let{gen:v,schema:d,data:f,allErrors:b,opts:u,self:p}=x,{RULES:m}=p;if(d.$ref&&(u.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(d,m)))return void v.block(()=>S(x,"$ref",m.all.$ref.definition));function h(_){(0,r.shouldUseGroup)(d,_)&&(_.type?(v.if((0,a.checkDataType)(_.type,f,u.strictNumbers)),E(x,_),1===e.length&&e[0]===_.type&&t&&(v.else(),(0,a.reportTypeError)(x)),v.endIf()):E(x,_),b||v.if((0,s._)`${i.default.errors} === ${n||0}`))}u.jtd||(_=x,A=e,!_.schemaEnv.meta&&_.opts.strictTypes&&(function(x,e){if(e.length){if(!x.dataTypes.length){x.dataTypes=e;return}e.forEach(e=>{j(x.dataTypes,e)||g(x,`type "${e}" not allowed by context "${x.dataTypes.join(",")}"`)}),function(x,e){let t=[];for(let r of x.dataTypes)j(e,r)?t.push(r):e.includes("integer")&&"number"===r&&t.push("integer");x.dataTypes=t}(x,e)}}(_,A),_.opts.allowUnionTypes||(o=_,(c=A).length>1&&!(2===c.length&&c.includes("null"))&&g(o,"use allowUnionTypes to allow union type keyword")),function(x,e){let t=x.self.RULES.all;for(let a in t){let n=t[a];if("object"==typeof n&&(0,r.shouldUseRule)(x.schema,n)){let{type:t}=n.definition;t.length&&!t.some(x=>{var t,r;return t=e,r=x,t.includes(r)||"number"===r&&t.includes("integer")})&&g(x,`missing type "${t.join(",")}" for keyword "${a}"`)}}}(_,_.dataTypes))),v.block(()=>{for(let x of m.rules)h(x);h(m.post)})}function E(x,e){let{gen:t,schema:a,opts:{useDefaults:_}}=x;_&&(0,n.assignDefaults)(x,e.type),t.block(()=>{for(let t of e.rules)(0,r.shouldUseRule)(a,t)&&S(x,t.keyword,t.definition,e.type)})}function j(x,e){return x.includes(e)||"integer"===e&&x.includes("number")}function g(x,e){let t=x.schemaEnv.baseId+x.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,l.checkStrictMode)(x,e,x.opts.strictTypes)}x.validateFunctionCode=function(x){b(x)&&(u(x),f(x))?function(x){let{schema:e,opts:t,gen:r}=x;v(x,()=>{t.$comment&&e.$comment&&m(x),function(x){let{schema:e,opts:t}=x;void 0!==e.default&&t.useDefaults&&t.strictSchema&&(0,l.checkStrictMode)(x,"default is ignored in the schema root")}(x),r.let(i.default.vErrors,null),r.let(i.default.errors,0),t.unevaluated&&function(x){let{gen:e,validateName:t}=x;x.evaluated=e.const("evaluated",(0,s._)`${t}.evaluated`),e.if((0,s._)`${x.evaluated}.dynamicProps`,()=>e.assign((0,s._)`${x.evaluated}.props`,(0,s._)`undefined`)),e.if((0,s._)`${x.evaluated}.dynamicItems`,()=>e.assign((0,s._)`${x.evaluated}.items`,(0,s._)`undefined`))}(x),p(x),function(x){let{gen:e,schemaEnv:t,validateName:r,ValidationError:a,opts:n}=x;t.$async?e.if((0,s._)`${i.default.errors} === 0`,()=>e.return(i.default.data),()=>e.throw((0,s._)`new ${a}(${i.default.vErrors})`)):(e.assign((0,s._)`${r}.errors`,i.default.vErrors),n.unevaluated&&function({gen:x,evaluated:e,props:t,items:r}){t instanceof s.Name&&x.assign((0,s._)`${e}.props`,t),r instanceof s.Name&&x.assign((0,s._)`${e}.items`,r)}(x),e.return((0,s._)`${i.default.errors} === 0`))}(x)})}(x):v(x,()=>(0,e.topBoolOrEmptySchema)(x))};var y=class{constructor(x,e,t){if((0,_.validateKeywordUsage)(x,e,t),this.gen=x.gen,this.allErrors=x.allErrors,this.keyword=t,this.data=x.data,this.schema=x.schema[t],this.$data=e.$data&&x.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(x,this.schema,t,this.$data),this.schemaType=e.schemaType,this.parentSchema=x.schema,this.params={},this.it=x,this.def=e,this.$data)this.schemaCode=x.gen.const("vSchema",B(this.$data,x));else if(this.schemaCode=this.schemaValue,!(0,_.validSchemaType)(this.schema,e.schemaType,e.allowUndefined))throw Error(`${t} value must be ${JSON.stringify(e.schemaType)}`);("code"in e?e.trackErrors:!1!==e.errors)&&(this.errsCount=x.gen.const("_errs",i.default.errors))}result(x,e,t){this.failResult((0,s.not)(x),e,t)}failResult(x,e,t){this.gen.if(x),t?t():this.error(),e?(this.gen.else(),e(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(x,e){this.failResult((0,s.not)(x),void 0,e)}fail(x){if(void 0===x){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(x),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(x){if(!this.$data)return this.fail(x);let{schemaCode:e}=this;this.fail((0,s._)`${e} !== undefined && (${(0,s.or)(this.invalid$data(),x)})`)}error(x,e,t){if(e){this.setParams(e),this._error(x,t),this.setParams({});return}this._error(x,t)}_error(x,e){(x?c.reportExtraError:c.reportError)(this,this.def.error,e)}$dataError(){(0,c.reportError)(this,this.def.$dataError||c.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,c.resetErrorsCount)(this.gen,this.errsCount)}ok(x){this.allErrors||this.gen.if(x)}setParams(x,e){e?Object.assign(this.params,x):this.params=x}block$data(x,e,t=s.nil){this.gen.block(()=>{this.check$data(x,t),e()})}check$data(x=s.nil,e=s.nil){if(!this.$data)return;let{gen:t,schemaCode:r,schemaType:a,def:n}=this;t.if((0,s.or)((0,s._)`${r} === undefined`,e)),x!==s.nil&&t.assign(x,!0),(a.length||n.validateSchema)&&(t.elseIf(this.invalid$data()),this.$dataError(),x!==s.nil&&t.assign(x,!1)),t.else()}invalid$data(){let{gen:x,schemaCode:e,schemaType:t,def:r,it:n}=this;return(0,s.or)(function(){if(t.length){if(!(e instanceof s.Name))throw Error("ajv implementation error");let x=Array.isArray(t)?t:[t];return(0,s._)`${(0,a.checkDataTypes)(x,e,n.opts.strictNumbers,a.DataType.Wrong)}`}return s.nil}(),function(){if(r.validateSchema){let t=x.scopeValue("validate$data",{ref:r.validateSchema});return(0,s._)`!${t}(${e})`}return s.nil}())}subschema(x,t){let r=(0,A.getSubschema)(this.it,x);(0,A.extendSubschemaData)(r,this.it,x),(0,A.extendSubschemaMode)(r,x);let a={...this.it,...r,items:void 0,props:void 0};return!function(x,t){if(b(x)&&(u(x),f(x)))return function(x,e){var t;let r,{schema:a,gen:n,opts:_}=x;_.$comment&&a.$comment&&m(x),(r=(t=x).schema[t.opts.schemaId])&&(t.baseId=(0,o.resolveUrl)(t.opts.uriResolver,t.baseId,r)),function(x){if(x.schema.$async&&!x.schemaEnv.$async)throw Error("async schema in sync schema")}(x);let A=n.const("_errs",i.default.errors);p(x,A),n.var(e,(0,s._)`${A} === ${i.default.errors}`)}(x,t);(0,e.boolOrEmptySchema)(x,t)}(a,t),a}mergeEvaluated(x,e){let{it:t,gen:r}=this;t.opts.unevaluated&&(!0!==t.props&&void 0!==x.props&&(t.props=l.mergeEvaluated.props(r,x.props,t.props,e)),!0!==t.items&&void 0!==x.items&&(t.items=l.mergeEvaluated.items(r,x.items,t.items,e)))}mergeValidEvaluated(x,e){let{it:t,gen:r}=this;if(t.opts.unevaluated&&(!0!==t.props||!0!==t.items))return r.if(e,()=>this.mergeEvaluated(x,s.Name)),!0}};function S(x,e,t,r){let a=new y(x,t,e);"code"in t?t.code(a,r):a.$data&&t.validate?(0,_.funcKeywordCode)(a,t):"macro"in t?(0,_.macroKeywordCode)(a,t):(t.compile||t.validate)&&(0,_.funcKeywordCode)(a,t)}x.KeywordCxt=y;let I=/^\/(?:[^~]|~0|~1)*$/,N=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function B(x,{dataLevel:e,dataNames:t,dataPathArr:r}){let a,n;if(""===x)return i.default.rootData;if("/"===x[0]){if(!I.test(x))throw Error(`Invalid JSON-pointer: ${x}`);a=x,n=i.default.rootData}else{let _=N.exec(x);if(!_)throw Error(`Invalid JSON-pointer: ${x}`);let s=+_[1];if("#"===(a=_[2])){if(s>=e)throw Error(A("property/index",s));return r[e-s]}if(s>e)throw Error(A("data",s));if(n=t[e-s],!a)return n}let _=n;for(let x of a.split("/"))x&&(n=(0,s._)`${n}${(0,s.getProperty)((0,l.unescapeJsonPointer)(x))}`,_=(0,s._)`${_} && ${n}`);return _;function A(x,t){return`Cannot access ${x} ${t} levels up, current level is ${e}`}}x.getData=B}),u4=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default=class extends Error{constructor(x){super("validation failed"),this.errors=x,this.ajv=this.validation=!0}}}),u5=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u3();x.default=class extends Error{constructor(x,t,r,a){super(a||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,e.resolveUrl)(x,t,r),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(x,this.missingRef))}}}),u7=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.resolveSchema=x.getCompilingSchema=x.resolveRef=x.compileSchema=x.SchemaEnv=void 0;let e=uK(),t=u4(),r=uM(),a=u3(),n=uQ(),_=u6();var A=class{constructor(x){var e;let t;this.refs={},this.dynamicAnchors={},"object"==typeof x.schema&&(t=x.schema),this.schema=x.schema,this.schemaId=x.schemaId,this.root=x.root||this,this.baseId=null!=(e=x.baseId)?e:(0,a.normalizeId)(null==t?void 0:t[x.schemaId||"$id"]),this.schemaPath=x.schemaPath,this.localRefs=x.localRefs,this.meta=x.meta,this.$async=null==t?void 0:t.$async,this.refs={}}};function s(x){let n,A,s=o.call(this,x);if(s)return s;let i=(0,a.getFullPath)(this.opts.uriResolver,x.root.baseId),{es5:l,lines:c}=this.opts.code,{ownProperties:v}=this.opts,d=new e.CodeGen(this.scope,{es5:l,lines:c,ownProperties:v});x.$async&&(n=d.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let f=d.scopeName("validate");x.validateName=f;let b={gen:d,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:d.scopeValue("schema",!0===this.opts.code.source?{ref:x.schema,code:(0,e.stringify)(x.schema)}:{ref:x.schema}),validateName:f,ValidationError:n,schema:x.schema,schemaEnv:x,rootId:i,baseId:x.baseId||i,schemaPath:e.nil,errSchemaPath:x.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};try{this._compilations.add(x),(0,_.validateFunctionCode)(b),d.optimize(this.opts.code.optimize);let t=d.toString();A=`${d.scopeRefs(r.default.scope)}return ${t}`,this.opts.code.process&&(A=this.opts.code.process(A,x));let a=Function(`${r.default.self}`,`${r.default.scope}`,A)(this,this.scope.get());if(this.scope.value(f,{ref:a}),a.errors=null,a.schema=x.schema,a.schemaEnv=x,x.$async&&(a.$async=!0),!0===this.opts.code.source&&(a.source={validateName:f,validateCode:t,scopeValues:d._values}),this.opts.unevaluated){let{props:x,items:t}=b;a.evaluated={props:x instanceof e.Name?void 0:x,items:t instanceof e.Name?void 0:t,dynamicProps:x instanceof e.Name,dynamicItems:t instanceof e.Name},a.source&&(a.source.evaluated=(0,e.stringify)(a.evaluated))}return x.validate=a,x}catch(e){throw delete x.validate,delete x.validateName,A&&this.logger.error("Error compiling schema, function code:",A),e}finally{this._compilations.delete(x)}}function i(x){return(0,a.inlineRef)(x.schema,this.opts.inlineRefs)?x.schema:x.validate?x:s.call(this,x)}function o(x){for(let r of this._compilations){var e,t;if(e=r,t=x,e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId)return r}}function l(x,e){let t;for(;"string"==typeof(t=this.refs[e]);)e=t;return t||this.schemas[e]||c.call(this,x,e)}function c(x,e){let t=this.opts.uriResolver.parse(e),r=(0,a._getFullPath)(this.opts.uriResolver,t),n=(0,a.getFullPath)(this.opts.uriResolver,x.baseId,void 0);if(Object.keys(x.schema).length>0&&r===n)return d.call(this,t,x);let _=(0,a.normalizeId)(r),i=this.refs[_]||this.schemas[_];if("string"==typeof i){let e=c.call(this,x,i);if("object"!=typeof(null==e?void 0:e.schema))return;return d.call(this,t,e)}if("object"==typeof(null==i?void 0:i.schema)){if(i.validate||s.call(this,i),_===(0,a.normalizeId)(e)){let{schema:e}=i,{schemaId:t}=this.opts,r=e[t];return r&&(n=(0,a.resolveUrl)(this.opts.uriResolver,n,r)),new A({schema:e,schemaId:t,root:x,baseId:n})}return d.call(this,t,i)}}x.SchemaEnv=A,x.compileSchema=s,x.resolveRef=function(x,e,t){var r;t=(0,a.resolveUrl)(this.opts.uriResolver,e,t);let n=x.refs[t];if(n)return n;let _=l.call(this,x,t);if(void 0===_){let a=null==(r=x.localRefs)?void 0:r[t],{schemaId:n}=this.opts;a&&(_=new A({schema:a,schemaId:n,root:x,baseId:e}))}if(void 0!==_)return x.refs[t]=i.call(this,_)},x.getCompilingSchema=o,x.resolveSchema=c;let v=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function d(x,{baseId:e,schema:t,root:r}){var _;let s;if((null==(_=x.fragment)?void 0:_[0])!=="/")return;for(let r of x.fragment.slice(1).split("/")){if("boolean"==typeof t)return;let x=t[(0,n.unescapeFragment)(r)];if(void 0===x)return;let _="object"==typeof(t=x)&&t[this.opts.schemaId];!v.has(r)&&_&&(e=(0,a.resolveUrl)(this.opts.uriResolver,e,_))}if("boolean"!=typeof t&&t.$ref&&!(0,n.schemaHasRulesButRef)(t,this.RULES)){let x=(0,a.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=c.call(this,r,x)}let{schemaId:i}=this.opts;if((s=s||new A({schema:t,schemaId:i,root:r,baseId:e})).schema!==s.root.schema)return s}}),u8=fR((x,e)=>{e.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),u9=fR((x,e)=>{let t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function a(x){let e="",t=0,r=0;for(r=0;r<x.length;r++)if(48!==(t=x[r].charCodeAt(0))){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=x[r];break}for(r+=1;r<x.length;r++){if(!((t=x[r].charCodeAt(0))>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=x[r]}return e}function n(x){return x.length=0,!0}function _(x,e,t){if(x.length){let r=a(x);if(""===r)return t.error=!0,!1;e.push(r),x.length=0}return!0}function A(x){if(2>function(x){let e=0;for(let t=0;t<x.length;t++)":"===x[t]&&e++;return e}(x))return{host:x,isIPV6:!1};let e=function(x){let e=0,t={error:!1,address:"",zone:""},r=[],A=[],s=!1,i=!1,o=_;for(let a=0;a<x.length;a++){let _=x[a];if("["!==_&&"]"!==_)if(":"===_){if(!0===s&&(i=!0),!o(A,r,t))break;if(++e>7){t.error=!0;break}a>0&&":"===x[a-1]&&(s=!0),r.push(":");continue}else if("%"===_){if(!o(A,r,t))break;o=n}else{A.push(_);continue}}return A.length&&(o===n?t.zone=A.join(""):i?r.push(A.join("")):r.push(a(A))),t.address=r.join(""),t}(x);if(e.error)return{host:x,isIPV6:!1};{let x=e.address,t=e.address;return e.zone&&(x+="%"+e.zone,t+="%25"+e.zone),{host:x,isIPV6:!0,escapedHost:t}}}e.exports={nonSimpleDomain:RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),recomposeAuthority:function(x){let e=[];if(void 0!==x.userinfo&&(e.push(x.userinfo),e.push("@")),void 0!==x.host){let t=unescape(x.host);if(!r(t)){let e=A(t);t=!0===e.isIPV6?`[${e.escapedHost}]`:x.host}e.push(t)}return("number"==typeof x.port||"string"==typeof x.port)&&(e.push(":"),e.push(String(x.port))),e.length?e.join(""):void 0},normalizeComponentEncoding:function(x,e){let t=!0!==e?escape:unescape;return void 0!==x.scheme&&(x.scheme=t(x.scheme)),void 0!==x.userinfo&&(x.userinfo=t(x.userinfo)),void 0!==x.host&&(x.host=t(x.host)),void 0!==x.path&&(x.path=t(x.path)),void 0!==x.query&&(x.query=t(x.query)),void 0!==x.fragment&&(x.fragment=t(x.fragment)),x},removeDotSegments:function(x){let e=x,t=[],r=-1,a=0;for(;a=e.length;){if(1===a)if("."===e)break;else if("/"===e){t.push("/");break}else{t.push(e);break}if(2===a){if("."===e[0]){if("."===e[1])break;else if("/"===e[1]){e=e.slice(2);continue}}else if("/"===e[0]&&("."===e[1]||"/"===e[1])){t.push("/");break}}else if(3===a&&"/.."===e){0!==t.length&&t.pop(),t.push("/");break}if("."===e[0]){if("."===e[1]){if("/"===e[2]){e=e.slice(3);continue}}else if("/"===e[1]){e=e.slice(2);continue}}else if("/"===e[0]&&"."===e[1]){if("/"===e[2]){e=e.slice(2);continue}else if("."===e[2]&&"/"===e[3]){e=e.slice(3),0!==t.length&&t.pop();continue}}if(-1===(r=e.indexOf("/",1))){t.push(e);break}t.push(e.slice(0,r)),e=e.slice(r)}return t.join("")},isIPv4:r,isUUID:t,normalizeIPv6:A,stringArrayToHexStripped:a}}),px=fR((x,e)=>{let{isUUID:t}=u9(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,a=["http","https","ws","wss","urn","urn:uuid"];function n(x){return!0===x.secure||!1!==x.secure&&!!x.scheme&&3===x.scheme.length&&("w"===x.scheme[0]||"W"===x.scheme[0])&&("s"===x.scheme[1]||"S"===x.scheme[1])&&("s"===x.scheme[2]||"S"===x.scheme[2])}function _(x){return x.host||(x.error=x.error||"HTTP URIs must have a host."),x}function A(x){let e="https"===String(x.scheme).toLowerCase();return(x.port===(e?443:80)||""===x.port)&&(x.port=void 0),x.path||(x.path="/"),x}let s={scheme:"http",domainHost:!0,parse:_,serialize:A},i={scheme:"https",domainHost:s.domainHost,parse:_,serialize:A},o={scheme:"ws",domainHost:!0,parse:function(x){return x.secure=n(x),x.resourceName=(x.path||"/")+(x.query?"?"+x.query:""),x.path=void 0,x.query=void 0,x},serialize:function(x){if((x.port===(n(x)?443:80)||""===x.port)&&(x.port=void 0),"boolean"==typeof x.secure&&(x.scheme=x.secure?"wss":"ws",x.secure=void 0),x.resourceName){let[e,t]=x.resourceName.split("?");x.path=e&&"/"!==e?e:void 0,x.query=t,x.resourceName=void 0}return x.fragment=void 0,x}},l={scheme:"wss",domainHost:o.domainHost,parse:o.parse,serialize:o.serialize},c={http:s,https:i,ws:o,wss:l,urn:{scheme:"urn",parse:function(x,e){if(!x.path)return x.error="URN can not be parsed",x;let t=x.path.match(r);if(t){let r=e.scheme||x.scheme||"urn";x.nid=t[1].toLowerCase(),x.nss=t[2];let a=v(`${r}:${e.nid||x.nid}`);x.path=void 0,a&&(x=a.parse(x,e))}else x.error=x.error||"URN can not be parsed.";return x},serialize:function(x,e){if(void 0===x.nid)throw Error("URN without nid cannot be serialized");let t=e.scheme||x.scheme||"urn",r=x.nid.toLowerCase(),a=v(`${t}:${e.nid||r}`);a&&(x=a.serialize(x,e));let n=x,_=x.nss;return n.path=`${r||e.nid}:${_}`,e.skipEscape=!0,n},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(x,e){return x.uuid=x.nss,x.nss=void 0,e.tolerant||x.uuid&&t(x.uuid)||(x.error=x.error||"UUID is not valid."),x},serialize:function(x){return x.nss=(x.uuid||"").toLowerCase(),x},skipNormalize:!0}};function v(x){return x&&(c[x]||c[x.toLowerCase()])||void 0}Object.setPrototypeOf(c,null),e.exports={wsIsSecure:n,SCHEMES:c,isValidSchemeName:function(x){return -1!==a.indexOf(x)},getSchemeHandler:v}}),pe=fR((x,e)=>{let{normalizeIPv6:t,removeDotSegments:r,recomposeAuthority:a,normalizeComponentEncoding:n,isIPv4:_,nonSimpleDomain:A}=u9(),{SCHEMES:s,getSchemeHandler:i}=px();function o(x,e,t,a){let n={};return a||(x=v(l(x,t),t),e=v(l(e,t),t)),!(t=t||{}).tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=r(e.path||""),n.query=e.query):(void 0!==e.userinfo||void 0!==e.host||void 0!==e.port?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=r(e.path||""),n.query=e.query):(e.path?("/"===e.path[0]?n.path=r(e.path):(void 0===x.userinfo&&void 0===x.host&&void 0===x.port||x.path?x.path?n.path=x.path.slice(0,x.path.lastIndexOf("/")+1)+e.path:n.path=e.path:n.path="/"+e.path,n.path=r(n.path)),n.query=e.query):(n.path=x.path,void 0!==e.query?n.query=e.query:n.query=x.query),n.userinfo=x.userinfo,n.host=x.host,n.port=x.port),n.scheme=x.scheme),n.fragment=e.fragment,n}function l(x,e){let t={host:x.host,scheme:x.scheme,userinfo:x.userinfo,port:x.port,path:x.path,query:x.query,nid:x.nid,nss:x.nss,uuid:x.uuid,fragment:x.fragment,reference:x.reference,resourceName:x.resourceName,secure:x.secure,error:""},n=Object.assign({},e),_=[],A=i(n.scheme||t.scheme);A&&A.serialize&&A.serialize(t,n),void 0!==t.path&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),void 0!==t.scheme&&(t.path=t.path.split("%3A").join(":")))),"suffix"!==n.reference&&t.scheme&&_.push(t.scheme,":");let s=a(t);if(void 0!==s&&("suffix"!==n.reference&&_.push("//"),_.push(s),t.path&&"/"!==t.path[0]&&_.push("/")),void 0!==t.path){let x=t.path;n.absolutePath||A&&A.absolutePath||(x=r(x)),void 0===s&&"/"===x[0]&&"/"===x[1]&&(x="/%2F"+x.slice(2)),_.push(x)}return void 0!==t.query&&_.push("?",t.query),void 0!==t.fragment&&_.push("#",t.fragment),_.join("")}let c=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function v(x,e){let r=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;"suffix"===r.reference&&(x=r.scheme?r.scheme+":"+x:"//"+x);let s=x.match(c);if(s){if(a.scheme=s[1],a.userinfo=s[3],a.host=s[4],a.port=parseInt(s[5],10),a.path=s[6]||"",a.query=s[7],a.fragment=s[8],isNaN(a.port)&&(a.port=s[5]),a.host)if(!1===_(a.host)){let x=t(a.host);a.host=x.host.toLowerCase(),n=x.isIPV6}else n=!0;void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");let e=i(r.scheme||a.scheme);if(!r.unicodeSupport&&(!e||!e.unicodeSupport)&&a.host&&(r.domainHost||e&&e.domainHost)&&!1===n&&A(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(x){a.error=a.error||"Host's domain name can not be converted to ASCII: "+x}(!e||e&&!e.skipNormalize)&&(-1!==x.indexOf("%")&&(void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),void 0!==a.host&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),e&&e.parse&&e.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}let d={SCHEMES:s,normalize:function(x,e){return"string"==typeof x?x=l(v(x,e),e):"object"==typeof x&&(x=v(l(x,e),e)),x},resolve:function(x,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},a=o(v(x,r),v(e,r),r,!0);return r.skipEscape=!0,l(a,r)},resolveComponent:o,equal:function(x,e,t){return"string"==typeof x?x=l(n(v(x=unescape(x),t),!0),{...t,skipEscape:!0}):"object"==typeof x&&(x=l(n(x,!0),{...t,skipEscape:!0})),"string"==typeof e?e=l(n(v(e=unescape(e),t),!0),{...t,skipEscape:!0}):"object"==typeof e&&(e=l(n(e,!0),{...t,skipEscape:!0})),x.toLowerCase()===e.toLowerCase()},serialize:l,parse:v};e.exports=d,e.exports.default=d,e.exports.fastUri=d}),pt=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pe();e.code='require("ajv/dist/runtime/uri").default',x.default=e}),pr=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=void 0;var e=u6();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var t=uK();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return t._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return t.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return t.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return t.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return t.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return t.CodeGen}});let r=u4(),a=u5(),n=uV(),_=u7(),A=uK(),s=u3(),i=uU(),o=uQ(),l=u8(),c=pt(),v=(x,e)=>new RegExp(x,e);v.code="new RegExp";let d=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},u={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};var p=class{constructor(x={}){var e,t,r,a,_,s,i,o,l,d,p,h,I,N,B,F,w,C,P,k,D,L,q,T,R,$;let G,O,X,K,Q;this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,x=this.opts={...x,...(G=(e=x).strict,X=!0===(O=null==(t=e.code)?void 0:t.optimize)||void 0===O?1:O||0,K=null!=(a=null==(r=e.code)?void 0:r.regExp)?a:v,Q=null!=(_=e.uriResolver)?_:c.default,{strictSchema:null==(i=null!=(s=e.strictSchema)?s:G)||i,strictNumbers:null==(l=null!=(o=e.strictNumbers)?o:G)||l,strictTypes:null!=(p=null!=(d=e.strictTypes)?d:G)?p:"log",strictTuples:null!=(I=null!=(h=e.strictTuples)?h:G)?I:"log",strictRequired:null!=(B=null!=(N=e.strictRequired)?N:G)&&B,code:e.code?{...e.code,optimize:X,regExp:K}:{optimize:X,regExp:K},loopRequired:null!=(F=e.loopRequired)?F:200,loopEnum:null!=(w=e.loopEnum)?w:200,meta:null==(C=e.meta)||C,messages:null==(P=e.messages)||P,inlineRefs:null==(k=e.inlineRefs)||k,schemaId:null!=(D=e.schemaId)?D:"$id",addUsedSchema:null==(L=e.addUsedSchema)||L,validateSchema:null==(q=e.validateSchema)||q,validateFormats:null==(T=e.validateFormats)||T,unicodeRegExp:null==(R=e.unicodeRegExp)||R,int32range:null==($=e.int32range)||$,uriResolver:Q})};let{es5:M,lines:Z}=this.opts.code;this.scope=new A.ValueScope({scope:{},prefixes:f,es5:M,lines:Z}),this.logger=function(x){if(!1===x)return S;if(void 0===x)return console;if(x.log&&x.warn&&x.error)return x;throw Error("logger must implement log, warn and error methods")}(x.logger);let J=x.validateFormats;x.validateFormats=!1,this.RULES=(0,n.getRules)(),m.call(this,b,x,"NOT SUPPORTED"),m.call(this,u,x,"DEPRECATED","warn"),this._metaOpts=y.call(this),x.formats&&j.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),x.keywords&&g.call(this,x.keywords),"object"==typeof x.meta&&this.addMetaSchema(x.meta),E.call(this),x.validateFormats=J}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:x,meta:e,schemaId:t}=this.opts,r=l;"id"===t&&((r={...l}).id=r.$id,delete r.$id),e&&x&&this.addMetaSchema(r,r[t],!1)}defaultMeta(){let{meta:x,schemaId:e}=this.opts;return this.opts.defaultMeta="object"==typeof x?x[e]||x:void 0}validate(x,e){let t;if("string"==typeof x){if(!(t=this.getSchema(x)))throw Error(`no schema with key or ref "${x}"`)}else t=this.compile(x);let r=t(e);return"$async"in t||(this.errors=t.errors),r}compile(x,e){let t=this._addSchema(x,e);return t.validate||this._compileSchemaEnv(t)}compileAsync(x,e){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:t}=this.opts;return r.call(this,x,e);async function r(x,e){await n.call(this,x.$schema);let t=this._addSchema(x,e);return t.validate||_.call(this,t)}async function n(x){x&&!this.getSchema(x)&&await r.call(this,{$ref:x},!0)}async function _(x){try{return this._compileSchemaEnv(x)}catch(e){if(!(e instanceof a.default))throw e;return A.call(this,e),await s.call(this,e.missingSchema),_.call(this,x)}}function A({missingSchema:x,missingRef:e}){if(this.refs[x])throw Error(`AnySchema ${x} is loaded but ${e} cannot be resolved`)}async function s(x){let t=await i.call(this,x);this.refs[x]||await n.call(this,t.$schema),this.refs[x]||this.addSchema(t,x,e)}async function i(x){let e=this._loading[x];if(e)return e;try{return await (this._loading[x]=t(x))}finally{delete this._loading[x]}}}addSchema(x,e,t,r=this.opts.validateSchema){let a;if(Array.isArray(x)){for(let e of x)this.addSchema(e,void 0,t,r);return this}if("object"==typeof x){let{schemaId:e}=this.opts;if(void 0!==(a=x[e])&&"string"!=typeof a)throw Error(`schema ${e} must be string`)}return e=(0,s.normalizeId)(e||a),this._checkUnique(e),this.schemas[e]=this._addSchema(x,t,e,r,!0),this}addMetaSchema(x,e,t=this.opts.validateSchema){return this.addSchema(x,e,!0,t),this}validateSchema(x,e){let t;if("boolean"==typeof x)return!0;if(void 0!==(t=x.$schema)&&"string"!=typeof t)throw Error("$schema must be a string");if(!(t=t||this.opts.defaultMeta||this.defaultMeta()))return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(t,x);if(!r&&e){let x="schema is invalid: "+this.errorsText();if("log"===this.opts.validateSchema)this.logger.error(x);else throw Error(x)}return r}getSchema(x){let e;for(;"string"==typeof(e=h.call(this,x));)x=e;if(void 0===e){let{schemaId:t}=this.opts,r=new _.SchemaEnv({schema:{},schemaId:t});if(!(e=_.resolveSchema.call(this,r,x)))return;this.refs[x]=e}return e.validate||this._compileSchemaEnv(e)}removeSchema(x){if(x instanceof RegExp)return this._removeAllSchemas(this.schemas,x),this._removeAllSchemas(this.refs,x),this;switch(typeof x){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let e=h.call(this,x);return"object"==typeof e&&this._cache.delete(e.schema),delete this.schemas[x],delete this.refs[x],this}case"object":{this._cache.delete(x);let e=x[this.opts.schemaId];return e&&(e=(0,s.normalizeId)(e),delete this.schemas[e],delete this.refs[e]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(x){for(let e of x)this.addKeyword(e);return this}addKeyword(x,e){let t;if("string"==typeof x)t=x,"object"==typeof e&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),e.keyword=t);else if("object"==typeof x&&void 0===e){if(Array.isArray(t=(e=x).keyword)&&!t.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(N.call(this,t,e),!e)return(0,o.eachItem)(t,x=>B.call(this,x)),this;w.call(this,e);let r={...e,type:(0,i.getJSONTypes)(e.type),schemaType:(0,i.getJSONTypes)(e.schemaType)};return(0,o.eachItem)(t,0===r.type.length?x=>B.call(this,x,r):x=>r.type.forEach(e=>B.call(this,x,r,e))),this}getKeyword(x){let e=this.RULES.all[x];return"object"==typeof e?e.definition:!!e}removeKeyword(x){let{RULES:e}=this;for(let t of(delete e.keywords[x],delete e.all[x],e.rules)){let e=t.rules.findIndex(e=>e.keyword===x);e>=0&&t.rules.splice(e,1)}return this}addFormat(x,e){return"string"==typeof e&&(e=new RegExp(e)),this.formats[x]=e,this}errorsText(x=this.errors,{separator:e=", ",dataVar:t="data"}={}){return x&&0!==x.length?x.map(x=>`${t}${x.instancePath} ${x.message}`).reduce((x,t)=>x+e+t):"No errors"}$dataMetaSchema(x,e){let t=this.RULES.all;for(let r of(x=JSON.parse(JSON.stringify(x)),e)){let e=r.split("/").slice(1),a=x;for(let x of e)a=a[x];for(let x in t){let e=t[x];if("object"!=typeof e)continue;let{$data:r}=e.definition,n=a[x];r&&n&&(a[x]=P(n))}}return x}_removeAllSchemas(x,e){for(let t in x){let r=x[t];(!e||e.test(t))&&("string"==typeof r?delete x[t]:r&&!r.meta&&(this._cache.delete(r.schema),delete x[t]))}}_addSchema(x,e,t,r=this.opts.validateSchema,a=this.opts.addUsedSchema){let n,{schemaId:A}=this.opts;if("object"==typeof x)n=x[A];else if(this.opts.jtd)throw Error("schema must be object");else if("boolean"!=typeof x)throw Error("schema must be object or boolean");let i=this._cache.get(x);if(void 0!==i)return i;t=(0,s.normalizeId)(n||t);let o=s.getSchemaRefs.call(this,x,t);return i=new _.SchemaEnv({schema:x,schemaId:A,meta:e,baseId:t,localRefs:o}),this._cache.set(i.schema,i),a&&!t.startsWith("#")&&(t&&this._checkUnique(t),this.refs[t]=i),r&&this.validateSchema(x,!0),i}_checkUnique(x){if(this.schemas[x]||this.refs[x])throw Error(`schema with key or id "${x}" already exists`)}_compileSchemaEnv(x){if(x.meta?this._compileMetaSchema(x):_.compileSchema.call(this,x),!x.validate)throw Error("ajv implementation error");return x.validate}_compileMetaSchema(x){let e=this.opts;this.opts=this._metaOpts;try{_.compileSchema.call(this,x)}finally{this.opts=e}}};function m(x,e,t,r="error"){for(let a in x)a in e&&this.logger[r](`${t}: option ${a}. ${x[a]}`)}function h(x){return x=(0,s.normalizeId)(x),this.schemas[x]||this.refs[x]}function E(){let x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(let e in x)this.addSchema(x[e],e)}function j(){for(let x in this.opts.formats){let e=this.opts.formats[x];e&&this.addFormat(x,e)}}function g(x){if(Array.isArray(x))return void this.addVocabulary(x);for(let e in this.logger.warn("keywords option as map is deprecated, pass array"),x){let t=x[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function y(){let x={...this.opts};for(let e of d)delete x[e];return x}p.ValidationError=r.default,p.MissingRefError=a.default,x.default=p;let S={log(){},warn(){},error(){}},I=/^[a-z_$][a-z0-9_$:-]*$/i;function N(x,e){let{RULES:t}=this;if((0,o.eachItem)(x,x=>{if(t.keywords[x])throw Error(`Keyword ${x} is already defined`);if(!I.test(x))throw Error(`Keyword ${x} has invalid name`)}),e&&e.$data&&!("code"in e||"validate"in e))throw Error('$data keyword must have "code" or "validate" function')}function B(x,e,t){var r;let a=null==e?void 0:e.post;if(t&&a)throw Error('keyword with "post" flag cannot have "type"');let{RULES:n}=this,_=a?n.post:n.rules.find(({type:x})=>x===t);if(_||(_={type:t,rules:[]},n.rules.push(_)),n.keywords[x]=!0,!e)return;let A={keyword:x,definition:{...e,type:(0,i.getJSONTypes)(e.type),schemaType:(0,i.getJSONTypes)(e.schemaType)}};e.before?F.call(this,_,A,e.before):_.rules.push(A),n.all[x]=A,null==(r=e.implements)||r.forEach(x=>this.addKeyword(x))}function F(x,e,t){let r=x.rules.findIndex(x=>x.keyword===t);r>=0?x.rules.splice(r,0,e):(x.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function w(x){let{metaSchema:e}=x;void 0!==e&&(x.$data&&this.opts.$data&&(e=P(e)),x.validateSchema=this.compile(e,!0))}let C={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function P(x){return{anyOf:[x,C]}}}),pa=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}}}),pn=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.callRef=x.getValidate=void 0;let e=u5(),t=uz(),r=uK(),a=uM(),n=u7(),_=uQ();function A(x,e){let{gen:t}=x;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,r._)`${t.scopeValue("wrapper",{ref:e})}.validate`}function s(x,e,n,A){let{gen:s,it:i}=x,{allErrors:o,schemaEnv:l,opts:c}=i,v=c.passContext?a.default.this:r.nil;function d(x){let e=(0,r._)`${x}.errors`;s.assign(a.default.vErrors,(0,r._)`${a.default.vErrors} === null ? ${e} : ${a.default.vErrors}.concat(${e})`),s.assign(a.default.errors,(0,r._)`${a.default.vErrors}.length`)}function f(x){var e;if(!i.opts.unevaluated)return;let t=null==(e=null==n?void 0:n.validate)?void 0:e.evaluated;if(!0!==i.props)if(t&&!t.dynamicProps)void 0!==t.props&&(i.props=_.mergeEvaluated.props(s,t.props,i.props));else{let e=s.var("props",(0,r._)`${x}.evaluated.props`);i.props=_.mergeEvaluated.props(s,e,i.props,r.Name)}if(!0!==i.items)if(t&&!t.dynamicItems)void 0!==t.items&&(i.items=_.mergeEvaluated.items(s,t.items,i.items));else{let e=s.var("items",(0,r._)`${x}.evaluated.items`);i.items=_.mergeEvaluated.items(s,e,i.items,r.Name)}}A?function(){if(!l.$async)throw Error("async schema referenced by sync schema");let a=s.let("valid");s.try(()=>{s.code((0,r._)`await ${(0,t.callValidateCode)(x,e,v)}`),f(e),o||s.assign(a,!0)},x=>{s.if((0,r._)`!(${x} instanceof ${i.ValidationError})`,()=>s.throw(x)),d(x),o||s.assign(a,!1)}),x.ok(a)}():x.result((0,t.callValidateCode)(x,e,v),()=>f(e),()=>d(e))}x.getValidate=A,x.callRef=s,x.default={keyword:"$ref",schemaType:"string",code(x){var t,a;let _,i,o,{gen:l,schema:c,it:v}=x,{baseId:d,schemaEnv:f,validateName:b,opts:u,self:p}=v,{root:m}=f;if(("#"===c||"#/"===c)&&d===m.baseId){if(f===m)return s(x,b,f,f.$async);let e=l.scopeValue("root",{ref:m});return s(x,(0,r._)`${e}.validate`,m,m.$async)}let h=n.resolveRef.call(p,m,d,c);if(void 0===h)throw new e.default(v.opts.uriResolver,d,c);return h instanceof n.SchemaEnv?void s(x,A(x,t=h),t,t.$async):(a=h,_=l.scopeValue("schema",!0===u.code.source?{ref:a,code:(0,r.stringify)(a)}:{ref:a}),i=l.name("valid"),o=x.subschema({schema:a,dataTypes:[],schemaPath:r.nil,topSchemaRef:_,errSchemaPath:c},i),void(x.mergeEvaluated(o),x.ok(i)))}}}),p_=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pa(),t=pn();x.default=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default]}),pA=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}};x.default={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must be ${r[x].okStr} ${t}`,params:({keyword:x,schemaCode:t})=>(0,e._)`{comparison: ${r[x].okStr}, limit: ${t}}`},code(x){let{keyword:t,data:a,schemaCode:n}=x;x.fail$data((0,e._)`${a} ${r[t].fail} ${n} || isNaN(${a})`)}}}),ps=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK();x.default={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:x})=>(0,e.str)`must be multiple of ${x}`,params:({schemaCode:x})=>(0,e._)`{multipleOf: ${x}}`},code(x){let{gen:t,data:r,schemaCode:a,it:n}=x,_=n.opts.multipleOfPrecision,A=t.let("res"),s=_?(0,e._)`Math.abs(Math.round(${A}) - ${A}) > 1e-${_}`:(0,e._)`${A} !== parseInt(${A})`;x.fail$data((0,e._)`(${a} === 0 || (${A} = ${r}/${a}, ${s}))`)}}}),pi=fR(x=>{function e(x){let e,t=x.length,r=0,a=0;for(;a<t;)r++,(e=x.charCodeAt(a++))>=55296&&e<=56319&&a<t&&(64512&(e=x.charCodeAt(a)))==56320&&a++;return r}Object.defineProperty(x,"__esModule",{value:!0}),x.default=e,e.code='require("ajv/dist/runtime/ucs2length").default'}),po=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ(),r=pi();x.default={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxLength"===x?"more":"fewer"} than ${t} characters`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:a,data:n,schemaCode:_,it:A}=x,s="maxLength"===a?e.operators.GT:e.operators.LT,i=!1===A.opts.unicode?(0,e._)`${n}.length`:(0,e._)`${(0,t.useFunc)(x.gen,r.default)}(${n})`;x.fail$data((0,e._)`${i} ${s} ${_}`)}}}),pl=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uz(),t=uQ(),r=uK();x.default={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:x})=>(0,r.str)`must match pattern "${x}"`,params:({schemaCode:x})=>(0,r._)`{pattern: ${x}}`},code(x){let{gen:a,data:n,$data:_,schema:A,schemaCode:s,it:i}=x,o=i.opts.unicodeRegExp?"u":"";if(_){let{regExp:e}=i.opts.code,_="new RegExp"===e.code?(0,r._)`new RegExp`:(0,t.useFunc)(a,e),A=a.let("valid");a.try(()=>a.assign(A,(0,r._)`${_}(${s}, ${o}).test(${n})`),()=>a.assign(A,!1)),x.fail$data((0,r._)`!${A}`)}else{let t=(0,e.usePattern)(x,A);x.fail$data((0,r._)`!${t}.test(${n})`)}}}}),pc=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK();x.default={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxProperties"===x?"more":"fewer"} than ${t} properties`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:t,data:r,schemaCode:a}=x,n="maxProperties"===t?e.operators.GT:e.operators.LT;x.fail$data((0,e._)`Object.keys(${r}).length ${n} ${a}`)}}}),pv=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uz(),t=uK(),r=uQ();x.default={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:x}})=>(0,t.str)`must have required property '${x}'`,params:({params:{missingProperty:x}})=>(0,t._)`{missingProperty: ${x}}`},code(x){let{gen:a,schema:n,schemaCode:_,data:A,$data:s,it:i}=x,{opts:o}=i;if(!s&&0===n.length)return;let l=n.length>=o.loopRequired;if(i.allErrors?function(){if(l||s)x.block$data(t.nil,c);else for(let t of n)(0,e.checkReportMissingProp)(x,t)}():function(){let r=a.let("missing");if(l||s){let n=a.let("valid",!0);x.block$data(n,()=>{var s,i;return s=r,i=n,void(x.setParams({missingProperty:s}),a.forOf(s,_,()=>{a.assign(i,(0,e.propertyInData)(a,A,s,o.ownProperties)),a.if((0,t.not)(i),()=>{x.error(),a.break()})},t.nil))}),x.ok(n)}else a.if((0,e.checkMissingProp)(x,n,r)),(0,e.reportMissingProp)(x,r),a.else()}(),o.strictRequired){let e=x.parentSchema.properties,{definedProperties:t}=x.it;for(let x of n)if((null==e?void 0:e[x])===void 0&&!t.has(x)){let e=`required property "${x}" is not defined at "${i.schemaEnv.baseId+i.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(i,e,i.opts.strictRequired)}}function c(){a.forOf("prop",_,t=>{x.setParams({missingProperty:t}),a.if((0,e.noPropertyInData)(a,A,t,o.ownProperties),()=>x.error())})}}}}),pd=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK();x.default={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxItems"===x?"more":"fewer"} than ${t} items`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:t,data:r,schemaCode:a}=x,n="maxItems"===t?e.operators.GT:e.operators.LT;x.fail$data((0,e._)`${r}.length ${n} ${a}`)}}}),pf=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u1();e.code='require("ajv/dist/runtime/equal").default',x.default=e}),pb=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uU(),t=uK(),r=uQ(),a=pf();x.default={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:x,j:e}})=>(0,t.str)`must NOT have duplicate items (items ## ${e} and ${x} are identical)`,params:({params:{i:x,j:e}})=>(0,t._)`{i: ${x}, j: ${e}}`},code(x){let{gen:n,data:_,$data:A,schema:s,parentSchema:i,schemaCode:o,it:l}=x;if(!A&&!s)return;let c=n.let("valid"),v=i.items?(0,e.getSchemaTypes)(i.items):[];x.block$data(c,function(){let A=n.let("i",(0,t._)`${_}.length`),s=n.let("j");x.setParams({i:A,j:s}),n.assign(c,!0),n.if((0,t._)`${A} > 1`,()=>(v.length>0&&!v.some(x=>"object"===x||"array"===x)?function(r,a){let A=n.name("item"),s=(0,e.checkDataTypes)(v,A,l.opts.strictNumbers,e.DataType.Wrong),i=n.const("indices",(0,t._)`{}`);n.for((0,t._)`;${r}--;`,()=>{n.let(A,(0,t._)`${_}[${r}]`),n.if(s,(0,t._)`continue`),v.length>1&&n.if((0,t._)`typeof ${A} == "string"`,(0,t._)`${A} += "_"`),n.if((0,t._)`typeof ${i}[${A}] == "number"`,()=>{n.assign(a,(0,t._)`${i}[${A}]`),x.error(),n.assign(c,!1).break()}).code((0,t._)`${i}[${A}] = ${r}`)})}:function(e,A){let s=(0,r.useFunc)(n,a.default),i=n.name("outer");n.label(i).for((0,t._)`;${e}--;`,()=>n.for((0,t._)`${A} = ${e}; ${A}--;`,()=>n.if((0,t._)`${s}(${_}[${e}], ${_}[${A}])`,()=>{x.error(),n.assign(c,!1).break(i)})))})(A,s))},(0,t._)`${o} === false`),x.ok(c)}}}),pu=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ(),r=pf();x.default={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:x})=>(0,e._)`{allowedValue: ${x}}`},code(x){let{gen:a,data:n,$data:_,schemaCode:A,schema:s}=x;_||s&&"object"==typeof s?x.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${n}, ${A})`):x.fail((0,e._)`${s} !== ${n}`)}}}),pp=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ(),r=pf();x.default={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:x})=>(0,e._)`{allowedValues: ${x}}`},code(x){let a,n,{gen:_,data:A,$data:s,schema:i,schemaCode:o,it:l}=x;if(!s&&0===i.length)throw Error("enum must have non-empty array");let c=i.length>=l.opts.loopEnum,v=()=>null!=a?a:a=(0,t.useFunc)(_,r.default);if(c||s)n=_.let("valid"),x.block$data(n,function(){_.assign(n,!1),_.forOf("v",o,x=>_.if((0,e._)`${v()}(${A}, ${x})`,()=>_.assign(n,!0).break()))});else{if(!Array.isArray(i))throw Error("ajv implementation error");let x=_.const("vSchema",o);n=(0,e.or)(...i.map((t,r)=>{var a,n;let _;return a=x,"object"==typeof(_=i[n=r])&&null!==_?(0,e._)`${v()}(${A}, ${a}[${n}])`:(0,e._)`${A} === ${_}`}))}x.pass(n)}}}),pm=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pA(),t=ps(),r=po(),a=pl(),n=pc(),_=pv(),A=pd(),s=pb(),i=pu(),o=pp();x.default=[e.default,t.default,r.default,a.default,n.default,_.default,A.default,s.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},i.default,o.default]}),ph=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateAdditionalItems=void 0;let e=uK(),t=uQ();function r(x,r){let{gen:a,schema:n,data:_,keyword:A,it:s}=x;s.items=!0;let i=a.const("len",(0,e._)`${_}.length`);if(!1===n)x.setParams({len:r.length}),x.pass((0,e._)`${i} <= ${r.length}`);else if("object"==typeof n&&!(0,t.alwaysValidSchema)(s,n)){let n=a.var("valid",(0,e._)`${i} <= ${r.length}`);a.if((0,e.not)(n),()=>{var _;return _=n,void a.forRange("i",r.length,i,r=>{x.subschema({keyword:A,dataProp:r,dataPropType:t.Type.Num},_),s.allErrors||a.if((0,e.not)(_),()=>a.break())})}),x.ok(n)}}x.validateAdditionalItems=r,x.default={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{parentSchema:e,it:a}=x,{items:n}=e;Array.isArray(n)?r(x,n):(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas')}}}),pE=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateTuple=void 0;let e=uK(),t=uQ(),r=uz();function a(x,r,n=x.schema){let{gen:_,parentSchema:A,data:s,keyword:i,it:o}=x;(function(x){let{opts:e,errSchemaPath:a}=o,_=n.length,A=_===x.minItems&&(_===x.maxItems||!1===x[r]);if(e.strictTuples&&!A){let x=`"${i}" is ${_}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,t.checkStrictMode)(o,x,e.strictTuples)}})(A),o.opts.unevaluated&&n.length&&!0!==o.items&&(o.items=t.mergeEvaluated.items(_,n.length,o.items));let l=_.name("valid"),c=_.const("len",(0,e._)`${s}.length`);n.forEach((r,a)=>{(0,t.alwaysValidSchema)(o,r)||(_.if((0,e._)`${c} > ${a}`,()=>x.subschema({keyword:i,schemaProp:a,dataProp:a},l)),x.ok(l))})}x.validateTuple=a,x.default={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(x){let{schema:e,it:n}=x;if(Array.isArray(e))return a(x,"additionalItems",e);n.items=!0,(0,t.alwaysValidSchema)(n,e)||x.ok((0,r.validateArray)(x))}}}),pj=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pE();x.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:x=>(0,e.validateTuple)(x,"items")}}),pg=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ(),r=uz(),a=ph();x.default={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{schema:e,parentSchema:n,it:_}=x,{prefixItems:A}=n;_.items=!0,(0,t.alwaysValidSchema)(_,e)||(A?(0,a.validateAdditionalItems)(x,A):x.ok((0,r.validateArray)(x)))}}}),py=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ();x.default={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:x,max:t}})=>void 0===t?(0,e.str)`must contain at least ${x} valid item(s)`:(0,e.str)`must contain at least ${x} and no more than ${t} valid item(s)`,params:({params:{min:x,max:t}})=>void 0===t?(0,e._)`{minContains: ${x}}`:(0,e._)`{minContains: ${x}, maxContains: ${t}}`},code(x){let r,a,{gen:n,schema:_,parentSchema:A,data:s,it:i}=x,{minContains:o,maxContains:l}=A;i.opts.next?(r=void 0===o?1:o,a=l):r=1;let c=n.const("len",(0,e._)`${s}.length`);if(x.setParams({min:r,max:a}),void 0===a&&0===r)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==a&&r>a){(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),x.fail();return}if((0,t.alwaysValidSchema)(i,_)){let t=(0,e._)`${c} >= ${r}`;void 0!==a&&(t=(0,e._)`${t} && ${c} <= ${a}`),x.pass(t);return}i.items=!0;let v=n.name("valid");function d(){let x=n.name("_valid"),t=n.let("count",0);f(x,()=>n.if(x,()=>{var x;return x=t,void(n.code((0,e._)`${x}++`),void 0===a?n.if((0,e._)`${x} >= ${r}`,()=>n.assign(v,!0).break()):(n.if((0,e._)`${x} > ${a}`,()=>n.assign(v,!1).break()),1===r?n.assign(v,!0):n.if((0,e._)`${x} >= ${r}`,()=>n.assign(v,!0))))}))}function f(e,r){n.forRange("i",0,c,a=>{x.subschema({keyword:"contains",dataProp:a,dataPropType:t.Type.Num,compositeRule:!0},e),r()})}void 0===a&&1===r?f(v,()=>n.if(v,()=>n.break())):0===r?(n.let(v,!0),void 0!==a&&n.if((0,e._)`${s}.length > 0`,d)):(n.let(v,!1),d()),x.result(v,()=>x.reset())}}}),pS=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateSchemaDeps=x.validatePropertyDeps=x.error=void 0;let e=uK(),t=uQ(),r=uz();x.error={message:({params:{property:x,depsCount:t,deps:r}})=>(0,e.str)`must have ${1===t?"property":"properties"} ${r} when property ${x} is present`,params:({params:{property:x,depsCount:t,deps:r,missingProperty:a}})=>(0,e._)`{property: ${x},
376
+ || ${A} === "boolean" || ${a} === null`).assign(s,(0,_._)`[${a}]`)}}(x);r.else(),v(x),r.endIf(),r.if((0,_._)`${s} !== undefined`,()=>{r.assign(a,s),function({gen:x,parentData:e,parentDataProperty:t},r){x.if((0,_._)`${e} !== undefined`,()=>x.assign((0,_._)`${e}[${t}]`,r))}(x,s)})}(x,t,c):v(x)})}return d};let i=new Set(["string","number","integer","boolean","null"]);function o(x,t,r,a=e.Correct){let n,A=a===e.Correct?_.operators.EQ:_.operators.NEQ;switch(x){case"null":return(0,_._)`${t} ${A} null`;case"array":n=(0,_._)`Array.isArray(${t})`;break;case"object":n=(0,_._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":n=s((0,_._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":n=s();break;default:return(0,_._)`typeof ${t} ${A} ${x}`}return a===e.Correct?n:(0,_.not)(n);function s(x=_.nil){return(0,_.and)((0,_._)`typeof ${t} == "number"`,x,r?(0,_._)`isFinite(${t})`:_.nil)}}function l(x,e,t,r){let a;if(1===x.length)return o(x[0],e,t,r);let n=(0,A.toHash)(x);if(n.array&&n.object){let x=(0,_._)`typeof ${e} != "object"`;a=n.null?x:(0,_._)`!${e} || ${x}`,delete n.null,delete n.array,delete n.object}else a=_.nil;for(let x in n.number&&delete n.integer,n)a=(0,_.and)(a,o(x,e,t,r));return a}x.checkDataType=o,x.checkDataTypes=l;let c={message:({schema:x})=>`must be ${x}`,params:({schema:x,schemaValue:e})=>"string"==typeof x?(0,_._)`{type: ${x}}`:(0,_._)`{type: ${e}}`};function v(x){let e=function(x){let{gen:e,data:t,schema:r}=x,a=(0,A.schemaRefOrVal)(x,r,"type");return{gen:e,keyword:"type",data:t,schema:r.type,schemaCode:a,schemaValue:a,parentSchema:r,params:{},it:x}}(x);(0,n.reportError)(e,c)}x.reportTypeError=v}),uW=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.assignDefaults=void 0;let e=uM(),t=uZ();function r(x,r,a){let{gen:n,compositeRule:_,data:A,opts:s}=x;if(void 0===a)return;let i=(0,e._)`${A}${(0,e.getProperty)(r)}`;if(_)return void(0,t.checkStrictMode)(x,`default is ignored for: ${i}`);let o=(0,e._)`${i} === undefined`;"empty"===s.useDefaults&&(o=(0,e._)`${o} || ${i} === null || ${i} === ""`),n.if(o,(0,e._)`${i} = ${(0,e.stringify)(a)}`)}x.assignDefaults=function(x,e){let{properties:t,items:a}=x.schema;if("object"===e&&t)for(let e in t)r(x,e,t[e].default);else"array"===e&&Array.isArray(a)&&a.forEach((e,t)=>r(x,t,e.default))}}),u0=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateUnion=x.validateArray=x.usePattern=x.callValidateCode=x.schemaProperties=x.allSchemaProperties=x.noPropertyInData=x.propertyInData=x.isOwnProperty=x.hasPropFunc=x.reportMissingProp=x.checkMissingProp=x.checkReportMissingProp=void 0;let e=uM(),t=uZ(),r=uJ(),a=uZ();function n(x){return x.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}function _(x,t,r){return(0,e._)`${n(x)}.call(${t}, ${r})`}function A(x,t,r,a){let n=(0,e._)`${t}${(0,e.getProperty)(r)} === undefined`;return a?(0,e.or)(n,(0,e.not)(_(x,t,r))):n}function s(x){return x?Object.keys(x).filter(x=>"__proto__"!==x):[]}x.checkReportMissingProp=function(x,t){let{gen:r,data:a,it:n}=x;r.if(A(r,a,t,n.opts.ownProperties),()=>{x.setParams({missingProperty:(0,e._)`${t}`},!0),x.error()})},x.checkMissingProp=function({gen:x,data:t,it:{opts:r}},a,n){return(0,e.or)(...a.map(a=>(0,e.and)(A(x,t,a,r.ownProperties),(0,e._)`${n} = ${a}`)))},x.reportMissingProp=function(x,e){x.setParams({missingProperty:e},!0),x.error()},x.hasPropFunc=n,x.isOwnProperty=_,x.propertyInData=function(x,t,r,a){let n=(0,e._)`${t}${(0,e.getProperty)(r)} !== undefined`;return a?(0,e._)`${n} && ${_(x,t,r)}`:n},x.noPropertyInData=A,x.allSchemaProperties=s,x.schemaProperties=function(x,e){return s(e).filter(r=>!(0,t.alwaysValidSchema)(x,e[r]))},x.callValidateCode=function({schemaCode:x,data:t,it:{gen:a,topSchemaRef:n,schemaPath:_,errorPath:A},it:s},i,o,l){let c=l?(0,e._)`${x}, ${t}, ${n}${_}`:t,v=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,A)],[r.default.parentData,s.parentData],[r.default.parentDataProperty,s.parentDataProperty],[r.default.rootData,r.default.rootData]];s.opts.dynamicRef&&v.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let d=(0,e._)`${c}, ${a.object(...v)}`;return o!==e.nil?(0,e._)`${i}.call(${o}, ${d})`:(0,e._)`${i}(${d})`};let i=(0,e._)`new RegExp`;x.usePattern=function({gen:x,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:_}=t.code,A=_(r,n);return x.scopeValue("pattern",{key:A.toString(),ref:A,code:(0,e._)`${"new RegExp"===_.code?i:(0,a.useFunc)(x,_)}(${r}, ${n})`})},x.validateArray=function(x){let{gen:r,data:a,keyword:n,it:_}=x,A=r.name("valid");if(_.allErrors){let x=r.let("valid",!0);return s(()=>r.assign(x,!1)),x}return r.var(A,!0),s(()=>r.break()),A;function s(_){let s=r.const("len",(0,e._)`${a}.length`);r.forRange("i",0,s,a=>{x.subschema({keyword:n,dataProp:a,dataPropType:t.Type.Num},A),r.if((0,e.not)(A),_)})}},x.validateUnion=function(x){let{gen:r,schema:a,keyword:n,it:_}=x;if(!Array.isArray(a))throw Error("ajv implementation error");if(a.some(x=>(0,t.alwaysValidSchema)(_,x))&&!_.opts.unevaluated)return;let A=r.let("valid",!1),s=r.name("_valid");r.block(()=>a.forEach((t,a)=>{let _=x.subschema({keyword:n,schemaProp:a,compositeRule:!0},s);r.assign(A,(0,e._)`${A} || ${s}`),x.mergeValidEvaluated(_,s)||r.if((0,e.not)(A))})),x.result(A,()=>x.reset(),()=>x.error(!0))}}),u1=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateKeywordUsage=x.validSchemaType=x.funcKeywordCode=x.macroKeywordCode=void 0;let e=uM(),t=uJ(),r=u0(),a=uV();function n(x){let{gen:t,data:r,it:a}=x;t.if(a.parentData,()=>t.assign(r,(0,e._)`${a.parentData}[${a.parentDataProperty}]`))}function _(x,t,r){if(void 0===r)throw Error(`keyword "${t}" failed to compile`);return x.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,e.stringify)(r)})}x.macroKeywordCode=function(x,t){let{gen:r,keyword:a,schema:n,parentSchema:A,it:s}=x,i=t.macro.call(s.self,n,A,s),o=_(r,a,i);!1!==s.opts.validateSchema&&s.self.validateSchema(i,!0);let l=r.name("valid");x.subschema({schema:i,schemaPath:e.nil,errSchemaPath:`${s.errSchemaPath}/${a}`,topSchemaRef:o,compositeRule:!0},l),x.pass(l,()=>x.error(!0))},x.funcKeywordCode=function(x,A){var s;let{gen:i,keyword:o,schema:l,parentSchema:c,$data:v,it:d}=x;!function({schemaEnv:x},e){if(e.async&&!x.$async)throw Error("async keyword in sync schema")}(d,A);let f=_(i,o,!v&&A.compile?A.compile.call(d.self,l,c,d):A.validate),b=i.let("valid");function u(a=A.async?(0,e._)`await `:e.nil){let n=d.opts.passContext?t.default.this:t.default.self,_=!("compile"in A&&!v||!1===A.schema);i.assign(b,(0,e._)`${a}${(0,r.callValidateCode)(x,f,n,_)}`,A.modifying)}function p(x){var t;i.if((0,e.not)(null!=(t=A.valid)?t:b),x)}x.block$data(b,function(){if(!1===A.errors)u(),A.modifying&&n(x),p(()=>x.error());else{let r,_,s=A.async?(r=i.let("ruleErrs",null),i.try(()=>u((0,e._)`await `),x=>i.assign(b,!1).if((0,e._)`${x} instanceof ${d.ValidationError}`,()=>i.assign(r,(0,e._)`${x}.errors`),()=>i.throw(x))),r):(_=(0,e._)`${f}.errors`,i.assign(_,null),u(e.nil),_);A.modifying&&n(x),p(()=>(function(x,r){let{gen:n}=x;n.if((0,e._)`Array.isArray(${r})`,()=>{n.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${r} : ${t.default.vErrors}.concat(${r})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,a.extendErrors)(x)},()=>x.error())})(x,s))}}),x.ok(null!=(s=A.valid)?s:b)},x.validSchemaType=function(x,e,t=!1){return!e.length||e.some(e=>"array"===e?Array.isArray(x):"object"===e?x&&"object"==typeof x&&!Array.isArray(x):typeof x==e||t&&void 0===x)},x.validateKeywordUsage=function({schema:x,opts:e,self:t,errSchemaPath:r},a,n){if(Array.isArray(a.keyword)?!a.keyword.includes(n):a.keyword!==n)throw Error("ajv implementation error");let _=a.dependencies;if(null==_?void 0:_.some(e=>!Object.prototype.hasOwnProperty.call(x,e)))throw Error(`parent schema must have dependencies of ${n}: ${_.join(",")}`);if(a.validateSchema&&!a.validateSchema(x[n])){let x=`keyword "${n}" value is invalid at path "${r}": `+t.errorsText(a.validateSchema.errors);if("log"===e.validateSchema)t.logger.error(x);else throw Error(x)}}}),u2=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.extendSubschemaMode=x.extendSubschemaData=x.getSubschema=void 0;let e=uM(),t=uZ();x.getSubschema=function(x,{keyword:r,schemaProp:a,schema:n,schemaPath:_,errSchemaPath:A,topSchemaRef:s}){if(void 0!==r&&void 0!==n)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){let n=x.schema[r];return void 0===a?{schema:n,schemaPath:(0,e._)`${x.schemaPath}${(0,e.getProperty)(r)}`,errSchemaPath:`${x.errSchemaPath}/${r}`}:{schema:n[a],schemaPath:(0,e._)`${x.schemaPath}${(0,e.getProperty)(r)}${(0,e.getProperty)(a)}`,errSchemaPath:`${x.errSchemaPath}/${r}/${(0,t.escapeFragment)(a)}`}}if(void 0!==n){if(void 0===_||void 0===A||void 0===s)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:_,topSchemaRef:s,errSchemaPath:A}}throw Error('either "keyword" or "schema" must be passed')},x.extendSubschemaData=function(x,r,{dataProp:a,dataPropType:n,data:_,dataTypes:A,propertyName:s}){if(void 0!==_&&void 0!==a)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=r;if(void 0!==a){let{errorPath:_,dataPathArr:A,opts:s}=r;o(i.let("data",(0,e._)`${r.data}${(0,e.getProperty)(a)}`,!0)),x.errorPath=(0,e.str)`${_}${(0,t.getErrorPath)(a,n,s.jsPropertySyntax)}`,x.parentDataProperty=(0,e._)`${a}`,x.dataPathArr=[...A,x.parentDataProperty]}function o(e){x.data=e,x.dataLevel=r.dataLevel+1,x.dataTypes=[],r.definedProperties=new Set,x.parentData=r.data,x.dataNames=[...r.dataNames,e]}void 0!==_&&(o(_ instanceof e.Name?_:i.let("data",_,!0)),void 0!==s&&(x.propertyName=s)),A&&(x.dataTypes=A)},x.extendSubschemaMode=function(x,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:a,allErrors:n}){void 0!==r&&(x.compositeRule=r),void 0!==a&&(x.createErrors=a),void 0!==n&&(x.allErrors=n),x.jtdDiscriminator=e,x.jtdMetadata=t}}),u3=fG((x,e)=>{e.exports=function x(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;if(Array.isArray(e)){if((r=e.length)!=t.length)return!1;for(a=r;0!=a--;)if(!x(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if((r=(n=Object.keys(e)).length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var r,a,n,_=n[a];if(!x(e[_],t[_]))return!1}return!0}return e!=e&&t!=t}}),u6=fG((x,e)=>{var t=e.exports=function(x,e,r){"function"==typeof e&&(r=e,e={});var a="function"==typeof(r=e.cb||r)?r:r.pre||function(){};!function x(e,r,a,n,_,A,s,i,o,l){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var c in r(n,_,A,s,i,o,l),n){var v=n[c];if(Array.isArray(v)){if(c in t.arrayKeywords)for(var d=0;d<v.length;d++)x(e,r,a,v[d],_+"/"+c+"/"+d,A,_,c,n,d)}else if(c in t.propsKeywords){if(v&&"object"==typeof v)for(var f in v)x(e,r,a,v[f],_+"/"+c+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),A,_,c,n,f)}else(c in t.keywords||e.allKeys&&!(c in t.skipKeywords))&&x(e,r,a,v,_+"/"+c,A,_,c,n)}a(n,_,A,s,i,o,l)}}(e,a,r.post||function(){},x,"",x)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}}),u4=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getSchemaRefs=x.resolveUrl=x.normalizeId=x._getFullPath=x.getFullPath=x.inlineRef=void 0;let e=uZ(),t=u3(),r=u6(),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);x.inlineRef=function(x,t=!0){return"boolean"==typeof x||(!0===t?!function x(e){for(let t in e){if(n.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(x)||"object"==typeof r&&x(r))return!0}return!1}(x):!!t&&function x(t){let r=0;for(let n in t)if("$ref"===n||(r++,!a.has(n)&&("object"==typeof t[n]&&(0,e.eachItem)(t[n],e=>r+=x(e)),r===1/0)))return 1/0;return r}(x)<=t)};let n=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _(x,e="",t){return!1!==t&&(e=i(e)),A(x,x.parse(e))}function A(x,e){return x.serialize(e).split("#")[0]+"#"}x.getFullPath=_,x._getFullPath=A;let s=/#\/?$/;function i(x){return x?x.replace(s,""):""}x.normalizeId=i,x.resolveUrl=function(x,e,t){return t=i(t),x.resolve(e,t)};let o=/^[a-z_][-a-z0-9._]*$/i;x.getSchemaRefs=function(x,e){if("boolean"==typeof x)return{};let{schemaId:a,uriResolver:n}=this.opts,A=i(x[a]||e),s={"":A},l=_(n,A,!1),c={},v=new Set;return r(x,{allKeys:!0},(x,e,t,r)=>{if(void 0===r)return;let n=l+e,_=s[r];function A(e){let t=this.opts.uriResolver.resolve;if(e=i(_?t(_,e):e),v.has(e))throw f(e);v.add(e);let r=this.refs[e];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?d(x,r.schema,e):e!==i(n)&&("#"===e[0]?(d(x,c[e],e),c[e]=x):this.refs[e]=n),e}function b(x){if("string"==typeof x){if(!o.test(x))throw Error(`invalid anchor "${x}"`);A.call(this,`#${x}`)}}"string"==typeof x[a]&&(_=A.call(this,x[a])),b.call(this,x.$anchor),b.call(this,x.$dynamicAnchor),s[e]=_}),c;function d(x,e,r){if(void 0!==e&&!t(x,e))throw f(r)}function f(x){return Error(`reference "${x}" resolves to more than one schema`)}}}),u5=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.getData=x.KeywordCxt=x.validateFunctionCode=void 0;let e=uH(),t=uz(),r=uY(),a=uz(),n=uW(),_=u1(),A=u2(),s=uM(),i=uJ(),o=u4(),l=uZ(),c=uV();function v({gen:x,validateName:e,schema:t,schemaEnv:r,opts:a},n){var _;a.code.es5?x.func(e,(0,s._)`${i.default.data}, ${i.default.valCxt}`,r.$async,()=>{var e,r;x.code((0,s._)`"use strict"; ${d(t,a)}`),e=x,r=a,e.if(i.default.valCxt,()=>{e.var(i.default.instancePath,(0,s._)`${i.default.valCxt}.${i.default.instancePath}`),e.var(i.default.parentData,(0,s._)`${i.default.valCxt}.${i.default.parentData}`),e.var(i.default.parentDataProperty,(0,s._)`${i.default.valCxt}.${i.default.parentDataProperty}`),e.var(i.default.rootData,(0,s._)`${i.default.valCxt}.${i.default.rootData}`),r.dynamicRef&&e.var(i.default.dynamicAnchors,(0,s._)`${i.default.valCxt}.${i.default.dynamicAnchors}`)},()=>{e.var(i.default.instancePath,(0,s._)`""`),e.var(i.default.parentData,(0,s._)`undefined`),e.var(i.default.parentDataProperty,(0,s._)`undefined`),e.var(i.default.rootData,i.default.data),r.dynamicRef&&e.var(i.default.dynamicAnchors,(0,s._)`{}`)}),x.code(n)}):x.func(e,(0,s._)`${i.default.data}, ${(_=a,(0,s._)`{${i.default.instancePath}="", ${i.default.parentData}, ${i.default.parentDataProperty}, ${i.default.rootData}=${i.default.data}${_.dynamicRef?(0,s._)`, ${i.default.dynamicAnchors}={}`:s.nil}}={}`)}`,r.$async,()=>x.code(d(t,a)).code(n))}function d(x,e){let t="object"==typeof x&&x[e.schemaId];return t&&(e.code.source||e.code.process)?(0,s._)`/*# sourceURL=${t} */`:s.nil}function f({schema:x,self:e}){if("boolean"==typeof x)return!x;for(let t in x)if(e.RULES.all[t])return!0;return!1}function b(x){return"boolean"!=typeof x.schema}function u(x){(0,l.checkUnknownRules)(x),function(x){let{schema:e,errSchemaPath:t,opts:r,self:a}=x;e.$ref&&r.ignoreKeywordsWithRef&&(0,l.schemaHasRulesButRef)(e,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}(x)}function p(x,e){if(x.opts.jtd)return h(x,[],!1,e);let r=(0,t.getSchemaTypes)(x.schema);h(x,r,!(0,t.coerceAndCheckDataType)(x,r),e)}function m({gen:x,schemaEnv:e,schema:t,errSchemaPath:r,opts:a}){let n=t.$comment;if(!0===a.$comment)x.code((0,s._)`${i.default.self}.logger.log(${n})`);else if("function"==typeof a.$comment){let t=(0,s.str)`${r}/$comment`,a=x.scopeValue("root",{ref:e.root});x.code((0,s._)`${i.default.self}.opts.$comment(${n}, ${t}, ${a}.schema)`)}}function h(x,e,t,n){var _,A,o,c;let{gen:v,schema:d,data:f,allErrors:b,opts:u,self:p}=x,{RULES:m}=p;if(d.$ref&&(u.ignoreKeywordsWithRef||!(0,l.schemaHasRulesButRef)(d,m)))return void v.block(()=>S(x,"$ref",m.all.$ref.definition));function h(_){(0,r.shouldUseGroup)(d,_)&&(_.type?(v.if((0,a.checkDataType)(_.type,f,u.strictNumbers)),E(x,_),1===e.length&&e[0]===_.type&&t&&(v.else(),(0,a.reportTypeError)(x)),v.endIf()):E(x,_),b||v.if((0,s._)`${i.default.errors} === ${n||0}`))}u.jtd||(_=x,A=e,!_.schemaEnv.meta&&_.opts.strictTypes&&(function(x,e){if(e.length){if(!x.dataTypes.length){x.dataTypes=e;return}e.forEach(e=>{j(x.dataTypes,e)||g(x,`type "${e}" not allowed by context "${x.dataTypes.join(",")}"`)}),function(x,e){let t=[];for(let r of x.dataTypes)j(e,r)?t.push(r):e.includes("integer")&&"number"===r&&t.push("integer");x.dataTypes=t}(x,e)}}(_,A),_.opts.allowUnionTypes||(o=_,(c=A).length>1&&!(2===c.length&&c.includes("null"))&&g(o,"use allowUnionTypes to allow union type keyword")),function(x,e){let t=x.self.RULES.all;for(let a in t){let n=t[a];if("object"==typeof n&&(0,r.shouldUseRule)(x.schema,n)){let{type:t}=n.definition;t.length&&!t.some(x=>{var t,r;return t=e,r=x,t.includes(r)||"number"===r&&t.includes("integer")})&&g(x,`missing type "${t.join(",")}" for keyword "${a}"`)}}}(_,_.dataTypes))),v.block(()=>{for(let x of m.rules)h(x);h(m.post)})}function E(x,e){let{gen:t,schema:a,opts:{useDefaults:_}}=x;_&&(0,n.assignDefaults)(x,e.type),t.block(()=>{for(let t of e.rules)(0,r.shouldUseRule)(a,t)&&S(x,t.keyword,t.definition,e.type)})}function j(x,e){return x.includes(e)||"integer"===e&&x.includes("number")}function g(x,e){let t=x.schemaEnv.baseId+x.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,l.checkStrictMode)(x,e,x.opts.strictTypes)}x.validateFunctionCode=function(x){b(x)&&(u(x),f(x))?function(x){let{schema:e,opts:t,gen:r}=x;v(x,()=>{t.$comment&&e.$comment&&m(x),function(x){let{schema:e,opts:t}=x;void 0!==e.default&&t.useDefaults&&t.strictSchema&&(0,l.checkStrictMode)(x,"default is ignored in the schema root")}(x),r.let(i.default.vErrors,null),r.let(i.default.errors,0),t.unevaluated&&function(x){let{gen:e,validateName:t}=x;x.evaluated=e.const("evaluated",(0,s._)`${t}.evaluated`),e.if((0,s._)`${x.evaluated}.dynamicProps`,()=>e.assign((0,s._)`${x.evaluated}.props`,(0,s._)`undefined`)),e.if((0,s._)`${x.evaluated}.dynamicItems`,()=>e.assign((0,s._)`${x.evaluated}.items`,(0,s._)`undefined`))}(x),p(x),function(x){let{gen:e,schemaEnv:t,validateName:r,ValidationError:a,opts:n}=x;t.$async?e.if((0,s._)`${i.default.errors} === 0`,()=>e.return(i.default.data),()=>e.throw((0,s._)`new ${a}(${i.default.vErrors})`)):(e.assign((0,s._)`${r}.errors`,i.default.vErrors),n.unevaluated&&function({gen:x,evaluated:e,props:t,items:r}){t instanceof s.Name&&x.assign((0,s._)`${e}.props`,t),r instanceof s.Name&&x.assign((0,s._)`${e}.items`,r)}(x),e.return((0,s._)`${i.default.errors} === 0`))}(x)})}(x):v(x,()=>(0,e.topBoolOrEmptySchema)(x))};var y=class{constructor(x,e,t){if((0,_.validateKeywordUsage)(x,e,t),this.gen=x.gen,this.allErrors=x.allErrors,this.keyword=t,this.data=x.data,this.schema=x.schema[t],this.$data=e.$data&&x.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,l.schemaRefOrVal)(x,this.schema,t,this.$data),this.schemaType=e.schemaType,this.parentSchema=x.schema,this.params={},this.it=x,this.def=e,this.$data)this.schemaCode=x.gen.const("vSchema",B(this.$data,x));else if(this.schemaCode=this.schemaValue,!(0,_.validSchemaType)(this.schema,e.schemaType,e.allowUndefined))throw Error(`${t} value must be ${JSON.stringify(e.schemaType)}`);("code"in e?e.trackErrors:!1!==e.errors)&&(this.errsCount=x.gen.const("_errs",i.default.errors))}result(x,e,t){this.failResult((0,s.not)(x),e,t)}failResult(x,e,t){this.gen.if(x),t?t():this.error(),e?(this.gen.else(),e(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(x,e){this.failResult((0,s.not)(x),void 0,e)}fail(x){if(void 0===x){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(x),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(x){if(!this.$data)return this.fail(x);let{schemaCode:e}=this;this.fail((0,s._)`${e} !== undefined && (${(0,s.or)(this.invalid$data(),x)})`)}error(x,e,t){if(e){this.setParams(e),this._error(x,t),this.setParams({});return}this._error(x,t)}_error(x,e){(x?c.reportExtraError:c.reportError)(this,this.def.error,e)}$dataError(){(0,c.reportError)(this,this.def.$dataError||c.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,c.resetErrorsCount)(this.gen,this.errsCount)}ok(x){this.allErrors||this.gen.if(x)}setParams(x,e){e?Object.assign(this.params,x):this.params=x}block$data(x,e,t=s.nil){this.gen.block(()=>{this.check$data(x,t),e()})}check$data(x=s.nil,e=s.nil){if(!this.$data)return;let{gen:t,schemaCode:r,schemaType:a,def:n}=this;t.if((0,s.or)((0,s._)`${r} === undefined`,e)),x!==s.nil&&t.assign(x,!0),(a.length||n.validateSchema)&&(t.elseIf(this.invalid$data()),this.$dataError(),x!==s.nil&&t.assign(x,!1)),t.else()}invalid$data(){let{gen:x,schemaCode:e,schemaType:t,def:r,it:n}=this;return(0,s.or)(function(){if(t.length){if(!(e instanceof s.Name))throw Error("ajv implementation error");let x=Array.isArray(t)?t:[t];return(0,s._)`${(0,a.checkDataTypes)(x,e,n.opts.strictNumbers,a.DataType.Wrong)}`}return s.nil}(),function(){if(r.validateSchema){let t=x.scopeValue("validate$data",{ref:r.validateSchema});return(0,s._)`!${t}(${e})`}return s.nil}())}subschema(x,t){let r=(0,A.getSubschema)(this.it,x);(0,A.extendSubschemaData)(r,this.it,x),(0,A.extendSubschemaMode)(r,x);let a={...this.it,...r,items:void 0,props:void 0};return!function(x,t){if(b(x)&&(u(x),f(x)))return function(x,e){var t;let r,{schema:a,gen:n,opts:_}=x;_.$comment&&a.$comment&&m(x),(r=(t=x).schema[t.opts.schemaId])&&(t.baseId=(0,o.resolveUrl)(t.opts.uriResolver,t.baseId,r)),function(x){if(x.schema.$async&&!x.schemaEnv.$async)throw Error("async schema in sync schema")}(x);let A=n.const("_errs",i.default.errors);p(x,A),n.var(e,(0,s._)`${A} === ${i.default.errors}`)}(x,t);(0,e.boolOrEmptySchema)(x,t)}(a,t),a}mergeEvaluated(x,e){let{it:t,gen:r}=this;t.opts.unevaluated&&(!0!==t.props&&void 0!==x.props&&(t.props=l.mergeEvaluated.props(r,x.props,t.props,e)),!0!==t.items&&void 0!==x.items&&(t.items=l.mergeEvaluated.items(r,x.items,t.items,e)))}mergeValidEvaluated(x,e){let{it:t,gen:r}=this;if(t.opts.unevaluated&&(!0!==t.props||!0!==t.items))return r.if(e,()=>this.mergeEvaluated(x,s.Name)),!0}};function S(x,e,t,r){let a=new y(x,t,e);"code"in t?t.code(a,r):a.$data&&t.validate?(0,_.funcKeywordCode)(a,t):"macro"in t?(0,_.macroKeywordCode)(a,t):(t.compile||t.validate)&&(0,_.funcKeywordCode)(a,t)}x.KeywordCxt=y;let I=/^\/(?:[^~]|~0|~1)*$/,N=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function B(x,{dataLevel:e,dataNames:t,dataPathArr:r}){let a,n;if(""===x)return i.default.rootData;if("/"===x[0]){if(!I.test(x))throw Error(`Invalid JSON-pointer: ${x}`);a=x,n=i.default.rootData}else{let _=N.exec(x);if(!_)throw Error(`Invalid JSON-pointer: ${x}`);let s=+_[1];if("#"===(a=_[2])){if(s>=e)throw Error(A("property/index",s));return r[e-s]}if(s>e)throw Error(A("data",s));if(n=t[e-s],!a)return n}let _=n;for(let x of a.split("/"))x&&(n=(0,s._)`${n}${(0,s.getProperty)((0,l.unescapeJsonPointer)(x))}`,_=(0,s._)`${_} && ${n}`);return _;function A(x,t){return`Cannot access ${x} ${t} levels up, current level is ${e}`}}x.getData=B}),u7=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default=class extends Error{constructor(x){super("validation failed"),this.errors=x,this.ajv=this.validation=!0}}}),u8=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u4();x.default=class extends Error{constructor(x,t,r,a){super(a||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,e.resolveUrl)(x,t,r),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(x,this.missingRef))}}}),u9=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.resolveSchema=x.getCompilingSchema=x.resolveRef=x.compileSchema=x.SchemaEnv=void 0;let e=uM(),t=u7(),r=uJ(),a=u4(),n=uZ(),_=u5();var A=class{constructor(x){var e;let t;this.refs={},this.dynamicAnchors={},"object"==typeof x.schema&&(t=x.schema),this.schema=x.schema,this.schemaId=x.schemaId,this.root=x.root||this,this.baseId=null!=(e=x.baseId)?e:(0,a.normalizeId)(null==t?void 0:t[x.schemaId||"$id"]),this.schemaPath=x.schemaPath,this.localRefs=x.localRefs,this.meta=x.meta,this.$async=null==t?void 0:t.$async,this.refs={}}};function s(x){let n,A,s=o.call(this,x);if(s)return s;let i=(0,a.getFullPath)(this.opts.uriResolver,x.root.baseId),{es5:l,lines:c}=this.opts.code,{ownProperties:v}=this.opts,d=new e.CodeGen(this.scope,{es5:l,lines:c,ownProperties:v});x.$async&&(n=d.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let f=d.scopeName("validate");x.validateName=f;let b={gen:d,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:d.scopeValue("schema",!0===this.opts.code.source?{ref:x.schema,code:(0,e.stringify)(x.schema)}:{ref:x.schema}),validateName:f,ValidationError:n,schema:x.schema,schemaEnv:x,rootId:i,baseId:x.baseId||i,schemaPath:e.nil,errSchemaPath:x.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};try{this._compilations.add(x),(0,_.validateFunctionCode)(b),d.optimize(this.opts.code.optimize);let t=d.toString();A=`${d.scopeRefs(r.default.scope)}return ${t}`,this.opts.code.process&&(A=this.opts.code.process(A,x));let a=Function(`${r.default.self}`,`${r.default.scope}`,A)(this,this.scope.get());if(this.scope.value(f,{ref:a}),a.errors=null,a.schema=x.schema,a.schemaEnv=x,x.$async&&(a.$async=!0),!0===this.opts.code.source&&(a.source={validateName:f,validateCode:t,scopeValues:d._values}),this.opts.unevaluated){let{props:x,items:t}=b;a.evaluated={props:x instanceof e.Name?void 0:x,items:t instanceof e.Name?void 0:t,dynamicProps:x instanceof e.Name,dynamicItems:t instanceof e.Name},a.source&&(a.source.evaluated=(0,e.stringify)(a.evaluated))}return x.validate=a,x}catch(e){throw delete x.validate,delete x.validateName,A&&this.logger.error("Error compiling schema, function code:",A),e}finally{this._compilations.delete(x)}}function i(x){return(0,a.inlineRef)(x.schema,this.opts.inlineRefs)?x.schema:x.validate?x:s.call(this,x)}function o(x){for(let r of this._compilations){var e,t;if(e=r,t=x,e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId)return r}}function l(x,e){let t;for(;"string"==typeof(t=this.refs[e]);)e=t;return t||this.schemas[e]||c.call(this,x,e)}function c(x,e){let t=this.opts.uriResolver.parse(e),r=(0,a._getFullPath)(this.opts.uriResolver,t),n=(0,a.getFullPath)(this.opts.uriResolver,x.baseId,void 0);if(Object.keys(x.schema).length>0&&r===n)return d.call(this,t,x);let _=(0,a.normalizeId)(r),i=this.refs[_]||this.schemas[_];if("string"==typeof i){let e=c.call(this,x,i);if("object"!=typeof(null==e?void 0:e.schema))return;return d.call(this,t,e)}if("object"==typeof(null==i?void 0:i.schema)){if(i.validate||s.call(this,i),_===(0,a.normalizeId)(e)){let{schema:e}=i,{schemaId:t}=this.opts,r=e[t];return r&&(n=(0,a.resolveUrl)(this.opts.uriResolver,n,r)),new A({schema:e,schemaId:t,root:x,baseId:n})}return d.call(this,t,i)}}x.SchemaEnv=A,x.compileSchema=s,x.resolveRef=function(x,e,t){var r;t=(0,a.resolveUrl)(this.opts.uriResolver,e,t);let n=x.refs[t];if(n)return n;let _=l.call(this,x,t);if(void 0===_){let a=null==(r=x.localRefs)?void 0:r[t],{schemaId:n}=this.opts;a&&(_=new A({schema:a,schemaId:n,root:x,baseId:e}))}if(void 0!==_)return x.refs[t]=i.call(this,_)},x.getCompilingSchema=o,x.resolveSchema=c;let v=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function d(x,{baseId:e,schema:t,root:r}){var _;let s;if((null==(_=x.fragment)?void 0:_[0])!=="/")return;for(let r of x.fragment.slice(1).split("/")){if("boolean"==typeof t)return;let x=t[(0,n.unescapeFragment)(r)];if(void 0===x)return;let _="object"==typeof(t=x)&&t[this.opts.schemaId];!v.has(r)&&_&&(e=(0,a.resolveUrl)(this.opts.uriResolver,e,_))}if("boolean"!=typeof t&&t.$ref&&!(0,n.schemaHasRulesButRef)(t,this.RULES)){let x=(0,a.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=c.call(this,r,x)}let{schemaId:i}=this.opts;if((s=s||new A({schema:t,schemaId:i,root:r,baseId:e})).schema!==s.root.schema)return s}}),px=fG((x,e)=>{e.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),pe=fG((x,e)=>{let t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function a(x){let e="",t=0,r=0;for(r=0;r<x.length;r++)if(48!==(t=x[r].charCodeAt(0))){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=x[r];break}for(r+=1;r<x.length;r++){if(!((t=x[r].charCodeAt(0))>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=x[r]}return e}function n(x){return x.length=0,!0}function _(x,e,t){if(x.length){let r=a(x);if(""===r)return t.error=!0,!1;e.push(r),x.length=0}return!0}function A(x){if(2>function(x){let e=0;for(let t=0;t<x.length;t++)":"===x[t]&&e++;return e}(x))return{host:x,isIPV6:!1};let e=function(x){let e=0,t={error:!1,address:"",zone:""},r=[],A=[],s=!1,i=!1,o=_;for(let a=0;a<x.length;a++){let _=x[a];if("["!==_&&"]"!==_)if(":"===_){if(!0===s&&(i=!0),!o(A,r,t))break;if(++e>7){t.error=!0;break}a>0&&":"===x[a-1]&&(s=!0),r.push(":");continue}else if("%"===_){if(!o(A,r,t))break;o=n}else{A.push(_);continue}}return A.length&&(o===n?t.zone=A.join(""):i?r.push(A.join("")):r.push(a(A))),t.address=r.join(""),t}(x);if(e.error)return{host:x,isIPV6:!1};{let x=e.address,t=e.address;return e.zone&&(x+="%"+e.zone,t+="%25"+e.zone),{host:x,isIPV6:!0,escapedHost:t}}}e.exports={nonSimpleDomain:RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u),recomposeAuthority:function(x){let e=[];if(void 0!==x.userinfo&&(e.push(x.userinfo),e.push("@")),void 0!==x.host){let t=unescape(x.host);if(!r(t)){let e=A(t);t=!0===e.isIPV6?`[${e.escapedHost}]`:x.host}e.push(t)}return("number"==typeof x.port||"string"==typeof x.port)&&(e.push(":"),e.push(String(x.port))),e.length?e.join(""):void 0},normalizeComponentEncoding:function(x,e){let t=!0!==e?escape:unescape;return void 0!==x.scheme&&(x.scheme=t(x.scheme)),void 0!==x.userinfo&&(x.userinfo=t(x.userinfo)),void 0!==x.host&&(x.host=t(x.host)),void 0!==x.path&&(x.path=t(x.path)),void 0!==x.query&&(x.query=t(x.query)),void 0!==x.fragment&&(x.fragment=t(x.fragment)),x},removeDotSegments:function(x){let e=x,t=[],r=-1,a=0;for(;a=e.length;){if(1===a)if("."===e)break;else if("/"===e){t.push("/");break}else{t.push(e);break}if(2===a){if("."===e[0]){if("."===e[1])break;else if("/"===e[1]){e=e.slice(2);continue}}else if("/"===e[0]&&("."===e[1]||"/"===e[1])){t.push("/");break}}else if(3===a&&"/.."===e){0!==t.length&&t.pop(),t.push("/");break}if("."===e[0]){if("."===e[1]){if("/"===e[2]){e=e.slice(3);continue}}else if("/"===e[1]){e=e.slice(2);continue}}else if("/"===e[0]&&"."===e[1]){if("/"===e[2]){e=e.slice(2);continue}else if("."===e[2]&&"/"===e[3]){e=e.slice(3),0!==t.length&&t.pop();continue}}if(-1===(r=e.indexOf("/",1))){t.push(e);break}t.push(e.slice(0,r)),e=e.slice(r)}return t.join("")},isIPv4:r,isUUID:t,normalizeIPv6:A,stringArrayToHexStripped:a}}),pt=fG((x,e)=>{let{isUUID:t}=pe(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,a=["http","https","ws","wss","urn","urn:uuid"];function n(x){return!0===x.secure||!1!==x.secure&&!!x.scheme&&3===x.scheme.length&&("w"===x.scheme[0]||"W"===x.scheme[0])&&("s"===x.scheme[1]||"S"===x.scheme[1])&&("s"===x.scheme[2]||"S"===x.scheme[2])}function _(x){return x.host||(x.error=x.error||"HTTP URIs must have a host."),x}function A(x){let e="https"===String(x.scheme).toLowerCase();return(x.port===(e?443:80)||""===x.port)&&(x.port=void 0),x.path||(x.path="/"),x}let s={scheme:"http",domainHost:!0,parse:_,serialize:A},i={scheme:"https",domainHost:s.domainHost,parse:_,serialize:A},o={scheme:"ws",domainHost:!0,parse:function(x){return x.secure=n(x),x.resourceName=(x.path||"/")+(x.query?"?"+x.query:""),x.path=void 0,x.query=void 0,x},serialize:function(x){if((x.port===(n(x)?443:80)||""===x.port)&&(x.port=void 0),"boolean"==typeof x.secure&&(x.scheme=x.secure?"wss":"ws",x.secure=void 0),x.resourceName){let[e,t]=x.resourceName.split("?");x.path=e&&"/"!==e?e:void 0,x.query=t,x.resourceName=void 0}return x.fragment=void 0,x}},l={scheme:"wss",domainHost:o.domainHost,parse:o.parse,serialize:o.serialize},c={http:s,https:i,ws:o,wss:l,urn:{scheme:"urn",parse:function(x,e){if(!x.path)return x.error="URN can not be parsed",x;let t=x.path.match(r);if(t){let r=e.scheme||x.scheme||"urn";x.nid=t[1].toLowerCase(),x.nss=t[2];let a=v(`${r}:${e.nid||x.nid}`);x.path=void 0,a&&(x=a.parse(x,e))}else x.error=x.error||"URN can not be parsed.";return x},serialize:function(x,e){if(void 0===x.nid)throw Error("URN without nid cannot be serialized");let t=e.scheme||x.scheme||"urn",r=x.nid.toLowerCase(),a=v(`${t}:${e.nid||r}`);a&&(x=a.serialize(x,e));let n=x,_=x.nss;return n.path=`${r||e.nid}:${_}`,e.skipEscape=!0,n},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(x,e){return x.uuid=x.nss,x.nss=void 0,e.tolerant||x.uuid&&t(x.uuid)||(x.error=x.error||"UUID is not valid."),x},serialize:function(x){return x.nss=(x.uuid||"").toLowerCase(),x},skipNormalize:!0}};function v(x){return x&&(c[x]||c[x.toLowerCase()])||void 0}Object.setPrototypeOf(c,null),e.exports={wsIsSecure:n,SCHEMES:c,isValidSchemeName:function(x){return -1!==a.indexOf(x)},getSchemeHandler:v}}),pr=fG((x,e)=>{let{normalizeIPv6:t,removeDotSegments:r,recomposeAuthority:a,normalizeComponentEncoding:n,isIPv4:_,nonSimpleDomain:A}=pe(),{SCHEMES:s,getSchemeHandler:i}=pt();function o(x,e,t,a){let n={};return a||(x=v(l(x,t),t),e=v(l(e,t),t)),!(t=t||{}).tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=r(e.path||""),n.query=e.query):(void 0!==e.userinfo||void 0!==e.host||void 0!==e.port?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=r(e.path||""),n.query=e.query):(e.path?("/"===e.path[0]?n.path=r(e.path):(void 0===x.userinfo&&void 0===x.host&&void 0===x.port||x.path?x.path?n.path=x.path.slice(0,x.path.lastIndexOf("/")+1)+e.path:n.path=e.path:n.path="/"+e.path,n.path=r(n.path)),n.query=e.query):(n.path=x.path,void 0!==e.query?n.query=e.query:n.query=x.query),n.userinfo=x.userinfo,n.host=x.host,n.port=x.port),n.scheme=x.scheme),n.fragment=e.fragment,n}function l(x,e){let t={host:x.host,scheme:x.scheme,userinfo:x.userinfo,port:x.port,path:x.path,query:x.query,nid:x.nid,nss:x.nss,uuid:x.uuid,fragment:x.fragment,reference:x.reference,resourceName:x.resourceName,secure:x.secure,error:""},n=Object.assign({},e),_=[],A=i(n.scheme||t.scheme);A&&A.serialize&&A.serialize(t,n),void 0!==t.path&&(n.skipEscape?t.path=unescape(t.path):(t.path=escape(t.path),void 0!==t.scheme&&(t.path=t.path.split("%3A").join(":")))),"suffix"!==n.reference&&t.scheme&&_.push(t.scheme,":");let s=a(t);if(void 0!==s&&("suffix"!==n.reference&&_.push("//"),_.push(s),t.path&&"/"!==t.path[0]&&_.push("/")),void 0!==t.path){let x=t.path;n.absolutePath||A&&A.absolutePath||(x=r(x)),void 0===s&&"/"===x[0]&&"/"===x[1]&&(x="/%2F"+x.slice(2)),_.push(x)}return void 0!==t.query&&_.push("?",t.query),void 0!==t.fragment&&_.push("#",t.fragment),_.join("")}let c=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function v(x,e){let r=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;"suffix"===r.reference&&(x=r.scheme?r.scheme+":"+x:"//"+x);let s=x.match(c);if(s){if(a.scheme=s[1],a.userinfo=s[3],a.host=s[4],a.port=parseInt(s[5],10),a.path=s[6]||"",a.query=s[7],a.fragment=s[8],isNaN(a.port)&&(a.port=s[5]),a.host)if(!1===_(a.host)){let x=t(a.host);a.host=x.host.toLowerCase(),n=x.isIPV6}else n=!0;void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");let e=i(r.scheme||a.scheme);if(!r.unicodeSupport&&(!e||!e.unicodeSupport)&&a.host&&(r.domainHost||e&&e.domainHost)&&!1===n&&A(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(x){a.error=a.error||"Host's domain name can not be converted to ASCII: "+x}(!e||e&&!e.skipNormalize)&&(-1!==x.indexOf("%")&&(void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),void 0!==a.host&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),e&&e.parse&&e.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}let d={SCHEMES:s,normalize:function(x,e){return"string"==typeof x?x=l(v(x,e),e):"object"==typeof x&&(x=v(l(x,e),e)),x},resolve:function(x,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},a=o(v(x,r),v(e,r),r,!0);return r.skipEscape=!0,l(a,r)},resolveComponent:o,equal:function(x,e,t){return"string"==typeof x?x=l(n(v(x=unescape(x),t),!0),{...t,skipEscape:!0}):"object"==typeof x&&(x=l(n(x,!0),{...t,skipEscape:!0})),"string"==typeof e?e=l(n(v(e=unescape(e),t),!0),{...t,skipEscape:!0}):"object"==typeof e&&(e=l(n(e,!0),{...t,skipEscape:!0})),x.toLowerCase()===e.toLowerCase()},serialize:l,parse:v};e.exports=d,e.exports.default=d,e.exports.fastUri=d}),pa=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pr();e.code='require("ajv/dist/runtime/uri").default',x.default=e}),pn=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=void 0;var e=u5();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var t=uM();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return t._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return t.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return t.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return t.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return t.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return t.CodeGen}});let r=u7(),a=u8(),n=uU(),_=u9(),A=uM(),s=u4(),i=uz(),o=uZ(),l=px(),c=pa(),v=(x,e)=>new RegExp(x,e);v.code="new RegExp";let d=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},u={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};var p=class{constructor(x={}){var e,t,r,a,_,s,i,o,l,d,p,h,I,N,B,F,w,C,P,k,D,L,q,T,R,$;let G,O,X,K,Q;this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,x=this.opts={...x,...(G=(e=x).strict,X=!0===(O=null==(t=e.code)?void 0:t.optimize)||void 0===O?1:O||0,K=null!=(a=null==(r=e.code)?void 0:r.regExp)?a:v,Q=null!=(_=e.uriResolver)?_:c.default,{strictSchema:null==(i=null!=(s=e.strictSchema)?s:G)||i,strictNumbers:null==(l=null!=(o=e.strictNumbers)?o:G)||l,strictTypes:null!=(p=null!=(d=e.strictTypes)?d:G)?p:"log",strictTuples:null!=(I=null!=(h=e.strictTuples)?h:G)?I:"log",strictRequired:null!=(B=null!=(N=e.strictRequired)?N:G)&&B,code:e.code?{...e.code,optimize:X,regExp:K}:{optimize:X,regExp:K},loopRequired:null!=(F=e.loopRequired)?F:200,loopEnum:null!=(w=e.loopEnum)?w:200,meta:null==(C=e.meta)||C,messages:null==(P=e.messages)||P,inlineRefs:null==(k=e.inlineRefs)||k,schemaId:null!=(D=e.schemaId)?D:"$id",addUsedSchema:null==(L=e.addUsedSchema)||L,validateSchema:null==(q=e.validateSchema)||q,validateFormats:null==(T=e.validateFormats)||T,unicodeRegExp:null==(R=e.unicodeRegExp)||R,int32range:null==($=e.int32range)||$,uriResolver:Q})};let{es5:M,lines:Z}=this.opts.code;this.scope=new A.ValueScope({scope:{},prefixes:f,es5:M,lines:Z}),this.logger=function(x){if(!1===x)return S;if(void 0===x)return console;if(x.log&&x.warn&&x.error)return x;throw Error("logger must implement log, warn and error methods")}(x.logger);let J=x.validateFormats;x.validateFormats=!1,this.RULES=(0,n.getRules)(),m.call(this,b,x,"NOT SUPPORTED"),m.call(this,u,x,"DEPRECATED","warn"),this._metaOpts=y.call(this),x.formats&&j.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),x.keywords&&g.call(this,x.keywords),"object"==typeof x.meta&&this.addMetaSchema(x.meta),E.call(this),x.validateFormats=J}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:x,meta:e,schemaId:t}=this.opts,r=l;"id"===t&&((r={...l}).id=r.$id,delete r.$id),e&&x&&this.addMetaSchema(r,r[t],!1)}defaultMeta(){let{meta:x,schemaId:e}=this.opts;return this.opts.defaultMeta="object"==typeof x?x[e]||x:void 0}validate(x,e){let t;if("string"==typeof x){if(!(t=this.getSchema(x)))throw Error(`no schema with key or ref "${x}"`)}else t=this.compile(x);let r=t(e);return"$async"in t||(this.errors=t.errors),r}compile(x,e){let t=this._addSchema(x,e);return t.validate||this._compileSchemaEnv(t)}compileAsync(x,e){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:t}=this.opts;return r.call(this,x,e);async function r(x,e){await n.call(this,x.$schema);let t=this._addSchema(x,e);return t.validate||_.call(this,t)}async function n(x){x&&!this.getSchema(x)&&await r.call(this,{$ref:x},!0)}async function _(x){try{return this._compileSchemaEnv(x)}catch(e){if(!(e instanceof a.default))throw e;return A.call(this,e),await s.call(this,e.missingSchema),_.call(this,x)}}function A({missingSchema:x,missingRef:e}){if(this.refs[x])throw Error(`AnySchema ${x} is loaded but ${e} cannot be resolved`)}async function s(x){let t=await i.call(this,x);this.refs[x]||await n.call(this,t.$schema),this.refs[x]||this.addSchema(t,x,e)}async function i(x){let e=this._loading[x];if(e)return e;try{return await (this._loading[x]=t(x))}finally{delete this._loading[x]}}}addSchema(x,e,t,r=this.opts.validateSchema){let a;if(Array.isArray(x)){for(let e of x)this.addSchema(e,void 0,t,r);return this}if("object"==typeof x){let{schemaId:e}=this.opts;if(void 0!==(a=x[e])&&"string"!=typeof a)throw Error(`schema ${e} must be string`)}return e=(0,s.normalizeId)(e||a),this._checkUnique(e),this.schemas[e]=this._addSchema(x,t,e,r,!0),this}addMetaSchema(x,e,t=this.opts.validateSchema){return this.addSchema(x,e,!0,t),this}validateSchema(x,e){let t;if("boolean"==typeof x)return!0;if(void 0!==(t=x.$schema)&&"string"!=typeof t)throw Error("$schema must be a string");if(!(t=t||this.opts.defaultMeta||this.defaultMeta()))return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(t,x);if(!r&&e){let x="schema is invalid: "+this.errorsText();if("log"===this.opts.validateSchema)this.logger.error(x);else throw Error(x)}return r}getSchema(x){let e;for(;"string"==typeof(e=h.call(this,x));)x=e;if(void 0===e){let{schemaId:t}=this.opts,r=new _.SchemaEnv({schema:{},schemaId:t});if(!(e=_.resolveSchema.call(this,r,x)))return;this.refs[x]=e}return e.validate||this._compileSchemaEnv(e)}removeSchema(x){if(x instanceof RegExp)return this._removeAllSchemas(this.schemas,x),this._removeAllSchemas(this.refs,x),this;switch(typeof x){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let e=h.call(this,x);return"object"==typeof e&&this._cache.delete(e.schema),delete this.schemas[x],delete this.refs[x],this}case"object":{this._cache.delete(x);let e=x[this.opts.schemaId];return e&&(e=(0,s.normalizeId)(e),delete this.schemas[e],delete this.refs[e]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(x){for(let e of x)this.addKeyword(e);return this}addKeyword(x,e){let t;if("string"==typeof x)t=x,"object"==typeof e&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),e.keyword=t);else if("object"==typeof x&&void 0===e){if(Array.isArray(t=(e=x).keyword)&&!t.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(N.call(this,t,e),!e)return(0,o.eachItem)(t,x=>B.call(this,x)),this;w.call(this,e);let r={...e,type:(0,i.getJSONTypes)(e.type),schemaType:(0,i.getJSONTypes)(e.schemaType)};return(0,o.eachItem)(t,0===r.type.length?x=>B.call(this,x,r):x=>r.type.forEach(e=>B.call(this,x,r,e))),this}getKeyword(x){let e=this.RULES.all[x];return"object"==typeof e?e.definition:!!e}removeKeyword(x){let{RULES:e}=this;for(let t of(delete e.keywords[x],delete e.all[x],e.rules)){let e=t.rules.findIndex(e=>e.keyword===x);e>=0&&t.rules.splice(e,1)}return this}addFormat(x,e){return"string"==typeof e&&(e=new RegExp(e)),this.formats[x]=e,this}errorsText(x=this.errors,{separator:e=", ",dataVar:t="data"}={}){return x&&0!==x.length?x.map(x=>`${t}${x.instancePath} ${x.message}`).reduce((x,t)=>x+e+t):"No errors"}$dataMetaSchema(x,e){let t=this.RULES.all;for(let r of(x=JSON.parse(JSON.stringify(x)),e)){let e=r.split("/").slice(1),a=x;for(let x of e)a=a[x];for(let x in t){let e=t[x];if("object"!=typeof e)continue;let{$data:r}=e.definition,n=a[x];r&&n&&(a[x]=P(n))}}return x}_removeAllSchemas(x,e){for(let t in x){let r=x[t];(!e||e.test(t))&&("string"==typeof r?delete x[t]:r&&!r.meta&&(this._cache.delete(r.schema),delete x[t]))}}_addSchema(x,e,t,r=this.opts.validateSchema,a=this.opts.addUsedSchema){let n,{schemaId:A}=this.opts;if("object"==typeof x)n=x[A];else if(this.opts.jtd)throw Error("schema must be object");else if("boolean"!=typeof x)throw Error("schema must be object or boolean");let i=this._cache.get(x);if(void 0!==i)return i;t=(0,s.normalizeId)(n||t);let o=s.getSchemaRefs.call(this,x,t);return i=new _.SchemaEnv({schema:x,schemaId:A,meta:e,baseId:t,localRefs:o}),this._cache.set(i.schema,i),a&&!t.startsWith("#")&&(t&&this._checkUnique(t),this.refs[t]=i),r&&this.validateSchema(x,!0),i}_checkUnique(x){if(this.schemas[x]||this.refs[x])throw Error(`schema with key or id "${x}" already exists`)}_compileSchemaEnv(x){if(x.meta?this._compileMetaSchema(x):_.compileSchema.call(this,x),!x.validate)throw Error("ajv implementation error");return x.validate}_compileMetaSchema(x){let e=this.opts;this.opts=this._metaOpts;try{_.compileSchema.call(this,x)}finally{this.opts=e}}};function m(x,e,t,r="error"){for(let a in x)a in e&&this.logger[r](`${t}: option ${a}. ${x[a]}`)}function h(x){return x=(0,s.normalizeId)(x),this.schemas[x]||this.refs[x]}function E(){let x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(let e in x)this.addSchema(x[e],e)}function j(){for(let x in this.opts.formats){let e=this.opts.formats[x];e&&this.addFormat(x,e)}}function g(x){if(Array.isArray(x))return void this.addVocabulary(x);for(let e in this.logger.warn("keywords option as map is deprecated, pass array"),x){let t=x[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function y(){let x={...this.opts};for(let e of d)delete x[e];return x}p.ValidationError=r.default,p.MissingRefError=a.default,x.default=p;let S={log(){},warn(){},error(){}},I=/^[a-z_$][a-z0-9_$:-]*$/i;function N(x,e){let{RULES:t}=this;if((0,o.eachItem)(x,x=>{if(t.keywords[x])throw Error(`Keyword ${x} is already defined`);if(!I.test(x))throw Error(`Keyword ${x} has invalid name`)}),e&&e.$data&&!("code"in e||"validate"in e))throw Error('$data keyword must have "code" or "validate" function')}function B(x,e,t){var r;let a=null==e?void 0:e.post;if(t&&a)throw Error('keyword with "post" flag cannot have "type"');let{RULES:n}=this,_=a?n.post:n.rules.find(({type:x})=>x===t);if(_||(_={type:t,rules:[]},n.rules.push(_)),n.keywords[x]=!0,!e)return;let A={keyword:x,definition:{...e,type:(0,i.getJSONTypes)(e.type),schemaType:(0,i.getJSONTypes)(e.schemaType)}};e.before?F.call(this,_,A,e.before):_.rules.push(A),n.all[x]=A,null==(r=e.implements)||r.forEach(x=>this.addKeyword(x))}function F(x,e,t){let r=x.rules.findIndex(x=>x.keyword===t);r>=0?x.rules.splice(r,0,e):(x.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function w(x){let{metaSchema:e}=x;void 0!==e&&(x.$data&&this.opts.$data&&(e=P(e)),x.validateSchema=this.compile(e,!0))}let C={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function P(x){return{anyOf:[x,C]}}}),p_=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}}}),pA=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.callRef=x.getValidate=void 0;let e=u8(),t=u0(),r=uM(),a=uJ(),n=u9(),_=uZ();function A(x,e){let{gen:t}=x;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,r._)`${t.scopeValue("wrapper",{ref:e})}.validate`}function s(x,e,n,A){let{gen:s,it:i}=x,{allErrors:o,schemaEnv:l,opts:c}=i,v=c.passContext?a.default.this:r.nil;function d(x){let e=(0,r._)`${x}.errors`;s.assign(a.default.vErrors,(0,r._)`${a.default.vErrors} === null ? ${e} : ${a.default.vErrors}.concat(${e})`),s.assign(a.default.errors,(0,r._)`${a.default.vErrors}.length`)}function f(x){var e;if(!i.opts.unevaluated)return;let t=null==(e=null==n?void 0:n.validate)?void 0:e.evaluated;if(!0!==i.props)if(t&&!t.dynamicProps)void 0!==t.props&&(i.props=_.mergeEvaluated.props(s,t.props,i.props));else{let e=s.var("props",(0,r._)`${x}.evaluated.props`);i.props=_.mergeEvaluated.props(s,e,i.props,r.Name)}if(!0!==i.items)if(t&&!t.dynamicItems)void 0!==t.items&&(i.items=_.mergeEvaluated.items(s,t.items,i.items));else{let e=s.var("items",(0,r._)`${x}.evaluated.items`);i.items=_.mergeEvaluated.items(s,e,i.items,r.Name)}}A?function(){if(!l.$async)throw Error("async schema referenced by sync schema");let a=s.let("valid");s.try(()=>{s.code((0,r._)`await ${(0,t.callValidateCode)(x,e,v)}`),f(e),o||s.assign(a,!0)},x=>{s.if((0,r._)`!(${x} instanceof ${i.ValidationError})`,()=>s.throw(x)),d(x),o||s.assign(a,!1)}),x.ok(a)}():x.result((0,t.callValidateCode)(x,e,v),()=>f(e),()=>d(e))}x.getValidate=A,x.callRef=s,x.default={keyword:"$ref",schemaType:"string",code(x){var t,a;let _,i,o,{gen:l,schema:c,it:v}=x,{baseId:d,schemaEnv:f,validateName:b,opts:u,self:p}=v,{root:m}=f;if(("#"===c||"#/"===c)&&d===m.baseId){if(f===m)return s(x,b,f,f.$async);let e=l.scopeValue("root",{ref:m});return s(x,(0,r._)`${e}.validate`,m,m.$async)}let h=n.resolveRef.call(p,m,d,c);if(void 0===h)throw new e.default(v.opts.uriResolver,d,c);return h instanceof n.SchemaEnv?void s(x,A(x,t=h),t,t.$async):(a=h,_=l.scopeValue("schema",!0===u.code.source?{ref:a,code:(0,r.stringify)(a)}:{ref:a}),i=l.name("valid"),o=x.subschema({schema:a,dataTypes:[],schemaPath:r.nil,topSchemaRef:_,errSchemaPath:c},i),void(x.mergeEvaluated(o),x.ok(i)))}}}),ps=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p_(),t=pA();x.default=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default]}),pi=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}};x.default={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must be ${r[x].okStr} ${t}`,params:({keyword:x,schemaCode:t})=>(0,e._)`{comparison: ${r[x].okStr}, limit: ${t}}`},code(x){let{keyword:t,data:a,schemaCode:n}=x;x.fail$data((0,e._)`${a} ${r[t].fail} ${n} || isNaN(${a})`)}}}),po=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM();x.default={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:x})=>(0,e.str)`must be multiple of ${x}`,params:({schemaCode:x})=>(0,e._)`{multipleOf: ${x}}`},code(x){let{gen:t,data:r,schemaCode:a,it:n}=x,_=n.opts.multipleOfPrecision,A=t.let("res"),s=_?(0,e._)`Math.abs(Math.round(${A}) - ${A}) > 1e-${_}`:(0,e._)`${A} !== parseInt(${A})`;x.fail$data((0,e._)`(${a} === 0 || (${A} = ${r}/${a}, ${s}))`)}}}),pl=fG(x=>{function e(x){let e,t=x.length,r=0,a=0;for(;a<t;)r++,(e=x.charCodeAt(a++))>=55296&&e<=56319&&a<t&&(64512&(e=x.charCodeAt(a)))==56320&&a++;return r}Object.defineProperty(x,"__esModule",{value:!0}),x.default=e,e.code='require("ajv/dist/runtime/ucs2length").default'}),pc=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ(),r=pl();x.default={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxLength"===x?"more":"fewer"} than ${t} characters`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:a,data:n,schemaCode:_,it:A}=x,s="maxLength"===a?e.operators.GT:e.operators.LT,i=!1===A.opts.unicode?(0,e._)`${n}.length`:(0,e._)`${(0,t.useFunc)(x.gen,r.default)}(${n})`;x.fail$data((0,e._)`${i} ${s} ${_}`)}}}),pv=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u0(),t=uZ(),r=uM();x.default={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:x})=>(0,r.str)`must match pattern "${x}"`,params:({schemaCode:x})=>(0,r._)`{pattern: ${x}}`},code(x){let{gen:a,data:n,$data:_,schema:A,schemaCode:s,it:i}=x,o=i.opts.unicodeRegExp?"u":"";if(_){let{regExp:e}=i.opts.code,_="new RegExp"===e.code?(0,r._)`new RegExp`:(0,t.useFunc)(a,e),A=a.let("valid");a.try(()=>a.assign(A,(0,r._)`${_}(${s}, ${o}).test(${n})`),()=>a.assign(A,!1)),x.fail$data((0,r._)`!${A}`)}else{let t=(0,e.usePattern)(x,A);x.fail$data((0,r._)`!${t}.test(${n})`)}}}}),pd=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM();x.default={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxProperties"===x?"more":"fewer"} than ${t} properties`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:t,data:r,schemaCode:a}=x,n="maxProperties"===t?e.operators.GT:e.operators.LT;x.fail$data((0,e._)`Object.keys(${r}).length ${n} ${a}`)}}}),pf=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u0(),t=uM(),r=uZ();x.default={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:x}})=>(0,t.str)`must have required property '${x}'`,params:({params:{missingProperty:x}})=>(0,t._)`{missingProperty: ${x}}`},code(x){let{gen:a,schema:n,schemaCode:_,data:A,$data:s,it:i}=x,{opts:o}=i;if(!s&&0===n.length)return;let l=n.length>=o.loopRequired;if(i.allErrors?function(){if(l||s)x.block$data(t.nil,c);else for(let t of n)(0,e.checkReportMissingProp)(x,t)}():function(){let r=a.let("missing");if(l||s){let n=a.let("valid",!0);x.block$data(n,()=>{var s,i;return s=r,i=n,void(x.setParams({missingProperty:s}),a.forOf(s,_,()=>{a.assign(i,(0,e.propertyInData)(a,A,s,o.ownProperties)),a.if((0,t.not)(i),()=>{x.error(),a.break()})},t.nil))}),x.ok(n)}else a.if((0,e.checkMissingProp)(x,n,r)),(0,e.reportMissingProp)(x,r),a.else()}(),o.strictRequired){let e=x.parentSchema.properties,{definedProperties:t}=x.it;for(let x of n)if((null==e?void 0:e[x])===void 0&&!t.has(x)){let e=`required property "${x}" is not defined at "${i.schemaEnv.baseId+i.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(i,e,i.opts.strictRequired)}}function c(){a.forOf("prop",_,t=>{x.setParams({missingProperty:t}),a.if((0,e.noPropertyInData)(a,A,t,o.ownProperties),()=>x.error())})}}}}),pb=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM();x.default={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message:({keyword:x,schemaCode:t})=>(0,e.str)`must NOT have ${"maxItems"===x?"more":"fewer"} than ${t} items`,params:({schemaCode:x})=>(0,e._)`{limit: ${x}}`},code(x){let{keyword:t,data:r,schemaCode:a}=x,n="maxItems"===t?e.operators.GT:e.operators.LT;x.fail$data((0,e._)`${r}.length ${n} ${a}`)}}}),pu=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u3();e.code='require("ajv/dist/runtime/equal").default',x.default=e}),pp=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uz(),t=uM(),r=uZ(),a=pu();x.default={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:x,j:e}})=>(0,t.str)`must NOT have duplicate items (items ## ${e} and ${x} are identical)`,params:({params:{i:x,j:e}})=>(0,t._)`{i: ${x}, j: ${e}}`},code(x){let{gen:n,data:_,$data:A,schema:s,parentSchema:i,schemaCode:o,it:l}=x;if(!A&&!s)return;let c=n.let("valid"),v=i.items?(0,e.getSchemaTypes)(i.items):[];x.block$data(c,function(){let A=n.let("i",(0,t._)`${_}.length`),s=n.let("j");x.setParams({i:A,j:s}),n.assign(c,!0),n.if((0,t._)`${A} > 1`,()=>(v.length>0&&!v.some(x=>"object"===x||"array"===x)?function(r,a){let A=n.name("item"),s=(0,e.checkDataTypes)(v,A,l.opts.strictNumbers,e.DataType.Wrong),i=n.const("indices",(0,t._)`{}`);n.for((0,t._)`;${r}--;`,()=>{n.let(A,(0,t._)`${_}[${r}]`),n.if(s,(0,t._)`continue`),v.length>1&&n.if((0,t._)`typeof ${A} == "string"`,(0,t._)`${A} += "_"`),n.if((0,t._)`typeof ${i}[${A}] == "number"`,()=>{n.assign(a,(0,t._)`${i}[${A}]`),x.error(),n.assign(c,!1).break()}).code((0,t._)`${i}[${A}] = ${r}`)})}:function(e,A){let s=(0,r.useFunc)(n,a.default),i=n.name("outer");n.label(i).for((0,t._)`;${e}--;`,()=>n.for((0,t._)`${A} = ${e}; ${A}--;`,()=>n.if((0,t._)`${s}(${_}[${e}], ${_}[${A}])`,()=>{x.error(),n.assign(c,!1).break(i)})))})(A,s))},(0,t._)`${o} === false`),x.ok(c)}}}),pm=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ(),r=pu();x.default={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:x})=>(0,e._)`{allowedValue: ${x}}`},code(x){let{gen:a,data:n,$data:_,schemaCode:A,schema:s}=x;_||s&&"object"==typeof s?x.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${n}, ${A})`):x.fail((0,e._)`${s} !== ${n}`)}}}),ph=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ(),r=pu();x.default={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:x})=>(0,e._)`{allowedValues: ${x}}`},code(x){let a,n,{gen:_,data:A,$data:s,schema:i,schemaCode:o,it:l}=x;if(!s&&0===i.length)throw Error("enum must have non-empty array");let c=i.length>=l.opts.loopEnum,v=()=>null!=a?a:a=(0,t.useFunc)(_,r.default);if(c||s)n=_.let("valid"),x.block$data(n,function(){_.assign(n,!1),_.forOf("v",o,x=>_.if((0,e._)`${v()}(${A}, ${x})`,()=>_.assign(n,!0).break()))});else{if(!Array.isArray(i))throw Error("ajv implementation error");let x=_.const("vSchema",o);n=(0,e.or)(...i.map((t,r)=>{var a,n;let _;return a=x,"object"==typeof(_=i[n=r])&&null!==_?(0,e._)`${v()}(${A}, ${a}[${n}])`:(0,e._)`${A} === ${_}`}))}x.pass(n)}}}),pE=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pi(),t=po(),r=pc(),a=pv(),n=pd(),_=pf(),A=pb(),s=pp(),i=pm(),o=ph();x.default=[e.default,t.default,r.default,a.default,n.default,_.default,A.default,s.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},i.default,o.default]}),pj=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateAdditionalItems=void 0;let e=uM(),t=uZ();function r(x,r){let{gen:a,schema:n,data:_,keyword:A,it:s}=x;s.items=!0;let i=a.const("len",(0,e._)`${_}.length`);if(!1===n)x.setParams({len:r.length}),x.pass((0,e._)`${i} <= ${r.length}`);else if("object"==typeof n&&!(0,t.alwaysValidSchema)(s,n)){let n=a.var("valid",(0,e._)`${i} <= ${r.length}`);a.if((0,e.not)(n),()=>{var _;return _=n,void a.forRange("i",r.length,i,r=>{x.subschema({keyword:A,dataProp:r,dataPropType:t.Type.Num},_),s.allErrors||a.if((0,e.not)(_),()=>a.break())})}),x.ok(n)}}x.validateAdditionalItems=r,x.default={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{parentSchema:e,it:a}=x,{items:n}=e;Array.isArray(n)?r(x,n):(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas')}}}),pg=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateTuple=void 0;let e=uM(),t=uZ(),r=u0();function a(x,r,n=x.schema){let{gen:_,parentSchema:A,data:s,keyword:i,it:o}=x;(function(x){let{opts:e,errSchemaPath:a}=o,_=n.length,A=_===x.minItems&&(_===x.maxItems||!1===x[r]);if(e.strictTuples&&!A){let x=`"${i}" is ${_}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,t.checkStrictMode)(o,x,e.strictTuples)}})(A),o.opts.unevaluated&&n.length&&!0!==o.items&&(o.items=t.mergeEvaluated.items(_,n.length,o.items));let l=_.name("valid"),c=_.const("len",(0,e._)`${s}.length`);n.forEach((r,a)=>{(0,t.alwaysValidSchema)(o,r)||(_.if((0,e._)`${c} > ${a}`,()=>x.subschema({keyword:i,schemaProp:a,dataProp:a},l)),x.ok(l))})}x.validateTuple=a,x.default={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(x){let{schema:e,it:n}=x;if(Array.isArray(e))return a(x,"additionalItems",e);n.items=!0,(0,t.alwaysValidSchema)(n,e)||x.ok((0,r.validateArray)(x))}}}),py=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pg();x.default={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:x=>(0,e.validateTuple)(x,"items")}}),pS=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ(),r=u0(),a=pj();x.default={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{schema:e,parentSchema:n,it:_}=x,{prefixItems:A}=n;_.items=!0,(0,t.alwaysValidSchema)(_,e)||(A?(0,a.validateAdditionalItems)(x,A):x.ok((0,r.validateArray)(x)))}}}),pI=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ();x.default={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:x,max:t}})=>void 0===t?(0,e.str)`must contain at least ${x} valid item(s)`:(0,e.str)`must contain at least ${x} and no more than ${t} valid item(s)`,params:({params:{min:x,max:t}})=>void 0===t?(0,e._)`{minContains: ${x}}`:(0,e._)`{minContains: ${x}, maxContains: ${t}}`},code(x){let r,a,{gen:n,schema:_,parentSchema:A,data:s,it:i}=x,{minContains:o,maxContains:l}=A;i.opts.next?(r=void 0===o?1:o,a=l):r=1;let c=n.const("len",(0,e._)`${s}.length`);if(x.setParams({min:r,max:a}),void 0===a&&0===r)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==a&&r>a){(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),x.fail();return}if((0,t.alwaysValidSchema)(i,_)){let t=(0,e._)`${c} >= ${r}`;void 0!==a&&(t=(0,e._)`${t} && ${c} <= ${a}`),x.pass(t);return}i.items=!0;let v=n.name("valid");function d(){let x=n.name("_valid"),t=n.let("count",0);f(x,()=>n.if(x,()=>{var x;return x=t,void(n.code((0,e._)`${x}++`),void 0===a?n.if((0,e._)`${x} >= ${r}`,()=>n.assign(v,!0).break()):(n.if((0,e._)`${x} > ${a}`,()=>n.assign(v,!1).break()),1===r?n.assign(v,!0):n.if((0,e._)`${x} >= ${r}`,()=>n.assign(v,!0))))}))}function f(e,r){n.forRange("i",0,c,a=>{x.subschema({keyword:"contains",dataProp:a,dataPropType:t.Type.Num,compositeRule:!0},e),r()})}void 0===a&&1===r?f(v,()=>n.if(v,()=>n.break())):0===r?(n.let(v,!0),void 0!==a&&n.if((0,e._)`${s}.length > 0`,d)):(n.let(v,!1),d()),x.result(v,()=>x.reset())}}}),pN=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.validateSchemaDeps=x.validatePropertyDeps=x.error=void 0;let e=uM(),t=uZ(),r=u0();x.error={message:({params:{property:x,depsCount:t,deps:r}})=>(0,e.str)`must have ${1===t?"property":"properties"} ${r} when property ${x} is present`,params:({params:{property:x,depsCount:t,deps:r,missingProperty:a}})=>(0,e._)`{property: ${x},
377
377
  missingProperty: ${a},
378
378
  depsCount: ${t},
379
- deps: ${r}}`};let a={keyword:"dependencies",type:"object",schemaType:"object",error:x.error,code(x){let[e,t]=function({schema:x}){let e={},t={};for(let r in x)"__proto__"!==r&&((Array.isArray(x[r])?e:t)[r]=x[r]);return[e,t]}(x);n(x,e),_(x,t)}};function n(x,t=x.schema){let{gen:a,data:_,it:A}=x;if(0===Object.keys(t).length)return;let s=a.let("missing");for(let n in t){let i=t[n];if(0===i.length)continue;let o=(0,r.propertyInData)(a,_,n,A.opts.ownProperties);x.setParams({property:n,depsCount:i.length,deps:i.join(", ")}),A.allErrors?a.if(o,()=>{for(let e of i)(0,r.checkReportMissingProp)(x,e)}):(a.if((0,e._)`${o} && (${(0,r.checkMissingProp)(x,i,s)})`),(0,r.reportMissingProp)(x,s),a.else())}}function _(x,e=x.schema){let{gen:a,data:n,keyword:A,it:s}=x,i=a.name("valid");for(let _ in e)(0,t.alwaysValidSchema)(s,e[_])||(a.if((0,r.propertyInData)(a,n,_,s.opts.ownProperties),()=>{let e=x.subschema({keyword:A,schemaProp:_},i);x.mergeValidEvaluated(e,i)},()=>a.var(i,!0)),x.ok(i))}x.validatePropertyDeps=n,x.validateSchemaDeps=_,x.default=a}),pI=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ();x.default={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:x})=>(0,e._)`{propertyName: ${x.propertyName}}`},code(x){let{gen:r,schema:a,data:n,it:_}=x;if((0,t.alwaysValidSchema)(_,a))return;let A=r.name("valid");r.forIn("key",n,t=>{x.setParams({propertyName:t}),x.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},A),r.if((0,e.not)(A),()=>{x.error(!0),_.allErrors||r.break()})}),x.ok(A)}}}),pN=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uz(),t=uK(),r=uM(),a=uQ();x.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:x})=>(0,t._)`{additionalProperty: ${x.additionalProperty}}`},code(x){let{gen:n,schema:_,parentSchema:A,data:s,errsCount:i,it:o}=x;if(!i)throw Error("ajv implementation error");let{allErrors:l,opts:c}=o;if(o.props=!0,"all"!==c.removeAdditional&&(0,a.alwaysValidSchema)(o,_))return;let v=(0,e.allSchemaProperties)(A.properties),d=(0,e.allSchemaProperties)(A.patternProperties);function f(x){n.code((0,t._)`delete ${s}[${x}]`)}function b(e){if("all"===c.removeAdditional||c.removeAdditional&&!1===_)return void f(e);if(!1===_){x.setParams({additionalProperty:e}),x.error(),l||n.break();return}if("object"==typeof _&&!(0,a.alwaysValidSchema)(o,_)){let r=n.name("valid");"failing"===c.removeAdditional?(u(e,r,!1),n.if((0,t.not)(r),()=>{x.reset(),f(e)})):(u(e,r),l||n.if((0,t.not)(r),()=>n.break()))}}function u(e,t,r){let n={keyword:"additionalProperties",dataProp:e,dataPropType:a.Type.Str};!1===r&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),x.subschema(n,t)}n.forIn("key",s,r=>{v.length||d.length?n.if(function(r){let _;if(v.length>8){let x=(0,a.schemaRefOrVal)(o,A.properties,"properties");_=(0,e.isOwnProperty)(n,x,r)}else _=v.length?(0,t.or)(...v.map(x=>(0,t._)`${r} === ${x}`)):t.nil;return d.length&&(_=(0,t.or)(_,...d.map(a=>(0,t._)`${(0,e.usePattern)(x,a)}.test(${r})`))),(0,t.not)(_)}(r),()=>b(r)):b(r)}),x.ok((0,t._)`${i} === ${r.default.errors}`)}}}),pB=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u6(),t=uz(),r=uQ(),a=pN();x.default={keyword:"properties",type:"object",schemaType:"object",code(x){let{gen:n,schema:_,parentSchema:A,data:s,it:i}=x;"all"===i.opts.removeAdditional&&void 0===A.additionalProperties&&a.default.code(new e.KeywordCxt(i,a.default,"additionalProperties"));let o=(0,t.allSchemaProperties)(_);for(let x of o)i.definedProperties.add(x);i.opts.unevaluated&&o.length&&!0!==i.props&&(i.props=r.mergeEvaluated.props(n,(0,r.toHash)(o),i.props));let l=o.filter(x=>!(0,r.alwaysValidSchema)(i,_[x]));if(0===l.length)return;let c=n.name("valid");for(let e of l){var v;(v=e,i.opts.useDefaults&&!i.compositeRule&&void 0!==_[v].default)?d(e):(n.if((0,t.propertyInData)(n,s,e,i.opts.ownProperties)),d(e),i.allErrors||n.else().var(c,!0),n.endIf()),x.it.definedProperties.add(e),x.ok(c)}function d(e){x.subschema({keyword:"properties",schemaProp:e,dataProp:e},c)}}}}),pF=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uz(),t=uK(),r=uQ(),a=uQ();x.default={keyword:"patternProperties",type:"object",schemaType:"object",code(x){let{gen:n,schema:_,data:A,parentSchema:s,it:i}=x,{opts:o}=i,l=(0,e.allSchemaProperties)(_),c=l.filter(x=>(0,r.alwaysValidSchema)(i,_[x]));if(0===l.length||c.length===l.length&&(!i.opts.unevaluated||!0===i.props))return;let v=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=n.name("valid");!0===i.props||i.props instanceof t.Name||(i.props=(0,a.evaluatedPropsToName)(n,i.props));let{props:f}=i;for(let x of l)v&&function(x){for(let e in v)new RegExp(x).test(e)&&(0,r.checkStrictMode)(i,`property ${e} matches pattern ${x} (use allowMatchingProperties)`)}(x),i.allErrors?b(x):(n.var(d,!0),b(x),n.if(d));function b(r){n.forIn("key",A,_=>{n.if((0,t._)`${(0,e.usePattern)(x,r)}.test(${_})`,()=>{let e=c.includes(r);e||x.subschema({keyword:"patternProperties",schemaProp:r,dataProp:_,dataPropType:a.Type.Str},d),i.opts.unevaluated&&!0!==f?n.assign((0,t._)`${f}[${_}]`,!0):e||i.allErrors||n.if((0,t.not)(d),()=>n.break())})})}}}}),pw=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uQ();x.default={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(x){let{gen:t,schema:r,it:a}=x;if((0,e.alwaysValidSchema)(a,r))return void x.fail();let n=t.name("valid");x.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),x.failResult(n,()=>x.reset(),()=>x.error())},error:{message:"must NOT be valid"}}}),pC=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:uz().validateUnion,error:{message:"must match a schema in anyOf"}}}),pP=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ();x.default={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:x})=>(0,e._)`{passingSchemas: ${x.passing}}`},code(x){let{gen:r,schema:a,parentSchema:n,it:_}=x;if(!Array.isArray(a))throw Error("ajv implementation error");if(_.opts.discriminator&&n.discriminator)return;let A=r.let("valid",!1),s=r.let("passing",null),i=r.name("_valid");x.setParams({passing:s}),r.block(function(){a.forEach((a,n)=>{let o;(0,t.alwaysValidSchema)(_,a)?r.var(i,!0):o=x.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},i),n>0&&r.if((0,e._)`${i} && ${A}`).assign(A,!1).assign(s,(0,e._)`[${s}, ${n}]`).else(),r.if(i,()=>{r.assign(A,!0),r.assign(s,n),o&&x.mergeEvaluated(o,e.Name)})})}),x.result(A,()=>x.reset(),()=>x.error(!0))}}}),pk=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uQ();x.default={keyword:"allOf",schemaType:"array",code(x){let{gen:t,schema:r,it:a}=x;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((t,r)=>{if((0,e.alwaysValidSchema)(a,t))return;let _=x.subschema({keyword:"allOf",schemaProp:r},n);x.ok(n),x.mergeEvaluated(_)})}}}),pD=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ();function r(x,e){let r=x.schema[e];return void 0!==r&&!(0,t.alwaysValidSchema)(x,r)}x.default={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:x})=>(0,e.str)`must match "${x.ifClause}" schema`,params:({params:x})=>(0,e._)`{failingKeyword: ${x.ifClause}}`},code(x){let a,{gen:n,parentSchema:_,it:A}=x;void 0===_.then&&void 0===_.else&&(0,t.checkStrictMode)(A,'"if" without "then" and "else" is ignored');let s=r(A,"then"),i=r(A,"else");if(!s&&!i)return;let o=n.let("valid",!0),l=n.name("_valid");if(a=x.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l),x.mergeEvaluated(a),x.reset(),s&&i){let e=n.let("ifClause");x.setParams({ifClause:e}),n.if(l,c("then",e),c("else",e))}else s?n.if(l,c("then")):n.if((0,e.not)(l),c("else"));function c(t,r){return()=>{let a=x.subschema({keyword:t},l);n.assign(o,l),x.mergeValidEvaluated(a,o),r?n.assign(r,(0,e._)`${t}`):x.setParams({ifClause:t})}}x.pass(o,()=>x.error(!0))}}}),pL=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uQ();x.default={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:x,parentSchema:t,it:r}){void 0===t.if&&(0,e.checkStrictMode)(r,`"${x}" without "if" is ignored`)}}}),pq=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=ph(),t=pj(),r=pE(),a=pg(),n=py(),_=pS(),A=pI(),s=pN(),i=pB(),o=pF(),l=pw(),c=pC(),v=pP(),d=pk(),f=pD(),b=pL();x.default=function(x=!1){let u=[l.default,c.default,v.default,d.default,f.default,b.default,A.default,s.default,_.default,i.default,o.default];return x?u.push(t.default,a.default):u.push(e.default,r.default),u.push(n.default),u}}),pT=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK();x.default={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:x})=>(0,e.str)`must match format "${x}"`,params:({schemaCode:x})=>(0,e._)`{format: ${x}}`},code(x,t){let r,a,n,_,A,s,{gen:i,data:o,$data:l,schema:c,schemaCode:v,it:d}=x,{opts:f,errSchemaPath:b,schemaEnv:u,self:p}=d;f.validateFormats&&(l?(r=i.scopeValue("formats",{ref:p.formats,code:f.code.formats}),a=i.const("fDef",(0,e._)`${r}[${v}]`),n=i.let("fType"),_=i.let("format"),i.if((0,e._)`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>i.assign(n,(0,e._)`${a}.type || "string"`).assign(_,(0,e._)`${a}.validate`),()=>i.assign(n,(0,e._)`"string"`).assign(_,a)),x.fail$data((0,e.or)(!1===f.strictSchema?e.nil:(0,e._)`${v} && !${_}`,(A=u.$async?(0,e._)`(${a}.async ? await ${_}(${o}) : ${_}(${o}))`:(0,e._)`${_}(${o})`,s=(0,e._)`(typeof ${_} == "function" ? ${A} : ${_}.test(${o}))`,(0,e._)`${_} && ${_} !== true && ${n} === ${t} && !${s}`)))):function(){var r;let a,n,_=p.formats[c];if(!_){if(!1===f.strictSchema)return p.logger.warn(A());throw Error(A());function A(){return`unknown format "${c}" ignored in schema at path "${b}"`}}if(!0===_)return;let[s,l,v]=(a=(r=_)instanceof RegExp?(0,e.regexpCode)(r):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(c)}`:void 0,n=i.scopeValue("formats",{key:c,ref:r,code:a}),"object"!=typeof r||r instanceof RegExp?["string",r,n]:[r.type||"string",r.validate,(0,e._)`${n}.validate`]);s===t&&x.pass(function(){if("object"==typeof _&&!(_ instanceof RegExp)&&_.async){if(!u.$async)throw Error("async format in sync schema");return(0,e._)`await ${v}(${o})`}return"function"==typeof l?(0,e._)`${v}(${o})`:(0,e._)`${v}.test(${o})`}())}())}}}),pR=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default=[pT().default]}),p$=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.contentVocabulary=x.metadataVocabulary=void 0,x.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],x.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),pG=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p_(),t=pm(),r=pq(),a=pR(),n=p$();x.default=[e.default,t.default,(0,r.default)(),a.default,n.metadataVocabulary,n.contentVocabulary]}),pO=fR(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.DiscrError=void 0,(t=e||(x.DiscrError=e={})).Tag="tag",t.Mapping="mapping"}),pX=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=pO(),r=u7(),a=u5(),n=uQ();x.default={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:x,tagName:e}})=>x===t.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:x,tag:t,tagName:r}})=>(0,e._)`{error: ${x}, tag: ${r}, tagValue: ${t}}`},code(x){let{gen:_,data:A,schema:s,parentSchema:i,it:o}=x,{oneOf:l}=i;if(!o.opts.discriminator)throw Error("discriminator: requires discriminator option");let c=s.propertyName;if("string"!=typeof c)throw Error("discriminator: requires propertyName");if(s.mapping)throw Error("discriminator: mapping is not supported");if(!l)throw Error("discriminator: requires oneOf keyword");let v=_.let("valid",!1),d=_.const("tag",(0,e._)`${A}${(0,e.getProperty)(c)}`);_.if((0,e._)`typeof ${d} == "string"`,()=>(function(){let A=function(){var x;let e={},t=A(i),_=!0;for(let e=0;e<l.length;e++){let i=l[e];if((null==i?void 0:i.$ref)&&!(0,n.schemaHasRulesButRef)(i,o.self.RULES)){let x=i.$ref;if((i=r.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,x))instanceof r.SchemaEnv&&(i=i.schema),void 0===i)throw new a.default(o.opts.uriResolver,o.baseId,x)}let v=null==(x=null==i?void 0:i.properties)?void 0:x[c];if("object"!=typeof v)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(t||A(i)),function(x,e){if(x.const)s(x.const,e);else if(x.enum)for(let t of x.enum)s(t,e);else throw Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}(v,e)}if(!_)throw Error(`discriminator: "${c}" must be required`);return e;function A({required:x}){return Array.isArray(x)&&x.includes(c)}function s(x,t){if("string"!=typeof x||x in e)throw Error(`discriminator: "${c}" values must be unique strings`);e[x]=t}}();for(let t in _.if(!1),A)_.elseIf((0,e._)`${d} === ${t}`),_.assign(v,function(t){let r=_.name("valid"),a=x.subschema({keyword:"oneOf",schemaProp:t},r);return x.mergeEvaluated(a,e.Name),r}(A[t]));_.else(),x.error(!1,{discrError:t.DiscrError.Mapping,tag:d,tagName:c}),_.endIf()})(),()=>x.error(!1,{discrError:t.DiscrError.Tag,tag:d,tagName:c})),x.ok(v)}}}),pK=fR((x,e)=>{e.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),pQ=fR((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv=void 0;let t=pr(),r=pG(),a=pX(),n=pK(),_=["/properties"],A="http://json-schema.org/draft-07/schema";var s=class extends t.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(x=>this.addVocabulary(x)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let x=this.opts.$data?this.$dataMetaSchema(n,_):n;this.addMetaSchema(x,A,!1),this.refs["http://json-schema.org/schema"]=A}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(A)?A:void 0)}};x.Ajv=s,e.exports=x=s,e.exports.Ajv=s,Object.defineProperty(x,"__esModule",{value:!0}),x.default=s;var i=u6();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return i.KeywordCxt}});var o=uK();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return o.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return o.CodeGen}});var l=u4();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return l.default}});var c=u5();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return c.default}})}),pM=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.dynamicAnchor=void 0;let e=uK(),t=uM(),r=u7(),a=pn();function n(x,n){let{gen:_,it:A}=x;A.schemaEnv.root.dynamicAnchors[n]=!0;let s=(0,e._)`${t.default.dynamicAnchors}${(0,e.getProperty)(n)}`,i="#"===A.errSchemaPath?A.validateName:function(x){let{schemaEnv:e,schema:t,self:n}=x.it,{root:_,baseId:A,localRefs:s,meta:i}=e.root,{schemaId:o}=n.opts,l=new r.SchemaEnv({schema:t,schemaId:o,root:_,baseId:A,localRefs:s,meta:i});return r.compileSchema.call(n,l),(0,a.getValidate)(x,l)}(x);_.if((0,e._)`!${s}`,()=>_.assign(s,i))}x.dynamicAnchor=n,x.default={keyword:"$dynamicAnchor",schemaType:"string",code:x=>n(x,x.schema)}}),pZ=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.dynamicRef=void 0;let e=uK(),t=uM(),r=pn();function a(x,a){let{gen:n,keyword:_,it:A}=x;if("#"!==a[0])throw Error(`"${_}" only supports hash fragment reference`);let s=a.slice(1);if(A.allErrors)i();else{let e=n.let("valid",!1);i(e),x.ok(e)}function i(x){if(A.schemaEnv.root.dynamicAnchors[s]){let r=n.let("_v",(0,e._)`${t.default.dynamicAnchors}${(0,e.getProperty)(s)}`);n.if(r,o(r,x),o(A.validateName,x))}else o(A.validateName,x)()}function o(e,t){return t?()=>n.block(()=>{(0,r.callRef)(x,e),n.let(t,!0)}):()=>(0,r.callRef)(x,e)}}x.dynamicRef=a,x.default={keyword:"$dynamicRef",schemaType:"string",code:x=>a(x,x.schema)}}),pJ=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pM(),t=uQ();x.default={keyword:"$recursiveAnchor",schemaType:"boolean",code(x){x.schema?(0,e.dynamicAnchor)(x,""):(0,t.checkStrictMode)(x.it,"$recursiveAnchor: false is ignored")}}}),pV=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pZ();x.default={keyword:"$recursiveRef",schemaType:"string",code:x=>(0,e.dynamicRef)(x,x.schema)}}),pH=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pM(),t=pZ(),r=pJ(),a=pV();x.default=[e.default,t.default,r.default,a.default]}),pU=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pS();x.default={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:x=>(0,e.validatePropertyDeps)(x)}}),pY=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pS();x.default={keyword:"dependentSchemas",type:"object",schemaType:"object",code:x=>(0,e.validateSchemaDeps)(x)}}),pz=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uQ();x.default={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:x,parentSchema:t,it:r}){void 0===t.contains&&(0,e.checkStrictMode)(r,`"${x}" without "contains" is ignored`)}}}),pW=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pU(),t=pY(),r=pz();x.default=[e.default,t.default,r.default]}),p0=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ(),r=uM();x.default={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:x})=>(0,e._)`{unevaluatedProperty: ${x.unevaluatedProperty}}`},code(x){let{gen:a,schema:n,data:_,errsCount:A,it:s}=x;if(!A)throw Error("ajv implementation error");let{allErrors:i,props:o}=s;function l(r){if(!1===n){x.setParams({unevaluatedProperty:r}),x.error(),i||a.break();return}if(!(0,t.alwaysValidSchema)(s,n)){let n=a.name("valid");x.subschema({keyword:"unevaluatedProperties",dataProp:r,dataPropType:t.Type.Str},n),i||a.if((0,e.not)(n),()=>a.break())}}o instanceof e.Name?a.if((0,e._)`${o} !== true`,()=>a.forIn("key",_,x=>{var t,r;return a.if((t=o,r=x,(0,e._)`!${t} || !${t}[${r}]`),()=>l(x))})):!0!==o&&a.forIn("key",_,x=>void 0===o?l(x):a.if(function(x,t){let r=[];for(let a in x)!0===x[a]&&r.push((0,e._)`${t} !== ${a}`);return(0,e.and)(...r)}(o,x),()=>l(x))),s.props=!0,x.ok((0,e._)`${A} === ${r.default.errors}`)}}}),p1=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uK(),t=uQ();x.default={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{gen:r,schema:a,data:n,it:_}=x,A=_.items||0;if(!0===A)return;let s=r.const("len",(0,e._)`${n}.length`);if(!1===a)x.setParams({len:A}),x.fail((0,e._)`${s} > ${A}`);else if("object"==typeof a&&!(0,t.alwaysValidSchema)(_,a)){let a=r.var("valid",(0,e._)`${s} <= ${A}`);r.if((0,e.not)(a),()=>{var n,i;return n=a,i=A,void r.forRange("i",i,s,a=>{x.subschema({keyword:"unevaluatedItems",dataProp:a,dataPropType:t.Type.Num},n),_.allErrors||r.if((0,e.not)(n),()=>r.break())})}),x.ok(a)}_.items=!0}}}),p2=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p0(),t=p1();x.default=[e.default,t.default]}),p3=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}}),p6=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}}),p4=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}}),p5=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}}),p7=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}}),p8=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),p9=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),mx=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p3(),t=p6(),r=p4(),a=p5(),n=p7(),_=p8(),A=p9(),s=["/properties"];x.default=function(x){return[e,t,r,a,i(this,n),_,i(this,A)].forEach(x=>this.addMetaSchema(x,void 0,!1)),this;function i(e,t){return x?e.$dataMetaSchema(t,s):t}}}),me=fR((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv2019=void 0;let t=pr(),r=pG(),a=pH(),n=pW(),_=p2(),A=pX(),s=mx(),i="https://json-schema.org/draft/2019-09/schema";var o=class extends t.default{constructor(x={}){super({...x,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(a.default),r.default.forEach(x=>this.addVocabulary(x)),this.addVocabulary(n.default),this.addVocabulary(_.default),this.opts.discriminator&&this.addKeyword(A.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:x,meta:e}=this.opts;e&&(s.default.call(this,x),this.refs["http://json-schema.org/schema"]=i)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}};x.Ajv2019=o,e.exports=x=o,e.exports.Ajv2019=o,Object.defineProperty(x,"__esModule",{value:!0}),x.default=o;var l=u6();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var c=uK();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return c._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return c.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return c.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return c.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return c.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return c.CodeGen}});var v=u4();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return v.default}});var d=u5();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return d.default}})}),mt=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p_(),t=pm(),r=pq(),a=pH(),n=pW(),_=p2(),A=pR(),s=p$();x.default=[a.default,e.default,t.default,(0,r.default)(!0),A.default,s.metadataVocabulary,s.contentVocabulary,n.default,_.default]}),mr=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}}),ma=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}),mn=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}),m_=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}),mA=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}),ms=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}),mi=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),mo=fR((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),ml=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=mr(),t=ma(),r=mn(),a=m_(),n=mA(),_=ms(),A=mi(),s=mo(),i=["/properties"];x.default=function(x){return[e,t,r,a,n,o(this,_),A,o(this,s)].forEach(x=>this.addMetaSchema(x,void 0,!1)),this;function o(e,t){return x?e.$dataMetaSchema(t,i):t}}}),mc=fR((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv2020=void 0;let t=pr(),r=mt(),a=pX(),n=ml(),_="https://json-schema.org/draft/2020-12/schema";var A=class extends t.default{constructor(x={}){super({...x,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(x=>this.addVocabulary(x)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:x,meta:e}=this.opts;e&&(n.default.call(this,x),this.refs["http://json-schema.org/schema"]=_)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_)?_:void 0)}};x.Ajv2020=A,e.exports=x=A,e.exports.Ajv2020=A,Object.defineProperty(x,"__esModule",{value:!0}),x.default=A;var s=u6();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return s.KeywordCxt}});var i=uK();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return i.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return i.CodeGen}});var o=u4();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return o.default}});var l=u5();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return l.default}})}),mv=fR(x=>{function e(x,e){return{validate:x,compare:e}}Object.defineProperty(x,"__esModule",{value:!0}),x.formatNames=x.fastFormats=x.fullFormats=void 0,x.fullFormats={date:e(a,n),time:e(A(!0),s),"date-time":e(l(!0),c),"iso-time":e(A(),i),"iso-date-time":e(l(),v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(x){return d.test(x)&&f.test(x)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(x){if(h.test(x))return!1;try{return new RegExp(x),!0}catch(x){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(x){return b.lastIndex=0,b.test(x)},int32:{type:"number",validate:function(x){return Number.isInteger(x)&&x<=p&&x>=u}},int64:{type:"number",validate:function(x){return Number.isInteger(x)}},float:{type:"number",validate:m},double:{type:"number",validate:m},password:!0,binary:!0},x.fastFormats={...x.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,n),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,s),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,i),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,v),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},x.formatNames=Object.keys(x.fullFormats);let t=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(x){var e;let a=t.exec(x);if(!a)return!1;let n=+a[1],_=+a[2],A=+a[3];return _>=1&&_<=12&&A>=1&&A<=(2===_&&(e=n)%4==0&&(e%100!=0||e%400==0)?29:r[_])}function n(x,e){if(x&&e)return x>e?1:x<e?-1:0}let _=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function A(x){return function(e){let t=_.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],n=+t[3],A=t[4],s="-"===t[5]?-1:1,i=+(t[6]||0),o=+(t[7]||0);if(i>23||o>59||x&&!A)return!1;if(r<=23&&a<=59&&n<60)return!0;let l=a-o*s,c=r-i*s-(l<0);return(23===c||-1===c)&&(59===l||-1===l)&&n<61}}function s(x,e){if(!(x&&e))return;let t=new Date("2020-01-01T"+x).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(t&&r)return t-r}function i(x,e){if(!(x&&e))return;let t=_.exec(x),r=_.exec(e);if(t&&r)return(x=t[1]+t[2]+t[3])>(e=r[1]+r[2]+r[3])?1:x<e?-1:0}let o=/t|\s/i;function l(x){let e=A(x);return function(x){let t=x.split(o);return 2===t.length&&a(t[0])&&e(t[1])}}function c(x,e){if(!(x&&e))return;let t=new Date(x).valueOf(),r=new Date(e).valueOf();if(t&&r)return t-r}function v(x,e){if(!(x&&e))return;let[t,r]=x.split(o),[a,_]=e.split(o),A=n(t,a);if(void 0!==A)return A||s(r,_)}let d=/\/|:/,f=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,b=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,u=-0x80000000,p=0x80000000-1;function m(){return!0}let h=/[^\\]\\Z/}),md=fR(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.formatLimitDefinition=void 0;let e=pQ(),t=uK(),r=t.operators,a={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}};x.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:{message:({keyword:x,schemaCode:e})=>(0,t.str)`should be ${a[x].okStr} ${e}`,params:({keyword:x,schemaCode:e})=>(0,t._)`{comparison: ${a[x].okStr}, limit: ${e}}`},code(x){let r,n,{gen:_,data:A,schemaCode:s,keyword:i,it:o}=x,{opts:l,self:c}=o;if(!l.validateFormats)return;let v=new e.KeywordCxt(o,c.RULES.all.format.definition,"format");function d(x){return(0,t._)`${x}.compare(${A}, ${s}) ${a[i].fail} 0`}v.$data?(r=_.scopeValue("formats",{ref:c.formats,code:l.code.formats}),n=_.const("fmt",(0,t._)`${r}[${v.schemaCode}]`),x.fail$data((0,t.or)((0,t._)`typeof ${n} != "object"`,(0,t._)`${n} instanceof RegExp`,(0,t._)`typeof ${n}.compare != "function"`,d(n)))):function(){let e=v.schema,r=c.formats[e];if(!r||!0===r)return;if("object"!=typeof r||r instanceof RegExp||"function"!=typeof r.compare)throw Error(`"${i}": format "${e}" does not define "compare" function`);let a=_.scopeValue("formats",{key:e,ref:r,code:l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(e)}`:void 0});x.fail$data(d(a))}()},dependencies:["format"]},x.default=e=>(e.addKeyword(x.formatLimitDefinition),e)}),mf=fR((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0});let t=mv(),r=md(),a=uK(),n=new a.Name("fullFormats"),_=new a.Name("fastFormats"),A=(x,e={keywords:!0})=>{if(Array.isArray(e))return s(x,e,t.fullFormats,n),x;let[a,A]="fast"===e.mode?[t.fastFormats,_]:[t.fullFormats,n];return s(x,e.formats||t.formatNames,a,A),e.keywords&&(0,r.default)(x),x};function s(x,e,t,r){var n;for(let _ of(null!=(n=x.opts.code).formats||(n.formats=(0,a._)`require("ajv-formats/dist/formats").${r}`),e))x.addFormat(_,t[_])}A.get=(x,e="full")=>{let r=("fast"===e?t.fastFormats:t.fullFormats)[x];if(!r)throw Error(`Unknown format "${x}"`);return r},e.exports=x=A,Object.defineProperty(x,"__esModule",{value:!0}),x.default=A}),mb=pQ(),mu=me(),mp=mc();let mm=f$(mf(),1).default;function mh(x){let e=new x({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return mm(e),e}var mE=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(x){this._userAjv=void 0!==x,this._ajv=x}get ajv(){return this._ajv??=mh(mp.Ajv2020)}_engineFor(x){if(this._userAjv)return this.ajv;let e=function(x,e){if(!("$schema"in x)||"string"!=typeof x.$schema)return"2020-12";let t=x.$schema.replace(/#$/,"");if(fG.has(t))return"2020-12";if(fO.has(t))return"2019-09";if(fX.has(t)||fK.has(t))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${x.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${e}`)}(x,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return"2020-12"===e?this.ajv:"2019-09"===e?this._ajv2019??=mh(mu.Ajv2019):this._ajvDraft7??=mh(mb.Ajv)}getValidator(x){let e=this._engineFor(x),t="$id"in x&&"string"==typeof x.$id?e.getSchema(x.$id)??e.compile(x):e.compile(x);return x=>t(x)?{valid:!0,data:x,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:e.errorsText(t.errors)}}};mb.Ajv;let mj=Symbol.for("mcp.completable");function mg(x){return!!x&&"object"==typeof x&&mj in x}let my=0x80000000-1;function mS(x,e){if(!Number.isFinite(x)||x<1)return;let t=setInterval(e,Math.min(x,my));return t.unref?.(),t}var mI=class{_listeners=new Set;constructor(x){this.onerror=x}publish(x){for(let e of this._listeners)try{e(x)}catch(x){this.onerror?.(x instanceof Error?x:Error(String(x)))}}subscribe(x){this._listeners.add(x);let e=!0;return()=>{e&&(e=!1,this._listeners.delete(x))}}get listenerCount(){return this._listeners.size}};function mN(x,e,t){return Response.json({jsonrpc:"2.0",error:{code:e,message:t},id:x},{status:200})}function mB(x,e){return{method:x.method,params:{...x.params,_meta:{...x.params?._meta,[x2]:e}}}}function mF(x,e,t){if(null===t||"object"!=typeof t||"string"!=typeof t.method)throw new bp(bu.InternalError,`Handler for ${x} returned an invalid input request '${e}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=function(x){switch(x.method){case"elicitation/create":if(x.params?.mode==="url")return{elicitation:{url:{}}};return{elicitation:{form:{}}};case"sampling/createMessage":{let e=x.params;if(void 0!==e&&(void 0!==e.tools||void 0!==e.toolChoice))return{sampling:{tools:{}}};return{sampling:{}}}case"roots/list":return{roots:{}};default:return}}(t);if(void 0===r)throw new bp(bu.InternalError,`Handler for ${x} returned an input request '${e}' of kind '${t.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:t,required:r}}function mw(x,e){if("tools/call"===x)return{content:[{type:"text",text:e}],isError:!0};throw new bp(bu.InternalError,e)}var mC=class{constructor(x){this._host=x}async fulfill(x,e,t,r,a){let{maxRounds:n,roundTimeoutMs:_}=this._host,A=r.mcpReq.signal,s=a,i=0;for(;;){let a;if((i+=1)>n)return mw(x,`Multi-round-trip request '${x}' still required input after ${n} rounds (inputRequired.maxRounds)`);let o=s.inputRequests,l=null!=o&&Object.keys(o).length>0,c="string"==typeof s.requestState?s.requestState:void 0;if(!l&&void 0===c)throw new bp(bu.InternalError,`Handler for ${x} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let e=this._host.resolvedClientCapabilities(r),t=[];for(let[r,a]of Object.entries(o)){let{embedded:n,required:_}=mF(x,r,a);if("roots/list"!==n.method&&void 0===n.params)throw new bp(bu.InternalError,`Handler for ${x} returned an input request '${r}' of kind '${n.method}' without params`);if(void 0!==fY(_,e))return mw(x,`Cannot request input '${r}' (${n.method}): the client on this 2025-era connection did not declare the required capability${void 0===e?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);t.push([r,n])}let n=function(x){let e=new AbortController,t=()=>e.abort(x?.reason);return x?.addEventListener("abort",t,{once:!0}),x?.aborted&&e.abort(x.reason),{signal:e.signal,abort:x=>e.abort(x),dispose:()=>x?.removeEventListener("abort",t)}}(A);try{let x={relatedRequestId:r.mcpReq.id,timeout:_,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:n.signal},e=await Promise.all(t.map(async([e,t])=>{try{return[e,await this._dispatchLeg(t,x)]}catch(x){throw n.abort(x),x}}));a=Object.fromEntries(e)}catch(e){if(A.aborted)throw e;return mw(x,`Fulfilling input required by '${x}' failed: ${e instanceof Error?e.message:String(e)}`)}finally{n.dispose()}}else await function(x){return new Promise((e,t)=>{if(x?.aborted)return void t(x.reason instanceof fV?x.reason:new fV(fJ.RequestTimeout,String(x.reason)));let r=setTimeout(()=>{x?.removeEventListener("abort",a),e()},250),a=()=>{clearTimeout(r),t(x?.reason instanceof fV?x.reason:new fV(fJ.RequestTimeout,String(x?.reason)))};x?.addEventListener("abort",a,{once:!0})})}(A);let v={...r,mcpReq:{...r.mcpReq,inputResponses:a,droppedInputResponseKeys:void 0,requestState:function(x){return()=>x}(c)}};if(void 0!==c){let e=await this._host.verifyRequestState(c,v,x);void 0!==e&&(v=uC(v,e))}let d=await e(t,v);if(!bW(d))return d;s=d}}async _dispatchLeg(x,e){switch(x.method){case"elicitation/create":{let t=x.params;return"url"===t.mode&&void 0===t.elicitationId&&(t={...t,elicitationId:function(){let x=globalThis.crypto;if(x?.randomUUID!==void 0)return x.randomUUID();let e=new Uint8Array(16);x.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;let t=[...e].map(x=>x.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}()}),await this._host.sendElicitation(t,e)}case"sampling/createMessage":return await this._host.sendSampling(x.params,e);case"roots/list":return await this._host.listRoots(x.params,e)}}};let mP=new Set(["tools/call","prompts/get","resources/read"]);var mk=class extends uP{_clientCapabilities;_clientVersion;static{i=(x,e)=>{void 0!==e.clientCapabilities&&(x._clientCapabilities=e.clientCapabilities),void 0!==e.clientInfo&&(x._clientVersion=e.clientInfo)},o=(x,e)=>{let t=e.filter(e=>!x._supportedProtocolVersions.includes(e));t.length>0&&(x._supportedProtocolVersions=[...x._supportedProtocolVersions,...t]),x.setRequestHandler("server/discover",()=>x._ondiscover())},l=x=>x._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new mC({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:x=>this._inputRequestCapabilityView(x),verifyRequestState:(x,e,t)=>this._verifyRequestState(x,e,t),sendElicitation:(x,e)=>this._sendElicitationLeg(x,e,{validateAcceptedContent:!1}),sendSampling:(x,e)=>this.createMessage(x,e),listRoots:(x,e)=>this.listRoots(x,e)})}oninitialized;constructor(x,e){if(super(e),this._serverInfo=x,this._capabilities=e?.capabilities?{...e.capabilities}:{},this._instructions=e?.instructions,this._jsonSchemaValidator=e?.jsonSchemaValidator??new mE,this._requestStateVerify=e?.requestState?.verify,this._inputRequiredServing=function(x){if(x?.maxRounds!==void 0&&(!Number.isInteger(x.maxRounds)||x.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${x.maxRounds})`);if(x?.roundTimeoutMs!==void 0&&(!Number.isFinite(x.roundTimeoutMs)||x.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${x.roundTimeoutMs})`);return{maxRounds:x?.maxRounds??8,roundTimeoutMs:x?.roundTimeoutMs??6e5,legacyShim:x?.legacyShim??!0}}(e?.inputRequired),e?.cacheHints!==void 0){for(let[x,t]of Object.entries(e.cacheHints))void 0!==t&&bb(t,`cacheHints['${x}']`);this._cacheHints=e.cacheHints}this.setRequestHandler("initialize",x=>this._oninitialize(x)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),f0(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(x,e)=>{let t=e.sessionId||e.http?.req?.headers.get("mcp-session-id")||void 0,{level:r}=x.params,a=rr(tc,r);return a.success&&this._loggingLevels.set(t,a.data),{}})}buildContext(x,e){let t=x.http||e?.request||e?.closeSSEStream||e?.closeStandaloneSSEStream;return{...x,mcpReq:{...x.mcpReq,log:(e,t,r)=>{let a;if(!this._capabilities.logging)return Promise.resolve();if(this._servedModernEra()){if(void 0===(a=x.mcpReq.envelope?.[t$]))return Promise.resolve()}else a=this._loggingLevels.get(x.sessionId)??this._loggingLevels.get(void 0);return void 0!==a&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():x.mcpReq.notify({method:"notifications/message",params:{level:e,data:t,logger:r}})},elicitInput:(x,e)=>this.elicitInput(x,e),requestSampling:(x,e)=>this.createMessage(x,e)},http:t?{...x.http,req:e?.request,closeSSE:e?.closeSSEStream,closeStandaloneSSE:e?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(tc.options.map((x,e)=>[x,e]));isMessageIgnored=(x,e)=>{let t=this._loggingLevels.get(e);return!!t&&this.LOG_LEVEL_SEVERITY.get(x)<this.LOG_LEVEL_SEVERITY.get(t)};registerCapabilities(x){if(this.transport)throw new fV(fJ.AlreadyConnected,"Cannot register capabilities after connecting to transport");let e=!!this._capabilities.logging;this._capabilities=function(x,e){let t={...x};for(let x in e){let r=e[x];if(void 0===r)continue;let a=t[x];t[x]=uk(a)&&uk(r)?{...a,...r}:r}return t}(this._capabilities,x),!e&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(x,e){if("tools/call"!==x){let t=this._cacheHints?.[x],r=mP.has(x);return void 0!==t||r?async(a,n)=>{let _=r?await this._invokeInputRequiredCapableHandler(x,e,a,n):await e(a,n);if(bW(_)){if(!r)throw new bp(bu.InternalError,`Handler for ${x} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return _}return void 0===t?_:bv(_,t)}:async(t,r)=>{let a=await e(t,r);if(bW(a))throw new bp(bu.InternalError,`Handler for ${x} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}}return async(x,t)=>{let r=bR(this._negotiatedProtocolVersion),a=r.validateRequest("tools/call",x);if(!a.ok)throw new bp("not-in-era"===a.reason?bu.InternalError:bu.InvalidParams,"not-in-era"===a.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let n=await this._invokeInputRequiredCapableHandler("tools/call",e,x,t);if(bW(n))return n;let _=f3(n),A=r.validateResult("tools/call",_);if(!A.ok)throw new bp("not-in-era"===A.reason?bu.InternalError:bu.InvalidParams,"not-in-era"===A.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${A.message}`);return A.value}}_servedModernEra(){return void 0!==this._negotiatedProtocolVersion&&this._negotiatedProtocolVersion>=fz}async _invokeInputRequiredCapableHandler(x,e,t,r){let a,n=this._servedModernEra(),_=r.mcpReq.requestState();if(void 0!==_&&"string"!=typeof _)throw new bp(bu.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let A=r;if("string"==typeof _){let e=await this._verifyRequestState(_,r,x);void 0!==e&&(A=uC(r,e))}try{a=await e(t,A)}catch(x){if(x instanceof bp&&x.code===bu.UrlElicitationRequired){if(!n)throw x;throw new bp(bu.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`)}throw x}if(!bW(a))return a;if(!n){if(!this._inputRequiredServing.legacyShim)throw new bp(bu.InternalError,`Handler for ${x} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??t3}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(x,e,t,A,a)}let s=a.inputRequests,i=null!=s&&Object.keys(s).length>0,o="string"==typeof a.requestState;if(!i&&!o)throw new bp(bu.InternalError,`Handler for ${x} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(i){let e=this._inputRequestCapabilityView(r);for(let[t,r]of Object.entries(s)){let{embedded:a,required:n}=mF(x,t,r),_=fY(n,e);if(void 0!==_)throw new bj({requiredCapabilities:_},`Cannot request input '${t}' (${a.method}): the request's client capabilities do not declare the required capability`)}}return a}async _verifyRequestState(x,e,t){if(void 0!==this._requestStateVerify)try{return await this._requestStateVerify(x,e)}catch(x){throw this.onerror?.(Error(`requestState verification rejected ${t}: ${x instanceof Error?x.message:String(x)}`)),new bp(bu.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(x){return this._servedModernEra()?x.mcpReq.envelope?.[ef]:this._clientCapabilities}_assertPushApiInServedEra(x){if(this._servedModernEra())throw new fV(fJ.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${x}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:x,era:"2026-07-28"})}assertCapabilityForMethod(x){switch(x){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new fV(fJ.CapabilityNotSupported,`Client does not support sampling (required for ${x})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new fV(fJ.CapabilityNotSupported,`Client does not support elicitation (required for ${x})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new fV(fJ.CapabilityNotSupported,`Client does not support listing roots (required for ${x})`)}}assertNotificationCapability(x){switch(x){case"notifications/message":if(!this._capabilities.logging)throw new fV(fJ.CapabilityNotSupported,`Server does not support logging (required for ${x})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new fV(fJ.CapabilityNotSupported,`Server does not support notifying about resources (required for ${x})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new fV(fJ.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${x})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new fV(fJ.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${x})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new fV(fJ.CapabilityNotSupported,`Client does not support URL elicitation (required for ${x})`)}}assertRequestHandlerCapability(x){switch(x){case"completion/complete":if(!this._capabilities.completions)throw new fV(fJ.CapabilityNotSupported,`Server does not support completions (required for ${x})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new fV(fJ.CapabilityNotSupported,`Server does not support logging (required for ${x})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new fV(fJ.CapabilityNotSupported,`Server does not support prompts (required for ${x})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new fV(fJ.CapabilityNotSupported,`Server does not support resources (required for ${x})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new fV(fJ.CapabilityNotSupported,`Server does not support tools (required for ${x})`)}}async _oninitialize(x){let e=x.params.protocolVersion;this._clientCapabilities=x.params.capabilities,this._clientVersion=x.params.clientInfo;let t=this._supportedProtocolVersions.filter(x=>!(x>=fz)),r=t.includes(e)?e:t[0]??t3;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:f0(this._supportedProtocolVersions),capabilities:{...this.getCapabilities()},...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(x,e){return this._wireCodec().projectCallToolResult(x,e)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(x,e){if(this._assertPushApiInServedEra("sampling/createMessage"),(x.tools||x.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new fV(fJ.CapabilityNotSupported,"Client does not support sampling tools capability.");if(x.messages.length>0){let e=x.messages.at(-1),t=Array.isArray(e.content)?e.content:[e.content],r=t.some(x=>"tool_result"===x.type),a=x.messages.length>1?x.messages.at(-2):void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],_=n.some(x=>"tool_use"===x.type);if(r){if(t.some(x=>"tool_result"!==x.type))throw new bp(bu.InvalidParams,"The last message must contain only tool_result content if any is present");if(!_)throw new bp(bu.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(_){let x=new Set(n.filter(x=>"tool_use"===x.type).map(x=>x.id)),e=new Set(t.filter(x=>"tool_result"===x.type).map(x=>x.toolUseId));if(x.size!==e.size||![...x].every(x=>e.has(x)))throw new bp(bu.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let t=!!(x.tools||x.toolChoice),r=await this.request({method:"sampling/createMessage",params:x},e),a=this._wireCodec().samplingResultVariant(t,r);if(!a.ok)throw new fV(fJ.InvalidResult,`Invalid sampling/createMessage result: ${"invalid"===a.reason?a.message:a.reason}`);return a.value}async elicitInput(x,e){switch(this._assertPushApiInServedEra("elicitation/create"),x.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new fV(fJ.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new fV(fJ.CapabilityNotSupported,"Client does not support form elicitation.")}return this._sendElicitationLeg(x,e)}async _sendElicitationLeg(x,e,t){let r=x.mode??"form",a=t?.validateAcceptedContent??!0;switch(r){case"url":return this.request({method:"elicitation/create",params:x},e);case"form":{let t="form"===x.mode?x:{...x,mode:"form"},r=await this.request({method:"elicitation/create",params:t},e);if(a&&"accept"===r.action&&r.content&&t.requestedSchema)try{let x=this._jsonSchemaValidator.getValidator(t.requestedSchema)(r.content);if(!x.valid)throw new bp(bu.InvalidParams,`Elicitation response content does not match requested schema: ${x.errorMessage}`)}catch(x){if(x instanceof bp)throw x;throw new bp(bu.InternalError,`Error validating elicitation response: ${x instanceof Error?x.message:String(x)}`)}return r}}}createElicitationCompletionNotifier(x,e){if(!this._clientCapabilities?.elicitation?.url)throw new fV(fJ.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:x}},e)}async listRoots(x,e){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:x},e)}async sendLoggingMessage(x,e){if(this._capabilities.logging&&!this.isMessageIgnored(x.level,e))return this.notification({method:"notifications/message",params:x})}async sendResourceUpdated(x){return this.notification({method:"notifications/resources/updated",params:x})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},mD=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(x){let e=this._registeredTools[x];if(void 0!==e&&e.enabled){if(Object.hasOwn(this._toolInputSchemaJson,x))return this._toolInputSchemaJson[x];if(void 0===e.inputSchema)return mq;try{let t=uv(e.inputSchema,"input");return this._toolInputSchemaJson[x]=t,t}catch{return}}}constructor(x,e){this.server=new mk(x,e),e?.capabilities?.tools&&this.setToolRequestHandlers(),e?.capabilities?.resources&&this.setResourceRequestHandlers(),e?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(x){return await this.server.connect(x)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,x])=>x.enabled).map(([x,e])=>{let t={name:x,title:e.title,description:e.description,inputSchema:e.inputSchema?uv(e.inputSchema,"input"):mq,annotations:e.annotations,icons:e.icons,execution:e.execution,_meta:e._meta};return e.outputSchema&&(t.outputSchema=uv(e.outputSchema,"output")),t})})),this.server.setRequestHandler("tools/call",async(x,e)=>{let t=this._registeredTools[x.params.name];if(!t)throw new bp(bu.InvalidParams,`Tool ${x.params.name} not found`);if(!t.enabled)throw new bp(bu.InvalidParams,`Tool ${x.params.name} disabled`);try{let r=await this.validateToolInput(t,x.params.arguments,x.params.name),a=await this.executeToolHandler(t,r,e);if(await this.validateToolOutput(t,a,x.params.name),bW(a))return a;return this.server.projectCallToolResult(a,t.outputSchemaJson)}catch(x){if(x instanceof bp&&x.code===bu.UrlElicitationRequired)throw x;return this.createToolError(x instanceof Error?x.message:String(x))}}),this._toolHandlersInitialized=!0)}createToolError(x){return{content:[{type:"text",text:x}],isError:!0}}async validateToolInput(x,e,t){if(!x.inputSchema)return;let r=await ud(x.inputSchema,e??{});if(!r.success)throw new bp(bu.InvalidParams,`Input validation error: Invalid arguments for tool ${t}: ${r.error}`);return r.data}async validateToolOutput(x,e,t){if(!x.outputSchema||bW(e)||e.isError)return;if(void 0===e.structuredContent)throw new bp(bu.InvalidParams,`Output validation error: Tool ${t} has an output schema but no structured content was provided`);let r=await ud(x.outputSchema,e.structuredContent);if(!r.success)throw new bp(bu.InvalidParams,`Output validation error: Invalid structured content for tool ${t}: ${r.error}`)}async executeToolHandler(x,e,t){return x.executor(e,t)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async x=>{switch(x.params.ref.type){case"ref/prompt":if("ref/prompt"!==x.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${x.params.ref.type}`);return this.handlePromptCompletion(x,x.params.ref);case"ref/resource":if("ref/resource"!==x.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${x.params.ref.type}`);return this.handleResourceCompletion(x,x.params.ref);default:throw new bp(bu.InvalidParams,`Invalid completion reference: ${x.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(x,e){let t=this._registeredPrompts[e.name];if(!t)throw new bp(bu.InvalidParams,`Prompt ${e.name} not found`);if(!t.enabled)throw new bp(bu.InvalidParams,`Prompt ${e.name} disabled`);if(!t.argsSchema)return mG;let r=mX(mO(t.argsSchema)?.[x.params.argument.name]);if(!mg(r))return mG;let a=r[mj]?.complete;return a?m$(await a(x.params.argument.value,x.params.context)):mG}async handleResourceCompletion(x,e){let t=Object.values(this._registeredResourceTemplates).find(x=>x.resourceTemplate.uriTemplate.toString()===e.uri);if(!t){if(this._registeredResources[e.uri])return mG;throw new bp(bu.InvalidParams,`Resource template ${x.params.ref.uri} not found`)}let r=t.resourceTemplate.completeCallback(x.params.argument.name);return r?m$(await r(x.params.argument.value,x.params.context)):mG}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(x,e)=>{let t=Object.entries(this._registeredResources).filter(([x,e])=>e.enabled).map(([x,e])=>({uri:x,name:e.name,...e.metadata})),r=[];for(let x of Object.values(this._registeredResourceTemplates))if(x.resourceTemplate.listCallback)for(let t of(await x.resourceTemplate.listCallback(e)).resources)r.push({...x.metadata,...t});return{resources:[...t,...r]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([x,e])=>({name:x,uriTemplate:e.resourceTemplate.uriTemplate.toString(),...e.metadata}))})),this.server.setRequestHandler("resources/read",async(x,e)=>{let t;try{t=new URL(x.params.uri)}catch{throw new bp(bu.InvalidParams,`Resource URI ${x.params.uri} is invalid`,{uri:x.params.uri,reason:"invalid_uri"})}let r=this._registeredResources[t.toString()];if(r){if(!r.enabled)throw new bp(bu.InvalidParams,`Resource ${t} disabled`);return bv(await r.readCallback(t,e),r.cacheHint)}for(let x of Object.values(this._registeredResourceTemplates)){let r=x.resourceTemplate.uriTemplate.match(t.toString());if(r)return bv(await x.readCallback(t,r,e),x.cacheHint)}throw new bm(x.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,x])=>x.enabled).map(([x,e])=>{let t,r,a;return{name:x,title:e.title,description:e.description,arguments:e.argsSchema?(r=(t=uv(e.argsSchema,"input")).properties||{},a=t.required||[],Object.entries(r).map(([x,e])=>({name:x,description:e?.description,required:a.includes(x)}))):void 0,icons:e.icons,_meta:e._meta}})})),this.server.setRequestHandler("prompts/get",async(x,e)=>{let t=this._registeredPrompts[x.params.name];if(!t)throw new bp(bu.InvalidParams,`Prompt ${x.params.name} not found`);if(!t.enabled)throw new bp(bu.InvalidParams,`Prompt ${x.params.name} disabled`);return t.handler(x.params.arguments,e)}),this._promptHandlersInitialized=!0)}registerResource(x,e,t,r){let a=t.cacheHint,n=t;if(void 0!==a){bb(a,`resource ${x}`);let e={...t};delete e.cacheHint,n=e}if("string"==typeof e){if(this._registeredResources[e])throw Error(`Resource ${e} is already registered`);let _=this._createRegisteredResource(x,t.title,e,n,r);return void 0!==a&&(_.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),_}{if(this._registeredResourceTemplates[x])throw Error(`Resource template ${x} is already registered`);let _=this._createRegisteredResourceTemplate(x,t.title,e,n,r);return void 0!==a&&(_.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),_}}_createRegisteredResource(x,e,t,r,a){let n={name:x,title:e,metadata:r,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:x=>{void 0!==x.uri&&x.uri!==t&&(delete this._registeredResources[t],x.uri&&(this._registeredResources[x.uri]=n)),void 0!==x.name&&(n.name=x.name),void 0!==x.title&&(n.title=x.title),void 0!==x.metadata&&(n.metadata=x.metadata),void 0!==x.callback&&(n.readCallback=x.callback),void 0!==x.enabled&&(n.enabled=x.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=n,n}_createRegisteredResourceTemplate(x,e,t,r,a){let n={resourceTemplate:t,title:e,metadata:r,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&(delete this._registeredResourceTemplates[x],e.name&&(this._registeredResourceTemplates[e.name]=n)),void 0!==e.title&&(n.title=e.title),void 0!==e.template&&(n.resourceTemplate=e.template),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[x]=n;let _=t.uriTemplate.variableNames;return Array.isArray(_)&&_.some(x=>!!t.completeCallback(x))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(x,e,t,r,a,n,_){let A=r,s=a,i={title:e,description:t,argsSchema:r,icons:n,_meta:_,handler:mR(x,r,a),enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&(delete this._registeredPrompts[x],e.name&&(this._registeredPrompts[e.name]=i)),void 0!==e.title&&(i.title=e.title),void 0!==e.description&&(i.description=e.description),void 0!==e.icons&&(i.icons=e.icons),void 0!==e._meta&&(i._meta=e._meta);let t=!1;void 0!==e.argsSchema&&(i.argsSchema=e.argsSchema,A=e.argsSchema,t=!0),void 0!==e.callback&&(s=e.callback,t=!0),t&&(i.handler=mR(x,A,s)),void 0!==e.enabled&&(i.enabled=e.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[x]=i,r){let x=mO(r);x&&Object.values(x).some(x=>mg(mX(x)))&&this.setCompletionRequestHandler()}return i}_createRegisteredTool(x,e,t,r,a,n,_,A,s,i){if(u$(x),void 0!==r)try{let e=uv(r,"input");this._toolInputSchemaJson[x]=e;let t=b3(e);t.valid||console.warn(`[mcp-sdk] tool '${x}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${t.reason}`)}catch{}let o=i,l={title:e,description:t,inputSchema:r,outputSchema:a,outputSchemaJson:mT(a),annotations:n,icons:_,execution:A,_meta:s,handler:i,executor:mL(r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&("string"==typeof e.name&&u$(e.name),delete this._registeredTools[x],delete this._toolInputSchemaJson[x],e.name&&(delete this._toolInputSchemaJson[e.name],this._registeredTools[e.name]=l,x=e.name)),void 0!==e.title&&(l.title=e.title),void 0!==e.description&&(l.description=e.description);let t=!1;void 0!==e.paramsSchema&&(l.inputSchema=e.paramsSchema,delete this._toolInputSchemaJson[x],t=!0),void 0!==e.callback&&(l.handler=e.callback,o=e.callback,t=!0),t&&(l.executor=mL(l.inputSchema,o)),void 0!==e.outputSchema&&(l.outputSchema=e.outputSchema,l.outputSchemaJson=mT(e.outputSchema)),void 0!==e.annotations&&(l.annotations=e.annotations),void 0!==e.icons&&(l.icons=e.icons),void 0!==e._meta&&(l._meta=e._meta),void 0!==e.enabled&&(l.enabled=e.enabled),this.sendToolListChanged()}};return this._registeredTools[x]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}registerTool(x,e,t){if(this._registeredTools[x])throw Error(`Tool ${x} is already registered`);let{title:r,description:a,inputSchema:n,outputSchema:_,annotations:A,icons:s,_meta:i}=e;return this._createRegisteredTool(x,r,a,uG(n),uG(_),A,s,void 0,i,t)}registerPrompt(x,e,t){if(this._registeredPrompts[x])throw Error(`Prompt ${x} is already registered`);let{title:r,description:a,argsSchema:n,icons:_,_meta:A}=e,s=this._createRegisteredPrompt(x,r,a,uG(n),t,_,A);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(x,e){return this.server.sendLoggingMessage(x,e)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function mL(x,e){return x?async(x,t)=>e(x,t):async(x,t)=>e(t)}let mq={type:"object",properties:{}};function mT(x){if(void 0!==x)try{return uv(x,"output")}catch{return}}function mR(x,e,t){return e?async(r,a)=>{let n=await ud(e,r);if(!n.success)throw new bp(bu.InvalidParams,`Invalid arguments for prompt ${x}: ${n.error}`);return t(n.data,a)}:async(x,e)=>t(e)}function m$(x){return{completion:{values:x.map(String).slice(0,100),total:x.length,hasMore:x.length>100}}}let mG={completion:{values:[],hasMore:!1}};function mO(x){if(x.shape&&"object"==typeof x.shape)return x.shape}function mX(x){return x?.type!=="optional"?x:x.def?.innerType??x}var mK=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(x){this._classification=x.classification,this._responseMode=x.responseMode??"auto",this._keepAliveMs=x.keepAliveMs??15e3}async start(){if(this._started)throw Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(x,e){if(this._used)throw Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||void 0===this.onmessage)throw Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw Error("PerRequestHTTPServerTransport is closed");this._used=!0;let t=e?.request?.signal;if(t?.aborted)throw await this.close(),new fV(fJ.ConnectionClosed,"The request was aborted before it could be handled");let r={classification:this._classification,...e?.request!==void 0&&{request:e.request},...e?.authInfo!==void 0&&{authInfo:e.authInfo}};if(bH(x)){let e,a;this._requestId=x.id;let n=new Promise((x,t)=>{e=x,a=t});if(this._deferredResponse={promise:n,resolve:e,reject:a,settled:!1},void 0!==t){let x=()=>void this.close();t.addEventListener("abort",x,{once:!0}),this._abortCleanup=()=>t.removeEventListener("abort",x)}this._dispatchWindowOpen=!0;try{this.onmessage(x,r)}finally{this._dispatchWindowOpen=!1}return"sse"!==this._responseMode||this._closed||this._deferredResponse.settled||this.upgradeToSse(),n}return this.onmessage(x,r),new Response(null,{status:202})}async send(x,e){if(this._closed)return;let t=bY(x)||bz(x),r=t?x.id:e?.relatedRequestId;if(void 0===this._requestId||void 0===r||r!==this._requestId){t&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(x.id)}`));return}if(t){if(this._terminalDelivered)return;this._terminalDelivered=!0;let e=bz(x)?x.error.code:void 0,t=void 0!==e&&(this._dispatchWindowOpen||e===bu.MissingRequiredClientCapability)?ut[e]:void 0;if(void 0!==t&&void 0===this._sse){this.settleResponse(Response.json(x,{status:t,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(void 0!==this._sse||"sse"===this._responseMode){void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(x),this.finalizeStream();return}this.settleResponse(Response.json(x,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}"json"!==this._responseMode&&(void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(x))}writeCommentFrame(x){if(this._closed||void 0===this._sse||this._sse.closed)return;let e=x.split("\n").map(x=>`: ${x}`).join("\n");this.writeFrame(`${e}
379
+ deps: ${r}}`};let a={keyword:"dependencies",type:"object",schemaType:"object",error:x.error,code(x){let[e,t]=function({schema:x}){let e={},t={};for(let r in x)"__proto__"!==r&&((Array.isArray(x[r])?e:t)[r]=x[r]);return[e,t]}(x);n(x,e),_(x,t)}};function n(x,t=x.schema){let{gen:a,data:_,it:A}=x;if(0===Object.keys(t).length)return;let s=a.let("missing");for(let n in t){let i=t[n];if(0===i.length)continue;let o=(0,r.propertyInData)(a,_,n,A.opts.ownProperties);x.setParams({property:n,depsCount:i.length,deps:i.join(", ")}),A.allErrors?a.if(o,()=>{for(let e of i)(0,r.checkReportMissingProp)(x,e)}):(a.if((0,e._)`${o} && (${(0,r.checkMissingProp)(x,i,s)})`),(0,r.reportMissingProp)(x,s),a.else())}}function _(x,e=x.schema){let{gen:a,data:n,keyword:A,it:s}=x,i=a.name("valid");for(let _ in e)(0,t.alwaysValidSchema)(s,e[_])||(a.if((0,r.propertyInData)(a,n,_,s.opts.ownProperties),()=>{let e=x.subschema({keyword:A,schemaProp:_},i);x.mergeValidEvaluated(e,i)},()=>a.var(i,!0)),x.ok(i))}x.validatePropertyDeps=n,x.validateSchemaDeps=_,x.default=a}),pB=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ();x.default={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:x})=>(0,e._)`{propertyName: ${x.propertyName}}`},code(x){let{gen:r,schema:a,data:n,it:_}=x;if((0,t.alwaysValidSchema)(_,a))return;let A=r.name("valid");r.forIn("key",n,t=>{x.setParams({propertyName:t}),x.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},A),r.if((0,e.not)(A),()=>{x.error(!0),_.allErrors||r.break()})}),x.ok(A)}}}),pF=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u0(),t=uM(),r=uJ(),a=uZ();x.default={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:x})=>(0,t._)`{additionalProperty: ${x.additionalProperty}}`},code(x){let{gen:n,schema:_,parentSchema:A,data:s,errsCount:i,it:o}=x;if(!i)throw Error("ajv implementation error");let{allErrors:l,opts:c}=o;if(o.props=!0,"all"!==c.removeAdditional&&(0,a.alwaysValidSchema)(o,_))return;let v=(0,e.allSchemaProperties)(A.properties),d=(0,e.allSchemaProperties)(A.patternProperties);function f(x){n.code((0,t._)`delete ${s}[${x}]`)}function b(e){if("all"===c.removeAdditional||c.removeAdditional&&!1===_)return void f(e);if(!1===_){x.setParams({additionalProperty:e}),x.error(),l||n.break();return}if("object"==typeof _&&!(0,a.alwaysValidSchema)(o,_)){let r=n.name("valid");"failing"===c.removeAdditional?(u(e,r,!1),n.if((0,t.not)(r),()=>{x.reset(),f(e)})):(u(e,r),l||n.if((0,t.not)(r),()=>n.break()))}}function u(e,t,r){let n={keyword:"additionalProperties",dataProp:e,dataPropType:a.Type.Str};!1===r&&Object.assign(n,{compositeRule:!0,createErrors:!1,allErrors:!1}),x.subschema(n,t)}n.forIn("key",s,r=>{v.length||d.length?n.if(function(r){let _;if(v.length>8){let x=(0,a.schemaRefOrVal)(o,A.properties,"properties");_=(0,e.isOwnProperty)(n,x,r)}else _=v.length?(0,t.or)(...v.map(x=>(0,t._)`${r} === ${x}`)):t.nil;return d.length&&(_=(0,t.or)(_,...d.map(a=>(0,t._)`${(0,e.usePattern)(x,a)}.test(${r})`))),(0,t.not)(_)}(r),()=>b(r)):b(r)}),x.ok((0,t._)`${i} === ${r.default.errors}`)}}}),pw=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u5(),t=u0(),r=uZ(),a=pF();x.default={keyword:"properties",type:"object",schemaType:"object",code(x){let{gen:n,schema:_,parentSchema:A,data:s,it:i}=x;"all"===i.opts.removeAdditional&&void 0===A.additionalProperties&&a.default.code(new e.KeywordCxt(i,a.default,"additionalProperties"));let o=(0,t.allSchemaProperties)(_);for(let x of o)i.definedProperties.add(x);i.opts.unevaluated&&o.length&&!0!==i.props&&(i.props=r.mergeEvaluated.props(n,(0,r.toHash)(o),i.props));let l=o.filter(x=>!(0,r.alwaysValidSchema)(i,_[x]));if(0===l.length)return;let c=n.name("valid");for(let e of l){var v;(v=e,i.opts.useDefaults&&!i.compositeRule&&void 0!==_[v].default)?d(e):(n.if((0,t.propertyInData)(n,s,e,i.opts.ownProperties)),d(e),i.allErrors||n.else().var(c,!0),n.endIf()),x.it.definedProperties.add(e),x.ok(c)}function d(e){x.subschema({keyword:"properties",schemaProp:e,dataProp:e},c)}}}}),pC=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=u0(),t=uM(),r=uZ(),a=uZ();x.default={keyword:"patternProperties",type:"object",schemaType:"object",code(x){let{gen:n,schema:_,data:A,parentSchema:s,it:i}=x,{opts:o}=i,l=(0,e.allSchemaProperties)(_),c=l.filter(x=>(0,r.alwaysValidSchema)(i,_[x]));if(0===l.length||c.length===l.length&&(!i.opts.unevaluated||!0===i.props))return;let v=o.strictSchema&&!o.allowMatchingProperties&&s.properties,d=n.name("valid");!0===i.props||i.props instanceof t.Name||(i.props=(0,a.evaluatedPropsToName)(n,i.props));let{props:f}=i;for(let x of l)v&&function(x){for(let e in v)new RegExp(x).test(e)&&(0,r.checkStrictMode)(i,`property ${e} matches pattern ${x} (use allowMatchingProperties)`)}(x),i.allErrors?b(x):(n.var(d,!0),b(x),n.if(d));function b(r){n.forIn("key",A,_=>{n.if((0,t._)`${(0,e.usePattern)(x,r)}.test(${_})`,()=>{let e=c.includes(r);e||x.subschema({keyword:"patternProperties",schemaProp:r,dataProp:_,dataPropType:a.Type.Str},d),i.opts.unevaluated&&!0!==f?n.assign((0,t._)`${f}[${_}]`,!0):e||i.allErrors||n.if((0,t.not)(d),()=>n.break())})})}}}}),pP=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uZ();x.default={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(x){let{gen:t,schema:r,it:a}=x;if((0,e.alwaysValidSchema)(a,r))return void x.fail();let n=t.name("valid");x.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),x.failResult(n,()=>x.reset(),()=>x.error())},error:{message:"must NOT be valid"}}}),pk=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:u0().validateUnion,error:{message:"must match a schema in anyOf"}}}),pD=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ();x.default={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:x})=>(0,e._)`{passingSchemas: ${x.passing}}`},code(x){let{gen:r,schema:a,parentSchema:n,it:_}=x;if(!Array.isArray(a))throw Error("ajv implementation error");if(_.opts.discriminator&&n.discriminator)return;let A=r.let("valid",!1),s=r.let("passing",null),i=r.name("_valid");x.setParams({passing:s}),r.block(function(){a.forEach((a,n)=>{let o;(0,t.alwaysValidSchema)(_,a)?r.var(i,!0):o=x.subschema({keyword:"oneOf",schemaProp:n,compositeRule:!0},i),n>0&&r.if((0,e._)`${i} && ${A}`).assign(A,!1).assign(s,(0,e._)`[${s}, ${n}]`).else(),r.if(i,()=>{r.assign(A,!0),r.assign(s,n),o&&x.mergeEvaluated(o,e.Name)})})}),x.result(A,()=>x.reset(),()=>x.error(!0))}}}),pL=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uZ();x.default={keyword:"allOf",schemaType:"array",code(x){let{gen:t,schema:r,it:a}=x;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((t,r)=>{if((0,e.alwaysValidSchema)(a,t))return;let _=x.subschema({keyword:"allOf",schemaProp:r},n);x.ok(n),x.mergeEvaluated(_)})}}}),pq=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ();function r(x,e){let r=x.schema[e];return void 0!==r&&!(0,t.alwaysValidSchema)(x,r)}x.default={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:x})=>(0,e.str)`must match "${x.ifClause}" schema`,params:({params:x})=>(0,e._)`{failingKeyword: ${x.ifClause}}`},code(x){let a,{gen:n,parentSchema:_,it:A}=x;void 0===_.then&&void 0===_.else&&(0,t.checkStrictMode)(A,'"if" without "then" and "else" is ignored');let s=r(A,"then"),i=r(A,"else");if(!s&&!i)return;let o=n.let("valid",!0),l=n.name("_valid");if(a=x.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l),x.mergeEvaluated(a),x.reset(),s&&i){let e=n.let("ifClause");x.setParams({ifClause:e}),n.if(l,c("then",e),c("else",e))}else s?n.if(l,c("then")):n.if((0,e.not)(l),c("else"));function c(t,r){return()=>{let a=x.subschema({keyword:t},l);n.assign(o,l),x.mergeValidEvaluated(a,o),r?n.assign(r,(0,e._)`${t}`):x.setParams({ifClause:t})}}x.pass(o,()=>x.error(!0))}}}),pT=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uZ();x.default={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:x,parentSchema:t,it:r}){void 0===t.if&&(0,e.checkStrictMode)(r,`"${x}" without "if" is ignored`)}}}),pR=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pj(),t=py(),r=pg(),a=pS(),n=pI(),_=pN(),A=pB(),s=pF(),i=pw(),o=pC(),l=pP(),c=pk(),v=pD(),d=pL(),f=pq(),b=pT();x.default=function(x=!1){let u=[l.default,c.default,v.default,d.default,f.default,b.default,A.default,s.default,_.default,i.default,o.default];return x?u.push(t.default,a.default):u.push(e.default,r.default),u.push(n.default),u}}),p$=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM();x.default={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:x})=>(0,e.str)`must match format "${x}"`,params:({schemaCode:x})=>(0,e._)`{format: ${x}}`},code(x,t){let r,a,n,_,A,s,{gen:i,data:o,$data:l,schema:c,schemaCode:v,it:d}=x,{opts:f,errSchemaPath:b,schemaEnv:u,self:p}=d;f.validateFormats&&(l?(r=i.scopeValue("formats",{ref:p.formats,code:f.code.formats}),a=i.const("fDef",(0,e._)`${r}[${v}]`),n=i.let("fType"),_=i.let("format"),i.if((0,e._)`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>i.assign(n,(0,e._)`${a}.type || "string"`).assign(_,(0,e._)`${a}.validate`),()=>i.assign(n,(0,e._)`"string"`).assign(_,a)),x.fail$data((0,e.or)(!1===f.strictSchema?e.nil:(0,e._)`${v} && !${_}`,(A=u.$async?(0,e._)`(${a}.async ? await ${_}(${o}) : ${_}(${o}))`:(0,e._)`${_}(${o})`,s=(0,e._)`(typeof ${_} == "function" ? ${A} : ${_}.test(${o}))`,(0,e._)`${_} && ${_} !== true && ${n} === ${t} && !${s}`)))):function(){var r;let a,n,_=p.formats[c];if(!_){if(!1===f.strictSchema)return p.logger.warn(A());throw Error(A());function A(){return`unknown format "${c}" ignored in schema at path "${b}"`}}if(!0===_)return;let[s,l,v]=(a=(r=_)instanceof RegExp?(0,e.regexpCode)(r):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(c)}`:void 0,n=i.scopeValue("formats",{key:c,ref:r,code:a}),"object"!=typeof r||r instanceof RegExp?["string",r,n]:[r.type||"string",r.validate,(0,e._)`${n}.validate`]);s===t&&x.pass(function(){if("object"==typeof _&&!(_ instanceof RegExp)&&_.async){if(!u.$async)throw Error("async format in sync schema");return(0,e._)`await ${v}(${o})`}return"function"==typeof l?(0,e._)`${v}(${o})`:(0,e._)`${v}.test(${o})`}())}())}}}),pG=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.default=[p$().default]}),pO=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.contentVocabulary=x.metadataVocabulary=void 0,x.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],x.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),pX=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=ps(),t=pE(),r=pR(),a=pG(),n=pO();x.default=[e.default,t.default,(0,r.default)(),a.default,n.metadataVocabulary,n.contentVocabulary]}),pK=fG(x=>{var e,t;Object.defineProperty(x,"__esModule",{value:!0}),x.DiscrError=void 0,(t=e||(x.DiscrError=e={})).Tag="tag",t.Mapping="mapping"}),pQ=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=pK(),r=u9(),a=u8(),n=uZ();x.default={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:x,tagName:e}})=>x===t.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:x,tag:t,tagName:r}})=>(0,e._)`{error: ${x}, tag: ${r}, tagValue: ${t}}`},code(x){let{gen:_,data:A,schema:s,parentSchema:i,it:o}=x,{oneOf:l}=i;if(!o.opts.discriminator)throw Error("discriminator: requires discriminator option");let c=s.propertyName;if("string"!=typeof c)throw Error("discriminator: requires propertyName");if(s.mapping)throw Error("discriminator: mapping is not supported");if(!l)throw Error("discriminator: requires oneOf keyword");let v=_.let("valid",!1),d=_.const("tag",(0,e._)`${A}${(0,e.getProperty)(c)}`);_.if((0,e._)`typeof ${d} == "string"`,()=>(function(){let A=function(){var x;let e={},t=A(i),_=!0;for(let e=0;e<l.length;e++){let i=l[e];if((null==i?void 0:i.$ref)&&!(0,n.schemaHasRulesButRef)(i,o.self.RULES)){let x=i.$ref;if((i=r.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,x))instanceof r.SchemaEnv&&(i=i.schema),void 0===i)throw new a.default(o.opts.uriResolver,o.baseId,x)}let v=null==(x=null==i?void 0:i.properties)?void 0:x[c];if("object"!=typeof v)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(t||A(i)),function(x,e){if(x.const)s(x.const,e);else if(x.enum)for(let t of x.enum)s(t,e);else throw Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}(v,e)}if(!_)throw Error(`discriminator: "${c}" must be required`);return e;function A({required:x}){return Array.isArray(x)&&x.includes(c)}function s(x,t){if("string"!=typeof x||x in e)throw Error(`discriminator: "${c}" values must be unique strings`);e[x]=t}}();for(let t in _.if(!1),A)_.elseIf((0,e._)`${d} === ${t}`),_.assign(v,function(t){let r=_.name("valid"),a=x.subschema({keyword:"oneOf",schemaProp:t},r);return x.mergeEvaluated(a,e.Name),r}(A[t]));_.else(),x.error(!1,{discrError:t.DiscrError.Mapping,tag:d,tagName:c}),_.endIf()})(),()=>x.error(!1,{discrError:t.DiscrError.Tag,tag:d,tagName:c})),x.ok(v)}}}),pM=fG((x,e)=>{e.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),pZ=fG((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv=void 0;let t=pn(),r=pX(),a=pQ(),n=pM(),_=["/properties"],A="http://json-schema.org/draft-07/schema";var s=class extends t.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(x=>this.addVocabulary(x)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let x=this.opts.$data?this.$dataMetaSchema(n,_):n;this.addMetaSchema(x,A,!1),this.refs["http://json-schema.org/schema"]=A}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(A)?A:void 0)}};x.Ajv=s,e.exports=x=s,e.exports.Ajv=s,Object.defineProperty(x,"__esModule",{value:!0}),x.default=s;var i=u5();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return i.KeywordCxt}});var o=uM();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return o.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return o.CodeGen}});var l=u7();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return l.default}});var c=u8();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return c.default}})}),pJ=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.dynamicAnchor=void 0;let e=uM(),t=uJ(),r=u9(),a=pA();function n(x,n){let{gen:_,it:A}=x;A.schemaEnv.root.dynamicAnchors[n]=!0;let s=(0,e._)`${t.default.dynamicAnchors}${(0,e.getProperty)(n)}`,i="#"===A.errSchemaPath?A.validateName:function(x){let{schemaEnv:e,schema:t,self:n}=x.it,{root:_,baseId:A,localRefs:s,meta:i}=e.root,{schemaId:o}=n.opts,l=new r.SchemaEnv({schema:t,schemaId:o,root:_,baseId:A,localRefs:s,meta:i});return r.compileSchema.call(n,l),(0,a.getValidate)(x,l)}(x);_.if((0,e._)`!${s}`,()=>_.assign(s,i))}x.dynamicAnchor=n,x.default={keyword:"$dynamicAnchor",schemaType:"string",code:x=>n(x,x.schema)}}),pV=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.dynamicRef=void 0;let e=uM(),t=uJ(),r=pA();function a(x,a){let{gen:n,keyword:_,it:A}=x;if("#"!==a[0])throw Error(`"${_}" only supports hash fragment reference`);let s=a.slice(1);if(A.allErrors)i();else{let e=n.let("valid",!1);i(e),x.ok(e)}function i(x){if(A.schemaEnv.root.dynamicAnchors[s]){let r=n.let("_v",(0,e._)`${t.default.dynamicAnchors}${(0,e.getProperty)(s)}`);n.if(r,o(r,x),o(A.validateName,x))}else o(A.validateName,x)()}function o(e,t){return t?()=>n.block(()=>{(0,r.callRef)(x,e),n.let(t,!0)}):()=>(0,r.callRef)(x,e)}}x.dynamicRef=a,x.default={keyword:"$dynamicRef",schemaType:"string",code:x=>a(x,x.schema)}}),pH=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pJ(),t=uZ();x.default={keyword:"$recursiveAnchor",schemaType:"boolean",code(x){x.schema?(0,e.dynamicAnchor)(x,""):(0,t.checkStrictMode)(x.it,"$recursiveAnchor: false is ignored")}}}),pU=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pV();x.default={keyword:"$recursiveRef",schemaType:"string",code:x=>(0,e.dynamicRef)(x,x.schema)}}),pY=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pJ(),t=pV(),r=pH(),a=pU();x.default=[e.default,t.default,r.default,a.default]}),pz=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pN();x.default={keyword:"dependentRequired",type:"object",schemaType:"object",error:e.error,code:x=>(0,e.validatePropertyDeps)(x)}}),pW=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pN();x.default={keyword:"dependentSchemas",type:"object",schemaType:"object",code:x=>(0,e.validateSchemaDeps)(x)}}),p0=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uZ();x.default={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:x,parentSchema:t,it:r}){void 0===t.contains&&(0,e.checkStrictMode)(r,`"${x}" without "contains" is ignored`)}}}),p1=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=pz(),t=pW(),r=p0();x.default=[e.default,t.default,r.default]}),p2=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ(),r=uJ();x.default={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:x})=>(0,e._)`{unevaluatedProperty: ${x.unevaluatedProperty}}`},code(x){let{gen:a,schema:n,data:_,errsCount:A,it:s}=x;if(!A)throw Error("ajv implementation error");let{allErrors:i,props:o}=s;function l(r){if(!1===n){x.setParams({unevaluatedProperty:r}),x.error(),i||a.break();return}if(!(0,t.alwaysValidSchema)(s,n)){let n=a.name("valid");x.subschema({keyword:"unevaluatedProperties",dataProp:r,dataPropType:t.Type.Str},n),i||a.if((0,e.not)(n),()=>a.break())}}o instanceof e.Name?a.if((0,e._)`${o} !== true`,()=>a.forIn("key",_,x=>{var t,r;return a.if((t=o,r=x,(0,e._)`!${t} || !${t}[${r}]`),()=>l(x))})):!0!==o&&a.forIn("key",_,x=>void 0===o?l(x):a.if(function(x,t){let r=[];for(let a in x)!0===x[a]&&r.push((0,e._)`${t} !== ${a}`);return(0,e.and)(...r)}(o,x),()=>l(x))),s.props=!0,x.ok((0,e._)`${A} === ${r.default.errors}`)}}}),p3=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=uM(),t=uZ();x.default={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:x}})=>(0,e.str)`must NOT have more than ${x} items`,params:({params:{len:x}})=>(0,e._)`{limit: ${x}}`},code(x){let{gen:r,schema:a,data:n,it:_}=x,A=_.items||0;if(!0===A)return;let s=r.const("len",(0,e._)`${n}.length`);if(!1===a)x.setParams({len:A}),x.fail((0,e._)`${s} > ${A}`);else if("object"==typeof a&&!(0,t.alwaysValidSchema)(_,a)){let a=r.var("valid",(0,e._)`${s} <= ${A}`);r.if((0,e.not)(a),()=>{var n,i;return n=a,i=A,void r.forRange("i",i,s,a=>{x.subschema({keyword:"unevaluatedItems",dataProp:a,dataPropType:t.Type.Num},n),_.allErrors||r.if((0,e.not)(n),()=>r.break())})}),x.ok(a)}_.items=!0}}}),p6=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p2(),t=p3();x.default=[e.default,t.default]}),p4=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/schema",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0,"https://json-schema.org/draft/2019-09/vocab/applicator":!0,"https://json-schema.org/draft/2019-09/vocab/validation":!0,"https://json-schema.org/draft/2019-09/vocab/meta-data":!0,"https://json-schema.org/draft/2019-09/vocab/format":!1,"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format"},{$ref:"meta/content"}],type:["object","boolean"],properties:{definitions:{$comment:"While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},dependencies:{$comment:'"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"',type:"object",additionalProperties:{anyOf:[{$recursiveRef:"#"},{$ref:"meta/validation#/$defs/stringArray"}]}}}}}),p5=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/applicator":!0},$recursiveAnchor:!0,title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{additionalItems:{$recursiveRef:"#"},unevaluatedItems:{$recursiveRef:"#"},items:{anyOf:[{$recursiveRef:"#"},{$ref:"#/$defs/schemaArray"}]},contains:{$recursiveRef:"#"},additionalProperties:{$recursiveRef:"#"},unevaluatedProperties:{$recursiveRef:"#"},properties:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$recursiveRef:"#"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$recursiveRef:"#"}},propertyNames:{$recursiveRef:"#"},if:{$recursiveRef:"#"},then:{$recursiveRef:"#"},else:{$recursiveRef:"#"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$recursiveRef:"#"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$recursiveRef:"#"}}}}}),p7=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/content",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/content":!0},$recursiveAnchor:!0,title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentMediaType:{type:"string"},contentEncoding:{type:"string"},contentSchema:{$recursiveRef:"#"}}}}),p8=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/core",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/core":!0},$recursiveAnchor:!0,title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{type:"string",format:"uri"},$anchor:{type:"string",pattern:"^[A-Za-z][-A-Za-z0-9.:_]*$"},$ref:{type:"string",format:"uri-reference"},$recursiveRef:{type:"string",format:"uri-reference"},$recursiveAnchor:{type:"boolean",default:!1},$vocabulary:{type:"object",propertyNames:{type:"string",format:"uri"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$recursiveRef:"#"},default:{}}}}}),p9=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/format",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/format":!0},$recursiveAnchor:!0,title:"Format vocabulary meta-schema",type:["object","boolean"],properties:{format:{type:"string"}}}}),mx=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/meta-data":!0},$recursiveAnchor:!0,title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),me=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://json-schema.org/draft/2019-09/meta/validation",$vocabulary:{"https://json-schema.org/draft/2019-09/vocab/validation":!0},$recursiveAnchor:!0,title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},const:!0,enum:{type:"array",items:!0},type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),mt=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=p4(),t=p5(),r=p7(),a=p8(),n=p9(),_=mx(),A=me(),s=["/properties"];x.default=function(x){return[e,t,r,a,i(this,n),_,i(this,A)].forEach(x=>this.addMetaSchema(x,void 0,!1)),this;function i(e,t){return x?e.$dataMetaSchema(t,s):t}}}),mr=fG((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv2019=void 0;let t=pn(),r=pX(),a=pY(),n=p1(),_=p6(),A=pQ(),s=mt(),i="https://json-schema.org/draft/2019-09/schema";var o=class extends t.default{constructor(x={}){super({...x,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),this.addVocabulary(a.default),r.default.forEach(x=>this.addVocabulary(x)),this.addVocabulary(n.default),this.addVocabulary(_.default),this.opts.discriminator&&this.addKeyword(A.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:x,meta:e}=this.opts;e&&(s.default.call(this,x),this.refs["http://json-schema.org/schema"]=i)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}};x.Ajv2019=o,e.exports=x=o,e.exports.Ajv2019=o,Object.defineProperty(x,"__esModule",{value:!0}),x.default=o;var l=u5();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var c=uM();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return c._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return c.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return c.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return c.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return c.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return c.CodeGen}});var v=u7();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return v.default}});var d=u8();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return d.default}})}),ma=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=ps(),t=pE(),r=pR(),a=pY(),n=p1(),_=p6(),A=pG(),s=pO();x.default=[a.default,e.default,t.default,(0,r.default)(!0),A.default,s.metadataVocabulary,s.contentVocabulary,n.default,_.default]}),mn=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}}),m_=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}}),mA=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}}),ms=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}}),mi=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}}),mo=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}}),ml=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}}),mc=fG((x,e)=>{e.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}}),mv=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0});let e=mn(),t=m_(),r=mA(),a=ms(),n=mi(),_=mo(),A=ml(),s=mc(),i=["/properties"];x.default=function(x){return[e,t,r,a,n,o(this,_),A,o(this,s)].forEach(x=>this.addMetaSchema(x,void 0,!1)),this;function o(e,t){return x?e.$dataMetaSchema(t,i):t}}}),md=fG((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0}),x.MissingRefError=x.ValidationError=x.CodeGen=x.Name=x.nil=x.stringify=x.str=x._=x.KeywordCxt=x.Ajv2020=void 0;let t=pn(),r=ma(),a=pQ(),n=mv(),_="https://json-schema.org/draft/2020-12/schema";var A=class extends t.default{constructor(x={}){super({...x,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),r.default.forEach(x=>this.addVocabulary(x)),this.opts.discriminator&&this.addKeyword(a.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:x,meta:e}=this.opts;e&&(n.default.call(this,x),this.refs["http://json-schema.org/schema"]=_)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_)?_:void 0)}};x.Ajv2020=A,e.exports=x=A,e.exports.Ajv2020=A,Object.defineProperty(x,"__esModule",{value:!0}),x.default=A;var s=u5();Object.defineProperty(x,"KeywordCxt",{enumerable:!0,get:function(){return s.KeywordCxt}});var i=uM();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(x,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return i.Name}}),Object.defineProperty(x,"CodeGen",{enumerable:!0,get:function(){return i.CodeGen}});var o=u7();Object.defineProperty(x,"ValidationError",{enumerable:!0,get:function(){return o.default}});var l=u8();Object.defineProperty(x,"MissingRefError",{enumerable:!0,get:function(){return l.default}})}),mf=fG(x=>{function e(x,e){return{validate:x,compare:e}}Object.defineProperty(x,"__esModule",{value:!0}),x.formatNames=x.fastFormats=x.fullFormats=void 0,x.fullFormats={date:e(a,n),time:e(A(!0),s),"date-time":e(l(!0),c),"iso-time":e(A(),i),"iso-date-time":e(l(),v),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(x){return d.test(x)&&f.test(x)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(x){if(h.test(x))return!1;try{return new RegExp(x),!0}catch(x){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(x){return b.lastIndex=0,b.test(x)},int32:{type:"number",validate:function(x){return Number.isInteger(x)&&x<=p&&x>=u}},int64:{type:"number",validate:function(x){return Number.isInteger(x)}},float:{type:"number",validate:m},double:{type:"number",validate:m},password:!0,binary:!0},x.fastFormats={...x.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,n),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,s),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,i),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,v),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},x.formatNames=Object.keys(x.fullFormats);let t=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(x){var e;let a=t.exec(x);if(!a)return!1;let n=+a[1],_=+a[2],A=+a[3];return _>=1&&_<=12&&A>=1&&A<=(2===_&&(e=n)%4==0&&(e%100!=0||e%400==0)?29:r[_])}function n(x,e){if(x&&e)return x>e?1:x<e?-1:0}let _=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function A(x){return function(e){let t=_.exec(e);if(!t)return!1;let r=+t[1],a=+t[2],n=+t[3],A=t[4],s="-"===t[5]?-1:1,i=+(t[6]||0),o=+(t[7]||0);if(i>23||o>59||x&&!A)return!1;if(r<=23&&a<=59&&n<60)return!0;let l=a-o*s,c=r-i*s-(l<0);return(23===c||-1===c)&&(59===l||-1===l)&&n<61}}function s(x,e){if(!(x&&e))return;let t=new Date("2020-01-01T"+x).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(t&&r)return t-r}function i(x,e){if(!(x&&e))return;let t=_.exec(x),r=_.exec(e);if(t&&r)return(x=t[1]+t[2]+t[3])>(e=r[1]+r[2]+r[3])?1:x<e?-1:0}let o=/t|\s/i;function l(x){let e=A(x);return function(x){let t=x.split(o);return 2===t.length&&a(t[0])&&e(t[1])}}function c(x,e){if(!(x&&e))return;let t=new Date(x).valueOf(),r=new Date(e).valueOf();if(t&&r)return t-r}function v(x,e){if(!(x&&e))return;let[t,r]=x.split(o),[a,_]=e.split(o),A=n(t,a);if(void 0!==A)return A||s(r,_)}let d=/\/|:/,f=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,b=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,u=-0x80000000,p=0x80000000-1;function m(){return!0}let h=/[^\\]\\Z/}),mb=fG(x=>{Object.defineProperty(x,"__esModule",{value:!0}),x.formatLimitDefinition=void 0;let e=pZ(),t=uM(),r=t.operators,a={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}};x.formatLimitDefinition={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:{message:({keyword:x,schemaCode:e})=>(0,t.str)`should be ${a[x].okStr} ${e}`,params:({keyword:x,schemaCode:e})=>(0,t._)`{comparison: ${a[x].okStr}, limit: ${e}}`},code(x){let r,n,{gen:_,data:A,schemaCode:s,keyword:i,it:o}=x,{opts:l,self:c}=o;if(!l.validateFormats)return;let v=new e.KeywordCxt(o,c.RULES.all.format.definition,"format");function d(x){return(0,t._)`${x}.compare(${A}, ${s}) ${a[i].fail} 0`}v.$data?(r=_.scopeValue("formats",{ref:c.formats,code:l.code.formats}),n=_.const("fmt",(0,t._)`${r}[${v.schemaCode}]`),x.fail$data((0,t.or)((0,t._)`typeof ${n} != "object"`,(0,t._)`${n} instanceof RegExp`,(0,t._)`typeof ${n}.compare != "function"`,d(n)))):function(){let e=v.schema,r=c.formats[e];if(!r||!0===r)return;if("object"!=typeof r||r instanceof RegExp||"function"!=typeof r.compare)throw Error(`"${i}": format "${e}" does not define "compare" function`);let a=_.scopeValue("formats",{key:e,ref:r,code:l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(e)}`:void 0});x.fail$data(d(a))}()},dependencies:["format"]},x.default=e=>(e.addKeyword(x.formatLimitDefinition),e)}),mu=fG((x,e)=>{Object.defineProperty(x,"__esModule",{value:!0});let t=mf(),r=mb(),a=uM(),n=new a.Name("fullFormats"),_=new a.Name("fastFormats"),A=(x,e={keywords:!0})=>{if(Array.isArray(e))return s(x,e,t.fullFormats,n),x;let[a,A]="fast"===e.mode?[t.fastFormats,_]:[t.fullFormats,n];return s(x,e.formats||t.formatNames,a,A),e.keywords&&(0,r.default)(x),x};function s(x,e,t,r){var n;for(let _ of(null!=(n=x.opts.code).formats||(n.formats=(0,a._)`require("ajv-formats/dist/formats").${r}`),e))x.addFormat(_,t[_])}A.get=(x,e="full")=>{let r=("fast"===e?t.fastFormats:t.fullFormats)[x];if(!r)throw Error(`Unknown format "${x}"`);return r},e.exports=x=A,Object.defineProperty(x,"__esModule",{value:!0}),x.default=A}),mp=pZ(),mm=mr(),mh=md();let mE=fO(mu(),1).default;function mj(x){let e=new x({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return mE(e),e}var mg=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor(x){this._userAjv=void 0!==x,this._ajv=x}get ajv(){return this._ajv??=mj(mh.Ajv2020)}_engineFor(x){if(this._userAjv)return this.ajv;let e=function(x,e){if(!("$schema"in x)||"string"!=typeof x.$schema)return"2020-12";let t=x.$schema.replace(/#$/,"");if(fX.has(t))return"2020-12";if(fK.has(t))return"2019-09";if(fQ.has(t)||fM.has(t))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${x.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${e}`)}(x,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");return"2020-12"===e?this.ajv:"2019-09"===e?this._ajv2019??=mj(mm.Ajv2019):this._ajvDraft7??=mj(mp.Ajv)}getValidator(x){let e=this._engineFor(x),t="$id"in x&&"string"==typeof x.$id?e.getSchema(x.$id)??e.compile(x):e.compile(x);return x=>t(x)?{valid:!0,data:x,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:e.errorsText(t.errors)}}};mp.Ajv;let my=Symbol.for("mcp.completable");function mS(x){return!!x&&"object"==typeof x&&my in x}let mI=0x80000000-1;function mN(x,e){if(!Number.isFinite(x)||x<1)return;let t=setInterval(e,Math.min(x,mI));return t.unref?.(),t}var mB=class{_listeners=new Set;constructor(x){this.onerror=x}publish(x){for(let e of this._listeners)try{e(x)}catch(x){this.onerror?.(x instanceof Error?x:Error(String(x)))}}subscribe(x){this._listeners.add(x);let e=!0;return()=>{e&&(e=!1,this._listeners.delete(x))}}get listenerCount(){return this._listeners.size}};function mF(x,e,t){return Response.json({jsonrpc:"2.0",error:{code:e,message:t},id:x},{status:200})}function mw(x,e){return{method:x.method,params:{...x.params,_meta:{...x.params?._meta,[x2]:e}}}}function mC(x,e,t){if(null===t||"object"!=typeof t||"string"!=typeof t.method)throw new bh(bm.InternalError,`Handler for ${x} returned an invalid input request '${e}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let r=function(x){switch(x.method){case"elicitation/create":if(x.params?.mode==="url")return{elicitation:{url:{}}};return{elicitation:{form:{}}};case"sampling/createMessage":{let e=x.params;if(void 0!==e&&(void 0!==e.tools||void 0!==e.toolChoice))return{sampling:{tools:{}}};return{sampling:{}}}case"roots/list":return{roots:{}};default:return}}(t);if(void 0===r)throw new bh(bm.InternalError,`Handler for ${x} returned an input request '${e}' of kind '${t.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:t,required:r}}function mP(x,e){if("tools/call"===x)return{content:[{type:"text",text:e}],isError:!0};throw new bh(bm.InternalError,e)}var mk=class{constructor(x){this._host=x}async fulfill(x,e,t,r,a){let{maxRounds:n,roundTimeoutMs:_}=this._host,A=r.mcpReq.signal,s=a,i=0;for(;;){let a;if((i+=1)>n)return mP(x,`Multi-round-trip request '${x}' still required input after ${n} rounds (inputRequired.maxRounds)`);let o=s.inputRequests,l=null!=o&&Object.keys(o).length>0,c="string"==typeof s.requestState?s.requestState:void 0;if(!l&&void 0===c)throw new bh(bm.InternalError,`Handler for ${x} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(l){let e=this._host.resolvedClientCapabilities(r),t=[];for(let[r,a]of Object.entries(o)){let{embedded:n,required:_}=mC(x,r,a);if("roots/list"!==n.method&&void 0===n.params)throw new bh(bm.InternalError,`Handler for ${x} returned an input request '${r}' of kind '${n.method}' without params`);if(void 0!==fW(_,e))return mP(x,`Cannot request input '${r}' (${n.method}): the client on this 2025-era connection did not declare the required capability${void 0===e?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);t.push([r,n])}let n=function(x){let e=new AbortController,t=()=>e.abort(x?.reason);return x?.addEventListener("abort",t,{once:!0}),x?.aborted&&e.abort(x.reason),{signal:e.signal,abort:x=>e.abort(x),dispose:()=>x?.removeEventListener("abort",t)}}(A);try{let x={relatedRequestId:r.mcpReq.id,timeout:_,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:n.signal},e=await Promise.all(t.map(async([e,t])=>{try{return[e,await this._dispatchLeg(t,x)]}catch(x){throw n.abort(x),x}}));a=Object.fromEntries(e)}catch(e){if(A.aborted)throw e;return mP(x,`Fulfilling input required by '${x}' failed: ${e instanceof Error?e.message:String(e)}`)}finally{n.dispose()}}else await function(x){return new Promise((e,t)=>{if(x?.aborted)return void t(x.reason instanceof fU?x.reason:new fU(fH.RequestTimeout,String(x.reason)));let r=setTimeout(()=>{x?.removeEventListener("abort",a),e()},250),a=()=>{clearTimeout(r),t(x?.reason instanceof fU?x.reason:new fU(fH.RequestTimeout,String(x?.reason)))};x?.addEventListener("abort",a,{once:!0})})}(A);let v={...r,mcpReq:{...r.mcpReq,inputResponses:a,droppedInputResponseKeys:void 0,requestState:function(x){return()=>x}(c)}};if(void 0!==c){let e=await this._host.verifyRequestState(c,v,x);void 0!==e&&(v=uk(v,e))}let d=await e(t,v);if(!b1(d))return d;s=d}}async _dispatchLeg(x,e){switch(x.method){case"elicitation/create":{let t=x.params;return"url"===t.mode&&void 0===t.elicitationId&&(t={...t,elicitationId:function(){let x=globalThis.crypto;if(x?.randomUUID!==void 0)return x.randomUUID();let e=new Uint8Array(16);x.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;let t=[...e].map(x=>x.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}()}),await this._host.sendElicitation(t,e)}case"sampling/createMessage":return await this._host.sendSampling(x.params,e);case"roots/list":return await this._host.listRoots(x.params,e)}}};let mD=new Set(["tools/call","prompts/get","resources/read"]);var mL=class extends uD{_clientCapabilities;_clientVersion;static{i=(x,e)=>{void 0!==e.clientCapabilities&&(x._clientCapabilities=e.clientCapabilities),void 0!==e.clientInfo&&(x._clientVersion=e.clientInfo)},o=(x,e)=>{let t=e.filter(e=>!x._supportedProtocolVersions.includes(e));t.length>0&&(x._supportedProtocolVersions=[...x._supportedProtocolVersions,...t]),x.setRequestHandler("server/discover",()=>x._ondiscover())},l=x=>x._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new mk({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:x=>this._inputRequestCapabilityView(x),verifyRequestState:(x,e,t)=>this._verifyRequestState(x,e,t),sendElicitation:(x,e)=>this._sendElicitationLeg(x,e,{validateAcceptedContent:!1}),sendSampling:(x,e)=>this.createMessage(x,e),listRoots:(x,e)=>this.listRoots(x,e)})}oninitialized;constructor(x,e){if(super(e),this._serverInfo=x,this._capabilities=e?.capabilities?{...e.capabilities}:{},this._instructions=e?.instructions,this._jsonSchemaValidator=e?.jsonSchemaValidator??new mg,this._requestStateVerify=e?.requestState?.verify,this._inputRequiredServing=function(x){if(x?.maxRounds!==void 0&&(!Number.isInteger(x.maxRounds)||x.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${x.maxRounds})`);if(x?.roundTimeoutMs!==void 0&&(!Number.isFinite(x.roundTimeoutMs)||x.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${x.roundTimeoutMs})`);return{maxRounds:x?.maxRounds??8,roundTimeoutMs:x?.roundTimeoutMs??6e5,legacyShim:x?.legacyShim??!0}}(e?.inputRequired),e?.cacheHints!==void 0){for(let[x,t]of Object.entries(e.cacheHints))void 0!==t&&bp(t,`cacheHints['${x}']`);this._cacheHints=e.cacheHints}this.setRequestHandler("initialize",x=>this._oninitialize(x)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),f2(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(x,e)=>{let t=e.sessionId||e.http?.req?.headers.get("mcp-session-id")||void 0,{level:r}=x.params,a=rr(tc,r);return a.success&&this._loggingLevels.set(t,a.data),{}})}buildContext(x,e){let t=x.http||e?.request||e?.closeSSEStream||e?.closeStandaloneSSEStream;return{...x,mcpReq:{...x.mcpReq,log:(e,t,r)=>{let a;if(!this._capabilities.logging)return Promise.resolve();if(this._servedModernEra()){if(void 0===(a=x.mcpReq.envelope?.[t$]))return Promise.resolve()}else a=this._loggingLevels.get(x.sessionId)??this._loggingLevels.get(void 0);return void 0!==a&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():x.mcpReq.notify({method:"notifications/message",params:{level:e,data:t,logger:r}})},elicitInput:(x,e)=>this.elicitInput(x,e),requestSampling:(x,e)=>this.createMessage(x,e)},http:t?{...x.http,req:e?.request,closeSSE:e?.closeSSEStream,closeStandaloneSSE:e?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(tc.options.map((x,e)=>[x,e]));isMessageIgnored=(x,e)=>{let t=this._loggingLevels.get(e);return!!t&&this.LOG_LEVEL_SEVERITY.get(x)<this.LOG_LEVEL_SEVERITY.get(t)};registerCapabilities(x){if(this.transport)throw new fU(fH.AlreadyConnected,"Cannot register capabilities after connecting to transport");let e=!!this._capabilities.logging;this._capabilities=function(x,e){let t={...x};for(let x in e){let r=e[x];if(void 0===r)continue;let a=t[x];t[x]=uL(a)&&uL(r)?{...a,...r}:r}return t}(this._capabilities,x),!e&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(x,e){if("tools/call"!==x){let t=this._cacheHints?.[x],r=mD.has(x);return void 0!==t||r?async(a,n)=>{let _=r?await this._invokeInputRequiredCapableHandler(x,e,a,n):await e(a,n);if(b1(_)){if(!r)throw new bh(bm.InternalError,`Handler for ${x} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return _}return void 0===t?_:bf(_,t)}:async(t,r)=>{let a=await e(t,r);if(b1(a))throw new bh(bm.InternalError,`Handler for ${x} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}}return async(x,t)=>{let r=bG(this._negotiatedProtocolVersion),a=r.validateRequest("tools/call",x);if(!a.ok)throw new bh("not-in-era"===a.reason?bm.InternalError:bm.InvalidParams,"not-in-era"===a.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let n=await this._invokeInputRequiredCapableHandler("tools/call",e,x,t);if(b1(n))return n;let _=f4(n),A=r.validateResult("tools/call",_);if(!A.ok)throw new bh("not-in-era"===A.reason?bm.InternalError:bm.InvalidParams,"not-in-era"===A.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${A.message}`);return A.value}}_servedModernEra(){return void 0!==this._negotiatedProtocolVersion&&this._negotiatedProtocolVersion>=f0}async _invokeInputRequiredCapableHandler(x,e,t,r){let a,n=this._servedModernEra(),_=r.mcpReq.requestState();if(void 0!==_&&"string"!=typeof _)throw new bh(bm.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let A=r;if("string"==typeof _){let e=await this._verifyRequestState(_,r,x);void 0!==e&&(A=uk(r,e))}try{a=await e(t,A)}catch(x){if(x instanceof bh&&x.code===bm.UrlElicitationRequired){if(!n)throw x;throw new bh(bm.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`)}throw x}if(!b1(a))return a;if(!n){if(!this._inputRequiredServing.legacyShim)throw new bh(bm.InternalError,`Handler for ${x} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??t3}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(x,e,t,A,a)}let s=a.inputRequests,i=null!=s&&Object.keys(s).length>0,o="string"==typeof a.requestState;if(!i&&!o)throw new bh(bm.InternalError,`Handler for ${x} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(i){let e=this._inputRequestCapabilityView(r);for(let[t,r]of Object.entries(s)){let{embedded:a,required:n}=mC(x,t,r),_=fW(n,e);if(void 0!==_)throw new by({requiredCapabilities:_},`Cannot request input '${t}' (${a.method}): the request's client capabilities do not declare the required capability`)}}return a}async _verifyRequestState(x,e,t){if(void 0!==this._requestStateVerify)try{return await this._requestStateVerify(x,e)}catch(x){throw this.onerror?.(Error(`requestState verification rejected ${t}: ${x instanceof Error?x.message:String(x)}`)),new bh(bm.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(x){return this._servedModernEra()?x.mcpReq.envelope?.[ef]:this._clientCapabilities}_assertPushApiInServedEra(x){if(this._servedModernEra())throw new fU(fH.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${x}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:x,era:"2026-07-28"})}assertCapabilityForMethod(x){switch(x){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new fU(fH.CapabilityNotSupported,`Client does not support sampling (required for ${x})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new fU(fH.CapabilityNotSupported,`Client does not support elicitation (required for ${x})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new fU(fH.CapabilityNotSupported,`Client does not support listing roots (required for ${x})`)}}assertNotificationCapability(x){switch(x){case"notifications/message":if(!this._capabilities.logging)throw new fU(fH.CapabilityNotSupported,`Server does not support logging (required for ${x})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new fU(fH.CapabilityNotSupported,`Server does not support notifying about resources (required for ${x})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new fU(fH.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${x})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new fU(fH.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${x})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new fU(fH.CapabilityNotSupported,`Client does not support URL elicitation (required for ${x})`)}}assertRequestHandlerCapability(x){switch(x){case"completion/complete":if(!this._capabilities.completions)throw new fU(fH.CapabilityNotSupported,`Server does not support completions (required for ${x})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new fU(fH.CapabilityNotSupported,`Server does not support logging (required for ${x})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new fU(fH.CapabilityNotSupported,`Server does not support prompts (required for ${x})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new fU(fH.CapabilityNotSupported,`Server does not support resources (required for ${x})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new fU(fH.CapabilityNotSupported,`Server does not support tools (required for ${x})`)}}async _oninitialize(x){let e=x.params.protocolVersion;this._clientCapabilities=x.params.capabilities,this._clientVersion=x.params.clientInfo;let t=this._supportedProtocolVersions.filter(x=>!(x>=f0)),r=t.includes(e)?e:t[0]??t3;return this._negotiatedProtocolVersion=r,this.transport?.setProtocolVersion?.(r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:f2(this._supportedProtocolVersions),capabilities:{...this.getCapabilities()},...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(x,e){return this._wireCodec().projectCallToolResult(x,e)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(x,e){if(this._assertPushApiInServedEra("sampling/createMessage"),(x.tools||x.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new fU(fH.CapabilityNotSupported,"Client does not support sampling tools capability.");if(x.messages.length>0){let e=x.messages.at(-1),t=Array.isArray(e.content)?e.content:[e.content],r=t.some(x=>"tool_result"===x.type),a=x.messages.length>1?x.messages.at(-2):void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],_=n.some(x=>"tool_use"===x.type);if(r){if(t.some(x=>"tool_result"!==x.type))throw new bh(bm.InvalidParams,"The last message must contain only tool_result content if any is present");if(!_)throw new bh(bm.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(_){let x=new Set(n.filter(x=>"tool_use"===x.type).map(x=>x.id)),e=new Set(t.filter(x=>"tool_result"===x.type).map(x=>x.toolUseId));if(x.size!==e.size||![...x].every(x=>e.has(x)))throw new bh(bm.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let t=!!(x.tools||x.toolChoice),r=await this.request({method:"sampling/createMessage",params:x},e),a=this._wireCodec().samplingResultVariant(t,r);if(!a.ok)throw new fU(fH.InvalidResult,`Invalid sampling/createMessage result: ${"invalid"===a.reason?a.message:a.reason}`);return a.value}async elicitInput(x,e){switch(this._assertPushApiInServedEra("elicitation/create"),x.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new fU(fH.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new fU(fH.CapabilityNotSupported,"Client does not support form elicitation.")}return this._sendElicitationLeg(x,e)}async _sendElicitationLeg(x,e,t){let r=x.mode??"form",a=t?.validateAcceptedContent??!0;switch(r){case"url":return this.request({method:"elicitation/create",params:x},e);case"form":{let t="form"===x.mode?x:{...x,mode:"form"},r=await this.request({method:"elicitation/create",params:t},e);if(a&&"accept"===r.action&&r.content&&t.requestedSchema)try{let x=this._jsonSchemaValidator.getValidator(t.requestedSchema)(r.content);if(!x.valid)throw new bh(bm.InvalidParams,`Elicitation response content does not match requested schema: ${x.errorMessage}`)}catch(x){if(x instanceof bh)throw x;throw new bh(bm.InternalError,`Error validating elicitation response: ${x instanceof Error?x.message:String(x)}`)}return r}}}createElicitationCompletionNotifier(x,e){if(!this._clientCapabilities?.elicitation?.url)throw new fU(fH.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:x}},e)}async listRoots(x,e){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:x},e)}async sendLoggingMessage(x,e){if(this._capabilities.logging&&!this.isMessageIgnored(x.level,e))return this.notification({method:"notifications/message",params:x})}async sendResourceUpdated(x){return this.notification({method:"notifications/resources/updated",params:x})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},mq=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(x){let e=this._registeredTools[x];if(void 0!==e&&e.enabled){if(Object.hasOwn(this._toolInputSchemaJson,x))return this._toolInputSchemaJson[x];if(void 0===e.inputSchema)return mR;try{let t=uf(e.inputSchema,"input");return this._toolInputSchemaJson[x]=t,t}catch{return}}}constructor(x,e){this.server=new mL(x,e),e?.capabilities?.tools&&this.setToolRequestHandlers(),e?.capabilities?.resources&&this.setResourceRequestHandlers(),e?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(x){return await this.server.connect(x)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,x])=>x.enabled).map(([x,e])=>{let t={name:x,title:e.title,description:e.description,inputSchema:e.inputSchema?uf(e.inputSchema,"input"):mR,annotations:e.annotations,icons:e.icons,execution:e.execution,_meta:e._meta};return e.outputSchema&&(t.outputSchema=uf(e.outputSchema,"output")),t})})),this.server.setRequestHandler("tools/call",async(x,e)=>{let t=this._registeredTools[x.params.name];if(!t)throw new bh(bm.InvalidParams,`Tool ${x.params.name} not found`);if(!t.enabled)throw new bh(bm.InvalidParams,`Tool ${x.params.name} disabled`);try{let r=await this.validateToolInput(t,x.params.arguments,x.params.name),a=await this.executeToolHandler(t,r,e);if(await this.validateToolOutput(t,a,x.params.name),b1(a))return a;return this.server.projectCallToolResult(a,t.outputSchemaJson)}catch(x){if(x instanceof bh&&x.code===bm.UrlElicitationRequired)throw x;return this.createToolError(x instanceof Error?x.message:String(x))}}),this._toolHandlersInitialized=!0)}createToolError(x){return{content:[{type:"text",text:x}],isError:!0}}async validateToolInput(x,e,t){if(!x.inputSchema)return;let r=await ub(x.inputSchema,e??{});if(!r.success)throw new bh(bm.InvalidParams,`Input validation error: Invalid arguments for tool ${t}: ${r.error}`);return r.data}async validateToolOutput(x,e,t){if(!x.outputSchema||b1(e)||e.isError)return;if(void 0===e.structuredContent)throw new bh(bm.InvalidParams,`Output validation error: Tool ${t} has an output schema but no structured content was provided`);let r=await ub(x.outputSchema,e.structuredContent);if(!r.success)throw new bh(bm.InvalidParams,`Output validation error: Invalid structured content for tool ${t}: ${r.error}`)}async executeToolHandler(x,e,t){return x.executor(e,t)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async x=>{switch(x.params.ref.type){case"ref/prompt":if("ref/prompt"!==x.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${x.params.ref.type}`);return this.handlePromptCompletion(x,x.params.ref);case"ref/resource":if("ref/resource"!==x.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${x.params.ref.type}`);return this.handleResourceCompletion(x,x.params.ref);default:throw new bh(bm.InvalidParams,`Invalid completion reference: ${x.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(x,e){let t=this._registeredPrompts[e.name];if(!t)throw new bh(bm.InvalidParams,`Prompt ${e.name} not found`);if(!t.enabled)throw new bh(bm.InvalidParams,`Prompt ${e.name} disabled`);if(!t.argsSchema)return mX;let r=mQ(mK(t.argsSchema)?.[x.params.argument.name]);if(!mS(r))return mX;let a=r[my]?.complete;return a?mO(await a(x.params.argument.value,x.params.context)):mX}async handleResourceCompletion(x,e){let t=Object.values(this._registeredResourceTemplates).find(x=>x.resourceTemplate.uriTemplate.toString()===e.uri);if(!t){if(this._registeredResources[e.uri])return mX;throw new bh(bm.InvalidParams,`Resource template ${x.params.ref.uri} not found`)}let r=t.resourceTemplate.completeCallback(x.params.argument.name);return r?mO(await r(x.params.argument.value,x.params.context)):mX}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(x,e)=>{let t=Object.entries(this._registeredResources).filter(([x,e])=>e.enabled).map(([x,e])=>({uri:x,name:e.name,...e.metadata})),r=[];for(let x of Object.values(this._registeredResourceTemplates))if(x.resourceTemplate.listCallback)for(let t of(await x.resourceTemplate.listCallback(e)).resources)r.push({...x.metadata,...t});return{resources:[...t,...r]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([x,e])=>({name:x,uriTemplate:e.resourceTemplate.uriTemplate.toString(),...e.metadata}))})),this.server.setRequestHandler("resources/read",async(x,e)=>{let t;try{t=new URL(x.params.uri)}catch{throw new bh(bm.InvalidParams,`Resource URI ${x.params.uri} is invalid`,{uri:x.params.uri,reason:"invalid_uri"})}let r=this._registeredResources[t.toString()];if(r){if(!r.enabled)throw new bh(bm.InvalidParams,`Resource ${t} disabled`);return bf(await r.readCallback(t,e),r.cacheHint)}for(let x of Object.values(this._registeredResourceTemplates)){let r=x.resourceTemplate.uriTemplate.match(t.toString());if(r)return bf(await x.readCallback(t,r,e),x.cacheHint)}throw new bE(x.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,x])=>x.enabled).map(([x,e])=>{let t,r,a;return{name:x,title:e.title,description:e.description,arguments:e.argsSchema?(r=(t=uf(e.argsSchema,"input")).properties||{},a=t.required||[],Object.entries(r).map(([x,e])=>({name:x,description:e?.description,required:a.includes(x)}))):void 0,icons:e.icons,_meta:e._meta}})})),this.server.setRequestHandler("prompts/get",async(x,e)=>{let t=this._registeredPrompts[x.params.name];if(!t)throw new bh(bm.InvalidParams,`Prompt ${x.params.name} not found`);if(!t.enabled)throw new bh(bm.InvalidParams,`Prompt ${x.params.name} disabled`);return t.handler(x.params.arguments,e)}),this._promptHandlersInitialized=!0)}registerResource(x,e,t,r){let a=t.cacheHint,n=t;if(void 0!==a){bp(a,`resource ${x}`);let e={...t};delete e.cacheHint,n=e}if("string"==typeof e){if(this._registeredResources[e])throw Error(`Resource ${e} is already registered`);let _=this._createRegisteredResource(x,t.title,e,n,r);return void 0!==a&&(_.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),_}{if(this._registeredResourceTemplates[x])throw Error(`Resource template ${x} is already registered`);let _=this._createRegisteredResourceTemplate(x,t.title,e,n,r);return void 0!==a&&(_.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),_}}_createRegisteredResource(x,e,t,r,a){let n={name:x,title:e,metadata:r,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:x=>{void 0!==x.uri&&x.uri!==t&&(delete this._registeredResources[t],x.uri&&(this._registeredResources[x.uri]=n)),void 0!==x.name&&(n.name=x.name),void 0!==x.title&&(n.title=x.title),void 0!==x.metadata&&(n.metadata=x.metadata),void 0!==x.callback&&(n.readCallback=x.callback),void 0!==x.enabled&&(n.enabled=x.enabled),this.sendResourceListChanged()}};return this._registeredResources[t]=n,n}_createRegisteredResourceTemplate(x,e,t,r,a){let n={resourceTemplate:t,title:e,metadata:r,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&(delete this._registeredResourceTemplates[x],e.name&&(this._registeredResourceTemplates[e.name]=n)),void 0!==e.title&&(n.title=e.title),void 0!==e.template&&(n.resourceTemplate=e.template),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[x]=n;let _=t.uriTemplate.variableNames;return Array.isArray(_)&&_.some(x=>!!t.completeCallback(x))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(x,e,t,r,a,n,_){let A=r,s=a,i={title:e,description:t,argsSchema:r,icons:n,_meta:_,handler:mG(x,r,a),enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&(delete this._registeredPrompts[x],e.name&&(this._registeredPrompts[e.name]=i)),void 0!==e.title&&(i.title=e.title),void 0!==e.description&&(i.description=e.description),void 0!==e.icons&&(i.icons=e.icons),void 0!==e._meta&&(i._meta=e._meta);let t=!1;void 0!==e.argsSchema&&(i.argsSchema=e.argsSchema,A=e.argsSchema,t=!0),void 0!==e.callback&&(s=e.callback,t=!0),t&&(i.handler=mG(x,A,s)),void 0!==e.enabled&&(i.enabled=e.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[x]=i,r){let x=mK(r);x&&Object.values(x).some(x=>mS(mQ(x)))&&this.setCompletionRequestHandler()}return i}_createRegisteredTool(x,e,t,r,a,n,_,A,s,i){if(uO(x),void 0!==r)try{let e=uf(r,"input");this._toolInputSchemaJson[x]=e;let t=b4(e);t.valid||console.warn(`[mcp-sdk] tool '${x}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${t.reason}`)}catch{}let o=i,l={title:e,description:t,inputSchema:r,outputSchema:a,outputSchemaJson:m$(a),annotations:n,icons:_,execution:A,_meta:s,handler:i,executor:mT(r,i),enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:e=>{void 0!==e.name&&e.name!==x&&("string"==typeof e.name&&uO(e.name),delete this._registeredTools[x],delete this._toolInputSchemaJson[x],e.name&&(delete this._toolInputSchemaJson[e.name],this._registeredTools[e.name]=l,x=e.name)),void 0!==e.title&&(l.title=e.title),void 0!==e.description&&(l.description=e.description);let t=!1;void 0!==e.paramsSchema&&(l.inputSchema=e.paramsSchema,delete this._toolInputSchemaJson[x],t=!0),void 0!==e.callback&&(l.handler=e.callback,o=e.callback,t=!0),t&&(l.executor=mT(l.inputSchema,o)),void 0!==e.outputSchema&&(l.outputSchema=e.outputSchema,l.outputSchemaJson=m$(e.outputSchema)),void 0!==e.annotations&&(l.annotations=e.annotations),void 0!==e.icons&&(l.icons=e.icons),void 0!==e._meta&&(l._meta=e._meta),void 0!==e.enabled&&(l.enabled=e.enabled),this.sendToolListChanged()}};return this._registeredTools[x]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}registerTool(x,e,t){if(this._registeredTools[x])throw Error(`Tool ${x} is already registered`);let{title:r,description:a,inputSchema:n,outputSchema:_,annotations:A,icons:s,_meta:i}=e;return this._createRegisteredTool(x,r,a,uX(n),uX(_),A,s,void 0,i,t)}registerPrompt(x,e,t){if(this._registeredPrompts[x])throw Error(`Prompt ${x} is already registered`);let{title:r,description:a,argsSchema:n,icons:_,_meta:A}=e,s=this._createRegisteredPrompt(x,r,a,uX(n),t,_,A);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(x,e){return this.server.sendLoggingMessage(x,e)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};function mT(x,e){return x?async(x,t)=>e(x,t):async(x,t)=>e(t)}let mR={type:"object",properties:{}};function m$(x){if(void 0!==x)try{return uf(x,"output")}catch{return}}function mG(x,e,t){return e?async(r,a)=>{let n=await ub(e,r);if(!n.success)throw new bh(bm.InvalidParams,`Invalid arguments for prompt ${x}: ${n.error}`);return t(n.data,a)}:async(x,e)=>t(e)}function mO(x){return{completion:{values:x.map(String).slice(0,100),total:x.length,hasMore:x.length>100}}}let mX={completion:{values:[],hasMore:!1}};function mK(x){if(x.shape&&"object"==typeof x.shape)return x.shape}function mQ(x){return x?.type!=="optional"?x:x.def?.innerType??x}var mM=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(x){this._classification=x.classification,this._responseMode=x.responseMode??"auto",this._keepAliveMs=x.keepAliveMs??15e3}async start(){if(this._started)throw Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(x,e){if(this._used)throw Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||void 0===this.onmessage)throw Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw Error("PerRequestHTTPServerTransport is closed");this._used=!0;let t=e?.request?.signal;if(t?.aborted)throw await this.close(),new fU(fH.ConnectionClosed,"The request was aborted before it could be handled");let r={classification:this._classification,...e?.request!==void 0&&{request:e.request},...e?.authInfo!==void 0&&{authInfo:e.authInfo}};if(bY(x)){let e,a;this._requestId=x.id;let n=new Promise((x,t)=>{e=x,a=t});if(this._deferredResponse={promise:n,resolve:e,reject:a,settled:!1},void 0!==t){let x=()=>void this.close();t.addEventListener("abort",x,{once:!0}),this._abortCleanup=()=>t.removeEventListener("abort",x)}this._dispatchWindowOpen=!0;try{this.onmessage(x,r)}finally{this._dispatchWindowOpen=!1}return"sse"!==this._responseMode||this._closed||this._deferredResponse.settled||this.upgradeToSse(),n}return this.onmessage(x,r),new Response(null,{status:202})}async send(x,e){if(this._closed)return;let t=bW(x)||b0(x),r=t?x.id:e?.relatedRequestId;if(void 0===this._requestId||void 0===r||r!==this._requestId){t&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(x.id)}`));return}if(t){if(this._terminalDelivered)return;this._terminalDelivered=!0;let e=b0(x)?x.error.code:void 0,t=void 0!==e&&(this._dispatchWindowOpen||e===bm.MissingRequiredClientCapability)?ua[e]:void 0;if(void 0!==t&&void 0===this._sse){this.settleResponse(Response.json(x,{status:t,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(void 0!==this._sse||"sse"===this._responseMode){void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(x),this.finalizeStream();return}this.settleResponse(Response.json(x,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}"json"!==this._responseMode&&(void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(x))}writeCommentFrame(x){if(this._closed||void 0===this._sse||this._sse.closed)return;let e=x.split("\n").map(x=>`: ${x}`).join("\n");this.writeFrame(`${e}
380
380
 
381
- `)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.reject(new fV(fJ.ConnectionClosed,"Connection closed before a response was produced"))),this.onclose?.()}}settleResponse(x){void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(x))}upgradeToSse(){let x,e=new ReadableStream({start:e=>{x=e},cancel:()=>{this.close()}});this._sse={controller:x,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=mS(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(e,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(x){this.writeFrame(`event: message
381
+ `)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.reject(new fU(fH.ConnectionClosed,"Connection closed before a response was produced"))),this.onclose?.()}}settleResponse(x){void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(x))}upgradeToSse(){let x,e=new ReadableStream({start:e=>{x=e},cancel:()=>{this.close()}});this._sse={controller:x,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=mN(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(e,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(x){this.writeFrame(`event: message
382
382
  data: ${JSON.stringify(x)}
383
383
 
384
- `)}writeFrame(x){if(void 0!==this._sse&&!this._sse.closed)try{this._sse.controller.enqueue(this._sse.encoder.encode(x))}catch(x){this.onerror?.(Error(`Failed to write to the response stream: ${x}`))}}};async function mQ(x,e,t){let r=new mK({classification:t.classification,...void 0!==t.responseMode&&{responseMode:t.responseMode},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return await x.connect(r),r.handleMessage(e,{...void 0!==t.request&&{request:t.request},...void 0!==t.authInfo&&{authInfo:t.authInfo}})}var mM=class{sessionIdGenerator;_started=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId="_GET_stream";_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;sessionId;onclose;onerror;onmessage;constructor(x={}){this.sessionIdGenerator=x.sessionIdGenerator,this._enableJsonResponse=x.enableJsonResponse??!1,this._eventStore=x.eventStore,this._onsessioninitialized=x.onsessioninitialized,this._onsessionclosed=x.onsessionclosed,this._allowedHosts=x.allowedHosts,this._allowedOrigins=x.allowedOrigins,this._enableDnsRebindingProtection=x.enableDnsRebindingProtection??!1,this._retryInterval=x.retryInterval,this._supportedProtocolVersions=x.supportedProtocolVersions??tO,this._keepAliveMs=x.keepAliveMs??15e3}startKeepAlive(x,e){if(this._closed)return;let t=mS(this._keepAliveMs,()=>{try{x.enqueue(e.encode(": keepalive\n\n"))}catch{void 0!==t&&clearInterval(t)}});return t}async start(){if(this._started)throw Error("Transport already started");this._started=!0}setSupportedProtocolVersions(x){this._supportedProtocolVersions=x}createJsonErrorResponse(x,e,t,r){let a={code:e,message:t};return r?.data!==void 0&&(a.data=r.data),Response.json({jsonrpc:"2.0",error:a,id:null},{status:x,headers:{"Content-Type":"application/json",...r?.headers}})}validateRequestHeaders(x){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let e=x.headers.get("host");if(!e||!this._allowedHosts.includes(e)){let x=`Invalid Host header: ${e}`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(403,-32e3,x)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let e=x.headers.get("origin");if(e&&!this._allowedOrigins.includes(e)){let x=`Invalid Origin header: ${e}`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(403,-32e3,x)}}}}async handleRequest(x,e){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let t=this.validateRequestHeaders(x);if(t)return t;switch(x.method){case"POST":return this.handlePostRequest(x,e);case"GET":return this.handleGetRequest(x);case"DELETE":return this.handleDeleteRequest(x);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(x){return this._supportedProtocolVersions.includes(x)&&x>="2025-11-25"}async writePrimingEvent(x,e,t,r){if(!this._eventStore||!this.supportsEmptySSEData(r))return;let a=await this._eventStore.storeEvent(t,{}),n=`id: ${a}
384
+ `)}writeFrame(x){if(void 0!==this._sse&&!this._sse.closed)try{this._sse.controller.enqueue(this._sse.encoder.encode(x))}catch(x){this.onerror?.(Error(`Failed to write to the response stream: ${x}`))}}};async function mZ(x,e,t){let r=new mM({classification:t.classification,...void 0!==t.responseMode&&{responseMode:t.responseMode},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return await x.connect(r),r.handleMessage(e,{...void 0!==t.request&&{request:t.request},...void 0!==t.authInfo&&{authInfo:t.authInfo}})}var mJ=class{sessionIdGenerator;_started=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId="_GET_stream";_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;sessionId;onclose;onerror;onmessage;constructor(x={}){this.sessionIdGenerator=x.sessionIdGenerator,this._enableJsonResponse=x.enableJsonResponse??!1,this._eventStore=x.eventStore,this._onsessioninitialized=x.onsessioninitialized,this._onsessionclosed=x.onsessionclosed,this._allowedHosts=x.allowedHosts,this._allowedOrigins=x.allowedOrigins,this._enableDnsRebindingProtection=x.enableDnsRebindingProtection??!1,this._retryInterval=x.retryInterval,this._supportedProtocolVersions=x.supportedProtocolVersions??tO,this._keepAliveMs=x.keepAliveMs??15e3}startKeepAlive(x,e){if(this._closed)return;let t=mN(this._keepAliveMs,()=>{try{x.enqueue(e.encode(": keepalive\n\n"))}catch{void 0!==t&&clearInterval(t)}});return t}async start(){if(this._started)throw Error("Transport already started");this._started=!0}setSupportedProtocolVersions(x){this._supportedProtocolVersions=x}createJsonErrorResponse(x,e,t,r){let a={code:e,message:t};return r?.data!==void 0&&(a.data=r.data),Response.json({jsonrpc:"2.0",error:a,id:null},{status:x,headers:{"Content-Type":"application/json",...r?.headers}})}validateRequestHeaders(x){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let e=x.headers.get("host");if(!e||!this._allowedHosts.includes(e)){let x=`Invalid Host header: ${e}`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(403,-32e3,x)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let e=x.headers.get("origin");if(e&&!this._allowedOrigins.includes(e)){let x=`Invalid Origin header: ${e}`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(403,-32e3,x)}}}}async handleRequest(x,e){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let t=this.validateRequestHeaders(x);if(t)return t;switch(x.method){case"POST":return this.handlePostRequest(x,e);case"GET":return this.handleGetRequest(x);case"DELETE":return this.handleDeleteRequest(x);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(x){return this._supportedProtocolVersions.includes(x)&&x>="2025-11-25"}async writePrimingEvent(x,e,t,r){if(!this._eventStore||!this.supportsEmptySSEData(r))return;let a=await this._eventStore.storeEvent(t,{}),n=`id: ${a}
385
385
  data:
386
386
 
387
387
  `;void 0!==this._retryInterval&&(n=`id: ${a}
@@ -392,45 +392,45 @@ data:
392
392
  `;return r&&(a+=`id: ${r}
393
393
  `),a+=`data: ${JSON.stringify(t)}
394
394
 
395
- `,x.enqueue(e.encode(a)),!0}catch(x){return this.onerror?.(x),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(x,e){try{let t,r,a,n,_=x.headers.get("accept");if(!_?.includes("application/json")||!_.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!uT(x.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(e?.parsedBody===void 0)try{t=await x.json()}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else t=e.parsedBody;try{r=Array.isArray(t)?t.map(x=>ei.parse(x)):[ei.parse(t)]}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let A=r.some(x=>x_.safeParse(x).success);if(A){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(r.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!A){let e=this.validateSession(x);if(e)return e;let t=this.validateProtocolVersion(x);if(t)return t}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!r.some(x=>bH(x))){for(let t of r)this.onmessage?.(t,{authInfo:e?.authInfo,request:x});return new Response(null,{status:202})}let s=crypto.randomUUID(),i=r.find(x=>x_.safeParse(x).success),o=i?i.params.protocolVersion:x.headers.get("mcp-protocol-version")??xQ;if(this._enableJsonResponse)return new Promise(t=>{for(let x of(this._streamMapping.set(s,{resolveJson:t,cleanup:()=>{this._streamMapping.delete(s)}}),r))bH(x)&&this._requestToStreamMapping.set(x.id,s);for(let t of r)this.onmessage?.(t,{authInfo:e?.authInfo,request:x})});let l=new TextEncoder,c=new ReadableStream({start:x=>{a=x},cancel:()=>{void 0!==n&&clearInterval(n),this._streamMapping.get(s)?.controller===a&&this._streamMapping.delete(s)}}),v={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let x of(void 0!==this.sessionId&&(v["mcp-session-id"]=this.sessionId),r))bH(x)&&(this._streamMapping.set(s,{controller:a,encoder:l,cleanup:()=>{void 0!==n&&clearInterval(n),this._streamMapping.delete(s);try{a.close()}catch{}}}),this._requestToStreamMapping.set(x.id,s));for(let t of(await this.writePrimingEvent(a,l,s,o),r)){let r,a;bH(t)&&this._eventStore&&this.supportsEmptySSEData(o)&&(r=()=>{this.closeSSEStream(t.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(t,{authInfo:e?.authInfo,request:x,closeSSEStream:r,closeStandaloneSSEStream:a})}return this._streamMapping.get(s)?.controller===a&&(n=this.startKeepAlive(a,l)),new Response(c,{status:200,headers:v})}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(x)})}}async handleDeleteRequest(x){let e=this.validateSession(x);if(e)return e;let t=this.validateProtocolVersion(x);if(t)return t;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(x){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let e=x.headers.get("mcp-session-id");return e?e!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(x){let e=x.headers.get("mcp-protocol-version");if(null!==e&&!this._supportedProtocolVersions.includes(e)){let x=`Bad Request: Unsupported protocol version: ${e} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(400,-32e3,x)}}async close(){if(!this._closed){for(let{cleanup:x}of(this._closed=!0,this._streamMapping.values()))x();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(x){let e=this._requestToStreamMapping.get(x);if(!e)return;let t=this._streamMapping.get(e);t&&t.cleanup()}closeStandaloneSSEStream(){let x=this._streamMapping.get(this._standaloneSseStreamId);x&&x.cleanup()}async send(x,e){let t=e?.relatedRequestId;if((bY(x)||bz(x))&&(t=x.id),void 0===t){let e;if(bY(x)||bz(x))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(e=await this._eventStore.storeEvent(this._standaloneSseStreamId,x));let t=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===t)return;t.controller&&t.encoder&&(void 0===e||!t.replayedEventIds?.has(e))&&this.writeSSEEvent(t.controller,t.encoder,x,e);return}let r=this._requestToStreamMapping.get(t);if(!r)throw Error(`No connection established for request ID: ${String(t)}`);let a=this._streamMapping.get(r);if(!this._enableJsonResponse){let e;this._eventStore&&(e=await this._eventStore.storeEvent(r,x),a=this._streamMapping.get(r)),a?.controller&&a?.encoder&&(void 0===e||!a.replayedEventIds?.has(e))&&this.writeSSEEvent(a.controller,a.encoder,x,e)}if(bY(x)||bz(x)){this._requestResponseMap.set(t,x);let e=[...this._requestToStreamMapping.entries()].filter(([x,e])=>e===r).map(([x])=>x);if(e.every(x=>this._requestResponseMap.has(x))){if(!a){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(t)}`);if(!this._eventStore){for(let x of(this.onerror?.(Error(`Response for request ID ${String(t)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),e))this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x);return}for(let x of e)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x);return}if(this._enableJsonResponse&&a.resolveJson){let x={"Content-Type":"application/json"};void 0!==this.sessionId&&(x["mcp-session-id"]=this.sessionId);let t=e.map(x=>this._requestResponseMap.get(x));1===t.length?a.resolveJson(Response.json(t[0],{status:200,headers:x})):a.resolveJson(Response.json(t,{status:200,headers:x})),a.cleanup()}else a.cleanup();for(let x of e)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x)}}}};function mZ(x){if(null===x||"object"!=typeof x||Array.isArray(x))return null;let{method:e,id:t}=x;return"string"!=typeof e?null:"string"==typeof t||"number"==typeof t?t:null}function mJ(x,e,t,r,a=null){return Response.json({jsonrpc:"2.0",error:{code:e,message:t,...void 0!==r&&{data:r}},id:a},{status:x})}function mV(x,e=null){return mJ(x.httpStatus,x.code,x.message,x.data,e)}function mH(x){return x instanceof Error?x:Error(String(x))}function mU(x=null){return mJ(500,-32603,"Internal server error",void 0,x)}async function mY(x,e,t=!0){let r,a=x.method.toUpperCase(),n=e,_=x,A=!1;if("POST"===a){if(void 0===n){let e;t&&(_=x.clone());try{e=await x.text()}catch{return{step:"unreadable-body"}}try{r=0===e.length?void 0:JSON.parse(e)}catch{A=!0}A||void 0===r||(n=r)}else r=n;if(A||void 0===r)return{step:"no-json-body",forwardRequest:_}}return{step:"classified",outcome:function(x){if("POST"!==(x={...x,...void 0!==x.protocolVersionHeader&&{protocolVersionHeader:u_(x.protocolVersionHeader)},...void 0!==x.mcpMethodHeader&&{mcpMethodHeader:u_(x.mcpMethodHeader)},...void 0!==x.mcpNameHeader&&{mcpNameHeader:u_(x.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let e=x.body;if(Array.isArray(e)){if(0===e.length)return ur("jsonrpc-shape","empty-batch",400,new bp(bu.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let x of e){if(bM(uA(x)?x.params:void 0))return ur("jsonrpc-shape","batch-with-modern-element",400,new bp(bu.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(bH(x)||bU(x)||bY(x)||bz(x)))return ur("jsonrpc-shape","batch-with-invalid-element",400,new bp(bu.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return bY(e)||bz(e)?{kind:"legacy",reason:"response"}:uA(e)&&bH(e)?function(x,e){let t=e.params,r=e.method,a=x.protocolVersionHeader,n=void 0!==a&&a>=fz;if("initialize"===r&&!function(x){if(!bM(x))return!1;let e=bZ(x);if(void 0===e||!(e>=fz))return!1;let t=bQ(x);return void 0!==t&&0===bJ(t).length}(t)){if(n)return ua("initialize-with-modern-header",a,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let x=uA(t)&&"string"==typeof t.protocolVersion?t.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==x&&{requestedVersion:x}}}if(bM(t)){let n=bQ(t),_=(void 0===n?[]:bJ(n))[0];if(void 0!==_)return ur("envelope","envelope-invalid",400,new bp(bu.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${_.key}: ${_.problem}`,{envelope:_}),!0);let A=bZ(t);return void 0!==a&&void 0!==A&&a!==A?ua("header-body-version-mismatch",a,`the body envelope names protocol version ${A} but the MCP-Protocol-Version header names ${a}`):void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?ua("method-header-mismatch",x.mcpMethodHeader,`the body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:e,classification:us(A)}}if(n){let x=bQ(t),e=bJ(x??{}).filter(x=>"missing"===x.problem).map(x=>x.key),r=void 0===x?["_meta"]:e.length>0?e:[xl];return ur("envelope","modern-header-without-claim",400,new bp(bu.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, but the request is missing the required per-request envelope key(s): ${r.join(", ")}`,{envelope:{missing:r}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==a&&{requestedVersion:a}}}(x,e):uA(e)&&bU(e)?function(x,e){let t=e.params,r=e.method,a=x.protocolVersionHeader,n=void 0!==a&&a>=fz;if(bM(t)){let n=bZ(t);if(void 0===n){let x=bQ(t),e=(void 0===x?[]:bJ(x)).find(x=>x.key===xl)??{key:xl,problem:"expected a protocol version string"};return ur("envelope","notification-envelope-invalid",400,new bp(bu.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${e.key}: ${e.problem}`,{envelope:e}),!0)}if(void 0!==a&&a!==n)return ua("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${a}`);let _=us(n);return"modern"===_.era&&void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?ua("notification-method-header-mismatch",x.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:e,classification:_}}return n?void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?ua("notification-method-header-mismatch",x.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:e,classification:{era:"modern",revision:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(x,e):ur("jsonrpc-shape","invalid-json-rpc-body",400,new bp(bu.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,protocolVersionHeader:x.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:x.headers.get("mcp-method")??void 0,mcpNameHeader:x.headers.get("mcp-name")??void 0,...void 0!==r&&{body:r}}),body:r,parsedBody:n,forwardRequest:_}}function mz(x,e={}){var t;let{legacy:r,onerror:a,responseMode:n}=e;if("function"==typeof r)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let _=new Set,A=!1,c=x=>{try{a?.(x)}catch{}},v=e.bus??new mI(c),d={toolsChanged:()=>v.publish({kind:"tools_list_changed"}),promptsChanged:()=>v.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>v.publish({kind:"resources_list_changed"}),resourceUpdated:x=>v.publish({kind:"resource_updated",uri:x})},f=function(x){let{bus:e,onerror:t}=x,r=x.maxSubscriptions??1024,a=x.keepAliveMs??15e3,n=new Set;return{serve:function(x,_,A,s){var i,o,l;let c,v,d,f,b,u,p;if(n.size>=r)return t?.(Error(`subscriptions/listen refused: subscription limit reached (${r})`)),mN(x.id,-32603,"Subscription limit reached");let m=(i=x,(b=bR(bT).validateRequest("subscriptions/listen",i)).ok?b.value.params?.notifications:void 0);if(void 0===m)return mN(x.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let h=(o=m,l=A,u={},p=x=>void 0===l||!0===x,!0===o.toolsListChanged&&p(l?.tools?.listChanged)&&(u.toolsListChanged=!0),!0===o.promptsListChanged&&p(l?.prompts?.listChanged)&&(u.promptsListChanged=!0),!0===o.resourcesListChanged&&p(l?.resources?.listChanged)&&(u.resourcesListChanged=!0),void 0!==o.resourceSubscriptions&&o.resourceSubscriptions.length>0&&p(l?.resources?.subscribe)&&(u.resourceSubscriptions=[...o.resourceSubscriptions]),u),E=x.id,j=new TextEncoder,g=!1,y=x=>{if(!g)try{c.enqueue(j.encode(x))}catch(x){t?.(x instanceof Error?x:Error(String(x)))}},S=(x,e)=>{y(`event: message
395
+ `,x.enqueue(e.encode(a)),!0}catch(x){return this.onerror?.(x),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(x,e){try{let t,r,a,n,_=x.headers.get("accept");if(!_?.includes("application/json")||!_.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!u$(x.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(e?.parsedBody===void 0)try{t=await x.json()}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else t=e.parsedBody;try{r=Array.isArray(t)?t.map(x=>ei.parse(x)):[ei.parse(t)]}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let A=r.some(x=>x_.safeParse(x).success);if(A){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(r.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!A){let e=this.validateSession(x);if(e)return e;let t=this.validateProtocolVersion(x);if(t)return t}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!r.some(x=>bY(x))){for(let t of r)this.onmessage?.(t,{authInfo:e?.authInfo,request:x});return new Response(null,{status:202})}let s=crypto.randomUUID(),i=r.find(x=>x_.safeParse(x).success),o=i?i.params.protocolVersion:x.headers.get("mcp-protocol-version")??xQ;if(this._enableJsonResponse)return new Promise(t=>{for(let x of(this._streamMapping.set(s,{resolveJson:t,cleanup:()=>{this._streamMapping.delete(s)}}),r))bY(x)&&this._requestToStreamMapping.set(x.id,s);for(let t of r)this.onmessage?.(t,{authInfo:e?.authInfo,request:x})});let l=new TextEncoder,c=new ReadableStream({start:x=>{a=x},cancel:()=>{void 0!==n&&clearInterval(n),this._streamMapping.get(s)?.controller===a&&this._streamMapping.delete(s)}}),v={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let x of(void 0!==this.sessionId&&(v["mcp-session-id"]=this.sessionId),r))bY(x)&&(this._streamMapping.set(s,{controller:a,encoder:l,cleanup:()=>{void 0!==n&&clearInterval(n),this._streamMapping.delete(s);try{a.close()}catch{}}}),this._requestToStreamMapping.set(x.id,s));for(let t of(await this.writePrimingEvent(a,l,s,o),r)){let r,a;bY(t)&&this._eventStore&&this.supportsEmptySSEData(o)&&(r=()=>{this.closeSSEStream(t.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(t,{authInfo:e?.authInfo,request:x,closeSSEStream:r,closeStandaloneSSEStream:a})}return this._streamMapping.get(s)?.controller===a&&(n=this.startKeepAlive(a,l)),new Response(c,{status:200,headers:v})}catch(x){return this.onerror?.(x),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(x)})}}async handleDeleteRequest(x){let e=this.validateSession(x);if(e)return e;let t=this.validateProtocolVersion(x);if(t)return t;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(x){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let e=x.headers.get("mcp-session-id");return e?e!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(x){let e=x.headers.get("mcp-protocol-version");if(null!==e&&!this._supportedProtocolVersions.includes(e)){let x=`Bad Request: Unsupported protocol version: ${e} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(x)),this.createJsonErrorResponse(400,-32e3,x)}}async close(){if(!this._closed){for(let{cleanup:x}of(this._closed=!0,this._streamMapping.values()))x();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(x){let e=this._requestToStreamMapping.get(x);if(!e)return;let t=this._streamMapping.get(e);t&&t.cleanup()}closeStandaloneSSEStream(){let x=this._streamMapping.get(this._standaloneSseStreamId);x&&x.cleanup()}async send(x,e){let t=e?.relatedRequestId;if((bW(x)||b0(x))&&(t=x.id),void 0===t){let e;if(bW(x)||b0(x))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(e=await this._eventStore.storeEvent(this._standaloneSseStreamId,x));let t=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===t)return;t.controller&&t.encoder&&(void 0===e||!t.replayedEventIds?.has(e))&&this.writeSSEEvent(t.controller,t.encoder,x,e);return}let r=this._requestToStreamMapping.get(t);if(!r)throw Error(`No connection established for request ID: ${String(t)}`);let a=this._streamMapping.get(r);if(!this._enableJsonResponse){let e;this._eventStore&&(e=await this._eventStore.storeEvent(r,x),a=this._streamMapping.get(r)),a?.controller&&a?.encoder&&(void 0===e||!a.replayedEventIds?.has(e))&&this.writeSSEEvent(a.controller,a.encoder,x,e)}if(bW(x)||b0(x)){this._requestResponseMap.set(t,x);let e=[...this._requestToStreamMapping.entries()].filter(([x,e])=>e===r).map(([x])=>x);if(e.every(x=>this._requestResponseMap.has(x))){if(!a){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(t)}`);if(!this._eventStore){for(let x of(this.onerror?.(Error(`Response for request ID ${String(t)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),e))this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x);return}for(let x of e)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x);return}if(this._enableJsonResponse&&a.resolveJson){let x={"Content-Type":"application/json"};void 0!==this.sessionId&&(x["mcp-session-id"]=this.sessionId);let t=e.map(x=>this._requestResponseMap.get(x));1===t.length?a.resolveJson(Response.json(t[0],{status:200,headers:x})):a.resolveJson(Response.json(t,{status:200,headers:x})),a.cleanup()}else a.cleanup();for(let x of e)this._requestResponseMap.delete(x),this._requestToStreamMapping.delete(x)}}}};function mV(x){if(null===x||"object"!=typeof x||Array.isArray(x))return null;let{method:e,id:t}=x;return"string"!=typeof e?null:"string"==typeof t||"number"==typeof t?t:null}function mH(x,e,t,r,a=null){return Response.json({jsonrpc:"2.0",error:{code:e,message:t,...void 0!==r&&{data:r}},id:a},{status:x})}function mU(x,e=null){return mH(x.httpStatus,x.code,x.message,x.data,e)}function mY(x){return x instanceof Error?x:Error(String(x))}function mz(x=null){return mH(500,-32603,"Internal server error",void 0,x)}async function mW(x,e,t=!0){let r,a=x.method.toUpperCase(),n=e,_=x,A=!1;if("POST"===a){if(void 0===n){let e;t&&(_=x.clone());try{e=await x.text()}catch{return{step:"unreadable-body"}}try{r=0===e.length?void 0:JSON.parse(e)}catch{A=!0}A||void 0===r||(n=r)}else r=n;if(A||void 0===r)return{step:"no-json-body",forwardRequest:_}}return{step:"classified",outcome:function(x){if("POST"!==(x={...x,...void 0!==x.protocolVersionHeader&&{protocolVersionHeader:us(x.protocolVersionHeader)},...void 0!==x.mcpMethodHeader&&{mcpMethodHeader:us(x.mcpMethodHeader)},...void 0!==x.mcpNameHeader&&{mcpNameHeader:us(x.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let e=x.body;if(Array.isArray(e)){if(0===e.length)return un("jsonrpc-shape","empty-batch",400,new bh(bm.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let x of e){if(bJ(ui(x)?x.params:void 0))return un("jsonrpc-shape","batch-with-modern-element",400,new bh(bm.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(bY(x)||bz(x)||bW(x)||b0(x)))return un("jsonrpc-shape","batch-with-invalid-element",400,new bh(bm.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return bW(e)||b0(e)?{kind:"legacy",reason:"response"}:ui(e)&&bY(e)?function(x,e){let t=e.params,r=e.method,a=x.protocolVersionHeader,n=void 0!==a&&a>=f0;if("initialize"===r&&!function(x){if(!bJ(x))return!1;let e=bV(x);if(void 0===e||!(e>=f0))return!1;let t=bZ(x);return void 0!==t&&0===bH(t).length}(t)){if(n)return u_("initialize-with-modern-header",a,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let x=ui(t)&&"string"==typeof t.protocolVersion?t.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==x&&{requestedVersion:x}}}if(bJ(t)){let n=bZ(t),_=(void 0===n?[]:bH(n))[0];if(void 0!==_)return un("envelope","envelope-invalid",400,new bh(bm.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${_.key}: ${_.problem}`,{envelope:_}),!0);let A=bV(t);return void 0!==a&&void 0!==A&&a!==A?u_("header-body-version-mismatch",a,`the body envelope names protocol version ${A} but the MCP-Protocol-Version header names ${a}`):void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?u_("method-header-mismatch",x.mcpMethodHeader,`the body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:e,classification:uo(A)}}if(n){let x=bZ(t),e=bH(x??{}).filter(x=>"missing"===x.problem).map(x=>x.key),r=void 0===x?["_meta"]:e.length>0?e:[xl];return un("envelope","modern-header-without-claim",400,new bh(bm.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, but the request is missing the required per-request envelope key(s): ${r.join(", ")}`,{envelope:{missing:r}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==a&&{requestedVersion:a}}}(x,e):ui(e)&&bz(e)?function(x,e){let t=e.params,r=e.method,a=x.protocolVersionHeader,n=void 0!==a&&a>=f0;if(bJ(t)){let n=bV(t);if(void 0===n){let x=bZ(t),e=(void 0===x?[]:bH(x)).find(x=>x.key===xl)??{key:xl,problem:"expected a protocol version string"};return un("envelope","notification-envelope-invalid",400,new bh(bm.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${e.key}: ${e.problem}`,{envelope:e}),!0)}if(void 0!==a&&a!==n)return u_("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${a}`);let _=uo(n);return"modern"===_.era&&void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?u_("notification-method-header-mismatch",x.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:e,classification:_}}return n?void 0!==x.mcpMethodHeader&&x.mcpMethodHeader!==r?u_("notification-method-header-mismatch",x.mcpMethodHeader,`the notification body names method ${r} but the Mcp-Method header names ${x.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:e,classification:{era:"modern",revision:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(x,e):un("jsonrpc-shape","invalid-json-rpc-body",400,new bh(bm.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,protocolVersionHeader:x.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:x.headers.get("mcp-method")??void 0,mcpNameHeader:x.headers.get("mcp-name")??void 0,...void 0!==r&&{body:r}}),body:r,parsedBody:n,forwardRequest:_}}function m0(x,e={}){var t;let{legacy:r,onerror:a,responseMode:n}=e;if("function"==typeof r)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let _=new Set,A=!1,c=x=>{try{a?.(x)}catch{}},v=e.bus??new mB(c),d={toolsChanged:()=>v.publish({kind:"tools_list_changed"}),promptsChanged:()=>v.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>v.publish({kind:"resources_list_changed"}),resourceUpdated:x=>v.publish({kind:"resource_updated",uri:x})},f=function(x){let{bus:e,onerror:t}=x,r=x.maxSubscriptions??1024,a=x.keepAliveMs??15e3,n=new Set;return{serve:function(x,_,A,s){var i,o,l;let c,v,d,f,b,u,p;if(n.size>=r)return t?.(Error(`subscriptions/listen refused: subscription limit reached (${r})`)),mF(x.id,-32603,"Subscription limit reached");let m=(i=x,(b=bG(b$).validateRequest("subscriptions/listen",i)).ok?b.value.params?.notifications:void 0);if(void 0===m)return mF(x.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let h=(o=m,l=A,u={},p=x=>void 0===l||!0===x,!0===o.toolsListChanged&&p(l?.tools?.listChanged)&&(u.toolsListChanged=!0),!0===o.promptsListChanged&&p(l?.prompts?.listChanged)&&(u.promptsListChanged=!0),!0===o.resourcesListChanged&&p(l?.resources?.listChanged)&&(u.resourcesListChanged=!0),void 0!==o.resourceSubscriptions&&o.resourceSubscriptions.length>0&&p(l?.resources?.subscribe)&&(u.resourceSubscriptions=[...o.resourceSubscriptions]),u),E=x.id,j=new TextEncoder,g=!1,y=x=>{if(!g)try{c.enqueue(j.encode(x))}catch(x){t?.(x instanceof Error?x:Error(String(x)))}},S=(x,e)=>{y(`event: message
396
396
  data: ${JSON.stringify({jsonrpc:"2.0",method:x,params:e})}
397
397
 
398
398
  `)},I=x=>{if(!g){x&&y(`event: message
399
399
  data: ${JSON.stringify({jsonrpc:"2.0",id:E,result:{resultType:"complete",_meta:{[x2]:E,[tS]:s}}})}
400
400
 
401
- `),g=!0;try{v?.()}catch(x){t?.(x instanceof Error?x:Error(String(x)))}void 0!==d&&clearInterval(d),f?.(),n.delete(I);try{c.close()}catch{}}},N=new ReadableStream({start(x){c=x;let t=mB({method:"notifications/subscriptions/acknowledged",params:{notifications:h}},E);S(t.method,t.params),v=e.subscribe(x=>{if(g||!function(x,e){switch(e.kind){case"tools_list_changed":return!0===x.toolsListChanged;case"prompts_list_changed":return!0===x.promptsListChanged;case"resources_list_changed":return!0===x.resourcesListChanged;case"resource_updated":return void 0!==x.resourceSubscriptions&&x.resourceSubscriptions.includes(e.uri)}}(h,x))return;let e=mB(function(x){switch(x.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:x.uri}}}}(x),E);S(e.method,e.params)}),d=mS(a,()=>y(": keepalive\n\n")),n.add(I)},cancel(){I(!1)}});if(void 0!==_)if(_.aborted)I(!1);else{let x=()=>I(!1);_.addEventListener("abort",x,{once:!0}),f=()=>_.removeEventListener("abort",x)}return new Response(N,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let x of n)x(!0)},get openCount(){return n.size}}}({bus:v,maxSubscriptions:e.maxSubscriptions??1024,keepAliveMs:e.keepAliveMs??15e3,onerror:c});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let b="reject"===r?void 0:(t=e.keepAliveMs,async(e,r)=>{if("POST"!==e.method.toUpperCase())return mJ(405,-32e3,"Method not allowed.");try{let a=await x({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:e}),n=new mM({sessionIdGenerator:void 0,...void 0!==t&&{keepAliveMs:t}});await a.connect(n);let _=()=>{n.close().catch(()=>{}),a.close().catch(()=>{})};e.signal?.addEventListener("abort",_,{once:!0});let A=await n.handleRequest(e,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(null===A.body||"text/event-stream"!==uq(A.headers.get("content-type")))return _(),A;let s=A.body.getReader(),i=!1,o=()=>{i||(i=!0,_())},l=new ReadableStream({pull:async x=>{try{let{done:e,value:t}=await s.read();if(e){o(),x.close();return}void 0!==t&&x.enqueue(t)}catch(e){o(),x.error(e)}},cancel:x=>(o(),s.cancel(x).catch(()=>{}))});return new Response(l,{status:A.status,statusText:A.statusText,headers:A.headers})}catch(x){try{c?.(mH(x))}catch{}return mU(mZ(r?.parsedBody))}});async function u(t,r,a){var A,v;let d=t.classification.revision;if(void 0===d||!fW.includes(d)){let x=new bE({supported:[...fW],requested:d??"unknown"});return c(x),mJ(400,x.code,x.message,x.data,mZ(t.message))}let b=function(x,e){if("request"!==e.messageKind)return;let t=e.message.method;if(void 0===x.mcpMethodHeader)return ua("method-header-missing","(missing)",`the body names method ${t} but the required Mcp-Method header is absent`,"standard-header-validation");let r=Object.hasOwn(un,t)?un[t]:void 0;if(void 0===r)return;let a=e.message.params?.[r],n="string"==typeof a?a:void 0;if(void 0===x.mcpNameHeader){if(void 0===n)return;return ua("name-header-missing","(missing)",`the body carries params.${r}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let _=u_(x.mcpNameHeader),A=b9(_);return void 0===A?ua("name-header-invalid-encoding",_,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&A!==n?ua("name-header-mismatch",_,`the body carries params.${r}="${n}" but the Mcp-Name header names "${A}"`,"standard-header-validation"):void 0}({httpMethod:r.method,mcpMethodHeader:r.headers.get("mcp-method")??void 0,mcpNameHeader:r.headers.get("mcp-name")??void 0},t);if(void 0!==b)return c(Error(`Rejected inbound request (${b.cell}): ${b.message}`)),mV(b,mZ(t.message));let u="request"===t.messageKind?bQ(t.message.params):void 0,p=u?.[ef];if("request"===t.messageKind){let x=Object.hasOwn(fH,A=t.message.method)?fH[A]:void 0;if(void 0!==x){let e=fY(x,p);if(void 0!==e){let x=new bj({requiredCapabilities:e});return c(x),mJ(ut[x.code]??400,x.code,x.message,x.data,t.message.id)}}}let m=await x({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:r}),h=m instanceof mD?m.server:m;if("request"===t.messageKind&&"subscriptions/listen"===t.message.method){let x=h.getCapabilities(),e=l(h);return m.close().catch(c),f.serve(t.message,r.signal,x,e)}if("request"===t.messageKind&&"tools/call"===t.message.method&&m instanceof mD){let x=t.message.params,e="string"==typeof x?.name?x.name:void 0,a=void 0===e?void 0:m.toolInputSchemaJson(e);if(void 0!==a){let e=b3(a);if(e.valid&&e.declarations.length>0){let a=function(x,e,t){for(let r of x){let x=`Mcp-Param-${r.headerName}`,a=t.get(x),n=function(x,e){let t=x;for(let x of e){if(null===t||"object"!=typeof t)return;t=t[x]}return t}(e,r.path);if(null==n)continue;let _=function(x){if("string"==typeof x)return x;if("boolean"==typeof x)return x?"true":"false";if("number"==typeof x){if(!Number.isFinite(x)||Number.isInteger(x)&&!Number.isSafeInteger(x))return;return String(x)}}(n);if(void 0===_)continue;if(null===a)return ux("param-header-missing",x,`the body carries ${b5(r.path)}=${JSON.stringify(n)} but the ${x} header is absent`);let A=b9(a);if(void 0===A)return ux("param-header-invalid-encoding",x,`the ${x} header carries an invalid Base64 sentinel value`);if(!(("integer"===r.type||"number"===r.type)&&b8.test(A)&&"number"==typeof n?Number(A)===n:A===_))return ux("param-header-mismatch",x,`the ${x} header decodes to ${JSON.stringify(A)} but the body carries ${b5(r.path)}=${JSON.stringify(n)}`)}}(e.declarations,x?.arguments,r.headers);if(void 0!==a)return m.close().catch(c),c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),mV(a,t.message.id)}}}s(h,d),o(h,fW),void 0!==u&&(v={clientInfo:u[xh],clientCapabilities:p},i(h,v));let E=h.onclose;_.add(h),h.onclose=()=>{_.delete(h),E?.()};try{let x=await mQ(m,t.message,{classification:t.classification,request:r,...void 0!==a&&{authInfo:a},...void 0!==n&&{responseMode:n},...void 0!==e.keepAliveMs&&{keepAliveMs:e.keepAliveMs}});return"notification"===t.messageKind&&queueMicrotask(()=>void h.close().catch(()=>{})),x}catch(x){if(x instanceof fV&&x.code===fJ.ConnectionClosed)return new Response(null,{status:499});return await h.close().catch(()=>{}),_.delete(h),c(mH(x)),mU(mZ(t.message))}}async function p(x,e,t,r){if(void 0!==b)return b(e,{...void 0!==t&&{authInfo:t},...void 0!==r&&{parsedBody:r}});let a=function(x,e){switch(x.reason){case"http-method":return ur("http-method","modern-only-method-not-allowed",405,new bp(-32e3,"Method not allowed."),!0);case"batch":return ur("jsonrpc-shape","modern-only-batch-not-supported",400,new bp(bu.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ur("jsonrpc-shape","modern-only-response-post",400,new bp(bu.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let t=x.requestedVersion;return ur("era-classification","modern-only-missing-envelope",400,void 0===t?new bp(bu.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...e]}):new bE({supported:[...e],requested:t}),!0)}}}(x,fW);return void 0===a?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),mV(a,mZ(r)))}async function m(x,e){let t=e?.authInfo;if("POST"===x.method.toUpperCase()&&!uT(x.headers.get("content-type")))return c(Error("Unsupported Media Type: Content-Type must be application/json")),mJ(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let r=await mY(x,e?.parsedBody);if("unreadable-body"===r.step)return mJ(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===r.step)return void 0!==b?b(r.forwardRequest,{...void 0!==t&&{authInfo:t}}):mJ(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:n,parsedBody:_,forwardRequest:A}=r;try{switch(a.kind){case"reject":return c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),mV(a,mZ(n));case"modern":return await u(a,x,t);case"legacy":return await p(a,A,t,_)}}catch(x){return c(mH(x)),mU(mZ(n))}}return{fetch:async(x,e)=>{if(A)throw Error("This MCP handler has been closed");try{return await m(x,e)}catch(x){return c(mH(x)),mU(mZ(e?.parsedBody))}},notify:d,bus:v,close:async()=>{A=!0,f.closeAll();let x=[..._].map(x=>x.close().catch(()=>{}));_.clear(),await Promise.all(x)}}}I("http"),I("http2");let mW=I("stream"),m0=I("crypto");var m1=globalThis.Request,m2=class extends m1{constructor(x,e){"object"==typeof x&&m6 in x&&(x=x[m6]()),void 0!==e?.body?.getReader&&(e.duplex??="half"),super(x,e)}},m3=Symbol("wrapBodyStream"),m6=Symbol("getRequestCache"),m4=Symbol("requestCache"),m5=Symbol("incomingKey"),m7=Symbol("urlKey"),m8=Symbol("headersKey"),m9=Symbol("abortControllerKey"),hx=Symbol("getAbortController"),he={get method(){return this[m5].method||"GET"},get url(){return this[m7]},get headers(){return this[m8]||=(x=>{let e=[],t=x.rawHeaders;for(let x=0;x<t.length;x+=2){let{[x]:r,[x+1]:a}=t;58!==r.charCodeAt(0)&&e.push([r,a])}return new Headers(e)})(this[m5])},[hx](){return this[m6](),this[m9]},[m6](){return this[m9]||=new AbortController,this[m4]||=((x,e,t,r,a)=>{let n={method:x,headers:t,signal:a.signal};if("TRACE"===x){n.method="GET";let x=new m2(e,n);return Object.defineProperty(x,"method",{get:()=>"TRACE"}),x}if("GET"!==x&&"HEAD"!==x)if("rawBody"in r&&r.rawBody instanceof Buffer)n.body=new ReadableStream({start(x){x.enqueue(r.rawBody),x.close()}});else if(r[m3]){let x;n.body=new ReadableStream({async pull(e){try{x||=mW.Readable.toWeb(r).getReader();let{done:t,value:a}=await x.read();t?e.close():e.enqueue(a)}catch(x){e.error(x)}}})}else n.body=mW.Readable.toWeb(r);return new m2(e,n)})(this.method,this[m7],this.headers,this[m5],this[m9])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(x=>{Object.defineProperty(he,x,{get(){return this[m6]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(he,x,{value:function(){return this[m6]()[x]()}})}),Object.defineProperty(he,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[m4]};return`Request (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(he,m2.prototype);var ht=Symbol("responseCache"),hr=Symbol("getResponseCache"),ha=Symbol("cache"),hn=globalThis.Response,h_=class x{#xC;#xP;[hr](){return delete this[ha],this[ht]||=new hn(this.#xC,this.#xP)}constructor(e,t){let r;if(this.#xC=e,t instanceof x){let x=t[ht];if(x){this.#xP=x,this[hr]();return}this.#xP=t.#xP,r=new Headers(t.#xP.headers)}else this.#xP=t;("string"==typeof e||void 0!==e?.getReader||e instanceof Blob||e instanceof Uint8Array)&&(this[ha]=[t?.status||200,e,r||t?.headers])}get headers(){let x=this[ha];return x?(x[2]instanceof Headers||(x[2]=new Headers(x[2]||{"content-type":"text/plain; charset=UTF-8"})),x[2]):this[hr]().headers}get status(){return this[ha]?.[0]??this[hr]().status}get ok(){let x=this.status;return x>=200&&x<300}};function hA(x,e){return async(t,r,a)=>{let n,_;"function"==typeof a&&(a=void 0);let A=!1,s=new AbortController;r.on("close",()=>{A||s.abort()}),!0===r.destroyed&&s.abort();try{let e=await hi(t,a,{signal:s.signal});n=await x.fetch(e,{...void 0!==t.auth&&{authInfo:t.auth},...void 0!==a&&{parsedBody:a}})}catch(x){var i;try{e?.onerror?.(x instanceof Error?x:Error(String(x)))}catch{}i=function(x){if(null===x||"object"!=typeof x||Array.isArray(x))return null;let{method:e,id:t}=x;return"string"!=typeof e?null:"string"==typeof t||"number"==typeof t?t:null}(a),n=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:i},{status:500})}let o={};for(let[x,e]of n.headers)o[x]=e;if(r.writeHead(n.status,o),null===n.body){A=!0,r.end();return}r.on("drain",()=>{_?.(),_=void 0});let l=new Promise(x=>{s.signal.addEventListener("abort",()=>x(),{once:!0})});try{for await(let x of n.body){if(s.signal.aborted)break;!1===r.write(x)&&await Promise.race([new Promise(x=>{_=x}),l])}}catch{}A=!0,r.end()}}function hs(x){return Array.isArray(x)?x[0]:x}async function hi(x,e,t){let r,a=(x.method??"GET").toUpperCase(),n=`http://${hs(x.headers.host)??hs(x.headers[":authority"])??"localhost"}${x.url??"/"}`,_=new Headers;for(let[e,t]of Object.entries(x.headers))if(!(void 0===t||e.startsWith(":")))if(Array.isArray(t))for(let x of t)_.append(e,x);else _.set(e,t);if("GET"!==a&&"HEAD"!==a)if(void 0===e){let e=new TextDecoder,t="";for await(let r of x)t+="string"==typeof r?r:e.decode(r,{stream:!0});(t+=e.decode()).length>0&&(r=t)}else{let x=JSON.stringify(e);_.delete("content-encoding"),_.delete("transfer-encoding"),void 0===x?_.delete("content-length"):(r=x,_.set("content-length",String(new TextEncoder().encode(x).byteLength)))}return new Request(n,{method:a,headers:_,...t?.signal!==void 0&&{signal:t.signal},...void 0!==r&&{body:r}})}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(x=>{Object.defineProperty(h_.prototype,x,{get(){return this[hr]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(h_.prototype,x,{value:function(){return this[hr]()[x]()}})}),Object.defineProperty(h_.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[ht]};return`Response (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(h_,hn),Object.setPrototypeOf(h_.prototype,hn.prototype),void 0===globalThis.crypto&&(globalThis.crypto=m0),Symbol("outgoingEnded"),Symbol("incomingDraining");let ho=I("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js");function hl(x,e,t){x.readyState!==rg.OPEN||x.bufferedAmount>0xa00000?x.terminate():x.send(JSON.stringify({type:e,data:t}))}let hc=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","VIEWPORT_FAILED","INSPECTION_FAILED","SCROLL_FAILED","SCREENSHOT_FAILED","SNAPSHOT_FAILED","CHAT_NOT_READY","CHAT_BUSY","CHAT_SUBMIT_FAILED","CHAT_TIMEOUT","TOOL_CALL_FAILED","COMMAND_TIMEOUT"]);class hv extends Error{code;constructor(x,e){super(e),this.name="DebuggerControlError",this.code=x}}function hd(x){return"render_page"===x||"render_widget"===x}function hf(x){return"number"==typeof x&&Number.isFinite(x)}function hb(x){return"number"==typeof x&&Number.isInteger(x)&&x>=1&&x<=9999}function hu(x){if("submit_chat_query"===x.type)return 12e4;if("execute_sandbox_tool_call"===x.type){let e=x.toolCall?.tool_call?.deadline_ms;if("number"==typeof e&&Number.isFinite(e))return Math.max(1,e-Date.now()+1e3)}return 15e3}class hp{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(x){this.snapshotStore=x}registerClient(x,e){let t=this.getSnapshotStore(x),r=this.clients.get(x);r&&this.disconnectClient(r,"Debugger control connection was replaced");let a={clientId:x,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(x)??0,parallelJobs:new Map,queue:[],socket:e};this.clients.set(x,a),this.snapshotsByClientId.set(x,t),e.once("close",()=>{this.disconnectClient(a,"Debugger control connection was closed",!1)})}getSnapshotStore(x){return this.snapshotsByClientId.get(x)??{}}noteSnapshot(x){if(!x)return;let e=this.getSnapshotStore(x);Object.assign(e,this.snapshotStore),this.snapshotsByClientId.set(x,e);let t=Date.now();this.lastSnapshotAtByClientId.set(x,t);let r=this.clients.get(x);r&&(r.lastSnapshotAtMs=t)}execute(x,e,t){let r=void 0!==t?this.clients.get(t):"execute_sandbox_tool_call"===x?this.getToolCallClient():this.getActiveClient();if(!r||r.socket.readyState!==rg.OPEN)return Promise.reject(new hv("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===x?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let a=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((t,n)=>{let _={command:{...e,commandId:a,type:x},reject:n,resolve:t};"execute_sandbox_tool_call"===x?this.startParallelJob(r,_):(r.queue.push(_),this.flushClient(r))})}handleResult(x){var e,t;let r,a=x.clientId?.trim(),n=x.commandId?.trim(),_=a?this.clients.get(a):void 0,A=n?_?.parallelJobs.get(n):void 0,s=A??_?.activeJob;if(!_||!s||s.command.commandId!==n)return!1;if(!0===x.ok&&hd(s.command.type)&&(e=x.snapshot,e.snapshot.command_id===n&&e.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=x.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(a),r={target:x.target}):!0===x.ok&&!hd(s.command.type)&&(r=function(x,e){if("set_viewport"===x)return hb(e.width)&&hb(e.height)?e:void 0;if("submit_chat_query"===x)return!0===e.completed&&e.query?.trim()&&e.requestId?.trim()?e:void 0;if("take_snapshot"===x){let x=e.runtimeSnapshot;return x?.target?{runtimeSnapshot:x}:void 0}if("execute_sandbox_tool_call"===x)return!0===e.reported&&e.request_id?.trim()&&e.tool_call_id?.trim()?e:void 0;if("take_screenshot"===x||e.uid?.trim()){if("get_computed_style"===x){if(!Array.isArray(e.computedStyle)||!e.computedStyle.every(x=>!!x.name?.trim()&&"string"==typeof x.value))return;return e}if("get_element_rect"===x)return[e.x,e.y,e.width,e.height].every(hf)?e:void 0;if("scroll_to"===x)return[e.x,e.y,e.maxX,e.maxY,e.viewportWidth,e.viewportHeight].every(x=>hf(x)&&x>=0)&&e.x<=e.maxX&&e.y<=e.maxY?e:void 0;if("take_screenshot"===x){let x="png"===e.format?"image/png":"jpeg"===e.format?"image/jpeg":"webp"===e.format?"image/webp":void 0;return"string"==typeof e.data&&e.data.length>0&&e.mimeType===x&&hf(e.width)&&hf(e.height)&&(void 0===e.uid||e.uid?.trim())?e:void 0}}}(s.command.type,x.result),"take_snapshot"===s.command.type&&r&&"runtimeSnapshot"in r&&this.storeRuntimeSnapshot(_.clientId,r.runtimeSnapshot)),r)s.resolve(r);else{let e=x.error??{},r=e.code?.trim(),a=r&&hc.has(r)?r:void 0;s.reject(new hv(a??(hd(t=s.command.type)?"RENDER_FAILED":"set_viewport"===t?"VIEWPORT_FAILED":"scroll_to"===t?"SCROLL_FAILED":"submit_chat_query"===t?"CHAT_SUBMIT_FAILED":"take_snapshot"===t?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===t?"TOOL_CALL_FAILED":"take_screenshot"===t?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),e.message?.trim()||"Debugger control command failed"))}return s.timeout&&clearTimeout(s.timeout),A?_.parallelJobs.delete(n):_.activeJob=void 0,this.flushClient(_),!0}getActiveClient(){return[...this.clients.values()].filter(x=>x.socket.readyState===rg.OPEN&&x.lastSnapshotAtMs>0).sort((x,e)=>e.lastSnapshotAtMs-x.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(x,e){let t=this.getSnapshotStore(x).snapshot,r=t?.snapshot;if(!t||!r||r.client_id!==x)return;let a=t.debug_snapshot,{root:n,..._}=e,A=Date.now();this.snapshotStore.snapshot={...t,stored_at:new Date(A).toISOString(),stored_at_ms:A,snapshot:{...r,runtime_snapshot:e},...a?{debug_snapshot:{...a,runtime_snapshot:_}}:{}},this.snapshotStore.updatedAtMs=A,this.noteSnapshot(x)}getConnectedClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===rg.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===rg.OPEN&&x.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(x,e){let t=e.command.commandId;x.parallelJobs.set(t,e),e.timeout=setTimeout(()=>{x.parallelJobs.delete(t)&&e.reject(new hv("TOOL_CALL_FAILED","Debugger control command timed out"))},hu(e.command));try{hl(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}flushClient(x){if(x.activeJob||x.socket.readyState!==rg.OPEN)return;let e=x.queue.shift();if(e){x.activeJob=e,e.timeout=setTimeout(()=>{if(x.activeJob===e){if("submit_chat_query"===e.command.type){e.timeout=void 0,e.reject(new hv("CHAT_TIMEOUT","Debugger control command timed out"));try{hl(x.socket,"control",{commandId:e.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(x,"Debugger control connection was closed");return}e.timeout=setTimeout(()=>{x.activeJob===e&&this.disconnectClient(x,"Debugger chat cancellation was not acknowledged")},5e3);return}x.activeJob=void 0,e.reject(new hv(hd(e.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(x)}},hu(e.command));try{hl(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}}disconnectClient(x,e,t=!0){if(this.clients.get(x.clientId)!==x)return;this.clients.delete(x.clientId),this.snapshotsByClientId.delete(x.clientId);let r=new hv("DEBUGGER_DISCONNECTED",e);for(let e of(x.activeJob?.timeout&&clearTimeout(x.activeJob.timeout),x.activeJob?.reject(r),x.activeJob=void 0,x.parallelJobs.values()))e.timeout&&clearTimeout(e.timeout),e.reject(r);for(let e of(x.parallelJobs.clear(),x.queue.splice(0)))e.reject(r);t&&x.socket.readyState===rg.OPEN&&x.socket.close()}}let hm=["page","widget","app"],hh=["log","info","warn","error","debug","eval"],hE=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function hj(x,e){let t=e.pageIdx??0,r=e.pageSize??50,a=t*r,n=x.slice(a,a+r);return{pageIdx:t,pageSize:r,total:x.length,hasMore:a+n.length<x.length,items:n}}function hg(x){if(!x.snapshot)return{stored:!1,updatedAtMs:x.updatedAtMs};let{debug_snapshot:e,...t}=x.snapshot;return{stored:!0,storedAt:t.stored_at,updatedAtMs:t.stored_at_ms??x.updatedAtMs,snapshot:t.snapshot}}function hy(x){return x.value??x.unserializableValue??x.description??x.type??""}function hS(x,e){var t,r;let a;return(t=x,"all"===(r=e)?hm:"page"===r||"widget"===r||"app"===r?[r]:(a=t.context,a?.page_id||a?.page_path?["page","app"]:a?.widget_id?["widget"]:hm)).flatMap(e=>{let t,r=(t=x.runtime_console?.[e],{entries:t?.entries??[],updatedAtMs:t?.updated_at_ms??t?.updatedAtMs});return r.entries.map((x,t)=>{var a;let n,_,A,s;return a=r.updatedAtMs,n=x.url??x.location?.url,_=x.lineNumber??x.location?.lineNumber,A=x.columnNumber??x.location?.columnNumber,s=x.id??String(t),{msgid:`${e}:${s}`,target:e,level:x.level??"log",source:x.source??"",timestamp:x.timestamp??0,text:x.message??(x.args??[]).map(hy).filter(Boolean).join(" "),...n?{url:n}:{},...void 0===_?{}:{lineNumber:_},...void 0===A?{}:{columnNumber:A},...void 0===a?{}:{updatedAtMs:a},entry:x}})})}function hI(x,e){return{id:x.toolCallId??x.id??`tool-call:${e}`,requestId:x.requestId??x.request_id??"",toolCallId:x.toolCallId??x.id??"",toolName:x.toolName??x.name??"",serverId:x.serverId??x.server_id??"",appKey:x.appKey??x.app_key??"",status:x.status??"",createdAtMs:x.createdAtMs??x.created_at_ms??0,updatedAtMs:x.updatedAtMs??x.updated_at_ms??0,requiresUserApproval:!0===x.requiresUserApproval,isMiniApp:!0===x.isMiniApp,message:x.message??"",resultSummary:x.resultSummary??x.structuredResultSummary}}function hN(x,e){if("page"===e){let{pageId:e,path:t}=x;if(!e||!t)return;return{pageId:e,path:t,name:x.name??e,isHome:!0===x.isHome}}let{widgetId:t}=x;if(t)return{widgetId:t,name:x.name??t}}let hB={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},hF={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},hw={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function hC(x,e={}){return{structuredContent:x,content:e.image?[{type:"image",...e.image}]:[{type:"text",text:e.text??JSON.stringify(x,null,2)}],...e.isError?{isError:!0}:{}}}async function hP(x,e={}){try{return await x()}catch(x){return function(x,e={}){let t=x instanceof hv?x:new hv("INSPECTION_FAILED",String(x));return hC({...e,error:{code:t.code,message:t.message}},{isError:!0})}(x,e)}}function hk(x,e,t,r){let a=tM(t.inputSchema);x.registerTool(e,{...t,inputSchema:a},r)}let hD="/__wsd_mcp";async function hL({request:x,response:e,url:t},r,a){if("OPTIONS"===x.method){fA(e),e.writeHead(204),e.end();return}if("POST"!==x.method)return void fs(e,405,"Method not allowed");let n=t.searchParams.get("clientId")??void 0,_=void 0===n?r:a.getSnapshotStore(n),A=mz(()=>{let x,e;return x=new mD({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),e=async x=>{var e;let t=hg(_);if(!t.stored)return hC(t);let r=hj((e=t.snapshot,[{source:"simulator",events:e.simulator?.trace_events??[]},{source:"widget_runtime",events:e.widget_runtime_trace_events??[]},{source:"page_runtime",events:e.page_runtime_trace_events??[]}].flatMap(({source:x,events:e})=>e.map((e,t)=>{let r;return r=e.payload??{},{source:x,id:e.id??`${x}:${t}`,timestamp:e.timestamp??0,category:r.category??e.display?.category??"",event:r.event??e.event??"",requestId:r.request_id??r.requestId??r.trace_id??r.trace?.trace_id??"",payload:e.payload??e}}))).filter(e=>{let t,r,a;return t=x.category??[],r=x.event?.trim(),a=x.requestId?.trim(),(0===t.length||t.includes(e.category))&&(!r||e.event===r)&&(!a||e.requestId===a)}),x);return hC({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,events:r.items})},hk(x,"list_chat_messages",{annotations:hB,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let x=hg(_);if(!x.stored)return hC(x);let e=_.snapshot?.debug_snapshot?.simulator??x.snapshot.simulator;return hC({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,streamStatus:e?.stream_status,messages:e?.messages??[]})}),hk(x,"list_console_messages",{annotations:hB,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:rc(x1(hh)).optional(),pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),query:ra().optional(),target:x1(["current","page","widget","app","all"]).optional()}},async x=>{let e=hg(_);if(!e.stored)return hC(e);let t=hj(hS(e.snapshot,x.target).filter(e=>{let t,r;return t=x.levels??[],r=x.query?.trim().toLowerCase(),(!(t.length>0)||!!t.includes(e.level))&&(!r||[e.text,e.url,e.source,e.target].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(r)))}),x);return hC({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,total:t.total,pageIdx:t.pageIdx,pageSize:t.pageSize,hasMore:t.hasMore,messages:t.items.map(({entry:x,...e})=>e)})}),hk(x,"get_console_message",{annotations:hB,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:ra()}},async x=>{let e=hg(_);if(!e.stored)return hC(e);let t=hS(e.snapshot,"all").find(e=>e.msgid===x.msgid);return hC({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,found:!!t,...t?{message:t}:{msgid:x.msgid}})}),hk(x,"get_log_snapshot",{annotations:hB,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let x=hg(_);return x.stored?hC({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,snapshot:x.snapshot}):hC(x)}),hk(x,"list_render_targets",{annotations:hB,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:x1(["all","page","widget"]).optional()}},async x=>{var e,t;let r,a=hg(_);return a.stored?hC({stored:!0,storedAt:a.storedAt,updatedAtMs:a.updatedAtMs,...(e=a.snapshot,t=x.type??"all",r=e.render_targets??{},{pages:"widget"===t?[]:(r.pages??[]).map(x=>hN(x,"page")).filter(Boolean),widgets:"page"===t?[]:(r.widgets??[]).map(x=>hN(x,"widget")).filter(Boolean),...r.currentTarget?{currentTarget:r.currentTarget}:{}})}):hC(a)}),hk(x,"take_snapshot",{annotations:hB,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:x1(["current","page","widget"]).optional(),verbose:eY().optional()}},x=>hP(async()=>{let e=function(x,e){var t,r;let a,n,_,A=x.runtime_snapshot;if(!A?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let s=A.target,i=s.type,o=e.target??"current";if(("page"===o||"widget"===o)&&i!==o)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:o,currentTarget:s};if(!A.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:s};let l=A.selectedUid,c=(t=A.root,r=!0===e.verbose,a=[],n=0,(_=(x,e)=>{var t,A;let{name:s,uid:i}=x;if(!i||!s)return;n+=1;let o=" ".repeat(e);if("text"===x.type)return void a.push(`${o}uid=${i} text ${JSON.stringify(x.text??"")}`);let c=[`uid=${i}`,s],{keyboardFocusable:v=!1,name:d,role:f}=x.accessibility??{};for(let e of(f&&(r||"generic"!==f)&&c.push(`role=${JSON.stringify(f)}`),d&&c.push(`name=${JSON.stringify(d)}`),(r||v)&&c.push(`focusable=${String(v)}`),(x.attributes??[]).map(x=>({name:x.name,value:x.value})).filter(x=>x.name&&(r||hE.has(x.name)||x.name.startsWith("aria-")))))c.push((t=e.name,(A=e.value)?`${t}=${JSON.stringify(A)}`:t));for(let t of(i===l&&c.push("[selected]"),a.push(`${o}${c.join(" ")}`),x.children??[]))_(t,e+1)})(t,0),{actualNodeCount:n,text:a.join("\n")});return{available:!0,target:s,nodeCount:A.nodeCount??c.actualNodeCount,...l?{selectedUid:l}:{},truncated:!0===A.truncated,snapshot:c.text,snapshotUpdatedAtMs:A.updatedAtMs}}({runtime_snapshot:(await a.execute("take_snapshot",{target:x.target??"current"},n)).runtimeSnapshot},x),t=hg(_),r={stored:t.stored,...t.stored?{storedAt:t.storedAt,updatedAtMs:t.updatedAtMs}:{},...e};return hC(r,{text:e.available?e.snapshot:JSON.stringify(r,null,2)})},{available:!1,stored:!1})),hk(x,"get_computed_style",{annotations:hB,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:rc(ra().min(1)).max(100).optional(),uid:ra().min(1)}},({properties:x,uid:e})=>hP(async()=>hC(await a.execute("get_computed_style",{uid:e,...x?{properties:x}:{}},n)))),hk(x,"get_element_rect",{annotations:hB,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:ra().min(1)}},({uid:x})=>hP(async()=>hC(await a.execute("get_element_rect",{uid:x},n)))),hk(x,"take_screenshot",{annotations:hB,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:x1(["png","jpeg","webp"]).optional(),quality:eD().min(0).max(100).optional(),uid:ra().min(1).optional()}},({format:x="png",quality:e,uid:t})=>hP(async()=>{let r=await a.execute("take_screenshot",{format:x,...void 0!==e?{quality:e}:{},...t?{uid:t}:{}},n),{data:_,...A}=r;return hC({captured:!0,...A},{image:{data:_,mimeType:r.mimeType}})},{captured:!1})),hk(x,"scroll_to",{annotations:hw,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:ra().min(1).optional(),x:eD().min(0).optional(),y:eD().min(0).optional()}},({uid:x,x:e,y:t})=>hP(async()=>hC({scrolled:!0,...await a.execute("scroll_to",{uid:x,x:e,y:t},n)}),{scrolled:!1})),hk(x,"set_viewport",{annotations:hw,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:eD().int().min(1).max(9999),width:eD().int().min(1).max(9999)}},({height:x,width:e})=>hP(async()=>hC({updated:!0,viewport:await a.execute("set_viewport",{height:x,width:e},n)}),{updated:!1})),hk(x,"render_page",{annotations:hF,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:ra().min(1)}},({url:x})=>hP(async()=>hC({rendered:!0,target:(await a.execute("render_page",{url:x},n)).target}),{rendered:!1})),hk(x,"render_widget",{annotations:hF,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:e6(ra(),x4()).optional(),widgetId:ra().min(1)}},({structuredContent:x,widgetId:e})=>hP(async()=>hC({rendered:!0,target:(await a.execute("render_widget",{structuredContent:x??{},widgetId:e},n)).target}),{rendered:!1})),hk(x,"submit_chat_query",{annotations:hF,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:ra().trim().min(1)}},({query:x})=>hP(async()=>hC({submitted:!0,...await a.execute("submit_chat_query",{query:x},n)}),{submitted:!1})),hk(x,"list_agent_trace_events",{annotations:hB,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:rc(ra()).optional(),event:ra().optional(),pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),requestId:ra().optional()}},e),hk(x,"list_agent_tool_calls",{annotations:hB,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),query:ra().optional(),requestId:ra().optional(),status:rc(ra()).optional(),toolName:ra().optional()}},async x=>{var e;let t=hg(_);if(!t.stored)return hC(t);let r=hj((e=t.snapshot,(e.simulator?.tool_calls??[]).map(hI)).filter(e=>{let t,r,a,n;return t=x.requestId?.trim(),r=x.toolName?.trim(),a=x.status??[],n=x.query?.trim().toLowerCase(),(!t||e.requestId===t)&&(!r||e.toolName===r)&&(!(a.length>0)||!!a.includes(e.status))&&(!n||[e.toolName,e.serverId,e.appKey,e.status,e.message,"string"==typeof e.resultSummary?e.resultSummary:void 0].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(n)))}),x);return hC({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,toolCalls:r.items})}),x}),s=hA(A);try{await s(x,e)}catch(x){e.headersSent?e.destroy(x instanceof Error?x:void 0):fs(e,500,x instanceof Error?x.message:String(x))}finally{await A.close().catch(()=>void 0)}}let hq="/__web_sdk_debug_scenes",hT="/__web_sdk_widget_view_data_templates",hR={"Cache-Control":"no-cache"};async function h$(x,e){try{let t=await e?.()??{templatesByEntry:{},templatesByWidget:{}};fi(x,200,t,hR)}catch(e){d6.error("加载 Widget viewData 模板失败",{error:e}),fi(x,500,{templatesByEntry:{},templatesByWidget:{}},hR)}}let hG="Action HUB request failed or returned an invalid response",hO=x=>null!=x&&0!==x&&"0"!==x;async function hX(x,e){if(!function({request:x,response:e}){return!function(x){if(!["127.0.0.1","::1","::ffff:127.0.0.1"].includes(x.socket.remoteAddress??""))return!1;try{let e=x.headers.host;if(!e)return!1;let t=new URL(`http://${e}`);if(!["127.0.0.1","[::1]","localhost"].includes(t.hostname)||t.username||t.password||"/"!==t.pathname||t.search||t.hash)return!1;let r=x.headers.origin;return!r||r===t.origin}catch{return!1}}(x)?(fs(e,403,"Forbidden origin or host"),!1):"OPTIONS"===x.method?(e.writeHead(204).end(),!1):"POST"!==x.method?(fs(e,405,"Method not allowed"),!1):x.headers["content-type"]?.split(";")[0].trim().toLowerCase()==="application/json"||(fs(e,415,"Content-Type must be application/json"),!1)}(x))return;let{request:t,response:r}=x,a=new AbortController,n=()=>a.abort(),_=mz(()=>(function(x,e){let t=new mk({name:"doubao-action-hub",version:"1.0.0"},{capabilities:{tools:{}}});for(let r of["tools/list","tools/call"])t.setRequestHandler(r,(t,r)=>hM(x,t,AbortSignal.any([e,r.mcpReq.signal])));return t})(e,a.signal)),A=setTimeout(()=>{a.abort(),r.headersSent||r.destroyed?(r.destroy(),t.destroy()):(r.once("finish",()=>t.destroy()),fs(r,504,"Action HUB request timed out"))},6e4);t.once("aborted",n),r.once("close",n);try{let e=await hK(x);void 0===e||a.signal.aborted||await hA(_)(t,r,e)}finally{clearTimeout(A),t.off("aborted",n),r.off("close",n),a.abort(),await _.close()}}async function hK({request:x,response:e}){let t;try{t=await fl(x,e,1048576)}catch{e.destroyed||e.writableEnded||fs(e,413,"Request body is too large or incomplete");return}try{return JSON.parse(t)}catch{fs(e,400,"Invalid JSON request");return}}async function hQ(x){if(!x.ok||!x.body)throw await x.body?.cancel(),Error(hG);let e=[],t=0;for await(let r of x.body){if((t+=r.byteLength)>4194304)throw Error(hG);e.push(r)}return JSON.parse(Buffer.concat(e).toString("utf8"))}async function hM(x,e,t){try{let r=await (x.fetcher??fetch)(`https://mcp.bytedance.net/mcp/proxy/${e.method}`,{method:"POST",redirect:"error",signal:t,headers:{...fy(),"Content-Type":"application/json","X-Access-Key":x.accessKey,"X-Client-Version":"doubao-web-simulator",...x.cluster?{cluster:x.cluster}:{}},body:JSON.stringify({mcp_server_names:[x.serverName],..."tools/call"===e.method?{name:e.params.name,arguments:JSON.stringify({...e.params.arguments,from_mcp_call:!0})}:{},...x.headers?{extra_info:{headers:JSON.stringify(x.headers)}}:{}})}),a=await hQ(r);if(!oS(a))throw Error(hG);let n=a.result;if("string"==typeof n)try{n=JSON.parse(n)}catch{}for(let t of(n=function x(e,t){return"string"==typeof e?e.split(t).join("[redacted]"):Array.isArray(e)?e.map(e=>x(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e.split(t).join("[redacted]"),x(r,t)])):e}(n,x.accessKey),"tools/list"===e.method?[a,n]:[a]))if(!oS(t)||void 0!==t.base_resp&&!oS(t.base_resp)||[t.error_code,t.code,t.status_code,t.base_resp?.status_code].some(hO)||!1===t.success||t.error||void 0!==t.status&&![0,"0","success","ok"].includes(t.status))throw Error(hG);if("tools/call"===e.method&&"string"==typeof n)return{content:[{type:"text",text:n}],structuredContent:{result:n}};if(!oS(n)||void 0!==n.base_resp&&(!oS(n.base_resp)||hO(n.base_resp.status_code)))throw Error(hG);if("tools/list"===e.method){if(!Array.isArray(n.tools))throw Error(hG);return{tools:n.tools.map(x=>{if(!oS(x))throw Error(hG);let e=x.input_schema??x.inputSchema,t={name:x.name,...void 0===x.description?{}:{description:x.description},inputSchema:"string"==typeof e?JSON.parse(e):e};if(!uS.Tool(t))throw Error(hG);return t})}}return{content:Array.isArray(n.content)&&n.content.every(uS.ContentBlock)?n.content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n,...hO(n.error_code)||hO(n.errorCode)||!0===n.isError?{isError:!0}:{}}}catch{throw Error(hG)}}let hZ="/__dbx_real_device_debug",hJ=`${hZ}/state`,hV=`${hZ}/start`,hH=`${hZ}/cancel`,hU=`${hZ}/qr`;class hY{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:hJ,startEndpoint:hV,cancelEndpoint:hH,qrEndpoint:hU,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(x){this.provider=x,this.accessToken=x?ar.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:x=>x.pathname.startsWith(hZ),handle:({request:x,response:e,url:t})=>this.serveRequest(x,e,t)}]}async serveRequest(x,e,t){if(!this.validateRequest(x,e))return;let r=this.provider;if(!r)return this.writeError(e,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let a=await this.readJsonBody(x,e);if(a)try{if(t.pathname===hJ||t.pathname===hV){if(Object.keys(a).length>0)return this.writeError(e,400,"INVALID_REQUEST","Unexpected request fields");let x=t.pathname===hJ?await r.getState():await r.start();fi(e,200,x);return}if(t.pathname===hH){let x=a.operationId;if("string"!=typeof x||!x||1!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid operationId");fi(e,200,await r.cancel(x));return}if(t.pathname===hU){let{operationId:x,kind:t}=a;if("string"!=typeof x||!x||"modern"!==t&&"legacy"!==t||2!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid QR request");let n=await r.getQrImage(x,t);if(!n)return this.writeError(e,404,"QR_NOT_FOUND","QR image is unavailable");fA(e),e.writeHead(200,{"Content-Length":n.body.byteLength,"Content-Type":n.contentType}),e.end(n.body);return}return this.writeError(e,404,"NOT_FOUND","Not found")}catch{return this.writeError(e,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(x,e){var t,r;let a,n,_;if(!function(x){if(!x)return!1;try{let e=new URL(`http://${x}`).hostname.toLowerCase();return"127.0.0.1"===e||"[::1]"===e||"localhost"===e}catch{return!1}}(x.headers.host))return this.writeError(e,403,"FORBIDDEN_HOST","Forbidden host"),!1;let A=x.headers["x-dbx-real-device-token"];if("string"!=typeof A||!this.accessToken||(t=A,r=this.accessToken,n=(a=new TextEncoder).encode(t),_=a.encode(r),!(n.length===_.length&&ar.timingSafeEqual(n,_))))return this.writeError(e,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==x.method)return this.writeError(e,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(x.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(e,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let s=x.headers.origin;return!s||s===`http://${x.headers.host}`||(this.writeError(e,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(x,e){let t,r;try{t=await fl(x,e,4096)}catch{return this.writeError(e,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!t.trim())return{};try{r=JSON.parse(t)}catch{return this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body")}return!r||"object"!=typeof r||Array.isArray(r)?this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body"):r}writeError(x,e,t,r){x.writableEnded||x.destroyed||fi(x,e,{error:{code:t,message:r}})}}let hz={"Cache-Control":"no-cache"},hW="/app_developer/api/sandbox/",h0=`${hW}session/business_info/update`,h1=new Set([`${hW}resources/notices/pull`,`${hW}resources/tasks/pull`]),h2={"Access-Control-Expose-Headers":fe},h3=new Set;function h6(x,e,t,r,a,n){if(!Z())return!1;let _=`${a[fx]??""} ${x} ${e.pathname}`,A=h1.has(e.pathname);if(A&&t>=500){if(h3.has(_))return!1;h3.add(_)}else A&&t<500&&h3.delete(_);let s=Number(process.hrtime.bigint()-r)/1e6;return d6.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:s,headers:a,logId:n}),!0}function h4({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){ff({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_})}function h5(x,e,t){return t&&!(h1.has(x.pathname)&&e>=500)}function h7(x,e){if(x.pathname!==h0||!e)return e;try{let x=JSON.parse(e);return JSON.stringify({...x,..."csr_pem"in x?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"Sandbox 业务信息请求无效"})}}async function h8({method:x,request:e,requestBody:t,requestHeaders:r,response:a,targetUrl:n,usePlatformFetch:_}){let A=process.hrtime.bigint(),s=fb(e,a);try{let e,i=_?await fN({internal:!0,path:`${n.pathname}${n.search}`,method:x,body:t,headers:r,signal:s}):await fetch(n,{body:"GET"===x||"HEAD"===x?void 0:t,headers:r,method:x,signal:s}),o=h6(x,n,i.status,A,r,i.headers.get(fe)??void 0);if(a.destroyed||a.writableEnded)return void i.body?.cancel().catch(()=>void 0);let l=await fc(i);return h5(n,i.status,o)&&h4({method:x,requestBody:h7(n,t),requestHeaders:r,responseBody:l,responseHeaders:i.headers,statusCode:i.status,targetUrl:n}),a.destroyed||a.writableEnded||(e=f_(i.headers,[fe]),fA(a,h2),a.writeHead(i.status,e),a.end(l)),{body:l,ok:i.ok}}catch(i){if(a.destroyed||a.writableEnded||s.aborted)return;let e=`代理 Sandbox 请求失败:${i instanceof Error?i.message:String(i)}`,_=h6(x,n,502,A,r);h5(n,502,_)&&h4({method:x,requestBody:h7(n,t),requestHeaders:r,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:n}),fs(a,502,e,h2)}}async function h9(x,e,t={}){let r;if("POST"!==x.method)return void fs(e,405,"不支持的请求方法",h2);try{r=JSON.parse(await fl(x,e,0xa00000))}catch(x){fs(e,400,`Sandbox 代理请求内容无效:${x.message}`,h2);return}let a=function(x,e){if(!x.url)return;let t=new URL(x.url,e);if(!t.pathname.startsWith(hW))return;let r=new URL(`${t.pathname}${t.search}`,e);var a=x.params;if(a)for(let[x,e]of Object.entries(a))null!=e&&r.searchParams.set(x,String(e));return r}(r,t.targetOrigin??oN);if(!a)return void fs(e,404,"未找到 Sandbox endpoint",h2);if(!t.sandboxSessionId)return void fi(e,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},h2);let n=function(x,e,t,r){if(e.pathname.startsWith(`${hW}session/`)&&e.pathname!==`${hW}session/create`)return JSON.stringify({..."object"==typeof x.data&&null!==x.data?x.data:{},sandbox_session_id:r});if(void 0===x.data)return;if("object"!=typeof x.data||null===x.data||!t)return JSON.stringify(x.data);let a={...x.data};return e.pathname.startsWith(`${hW}jsb/`)&&"app_key"in a&&(a.app_key=t),e.pathname===`${hW}passport/open/auth`&&"client_key"in a&&(a.client_key=t),JSON.stringify(a)}(r,a,t.sandboxAppId,t.sandboxSessionId),_=r.method||"POST",A=function(x,e,t,r,a){let n=Object.fromEntries(Object.entries(fa({...x.headers,...t,...void 0===r?{}:{"content-length":String(Buffer.byteLength(r))},"content-type":"application/json"},e,{...fy(),...a?{[fx]:a}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]));for(let x of Object.keys(n))"accept-encoding"===x.toLowerCase()&&delete n[x];return n["accept-encoding"]="identity",n}(x,a,r.headers,n,t.sandboxSessionId),s=await h8({method:_,request:x,requestBody:n,requestHeaders:A,response:e,targetUrl:a,usePlatformFetch:!t.targetOrigin});if(a.pathname===h0&&s?.ok)try{let x=JSON.parse(s.body.toString("utf8"));(void 0===x.code||0===x.code)&&t.onBusinessInfoUpdated?.(function(x){if(!x||"object"!=typeof x||Array.isArray(x))return;let e="string"==typeof x.csr_pem?x.csr_pem.trim():"",t="string"==typeof x.phone_num?x.phone_num.trim():"";return t?{...e?{csrPem:e}:{},phoneNum:t}:void 0}(r.data))}catch{}}let Ex="/app_developer/api/sandbox/bridge/events",Ee="/app_developer/api/sandbox/bridge/response",Et=new Set(["connection","content-length","host"]),Er=new Set(["heartbeat"]),Ea=[500,1e3,2e3,5e3],En=0;function E_(x){return x.length<=8?x:`${x.slice(0,4)}...${x.slice(-4)}`}function EA(x,e=new Headers,t=""){return{response:x,responseHeaders:Object.fromEntries(e),statusText:t}}async function Es(x){let e,t,r=x.request_id||"";if(!r)return EA({error_message:"Bridge 请求缺少 request_id",http_status:0,request_id:r,success:!1});if(!x.path?.startsWith("/"))return EA({error_message:`Bridge 请求路径无效:${x.path??""}`,http_status:0,request_id:r,success:!1});let a=function(x){if(x.origin)try{var e;return new URL(x.path??"/",(e=x.origin).endsWith("/")?e:`${e}/`)}catch{return}}(x);if(!a)return EA({error_message:`Bridge 请求 origin 无效:${x.origin??""}`,http_status:0,request_id:r,success:!1});let n=(x.method||"GET").toUpperCase(),_=function(x){let e={};for(let[t,r]of Object.entries(x??{}))!t||Et.has(t.toLowerCase())||(e[t]=r);return e}(x.headers),A="GET"===n||"HEAD"===n?void 0:x.body??"",s=new AbortController,i=setTimeout(()=>s.abort(),(e="number"==typeof x.timeout_ms?x.timeout_ms:3e3,t="number"==typeof x.deadline_ms?x.deadline_ms-Date.now():e,Math.max(1,Math.min(e,t))));try{var o;let x=await fetch(a,{body:A,headers:_,method:n,redirect:"manual",signal:s.signal}),e=await x.text();return o={method:n,requestBody:A,requestHeaders:_,responseBody:e,responseHeaders:x.headers,statusCode:x.status,targetUrl:a},ff(o),EA({body:e,http_status:x.status,request_id:r,success:!0},x.headers,x.statusText)}catch(x){return ff({method:n,requestBody:A,requestHeaders:_,responseBody:x instanceof Error?x.message:String(x),responseHeaders:new Headers,statusCode:0,targetUrl:a}),EA({error_message:x instanceof Error?x.message:String(x),http_status:0,request_id:r,success:!1})}finally{clearTimeout(i)}}function Ei(x,e=new Set){if(Array.isArray(x)){for(let t of x)Ei(t,e);return[...e]}if(!x||"object"!=typeof x)return[...e];for(let[t,r]of Object.entries(x)){if(t.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof r&&r)e.add(r);else if(Array.isArray(r))for(let x of r)"string"==typeof x&&x&&e.add(x);continue}Ei(r,e)}return[...e]}function Eo(x,e){x.onLog?.(e)}function El(x){try{return JSON.parse(x)}catch{return}}function Ec({detail:x,requestHeaders:e,status:t,targetUrl:r}){if(Z()){if("number"==typeof t)return void d6.request({method:"CONNECT",url:r.pathname,statusCode:t,headers:e,context:{detail:x}});d6.info("Bridge 连接等待中",{url:r.pathname,detail:x,ppe:Q(e)})}}function Ev(x,e={}){Z()&&d6.info(x,e)}async function Ed(x,e){let t=JSON.stringify({sandbox_session_id:x.sandboxSessionId,...e}),r={"content-type":"application/json",[fx]:x.sandboxSessionId,...fy()};if(x.targetOrigin){let e=new URL(Ee,x.targetOrigin),a=await fetch(e,{body:t,headers:r,method:"POST"}),n=await a.text();if(ff({method:"POST",requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:a.headers,statusCode:a.status,targetUrl:e}),!a.ok)throw Error(`上传 Bridge 响应失败:${a.status} ${n}`);return{responseBody:n,responseHeaders:Object.fromEntries(a.headers),responsePayload:El(n)}}let a=new URL(Ee,oN),n=await fN({body:t,headers:r,internal:!0,method:"POST",path:Ee}),_=await n.text();if(ff({method:"POST",requestBody:t,requestHeaders:r,responseBody:_,responseHeaders:n.headers,statusCode:n.status,targetUrl:a}),!n.ok)throw Error(`上传 Bridge 响应失败:${n.status} ${_}`);return{responseBody:_,responseHeaders:Object.fromEntries(n.headers),responsePayload:El(_)}}async function Ef(x,e){let t;try{t=JSON.parse(e)}catch(x){d6.warn("Sandbox Bridge 请求解析失败",{reason:x.message});return}let r=Date.now(),a=`bridge-${r}-${++En}`,n=t.request_id||"",_={id:a,request:t,requestId:n,sandboxSessionId:x.sandboxSessionId,timestamp:r};Eo(x,{..._,logIds:Ei(t),status:"pending",updatedAtMs:r});let A=await Es(t),s={...A.response,headers:A.responseHeaders,status_text:A.statusText};try{let e=await Ed(x,A.response);Eo(x,{..._,logIds:Ei([t,s,e]),response:s,status:A.response.success?"success":"error",updatedAtMs:Date.now()})}catch(e){throw Eo(x,{..._,errorMessage:e instanceof Error?e.message:String(e),logIds:Ei([t,s]),response:s,status:"error",updatedAtMs:Date.now()}),e}}async function Eb(x,e,t){let r={sandbox_session_id:x.sandboxSessionId},a=new URL(`${Ex}?sandbox_session_id=${encodeURIComponent(x.sandboxSessionId)}`,oN),n=(o=x.sandboxSessionId,{accept:"text/event-stream",host:a.host,[fx]:o,...fy()});Ec({detail:`host=${n.host} session=${E_(x.sandboxSessionId)}`,requestHeaders:n,status:"pending",targetUrl:a}),Ev("bridge/events request",{headers:{accept:n.accept,host:n.host,[fx]:E_(x.sandboxSessionId),"x-tt-env":n["x-tt-env"],"x-use-ppe":n["x-use-ppe"]},path:Ex,query:r});let _=await fN({headers:n,internal:!0,method:"GET",path:Ex,query:r,signal:e});if(Ec({detail:`content-type=${_.headers.get("content-type")??""}`,requestHeaders:n,status:_.status,targetUrl:a}),!_.ok||!_.body){let x=await _.text().catch(()=>"");ff({method:"GET",requestBody:void 0,requestHeaders:n,responseBody:x,responseHeaders:_.headers,statusCode:_.status,targetUrl:a}),d6.warn("Sandbox Bridge 事件请求失败",{status:_.status,body:x.slice(0,500)});let e=Error(`Sandbox Bridge SSE 请求失败:${_.status} ${x}`);throw e.status=_.status,e}ff({method:"GET",requestBody:void 0,requestHeaders:n,responseBody:"",responseHeaders:_.headers,statusCode:_.status,targetUrl:a}),t?.();let A=_.body.getReader(),s=new dY.TextDecoder,i="";for(;!e.aborted;){let{done:e,value:t}=await A.read();if(e){Ev("Bridge events 流已结束",{session:E_(x.sandboxSessionId)});break}let r=(i+=s.decode(t,{stream:!0})).search(/\r?\n\r?\n/);for(;r>=0;){let e=i.slice(0,r),t=i.slice(r).match(/^\r?\n\r?\n/);i=i.slice(r+(t?.[0].length??2));let A=function(x){let e="message",t=[];for(let r of x.split(/\r?\n/)){if(r.startsWith("event:")){e=r.slice(6).trim();continue}r.startsWith("data:")&&t.push(r.slice(5).trimStart())}return{data:t.join("\n"),name:e}}(e);if(!function(x,e){if(!Z()||Er.has(x.name))return;let t=function(x){try{let e=JSON.parse(x);return"string"==typeof e.request_id?e.request_id:void 0}catch{return}}(x.data);d6.info("已收到 Bridge 事件",{event:x.name,requestId:t,ppe:Q(e)}),d6.info(`事件详情
402
- ${x.data}`)}(A,n),"bridge_request"===A.name){var o,l,c=_.headers,v=_.status;ff({method:`EVENT ${A.name}`,requestBody:A.data,requestHeaders:n,responseBody:"",responseHeaders:c,statusCode:v,targetUrl:a}),Ef(x,A.data).catch(x=>{d6.warn("Sandbox Bridge 请求处理失败",{reason:x.message})})}else if("TOOL_CALL"===A.name){let e="object"==typeof(l=El(A.data))&&l?.tool_call?l:void 0;e?Promise.resolve(x.onSimulatorToolCall?.(e)).catch(x=>{d6.warn("Sandbox Tool 调用转发失败",{reason:x instanceof Error?x.message:String(x),requestId:e.request_id,toolCallId:e.tool_call.tool_call_id})}):d6.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===A.name){let e=function(x){let e=El(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.resource,a=t?.action,n=t?.resource_id,_=t?.revision;if(("notice"===r||"task"===r)&&("upsert"===a||"remove"===a)&&"string"==typeof n&&n&&("number"==typeof _||"string"==typeof _))return{action:a,eventId:"string"==typeof e.event_id?e.event_id:"",occurredAtMs:"number"==typeof e.occurred_at_ms?e.occurred_at_ms:void 0,resource:r,resourceId:n,revision:_}}(A.data);e?x.onResourceChanged?.(e):d6.warn("Sandbox 资源事件解析失败")}else if("card_delta"===A.name){let e=function(x){let e=El(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.card_delta;if(!("card_delta"!==e.type||!r||"object"!=typeof r||Array.isArray(r)))return r}(A.data);e?x.onSimulatorEvent?.({payload:e,type:"card_delta"}):d6.warn("Sandbox 模拟器事件解析失败",{event:A.name})}else if("get_simulator_card_snapshots"===A.name){let e=El(A.data);e&&"object"==typeof e&&!Array.isArray(e)?x.onSimulatorEvent?.({payload:e,type:A.name}):d6.warn("Sandbox 模拟器事件解析失败",{event:A.name})}r=i.search(/\r?\n\r?\n/)}}}async function Eu(x,e){let t=0,r=!1;for(;!e.aborted;){try{await Eb(x,e,()=>{r=!1,x.onConnectionStatusChange?.("connected")}),t=0}catch(t){if(e.aborted)return;let x=t.status;if(r||(d6.warn("无法接收来自平台服务的请求",{reason:t.message}),r=!0),401===x||403===x||404===x)return}x.onConnectionStatusChange?.("reconnecting"),await (0,D.setTimeout)(Ea[Math.min(t,Ea.length-1)],void 0,{signal:e}).catch(()=>void 0),t+=1}}let Ep="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",Em="/app_developer/api/sandbox/session/business_info/update";function Eh(x){if(!x)return!1;try{return r5.statSync(x).isFile()}catch{return!1}}async function EE({body:x,headers:e,method:t,sandboxPath:r,targetOrigin:a,targetUrl:n}){let _=new AbortController,A=setTimeout(()=>_.abort(),3e4);try{return a?await fetch(n,{body:x,headers:e,method:t,signal:_.signal}):await fN({internal:!0,path:r,body:x,headers:e,method:t,signal:_.signal})}catch(x){if(_.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${n}`);throw x}finally{clearTimeout(A)}}function Ej(x,e){return(x?.[e]??process.env[e])?.trim()??""}function Eg(x,e,t,r,a,n){if(!Z())return;let _=Number(process.hrtime.bigint()-r)/1e6;d6.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:_,headers:a,logId:n})}function Ey({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){ff({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_})}async function ES(x,e,t,r,a,n){let _,A,s="/app_developer/api/sandbox/session/create",i="POST",o=function(){let x=new Set;for(let e of(process.env[Ep]??"").split(",")){let t=e.trim();if(t)try{let e=new URL(t),r=e.hostname.replace(/^\[|\]$/g,"").toLowerCase(),a="localhost"===r||"::1"===r||4===(0,dU.isIP)(r)&&r.startsWith("127.");if("http:"!==e.protocol&&"https:"!==e.protocol||!a)throw Error("仅允许本机回环 HTTP(S) origin");x.add(e.origin)}catch(x){throw Error(`${Ep} 包含无效 origin:${t}(${x instanceof Error?x.message:String(x)})`)}}return[...x]}(),l=JSON.stringify({sandbox_project_id:x,manifest:t?.()??(Eh(e)?r5.readFileSync(e,"utf8"):""),business_templates:Eh(r)?r5.readFileSync(r,"utf8"):"",...n?{app_id:n}:{},...o.length>0?{bridge_origins:o}:{}}),c={"content-type":"application/json",...fy()},v=new URL(s,a??oN),d=process.hrtime.bigint();try{_=await EE({body:l,headers:c,method:i,sandboxPath:s,targetOrigin:a,targetUrl:v})}catch(e){let x=`创建 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw Eg(i,v,502,d,c),Ey({method:i,requestBody:l,requestHeaders:c,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:v}),e}let f=_.headers.get(fe)||"",b=await _.text();Eg(i,v,_.status,d,c,f),Ey({method:i,requestBody:l,requestHeaders:c,responseBody:b,responseHeaders:_.headers,statusCode:_.status,targetUrl:v});try{A=JSON.parse(b||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${_.status} ${_.statusText||b||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!_.ok||0!==A.code)throw Error(`创建 Sandbox session 失败:${A.message||_.statusText||_.status}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);let u=A.data?.sandbox_session_id,p=A.data?.sandbox_appid;if(!u||!p)throw Error(`创建 Sandbox session 失败:响应缺少 ${u?"sandbox_appid":"sandbox_session_id"}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);return{appId:p,sessionId:u}}async function EI(x,e,t,r,a,n){try{return await ES(x,e,t,r,a,n)}catch(x){return d6.warn(`Sandbox 平台服务模拟已跳过:${x instanceof Error?x.message:String(x)}`),{appId:"",sessionId:""}}}function EN(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function EB(x){return{csrUploaded:!!x,phoneNumberUploaded:!0}}async function EF(x,e){let t,r,a="/app_developer/api/sandbox/session/business_info/get",n="POST",_=JSON.stringify({sandbox_session_id:x}),A={"content-type":"application/json",...fy()},s=new URL(a,e??oN),i=process.hrtime.bigint();try{t=await EE({body:_,headers:A,method:n,sandboxPath:a,targetOrigin:e,targetUrl:s})}catch(x){throw Eg(n,s,502,i,A),x}let o=t.headers.get(fe)||"",l=await t.text();Eg(n,s,t.status,i,A,o);try{r=JSON.parse(l||"{}")}catch{throw Ey({method:n,requestBody:_,requestHeaders:A,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),Error(`获取 Sandbox session 信息失败:HTTP ${t.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}let c={csrUploaded:!!r.data?.csr_pem?.trim(),phoneNumberUploaded:!!r.data?.phone_num?.trim()};if(Ey({method:n,requestBody:_,requestHeaders:A,responseBody:JSON.stringify({code:r.code,data:c,log_id:r.log_id}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),!t.ok||void 0!==r.code&&0!==r.code)throw Error(`获取 Sandbox session 信息失败:${r.message||t.statusText||t.status}${r.log_id||o?`,log_id=${r.log_id||o}`:""}`);return c}async function Ew(x,e){if(!x)return EN();try{return await EF(x,e)}catch(x){return d6.warn(`Sandbox session 信息查询已跳过:${x instanceof Error?x.message:String(x)}`),EN()}}async function EC(x,e,t){let r,a,n="POST",_=JSON.stringify({...x.csrPem?{csr_pem:x.csrPem}:{},phone_num:x.phoneNum,sandbox_session_id:e}),A={"content-type":"application/json",...fy(),[fx]:e},s=new URL(Em,t??oN),i=process.hrtime.bigint();try{r=await EE({body:_,headers:A,method:n,sandboxPath:Em,targetOrigin:t,targetUrl:s})}catch(x){throw Eg(n,s,502,i,A),x}let o=r.headers.get(fe)||"",l=await r.text();Eg(n,s,r.status,i,A,o),Ey({method:n,requestBody:JSON.stringify({...x.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:e}),requestHeaders:A,responseBody:l,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});try{a=JSON.parse(l||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}if(!r.ok||void 0!==a.code&&0!==a.code)throw Error(`更新 Sandbox session 信息失败:${a.message||r.statusText||r.status}${a.log_id||o?`,log_id=${a.log_id||o}`:""}`)}async function EP(x,e,t,r){if(x&&e.phoneNum&&(!t||e.csrPem))try{return await EC({...e.csrPem?{csrPem:e.csrPem}:{},phoneNum:e.phoneNum},x,r),d6.info("Sandbox 业务信息已自动上传",{sessionId:x}),EB(e.csrPem)}catch(x){d6.warn(`Sandbox 业务信息自动上传已跳过:${x instanceof Error?x.message:String(x)}`);return}}async function Ek(x,e){let t,r="/app_developer/api/sandbox/session/revoke",a="POST",n=JSON.stringify({sandbox_session_id:x}),_={"content-type":"application/json",...fy()},A=new URL(r,e??oN),s=process.hrtime.bigint();try{t=await EE({body:n,headers:_,method:a,sandboxPath:r,targetOrigin:e,targetUrl:A})}catch(e){let x=`撤回 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw Eg(a,A,502,s,_),Ey({method:a,requestBody:n,requestHeaders:_,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:A}),e}let i=t.headers.get(fe)||"",o=await t.text();Eg(a,A,t.status,s,_,i),Ey({method:a,requestBody:n,requestHeaders:_,responseBody:o,responseHeaders:t.headers,statusCode:t.status,targetUrl:A});let l=JSON.parse(o||"{}");if(!t.ok||0!==l.code)throw Error(`撤回 Sandbox session 失败:${l.message||t.statusText||t.status}${l.log_id||i?`,log_id=${l.log_id||i}`:""}`)}async function ED(x){if(x.recreatePromise)return x.recreatePromise;x.recreatePromise=(async()=>{var e;let t=x.sandboxSessionId;t&&await Ek(t,x.sandboxTargetOrigin),x.bridge?.close(),x.bridge=void 0;let r=await ES(x.sandboxProjectId,x.simulatorManifestPath,x.simulatorManifestReader,x.simulatorBusinessTemplatesPath,x.sandboxTargetOrigin,x.sandboxSessionAppId),a=r.sessionId,n=!x.sandboxSessionAppId,_=await EP(a,x.businessInfoInput,n,x.sandboxTargetOrigin)??await Ew(a,x.sandboxTargetOrigin);return x.sandboxAppId=r.appId,x.sandboxSessionId=a,x.businessInfo=_,(e=x).resourceConnectionStatus="connecting",e.resourceEventSequence=0,e.resourceEvents.length=0,e.simulatorEventSequence=0,e.simulatorEvents.length=0,e.resourceGeneration+=1,ET(e),x.bridge=ER(x,a),d6.info("Sandbox session 已重建",{sessionId:a}),{...r,businessInfoUploaded:_.phoneNumberUploaded&&(!n||_.csrUploaded)}})();try{return await x.recreatePromise}finally{x.recreatePromise=void 0}}function EL(x){return{bridgeLogs:x.bridgeLogs,bridgeLogsUpdatedAtMs:x.bridgeLogsUpdatedAtMs,connectionStatus:x.resourceConnectionStatus,events:x.resourceEvents,generation:x.resourceGeneration,instanceId:x.resourceInstanceId,simulatorEvents:x.simulatorEvents,updatedAtMs:x.resourceEventsUpdatedAtMs}}function Eq(x){clearTimeout(x.logBroadcastTimer),x.logBroadcastTimer=void 0;let e=EL(x);for(let t of x.eventListeners)t(e)}function ET(x){x.resourceEventsUpdatedAtMs=Math.max(Date.now(),x.resourceEventsUpdatedAtMs+1),Eq(x)}function ER(x,e){var t={onConnectionStatusChange:e=>{x.resourceConnectionStatus!==e&&(x.resourceConnectionStatus=e,ET(x))},onLog:e=>{let t=x.bridgeLogs.findIndex(x=>x.id===e.id);t>=0?x.bridgeLogs[t]=e:(x.bridgeLogs.push(e),x.bridgeLogs.length>200&&x.bridgeLogs.splice(0,x.bridgeLogs.length-200)),x.bridgeLogsUpdatedAtMs=Math.max(Date.now(),x.bridgeLogsUpdatedAtMs+1),x.logBroadcastTimer??=setTimeout(()=>Eq(x),50)},onResourceChanged:e=>{x.resourceEvents.push({...e,sequence:++x.resourceEventSequence}),x.resourceEvents.length>200&&x.resourceEvents.splice(0,x.resourceEvents.length-200),ET(x)},onSimulatorEvent:e=>{x.simulatorEvents.push({...e,sequence:++x.simulatorEventSequence}),x.simulatorEvents.length>200&&x.simulatorEvents.splice(0,x.simulatorEvents.length-200),ET(x)},onSimulatorToolCall:x.onSimulatorToolCall,sandboxSessionId:e,targetOrigin:x.sandboxTargetOrigin};if(!t.sandboxSessionId)return void d6.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let r=new AbortController;return Ev("正在启动 Sandbox Bridge",{session:E_(t.sandboxSessionId)}),t.onConnectionStatusChange?.("connecting"),Eu(t,r.signal),{close:()=>r.abort()}}async function E$(x,e,t,r){if("POST"!==x.method)return void fs(e,405,"不支持的请求方法");if(EG(x,e,r)){if(!t)return void fs(e,503,"Sandbox session 尚未初始化");try{let r=await fl(x,e,1048576);if(r){let x=JSON.parse(r);if(void 0!==x.csrPem&&"string"!=typeof x.csrPem||"string"!=typeof x.phoneNum)return void fs(e,400,"Sandbox 业务信息无效");t.businessInfoInput={..."string"==typeof x.csrPem&&x.csrPem.trim()?{csrPem:x.csrPem.trim()}:{},phoneNum:x.phoneNum.trim()}}let a=await ED(t);fi(e,200,{code:0,data:{sandbox_appid:a.appId,business_info_uploaded:a.businessInfoUploaded,sandbox_session_id:a.sessionId},message:"ok"})}catch(x){fs(e,500,x.message)}}}function EG(x,e,t){let r=x.headers.origin;return"string"==typeof r&&!!t.includes(r)||(fs(e,403,"Sandbox 控制请求来源无效"),!1)}function EO(x){let e=x.appId?.trim(),t=e&&!e.startsWith("doubao-sandbox-app-")?e:void 0,r=function(x){let e=r4.resolve(x??process.cwd()),t=e;try{t=r5.realpathSync.native(e)}catch{}return(0,ar.createHash)("sha256").update(t).digest("hex")}(x.appDirectory),a=function(x,e){let t=Ej(x,"DOUBAO_SANDBOX_PHONE_NUM"),r=Ej(x,"DOUBAO_SANDBOX_CSR_FILE"),a=function(x,e){if(!x)return;let t=r4.isAbsolute(x)?x:r4.resolve(e??process.cwd(),x);return Eh(t)?t:void 0}(r,e),n="";if(r&&!a)d6.warn(`Sandbox CSR 文件不存在:${r}`);else if(a)try{n=r5.readFileSync(a,"utf8").trim()}catch(x){d6.warn(`Sandbox CSR 文件读取失败:${x instanceof Error?x.message:String(x)}`)}return{...t?{phoneNum:t}:{},...n?{csrPem:n}:{}}}(x.env,x.appDirectory),n=`${a.phoneNum??""}\0${a.csrPem??""}`;return{businessInfoInput:a,businessInfoInputKey:n,businessTemplatesPath:x.businessTemplatesPath,key:JSON.stringify([n,r,t,x.targetOrigin,x.businessTemplatesPath,x.manifestPath]),manifestReader:x.manifestReader,manifestPath:x.manifestPath,onSimulatorToolCall:x.onSimulatorToolCall,projectId:r,sessionAppId:t,targetOrigin:x.targetOrigin}}class EX{configKey;manifestReader;state;constructor(x,e,t){this.state=x,this.configKey=e,this.manifestReader=t}static async start(x){let e=EO(x),t=await EI(e.projectId,e.manifestPath,e.manifestReader,e.businessTemplatesPath,e.targetOrigin,e.sessionAppId),r=!e.sessionAppId,a={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await EP(t.sessionId,e.businessInfoInput,r,e.targetOrigin)??await Ew(t.sessionId,e.targetOrigin),businessInfoInput:e.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:e.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,ar.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:t.appId,sandboxProjectId:e.projectId,sandboxSessionAppId:e.sessionAppId,sandboxSessionId:t.sessionId,sandboxTargetOrigin:e.targetOrigin,simulatorBusinessTemplatesPath:e.businessTemplatesPath,simulatorManifestReader:e.manifestReader,simulatorManifestPath:e.manifestPath},n=new EX(a,e.key,e.manifestReader);return a.bridge=t.sessionId?ER(a,t.sessionId):void 0,n}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(x){return this.state.eventListeners.add(x),x(EL(this.state)),()=>{this.state.eventListeners.delete(x)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),Eq(this.state)}matches(x){let e=EO(x);return this.configKey===e.key&&this.manifestReader===e.manifestReader}getDebugContext(){var x;let e;return{fileSystemNamespace:(e=(x=this.state).sandboxSessionAppId?`real-app\0${x.sandboxSessionAppId}`:`virtual-app\0${x.sandboxAppId}\0${x.sandboxProjectId}`,`sandbox-v1:${(0,ar.createHash)("sha256").update(e).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(x=[]){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>{EG(e,t,x)&&h9(e,t,{onBusinessInfoUpdated:x=>{this.state.businessInfo=EB(x?.csrPem),x&&(this.state.businessInfoInput=x)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})}},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>E$(e,t,this.state,x)}]}}function EK(x,e){return x.relativePath<e.relativePath?-1:+(x.relativePath>e.relativePath)}let EQ="/__tools/tools.json",EM="/__events/events.json",EZ="manifest.yaml",EJ="skill";function EV(x){if(!x)return!1;try{return r5.statSync(x).isFile()}catch{return!1}}function EH(x,e){if(!x)return;let t=r4.isAbsolute(x)?x:r4.resolve(e??process.cwd(),x);return EV(t)?t:void 0}function EU(x,e){if(x&&e)return r4.relative(e,x).split(r4.sep).join("/")||"."}function EY(x){let e=r4.resolve(x);for(;;){if(EV(r4.join(e,EZ)))return e;let x=r4.dirname(e);if(x===e)return;e=x}}function Ez(x){try{return r5.lstatSync(x),!0}catch{return!1}}function EW(x,e,t,r){let a;if(!e.reader&&EV(e.sourcePath)){var n;let t,a=r5.statSync(e.sourcePath);fA(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":a.size,"Content-Type":r}),n=e.sourcePath,(t=r5.createReadStream(n)).once("error",()=>x.destroy()),t.pipe(x);return}try{a=e.reader?.()}catch{a=void 0}void 0===a?fs(x,404,`未找到 ${t}`):(fA(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(a),"Content-Type":r}),x.end(a))}function E0(x,e){return function(x){let e,t;if(!x)return{layout:"missing",entries:[]};let r=r4.resolve(x);try{e=r5.lstatSync(r)}catch(x){if("ENOENT"===x.code)return{directory:r,layout:"missing",entries:[]};return{directory:r,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${r}: ${x.message}`}}if(e.isSymbolicLink()||!e.isDirectory())return{directory:r,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${r}`};try{var a;let x;a=r,x=[],function e(t){for(let r of r5.readdirSync(t,{withFileTypes:!0})){if(r.isSymbolicLink())continue;let n=r4.join(t,r.name);r.isDirectory()?e(n):r.isFile()&&"SKILL.md"===r.name&&x.push(function(x,e){let t=r4.relative(x,e).split(r4.sep).join("/");return{content:r5.readFileSync(e,"utf8"),relativePath:t}}(a,n))}}(a),t=x}catch(x){return{directory:r,layout:"invalid",entries:[],error:`skill directory is not readable: ${r}: ${x.message}`}}return t.sort(EK),t.length>0?{directory:r,layout:"resolved",entries:t}:{directory:r,layout:"missing",entries:[]}}(function(x,e){if(e){if(!e)return;if(r4.isAbsolute(e))return e;let t=x?EY(x):void 0,r=[x,t,process.cwd()].map(x=>r4.resolve(x??process.cwd(),e));return[...new Set(r)].find(Ez)??r[0]}if(!x)return;let t=EY(x);return[...new Set([t?r4.join(t,EJ):void 0,r4.join(x,EJ),r4.join(process.cwd(),EJ)].filter(Boolean))].find(Ez)}(x,e))}class E1{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(x){var e,t,r;this.appDirectory=x.appDirectory,this.manifestPath=x.manifestPath?EH(x.manifestPath,x.appDirectory):x.manifestSourcePath??(x.manifestReader?void 0:function(x){if(!x)return;let e=EY(x);return[...new Set([e?r4.join(e,EZ):void 0,r4.join(process.cwd(),EZ)].filter(Boolean))].find(EV)}(x.appDirectory)),this.businessTemplatesPath=(e=this.manifestPath,t=x.businessTemplatesPath,r=x.appDirectory,t?EH(t,r):e?EH(r4.join(r4.dirname(e),"business-templates.yaml"),r):void 0),this.manifestReader=x.manifestReader,this.eventsConfigReader=x.eventsConfigReader,this.toolsConfigReader=x.toolsConfigReader,this.eventsConfigSource={reader:x.eventsConfigReader,sourcePath:x.eventsConfigSourcePath},this.skillsDirectory=x.skillsDirectory;let a=E0(x.appDirectory,this.skillsDirectory);if(x.skillsDirectory&&"resolved"!==a.layout)throw Error(a.error??`Simulator skills directory contains no runtime Skill: ${x.skillsDirectory}`);this.toolsConfigSource={reader:x.toolsConfigReader,sourcePath:x.toolsConfigSourcePath},this.manifestSource={reader:x.manifestReader,sourcePath:x.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(x){let e=new E1(x);return this.sourceKey===e.sourceKey&&this.eventsConfigReader===e.eventsConfigReader&&this.toolsConfigReader===e.toolsConfigReader&&this.manifestReader===e.manifestReader}getDebugContext(){let x=E0(this.appDirectory,this.skillsDirectory),e="resolved"===x.layout?x.directory:void 0,t=EU(this.businessTemplatesPath,this.appDirectory),r=EU(this.eventsConfigSource.sourcePath,this.appDirectory),a=EU(this.toolsConfigSource.sourcePath,this.appDirectory),n=EU(this.manifestSource.sourcePath,this.appDirectory),_=EU(e,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:EM,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...r?{eventsConfigRelativePath:r}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:EQ,...a?{toolsConfigRelativePath:a}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...n?{simulatorManifestRelativePath:n}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...t?{simulatorBusinessTemplatesRelativePath:t}:{}}:{},...e?{simulatorSkillsDirectoryOriginalUrl:e,..._?{simulatorSkillsDirectoryRelativePath:_}:{}}:{}}}getRequestRoutes(){return[{match:EM,handle:({response:x})=>EW(x,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:EQ,handle:({response:x})=>EW(x,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:x})=>EW(x,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:x})=>{let e;"missing"===(e=E0(this.appDirectory,this.skillsDirectory)).layout?fs(x,404,"未找到模拟器 Skill 目录"):"invalid"===e.layout?fs(x,422,e.error??"模拟器 Skill 目录结构无效"):fi(x,200,{skills:e.entries},{"Cache-Control":"no-cache"})}}]}}let E2="/app_developer/api",E3=`${E2}/simulator/images/upload`,E6=new Set([`${E2}/simulator/chat`,E3,`${E2}/simulator/tool/report`]),E4={"Access-Control-Expose-Headers":fe};async function E5(x,e,t,r){if(!E6.has(t.pathname))return void fs(e,404,"未找到模拟器接口",E4);let a=r.targetOrigin??oN,n=new URL(`${t.pathname}${t.search}`,a),_=fb(x,e);try{var A;let a=x.method??"GET",s=process.hrtime.bigint(),i=function(x,e,t){return Object.fromEntries(Object.entries(fa(x.headers,e,{...fy(),...t?{[fx]:t}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]))}(x,n,r.getSandboxSessionId?.()),o=await E7(x,e,t,a),l=r.targetOrigin?await fetch(n,{body:o,headers:i,method:a,signal:_}):await fN({internal:!0,path:`${t.pathname}${t.search}`,method:a,body:o,headers:i,signal:_});if(function(x,e,t,r,a,n){if(!Z())return;let _=Number(process.hrtime.bigint()-r)/1e6;d6.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:_,headers:a,logId:n})}(a,t,l.status,s,i,l.headers.get(fe)??void 0),e.destroyed||e.writableEnded)return void l.body?.cancel().catch(()=>void 0);await E8({method:a,requestBody:(A=o)instanceof Uint8Array?`(binary, ${A.byteLength} bytes)`:A,requestHeaders:i,requestUrl:t,response:e,upstreamResponse:l})}catch(x){if(e.destroyed||e.writableEnded||_.aborted)return;fs(e,502,`代理模拟器请求失败:${x instanceof Error?x.message:String(x)}`,E4)}}async function E7(x,e,t,r){if("GET"!==r&&"HEAD"!==r)return t.pathname===E3?await fo(x,e,0xb00000):await fl(x,e,0xb00000)}async function E8({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n}){var _,A;if(fA(a,E4),a.writeHead(n.status,f_(n.headers,[fe])),_=r,A=n,_.pathname===`${E2}/simulator/chat`||A.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await E9({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n});if(!Z())return n.body?void await (0,F.pipeline)(r3.Readable.fromWeb(n.body),a):void a.end();let s=await fc(n);ff({method:x,requestBody:e,requestHeaders:t,responseBody:s,responseHeaders:n.headers,statusCode:n.status,targetUrl:r}),a.end(s)}async function E9({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n}){if(!n.body){ff({method:x,requestBody:e,requestHeaders:t,responseBody:"",responseHeaders:n.headers,statusCode:n.status,targetUrl:r}),a.end();return}let _=r3.Readable.fromWeb(n.body);if(!Z())return void await (0,F.pipeline)(_,a);ff({method:x,requestBody:e,requestHeaders:t,responseBody:"(event stream)",responseHeaders:n.headers,statusCode:n.status,targetUrl:r});let A=new r3.Transform({transform(x,e,t){let a;try{a=String(x).split("\n\n").filter(Boolean)}catch(e){return d6.error(`事件流分片解码失败:${e?.toString()}`),t(null,x)}for(let x of a)d6.info(`来自 ${r.pathname}${r.search} 的事件
403
- ${x}`);t(null,x)}});await (0,F.pipeline)(_,A,a)}async function jx(x,e){if("POST"!==x.method)return void fi(e,405,{message:"不支持的请求方法"});let t=fb(x,e);try{var r,a;let n,_,A=JSON.parse(await fl(x,e,0xa00000)),s=function(x){if("GET"!==x&&"POST"!==x)throw Error(`Unsupported request method: ${String(x)}`);return x}(A.method),i=fr(A.url),o=await fetch(i,{signal:t,body:"POST"===s?function(x){if(void 0!==x.data&&null!==x.data){if("base64"===x.dataEncoding&&"string"==typeof x.data){var e;let t;return t=new ArrayBuffer((e=Buffer.from(x.data,"base64")).byteLength),new Uint8Array(t).set(e),t}if(void 0===x.dataEncoding&&"string"==typeof x.data)return x.data;throw Error("Invalid prepared request body")}}(A):void 0,headers:(r=A.header,n=new Headers(r),["connection","content-length","host","origin","referer"].forEach(x=>n.delete(x)),n),method:s}),l=Buffer.from(await o.arrayBuffer()).toString("base64");fi(e,200,{data:l,dataEncoding:"base64",header:(a=o.headers,_={},a.forEach((x,e)=>{_[e]=x}),_),statusCode:o.status})}catch(x){if(t.aborted||e.destroyed)return;fi(e,500,{message:x instanceof Error?x.message:String(x)})}}let je=I("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),jt="/__web_artifacts",jr="/assets/framework";function ja(x,e,t,r,a={}){fA(e,a.headers),je(x,r,{root:t}).once("error",r=>{if(404===r.statusCode&&a.fallbackPath)return void ja(x,e,t,a.fallbackPath,{headers:a.headers});if(e.headersSent)return void e.destroy(r);let n=r.statusCode??500;fs(e,n,d4.STATUS_CODES[n]??"Internal Server Error")}).pipe(e)}let jn="/__webview",j_=`${jn}/client.js`,jA=`${jn}/page`,js=`${jn}/runtime`,ji=`${jn}/sw.js`,jo="x-doubao-web-view-target",jl="Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",jc=new URL(I("../../debugger-server/dist/web-view-proxy-bootstrap.js"),I.b),jv=new URL(I("../../debugger-server/dist/web-view-proxy-page-client.js"),I.b),jd=new URL(I("../../debugger-server/dist/web-view-proxy-service-worker.js"),I.b);function jf(x,e,t,r=!1){if("GET"!==x.method&&"HEAD"!==x.method)return void fs(e,405,"不支持的请求方法");let a=r5.readFileSync(t,"utf8");fA(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(a),"content-type":"text/javascript; charset=utf-8",...r?{"service-worker-allowed":"/"}:{}}),e.end("HEAD"===x.method?void 0:a)}function jb(x,e){let t=x.searchParams.get("parentOrigin")??e[0];if(!e.includes(t))throw Error("WebView 父级 origin 无效");return t}async function ju(x,e,t,r){if("GET"!==x.method&&"HEAD"!==x.method)return void fs(e,405,"不支持的请求方法");let a=fb(x,e);try{let n=jb(t,r),_=fr(t.searchParams.get("url")??void 0),A=await fetch(_,{signal:a,headers:{"user-agent":jl,..."string"==typeof x.headers.accept?{accept:x.headers.accept}:{},..."string"==typeof x.headers["accept-language"]?{"accept-language":x.headers["accept-language"]}:{}},method:x.method}),s=A.url?new URL(A.url):_;s.hash=_.hash;let i=A.headers.get("content-type")??"",o=f_(A.headers);if(o["cache-control"]="no-cache",o["cross-origin-resource-policy"]="cross-origin",o["x-doubao-web-view-parent-origin"]=n,"HEAD"===x.method||!i.includes("text/html")){let t="HEAD"===x.method?void 0:Buffer.from(await A.arrayBuffer());fA(e),e.writeHead(A.status,{...o,[jo]:s.toString(),...t?{"content-length":t.byteLength}:{}}),e.end(t);return}let l=function(x,e,t){let r=new URLSearchParams({mobileUserAgent:jl,originalPath:`${e.pathname}${e.search}${e.hash}`,parentOrigin:t}).toString().replaceAll("&","&amp;"),a=`<script src="${j_}?${r}"></script>`,n=/<head[^>]*>/i.exec(x);if(n){let e=n.index+n[0].length;return`${x.slice(0,e)}${a}${x.slice(e)}`}return`${a}${x}`}(await A.text(),s,n);fA(e),e.writeHead(A.status,{...o,[jo]:s.toString(),"content-length":Buffer.byteLength(l)}),e.end(l)}catch(x){if(a.aborted||e.destroyed)return;fs(e,502,`代理 web-view 页面失败: ${x instanceof Error?x.message:String(x)}`)}}let jp=/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;async function jm(x){let e=new URL(x).toString();try{await w(e)}catch(x){d6.error("打开 Web 模拟器失败",{error:x}),d6.info("请手动打开 Web 模拟器(本地)",{url:e})}}async function jh(x,e){await new Promise((t,r)=>{let a=e=>{x.off("listening",n),r(e)},n=()=>{x.off("error",a),t()};x.once("error",a),x.once("listening",n),x.listen(e,"127.0.0.1")})}async function jE(x){let e=await d3(9e3),t=[`http://127.0.0.1:${e}`,`http://localhost:${e}`],r=d4.createServer(fm([{match:`${jn}/bootstrap`,handle:({request:x,response:e,url:r})=>{if("GET"!==x.method&&"HEAD"!==x.method)return void fs(e,405,"不支持的请求方法");try{fr(r.searchParams.get("url")??void 0),jb(r,t)}catch{fs(e,400,"WebView URL 无效");return}fA(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),e.end("HEAD"===x.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${jn}/bootstrap.js`,handle:({request:x,response:e})=>jf(x,e,jc)},{match:ji,handle:({request:x,response:e})=>jf(x,e,jd,!0)},{match:j_,handle:({request:x,response:e})=>jf(x,e,jv)},{match:js,handle:({request:x,response:e,url:t})=>(function(x,e,t){let r;try{r=fr(t.searchParams.get("url")??void 0)}catch(x){fs(e,400,`无效的 web-view 请求地址: ${x instanceof Error?x.message:String(x)}`);return}let a=fa(x.headers,r,{"user-agent":jl});for(let x of Object.keys(a))x.startsWith("sec-fetch-")&&delete a[x];fu(x,e,{createResponseHeaders:x=>{let e=fn(x),t=Array.isArray(x.location)?x.location[0]:x.location;if(t&&URL.canParse(t,r)){let x=new URL(t,r);e.location=`${js}?url=${encodeURIComponent(x.toString())}`}return e["cache-control"]="no-cache",e},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:a,targetUrl:r})})(x,e,t)},{match:jA,handle:({request:x,response:e,url:r})=>ju(x,e,r,t)}],({response:x})=>{fs(x,404,"未找到 WebView 资源")}));await jh(r,0);let a=r.address(),n=`http://127.0.0.1:${a.port}`,_=d4.createServer(function({artifactOrigin:x,debugScenes:e,debuggerOrigins:t,debuggerProtocol:r,distPath:a,getWidgetViewDataTemplates:n,mcp:_,physicalDeviceDebugGateway:A,sandboxRuntime:s,simulatorAssets:i,simulatorTargetOrigin:o,webViewOrigin:l}){var c;let v={routes:[{match:x=>x.pathname.startsWith(jt),handle:({request:e,response:t,url:r})=>(function(x,e,t,r){let a=t.pathname.slice(jt.length)||"/";if(a.startsWith("//"))return void fs(e,400,"Web 产物路径无效");let n=new URL(r),_=a.startsWith("/")?a:`/${a}`,A=new URL(`${_}${t.search}`,n);A.origin!==n.origin?fs(e,400,"Web 产物路径无效"):fu(x,e,{createResponseHeaders:x=>({...fn(x),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:fa(x.headers,A),targetUrl:A})})(e,t,r,x)},{match:x=>x.pathname===jr||x.pathname.startsWith(`${jr}/`),handle:({request:x,response:e,url:t})=>{let r;!(r=t.pathname.slice(`${jr}/`.length))||r!==r4.basename(r)?fs(e,404,"未找到资源"):ja(x,e,r4.join(a,jr.slice(1)),r,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:x,response:e})=>jx(x,e)},{match:"/__webview/page",handle:({request:x,response:e,url:t})=>{"GET"!==x.method&&"HEAD"!==x.method?fs(e,405,"不支持的请求方法"):(fA(e),e.writeHead(302,{"cache-control":"no-store",location:`${l}/__webview/bootstrap${t.search}`}),e.end())}},{match:"/__webview/sw.js",handle:({response:x})=>{fA(x),x.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),x.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
401
+ `),g=!0;try{v?.()}catch(x){t?.(x instanceof Error?x:Error(String(x)))}void 0!==d&&clearInterval(d),f?.(),n.delete(I);try{c.close()}catch{}}},N=new ReadableStream({start(x){c=x;let t=mw({method:"notifications/subscriptions/acknowledged",params:{notifications:h}},E);S(t.method,t.params),v=e.subscribe(x=>{if(g||!function(x,e){switch(e.kind){case"tools_list_changed":return!0===x.toolsListChanged;case"prompts_list_changed":return!0===x.promptsListChanged;case"resources_list_changed":return!0===x.resourcesListChanged;case"resource_updated":return void 0!==x.resourceSubscriptions&&x.resourceSubscriptions.includes(e.uri)}}(h,x))return;let e=mw(function(x){switch(x.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:x.uri}}}}(x),E);S(e.method,e.params)}),d=mN(a,()=>y(": keepalive\n\n")),n.add(I)},cancel(){I(!1)}});if(void 0!==_)if(_.aborted)I(!1);else{let x=()=>I(!1);_.addEventListener("abort",x,{once:!0}),f=()=>_.removeEventListener("abort",x)}return new Response(N,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let x of n)x(!0)},get openCount(){return n.size}}}({bus:v,maxSubscriptions:e.maxSubscriptions??1024,keepAliveMs:e.keepAliveMs??15e3,onerror:c});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let b="reject"===r?void 0:(t=e.keepAliveMs,async(e,r)=>{if("POST"!==e.method.toUpperCase())return mH(405,-32e3,"Method not allowed.");try{let a=await x({era:"legacy",...r?.authInfo!==void 0&&{authInfo:r.authInfo},requestInfo:e}),n=new mJ({sessionIdGenerator:void 0,...void 0!==t&&{keepAliveMs:t}});await a.connect(n);let _=()=>{n.close().catch(()=>{}),a.close().catch(()=>{})};e.signal?.addEventListener("abort",_,{once:!0});let A=await n.handleRequest(e,{...r?.authInfo!==void 0&&{authInfo:r.authInfo},...r?.parsedBody!==void 0&&{parsedBody:r.parsedBody}});if(null===A.body||"text/event-stream"!==uR(A.headers.get("content-type")))return _(),A;let s=A.body.getReader(),i=!1,o=()=>{i||(i=!0,_())},l=new ReadableStream({pull:async x=>{try{let{done:e,value:t}=await s.read();if(e){o(),x.close();return}void 0!==t&&x.enqueue(t)}catch(e){o(),x.error(e)}},cancel:x=>(o(),s.cancel(x).catch(()=>{}))});return new Response(l,{status:A.status,statusText:A.statusText,headers:A.headers})}catch(x){try{c?.(mY(x))}catch{}return mz(mV(r?.parsedBody))}});async function u(t,r,a){var A,v;let d=t.classification.revision;if(void 0===d||!f1.includes(d)){let x=new bg({supported:[...f1],requested:d??"unknown"});return c(x),mH(400,x.code,x.message,x.data,mV(t.message))}let b=function(x,e){if("request"!==e.messageKind)return;let t=e.message.method;if(void 0===x.mcpMethodHeader)return u_("method-header-missing","(missing)",`the body names method ${t} but the required Mcp-Method header is absent`,"standard-header-validation");let r=Object.hasOwn(uA,t)?uA[t]:void 0;if(void 0===r)return;let a=e.message.params?.[r],n="string"==typeof a?a:void 0;if(void 0===x.mcpNameHeader){if(void 0===n)return;return u_("name-header-missing","(missing)",`the body carries params.${r}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let _=us(x.mcpNameHeader),A=ue(_);return void 0===A?u_("name-header-invalid-encoding",_,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&A!==n?u_("name-header-mismatch",_,`the body carries params.${r}="${n}" but the Mcp-Name header names "${A}"`,"standard-header-validation"):void 0}({httpMethod:r.method,mcpMethodHeader:r.headers.get("mcp-method")??void 0,mcpNameHeader:r.headers.get("mcp-name")??void 0},t);if(void 0!==b)return c(Error(`Rejected inbound request (${b.cell}): ${b.message}`)),mU(b,mV(t.message));let u="request"===t.messageKind?bZ(t.message.params):void 0,p=u?.[ef];if("request"===t.messageKind){let x=Object.hasOwn(fY,A=t.message.method)?fY[A]:void 0;if(void 0!==x){let e=fW(x,p);if(void 0!==e){let x=new by({requiredCapabilities:e});return c(x),mH(ua[x.code]??400,x.code,x.message,x.data,t.message.id)}}}let m=await x({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:r}),h=m instanceof mq?m.server:m;if("request"===t.messageKind&&"subscriptions/listen"===t.message.method){let x=h.getCapabilities(),e=l(h);return m.close().catch(c),f.serve(t.message,r.signal,x,e)}if("request"===t.messageKind&&"tools/call"===t.message.method&&m instanceof mq){let x=t.message.params,e="string"==typeof x?.name?x.name:void 0,a=void 0===e?void 0:m.toolInputSchemaJson(e);if(void 0!==a){let e=b4(a);if(e.valid&&e.declarations.length>0){let a=function(x,e,t){for(let r of x){let x=`Mcp-Param-${r.headerName}`,a=t.get(x),n=function(x,e){let t=x;for(let x of e){if(null===t||"object"!=typeof t)return;t=t[x]}return t}(e,r.path);if(null==n)continue;let _=function(x){if("string"==typeof x)return x;if("boolean"==typeof x)return x?"true":"false";if("number"==typeof x){if(!Number.isFinite(x)||Number.isInteger(x)&&!Number.isSafeInteger(x))return;return String(x)}}(n);if(void 0===_)continue;if(null===a)return ut("param-header-missing",x,`the body carries ${b8(r.path)}=${JSON.stringify(n)} but the ${x} header is absent`);let A=ue(a);if(void 0===A)return ut("param-header-invalid-encoding",x,`the ${x} header carries an invalid Base64 sentinel value`);if(!(("integer"===r.type||"number"===r.type)&&ux.test(A)&&"number"==typeof n?Number(A)===n:A===_))return ut("param-header-mismatch",x,`the ${x} header decodes to ${JSON.stringify(A)} but the body carries ${b8(r.path)}=${JSON.stringify(n)}`)}}(e.declarations,x?.arguments,r.headers);if(void 0!==a)return m.close().catch(c),c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),mU(a,t.message.id)}}}s(h,d),o(h,f1),void 0!==u&&(v={clientInfo:u[xh],clientCapabilities:p},i(h,v));let E=h.onclose;_.add(h),h.onclose=()=>{_.delete(h),E?.()};try{let x=await mZ(m,t.message,{classification:t.classification,request:r,...void 0!==a&&{authInfo:a},...void 0!==n&&{responseMode:n},...void 0!==e.keepAliveMs&&{keepAliveMs:e.keepAliveMs}});return"notification"===t.messageKind&&queueMicrotask(()=>void h.close().catch(()=>{})),x}catch(x){if(x instanceof fU&&x.code===fH.ConnectionClosed)return new Response(null,{status:499});return await h.close().catch(()=>{}),_.delete(h),c(mY(x)),mz(mV(t.message))}}async function p(x,e,t,r){if(void 0!==b)return b(e,{...void 0!==t&&{authInfo:t},...void 0!==r&&{parsedBody:r}});let a=function(x,e){switch(x.reason){case"http-method":return un("http-method","modern-only-method-not-allowed",405,new bh(-32e3,"Method not allowed."),!0);case"batch":return un("jsonrpc-shape","modern-only-batch-not-supported",400,new bh(bm.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return un("jsonrpc-shape","modern-only-response-post",400,new bh(bm.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let t=x.requestedVersion;return un("era-classification","modern-only-missing-envelope",400,void 0===t?new bh(bm.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...e]}):new bg({supported:[...e],requested:t}),!0)}}}(x,f1);return void 0===a?new Response(null,{status:202}):(c(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),mU(a,mV(r)))}async function m(x,e){let t=e?.authInfo;if("POST"===x.method.toUpperCase()&&!u$(x.headers.get("content-type")))return c(Error("Unsupported Media Type: Content-Type must be application/json")),mH(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let r=await mW(x,e?.parsedBody);if("unreadable-body"===r.step)return mH(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===r.step)return void 0!==b?b(r.forwardRequest,{...void 0!==t&&{authInfo:t}}):mH(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:n,parsedBody:_,forwardRequest:A}=r;try{switch(a.kind){case"reject":return c(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),mU(a,mV(n));case"modern":return await u(a,x,t);case"legacy":return await p(a,A,t,_)}}catch(x){return c(mY(x)),mz(mV(n))}}return{fetch:async(x,e)=>{if(A)throw Error("This MCP handler has been closed");try{return await m(x,e)}catch(x){return c(mY(x)),mz(mV(e?.parsedBody))}},notify:d,bus:v,close:async()=>{A=!0,f.closeAll();let x=[..._].map(x=>x.close().catch(()=>{}));_.clear(),await Promise.all(x)}}}I("http"),I("http2");let m1=I("stream");var m2=globalThis.Request,m3=class extends m2{constructor(x,e){"object"==typeof x&&m4 in x&&(x=x[m4]()),void 0!==e?.body?.getReader&&(e.duplex??="half"),super(x,e)}},m6=Symbol("wrapBodyStream"),m4=Symbol("getRequestCache"),m5=Symbol("requestCache"),m7=Symbol("incomingKey"),m8=Symbol("urlKey"),m9=Symbol("headersKey"),hx=Symbol("abortControllerKey"),he=Symbol("getAbortController"),ht={get method(){return this[m7].method||"GET"},get url(){return this[m8]},get headers(){return this[m9]||=(x=>{let e=[],t=x.rawHeaders;for(let x=0;x<t.length;x+=2){let{[x]:r,[x+1]:a}=t;58!==r.charCodeAt(0)&&e.push([r,a])}return new Headers(e)})(this[m7])},[he](){return this[m4](),this[hx]},[m4](){return this[hx]||=new AbortController,this[m5]||=((x,e,t,r,a)=>{let n={method:x,headers:t,signal:a.signal};if("TRACE"===x){n.method="GET";let x=new m3(e,n);return Object.defineProperty(x,"method",{get:()=>"TRACE"}),x}if("GET"!==x&&"HEAD"!==x)if("rawBody"in r&&r.rawBody instanceof Buffer)n.body=new ReadableStream({start(x){x.enqueue(r.rawBody),x.close()}});else if(r[m6]){let x;n.body=new ReadableStream({async pull(e){try{x||=m1.Readable.toWeb(r).getReader();let{done:t,value:a}=await x.read();t?e.close():e.enqueue(a)}catch(x){e.error(x)}}})}else n.body=m1.Readable.toWeb(r);return new m3(e,n)})(this.method,this[m8],this.headers,this[m7],this[hx])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(x=>{Object.defineProperty(ht,x,{get(){return this[m4]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(ht,x,{value:function(){return this[m4]()[x]()}})}),Object.defineProperty(ht,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[m5]};return`Request (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(ht,m3.prototype);var hr=Symbol("responseCache"),ha=Symbol("getResponseCache"),hn=Symbol("cache"),h_=globalThis.Response,hA=class x{#xC;#xP;[ha](){return delete this[hn],this[hr]||=new h_(this.#xC,this.#xP)}constructor(e,t){let r;if(this.#xC=e,t instanceof x){let x=t[hr];if(x){this.#xP=x,this[ha]();return}this.#xP=t.#xP,r=new Headers(t.#xP.headers)}else this.#xP=t;("string"==typeof e||void 0!==e?.getReader||e instanceof Blob||e instanceof Uint8Array)&&(this[hn]=[t?.status||200,e,r||t?.headers])}get headers(){let x=this[hn];return x?(x[2]instanceof Headers||(x[2]=new Headers(x[2]||{"content-type":"text/plain; charset=UTF-8"})),x[2]):this[ha]().headers}get status(){return this[hn]?.[0]??this[ha]().status}get ok(){let x=this.status;return x>=200&&x<300}};function hs(x,e){return async(t,r,a)=>{let n,_;"function"==typeof a&&(a=void 0);let A=!1,s=new AbortController;r.on("close",()=>{A||s.abort()}),!0===r.destroyed&&s.abort();try{let e=await ho(t,a,{signal:s.signal});n=await x.fetch(e,{...void 0!==t.auth&&{authInfo:t.auth},...void 0!==a&&{parsedBody:a}})}catch(x){var i;try{e?.onerror?.(x instanceof Error?x:Error(String(x)))}catch{}i=function(x){if(null===x||"object"!=typeof x||Array.isArray(x))return null;let{method:e,id:t}=x;return"string"!=typeof e?null:"string"==typeof t||"number"==typeof t?t:null}(a),n=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:i},{status:500})}let o={};for(let[x,e]of n.headers)o[x]=e;if(r.writeHead(n.status,o),null===n.body){A=!0,r.end();return}r.on("drain",()=>{_?.(),_=void 0});let l=new Promise(x=>{s.signal.addEventListener("abort",()=>x(),{once:!0})});try{for await(let x of n.body){if(s.signal.aborted)break;!1===r.write(x)&&await Promise.race([new Promise(x=>{_=x}),l])}}catch{}A=!0,r.end()}}function hi(x){return Array.isArray(x)?x[0]:x}async function ho(x,e,t){let r,a=(x.method??"GET").toUpperCase(),n=`http://${hi(x.headers.host)??hi(x.headers[":authority"])??"localhost"}${x.url??"/"}`,_=new Headers;for(let[e,t]of Object.entries(x.headers))if(!(void 0===t||e.startsWith(":")))if(Array.isArray(t))for(let x of t)_.append(e,x);else _.set(e,t);if("GET"!==a&&"HEAD"!==a)if(void 0===e){let e=new TextDecoder,t="";for await(let r of x)t+="string"==typeof r?r:e.decode(r,{stream:!0});(t+=e.decode()).length>0&&(r=t)}else{let x=JSON.stringify(e);_.delete("content-encoding"),_.delete("transfer-encoding"),void 0===x?_.delete("content-length"):(r=x,_.set("content-length",String(new TextEncoder().encode(x).byteLength)))}return new Request(n,{method:a,headers:_,...t?.signal!==void 0&&{signal:t.signal},...void 0!==r&&{body:r}})}["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(x=>{Object.defineProperty(hA.prototype,x,{get(){return this[ha]()[x]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(x=>{Object.defineProperty(hA.prototype,x,{value:function(){return this[ha]()[x]()}})}),Object.defineProperty(hA.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(x,e,t){let r={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[hr]};return`Response (lightweight) ${t(r,{...e,depth:null==x?null:x-1})}`}}),Object.setPrototypeOf(hA,h_),Object.setPrototypeOf(hA.prototype,h_.prototype),void 0===globalThis.crypto&&(globalThis.crypto=cH),Symbol("outgoingEnded"),Symbol("incomingDraining");let hl=I("../../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js");function hc(x,e,t){x.readyState!==rg.OPEN||x.bufferedAmount>0xa00000?x.terminate():x.send(JSON.stringify({type:e,data:t}))}let hv=new Set(["DEBUGGER_NOT_CONNECTED","DEBUGGER_DISCONNECTED","TARGET_NOT_FOUND","ELEMENT_NOT_FOUND","RENDER_FAILED","RENDER_TIMEOUT","VIEWPORT_FAILED","INSPECTION_FAILED","SCROLL_FAILED","SCREENSHOT_FAILED","SNAPSHOT_FAILED","CHAT_NOT_READY","CHAT_BUSY","CHAT_SUBMIT_FAILED","CHAT_TIMEOUT","TOOL_CALL_FAILED","COMMAND_TIMEOUT"]);class hd extends Error{code;constructor(x,e){super(e),this.name="DebuggerControlError",this.code=x}}function hf(x){return"render_page"===x||"render_widget"===x}function hb(x){return"number"==typeof x&&Number.isFinite(x)}function hu(x){return"number"==typeof x&&Number.isInteger(x)&&x>=1&&x<=9999}function hp(x){if("submit_chat_query"===x.type)return 12e4;if("execute_sandbox_tool_call"===x.type){let e=x.toolCall?.tool_call?.deadline_ms;if("number"==typeof e&&Number.isFinite(e))return Math.max(1,e-Date.now()+1e3)}return 15e3}class hm{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(x){this.snapshotStore=x}registerClient(x,e){let t=this.getSnapshotStore(x),r=this.clients.get(x);r&&this.disconnectClient(r,"Debugger control connection was replaced");let a={clientId:x,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(x)??0,parallelJobs:new Map,queue:[],socket:e};this.clients.set(x,a),this.snapshotsByClientId.set(x,t),e.once("close",()=>{this.disconnectClient(a,"Debugger control connection was closed",!1)})}getSnapshotStore(x){return this.snapshotsByClientId.get(x)??{}}noteSnapshot(x){if(!x)return;let e=this.getSnapshotStore(x);Object.assign(e,this.snapshotStore),this.snapshotsByClientId.set(x,e);let t=Date.now();this.lastSnapshotAtByClientId.set(x,t);let r=this.clients.get(x);r&&(r.lastSnapshotAtMs=t)}execute(x,e,t){let r=void 0!==t?this.clients.get(t):"execute_sandbox_tool_call"===x?this.getToolCallClient():this.getActiveClient();if(!r||r.socket.readyState!==rg.OPEN)return Promise.reject(new hd("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===x?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let a=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((t,n)=>{let _={command:{...e,commandId:a,type:x},reject:n,resolve:t};"execute_sandbox_tool_call"===x?this.startParallelJob(r,_):(r.queue.push(_),this.flushClient(r))})}handleResult(x){var e,t;let r,a=x.clientId?.trim(),n=x.commandId?.trim(),_=a?this.clients.get(a):void 0,A=n?_?.parallelJobs.get(n):void 0,s=A??_?.activeJob;if(!_||!s||s.command.commandId!==n)return!1;if(!0===x.ok&&hf(s.command.type)&&(e=x.snapshot,e.snapshot.command_id===n&&e.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=x.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(a),r={target:x.target}):!0===x.ok&&!hf(s.command.type)&&(r=function(x,e){if("set_viewport"===x)return hu(e.width)&&hu(e.height)?e:void 0;if("submit_chat_query"===x)return!0===e.completed&&e.query?.trim()&&e.requestId?.trim()?e:void 0;if("take_snapshot"===x){let x=e.runtimeSnapshot;return x?.target?{runtimeSnapshot:x}:void 0}if("execute_sandbox_tool_call"===x)return!0===e.reported&&e.request_id?.trim()&&e.tool_call_id?.trim()?e:void 0;if("take_screenshot"===x||e.uid?.trim()){if("get_computed_style"===x){if(!Array.isArray(e.computedStyle)||!e.computedStyle.every(x=>!!x.name?.trim()&&"string"==typeof x.value))return;return e}if("get_element_rect"===x)return[e.x,e.y,e.width,e.height].every(hb)?e:void 0;if("scroll_to"===x)return[e.x,e.y,e.maxX,e.maxY,e.viewportWidth,e.viewportHeight].every(x=>hb(x)&&x>=0)&&e.x<=e.maxX&&e.y<=e.maxY?e:void 0;if("take_screenshot"===x){let x="png"===e.format?"image/png":"jpeg"===e.format?"image/jpeg":"webp"===e.format?"image/webp":void 0;return"string"==typeof e.data&&e.data.length>0&&e.mimeType===x&&hb(e.width)&&hb(e.height)&&(void 0===e.uid||e.uid?.trim())?e:void 0}}}(s.command.type,x.result),"take_snapshot"===s.command.type&&r&&"runtimeSnapshot"in r&&this.storeRuntimeSnapshot(_.clientId,r.runtimeSnapshot)),r)s.resolve(r);else{let e=x.error??{},r=e.code?.trim(),a=r&&hv.has(r)?r:void 0;s.reject(new hd(a??(hf(t=s.command.type)?"RENDER_FAILED":"set_viewport"===t?"VIEWPORT_FAILED":"scroll_to"===t?"SCROLL_FAILED":"submit_chat_query"===t?"CHAT_SUBMIT_FAILED":"take_snapshot"===t?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===t?"TOOL_CALL_FAILED":"take_screenshot"===t?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),e.message?.trim()||"Debugger control command failed"))}return s.timeout&&clearTimeout(s.timeout),A?_.parallelJobs.delete(n):_.activeJob=void 0,this.flushClient(_),!0}getActiveClient(){return[...this.clients.values()].filter(x=>x.socket.readyState===rg.OPEN&&x.lastSnapshotAtMs>0).sort((x,e)=>e.lastSnapshotAtMs-x.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(x,e){let t=this.getSnapshotStore(x).snapshot,r=t?.snapshot;if(!t||!r||r.client_id!==x)return;let a=t.debug_snapshot,{root:n,..._}=e,A=Date.now();this.snapshotStore.snapshot={...t,stored_at:new Date(A).toISOString(),stored_at_ms:A,snapshot:{...r,runtime_snapshot:e},...a?{debug_snapshot:{...a,runtime_snapshot:_}}:{}},this.snapshotStore.updatedAtMs=A,this.noteSnapshot(x)}getConnectedClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===rg.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(x=>x.socket.readyState===rg.OPEN&&x.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(x,e){let t=e.command.commandId;x.parallelJobs.set(t,e),e.timeout=setTimeout(()=>{x.parallelJobs.delete(t)&&e.reject(new hd("TOOL_CALL_FAILED","Debugger control command timed out"))},hp(e.command));try{hc(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}flushClient(x){if(x.activeJob||x.socket.readyState!==rg.OPEN)return;let e=x.queue.shift();if(e){x.activeJob=e,e.timeout=setTimeout(()=>{if(x.activeJob===e){if("submit_chat_query"===e.command.type){e.timeout=void 0,e.reject(new hd("CHAT_TIMEOUT","Debugger control command timed out"));try{hc(x.socket,"control",{commandId:e.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(x,"Debugger control connection was closed");return}e.timeout=setTimeout(()=>{x.activeJob===e&&this.disconnectClient(x,"Debugger chat cancellation was not acknowledged")},5e3);return}x.activeJob=void 0,e.reject(new hd(hf(e.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(x)}},hp(e.command));try{hc(x.socket,"control",e.command)}catch{this.disconnectClient(x,"Debugger control connection was closed")}}}disconnectClient(x,e,t=!0){if(this.clients.get(x.clientId)!==x)return;this.clients.delete(x.clientId),this.snapshotsByClientId.delete(x.clientId);let r=new hd("DEBUGGER_DISCONNECTED",e);for(let e of(x.activeJob?.timeout&&clearTimeout(x.activeJob.timeout),x.activeJob?.reject(r),x.activeJob=void 0,x.parallelJobs.values()))e.timeout&&clearTimeout(e.timeout),e.reject(r);for(let e of(x.parallelJobs.clear(),x.queue.splice(0)))e.reject(r);t&&x.socket.readyState===rg.OPEN&&x.socket.close()}}let hh=["page","widget","app"],hE=["log","info","warn","error","debug","eval"],hj=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function hg(x,e){let t=e.pageIdx??0,r=e.pageSize??50,a=t*r,n=x.slice(a,a+r);return{pageIdx:t,pageSize:r,total:x.length,hasMore:a+n.length<x.length,items:n}}function hy(x){if(!x.snapshot)return{stored:!1,updatedAtMs:x.updatedAtMs};let{debug_snapshot:e,...t}=x.snapshot;return{stored:!0,storedAt:t.stored_at,updatedAtMs:t.stored_at_ms??x.updatedAtMs,snapshot:t.snapshot}}function hS(x){return x.value??x.unserializableValue??x.description??x.type??""}function hI(x,e){var t,r;let a;return(t=x,"all"===(r=e)?hh:"page"===r||"widget"===r||"app"===r?[r]:(a=t.context,a?.page_id||a?.page_path?["page","app"]:a?.widget_id?["widget"]:hh)).flatMap(e=>{let t,r=(t=x.runtime_console?.[e],{entries:t?.entries??[],updatedAtMs:t?.updated_at_ms??t?.updatedAtMs});return r.entries.map((x,t)=>{var a;let n,_,A,s;return a=r.updatedAtMs,n=x.url??x.location?.url,_=x.lineNumber??x.location?.lineNumber,A=x.columnNumber??x.location?.columnNumber,s=x.id??String(t),{msgid:`${e}:${s}`,target:e,level:x.level??"log",source:x.source??"",timestamp:x.timestamp??0,text:x.message??(x.args??[]).map(hS).filter(Boolean).join(" "),...n?{url:n}:{},...void 0===_?{}:{lineNumber:_},...void 0===A?{}:{columnNumber:A},...void 0===a?{}:{updatedAtMs:a},entry:x}})})}function hN(x,e){return{id:x.toolCallId??x.id??`tool-call:${e}`,requestId:x.requestId??x.request_id??"",toolCallId:x.toolCallId??x.id??"",toolName:x.toolName??x.name??"",serverId:x.serverId??x.server_id??"",appKey:x.appKey??x.app_key??"",status:x.status??"",createdAtMs:x.createdAtMs??x.created_at_ms??0,updatedAtMs:x.updatedAtMs??x.updated_at_ms??0,requiresUserApproval:!0===x.requiresUserApproval,isMiniApp:!0===x.isMiniApp,message:x.message??"",resultSummary:x.resultSummary??x.structuredResultSummary}}function hB(x,e){if("page"===e){let{pageId:e,path:t}=x;if(!e||!t)return;return{pageId:e,path:t,name:x.name??e,isHome:!0===x.isHome}}let{widgetId:t}=x;if(t)return{widgetId:t,name:x.name??t}}let hF={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},hw={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},hC={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function hP(x,e={}){return{structuredContent:x,content:e.image?[{type:"image",...e.image}]:[{type:"text",text:e.text??JSON.stringify(x,null,2)}],...e.isError?{isError:!0}:{}}}async function hk(x,e={}){try{return await x()}catch(x){return function(x,e={}){let t=x instanceof hd?x:new hd("INSPECTION_FAILED",String(x));return hP({...e,error:{code:t.code,message:t.message}},{isError:!0})}(x,e)}}function hD(x,e,t,r){let a=tM(t.inputSchema);x.registerTool(e,{...t,inputSchema:a},r)}let hL="/__wsd_mcp";async function hq({request:x,response:e,url:t},r,a){if("OPTIONS"===x.method){fi(e),e.writeHead(204),e.end();return}if("POST"!==x.method)return void fo(e,405,"Method not allowed");let n=t.searchParams.get("clientId")??void 0,_=void 0===n?r:a.getSnapshotStore(n),A=m0(()=>{let x,e;return x=new mq({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),e=async x=>{var e;let t=hy(_);if(!t.stored)return hP(t);let r=hg((e=t.snapshot,[{source:"simulator",events:e.simulator?.trace_events??[]},{source:"widget_runtime",events:e.widget_runtime_trace_events??[]},{source:"page_runtime",events:e.page_runtime_trace_events??[]}].flatMap(({source:x,events:e})=>e.map((e,t)=>{let r;return r=e.payload??{},{source:x,id:e.id??`${x}:${t}`,timestamp:e.timestamp??0,category:r.category??e.display?.category??"",event:r.event??e.event??"",requestId:r.request_id??r.requestId??r.trace_id??r.trace?.trace_id??"",payload:e.payload??e}}))).filter(e=>{let t,r,a;return t=x.category??[],r=x.event?.trim(),a=x.requestId?.trim(),(0===t.length||t.includes(e.category))&&(!r||e.event===r)&&(!a||e.requestId===a)}),x);return hP({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,events:r.items})},hD(x,"list_chat_messages",{annotations:hF,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let x=hy(_);if(!x.stored)return hP(x);let e=_.snapshot?.debug_snapshot?.simulator??x.snapshot.simulator;return hP({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,streamStatus:e?.stream_status,messages:e?.messages??[]})}),hD(x,"list_console_messages",{annotations:hF,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:rc(x1(hE)).optional(),pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),query:ra().optional(),target:x1(["current","page","widget","app","all"]).optional()}},async x=>{let e=hy(_);if(!e.stored)return hP(e);let t=hg(hI(e.snapshot,x.target).filter(e=>{let t,r;return t=x.levels??[],r=x.query?.trim().toLowerCase(),(!(t.length>0)||!!t.includes(e.level))&&(!r||[e.text,e.url,e.source,e.target].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(r)))}),x);return hP({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,total:t.total,pageIdx:t.pageIdx,pageSize:t.pageSize,hasMore:t.hasMore,messages:t.items.map(({entry:x,...e})=>e)})}),hD(x,"get_console_message",{annotations:hF,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:ra()}},async x=>{let e=hy(_);if(!e.stored)return hP(e);let t=hI(e.snapshot,"all").find(e=>e.msgid===x.msgid);return hP({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,found:!!t,...t?{message:t}:{msgid:x.msgid}})}),hD(x,"get_log_snapshot",{annotations:hF,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let x=hy(_);return x.stored?hP({stored:!0,storedAt:x.storedAt,updatedAtMs:x.updatedAtMs,snapshot:x.snapshot}):hP(x)}),hD(x,"list_render_targets",{annotations:hF,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:x1(["all","page","widget"]).optional()}},async x=>{var e,t;let r,a=hy(_);return a.stored?hP({stored:!0,storedAt:a.storedAt,updatedAtMs:a.updatedAtMs,...(e=a.snapshot,t=x.type??"all",r=e.render_targets??{},{pages:"widget"===t?[]:(r.pages??[]).map(x=>hB(x,"page")).filter(Boolean),widgets:"page"===t?[]:(r.widgets??[]).map(x=>hB(x,"widget")).filter(Boolean),...r.currentTarget?{currentTarget:r.currentTarget}:{}})}):hP(a)}),hD(x,"take_snapshot",{annotations:hF,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:x1(["current","page","widget"]).optional(),verbose:eY().optional()}},x=>hk(async()=>{let e=function(x,e){var t,r;let a,n,_,A=x.runtime_snapshot;if(!A?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let s=A.target,i=s.type,o=e.target??"current";if(("page"===o||"widget"===o)&&i!==o)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:o,currentTarget:s};if(!A.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:s};let l=A.selectedUid,c=(t=A.root,r=!0===e.verbose,a=[],n=0,(_=(x,e)=>{var t,A;let{name:s,uid:i}=x;if(!i||!s)return;n+=1;let o=" ".repeat(e);if("text"===x.type)return void a.push(`${o}uid=${i} text ${JSON.stringify(x.text??"")}`);let c=[`uid=${i}`,s],{keyboardFocusable:v=!1,name:d,role:f}=x.accessibility??{};for(let e of(f&&(r||"generic"!==f)&&c.push(`role=${JSON.stringify(f)}`),d&&c.push(`name=${JSON.stringify(d)}`),(r||v)&&c.push(`focusable=${String(v)}`),(x.attributes??[]).map(x=>({name:x.name,value:x.value})).filter(x=>x.name&&(r||hj.has(x.name)||x.name.startsWith("aria-")))))c.push((t=e.name,(A=e.value)?`${t}=${JSON.stringify(A)}`:t));for(let t of(i===l&&c.push("[selected]"),a.push(`${o}${c.join(" ")}`),x.children??[]))_(t,e+1)})(t,0),{actualNodeCount:n,text:a.join("\n")});return{available:!0,target:s,nodeCount:A.nodeCount??c.actualNodeCount,...l?{selectedUid:l}:{},truncated:!0===A.truncated,snapshot:c.text,snapshotUpdatedAtMs:A.updatedAtMs}}({runtime_snapshot:(await a.execute("take_snapshot",{target:x.target??"current"},n)).runtimeSnapshot},x),t=hy(_),r={stored:t.stored,...t.stored?{storedAt:t.storedAt,updatedAtMs:t.updatedAtMs}:{},...e};return hP(r,{text:e.available?e.snapshot:JSON.stringify(r,null,2)})},{available:!1,stored:!1})),hD(x,"get_computed_style",{annotations:hF,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:rc(ra().min(1)).max(100).optional(),uid:ra().min(1)}},({properties:x,uid:e})=>hk(async()=>hP(await a.execute("get_computed_style",{uid:e,...x?{properties:x}:{}},n)))),hD(x,"get_element_rect",{annotations:hF,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:ra().min(1)}},({uid:x})=>hk(async()=>hP(await a.execute("get_element_rect",{uid:x},n)))),hD(x,"take_screenshot",{annotations:hF,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:x1(["png","jpeg","webp"]).optional(),quality:eD().min(0).max(100).optional(),uid:ra().min(1).optional()}},({format:x="png",quality:e,uid:t})=>hk(async()=>{let r=await a.execute("take_screenshot",{format:x,...void 0!==e?{quality:e}:{},...t?{uid:t}:{}},n),{data:_,...A}=r;return hP({captured:!0,...A},{image:{data:_,mimeType:r.mimeType}})},{captured:!1})),hD(x,"scroll_to",{annotations:hC,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:ra().min(1).optional(),x:eD().min(0).optional(),y:eD().min(0).optional()}},({uid:x,x:e,y:t})=>hk(async()=>hP({scrolled:!0,...await a.execute("scroll_to",{uid:x,x:e,y:t},n)}),{scrolled:!1})),hD(x,"set_viewport",{annotations:hC,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:eD().int().min(1).max(9999),width:eD().int().min(1).max(9999)}},({height:x,width:e})=>hk(async()=>hP({updated:!0,viewport:await a.execute("set_viewport",{height:x,width:e},n)}),{updated:!1})),hD(x,"render_page",{annotations:hw,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:ra().min(1)}},({url:x})=>hk(async()=>hP({rendered:!0,target:(await a.execute("render_page",{url:x},n)).target}),{rendered:!1})),hD(x,"render_widget",{annotations:hw,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:e6(ra(),x4()).optional(),widgetId:ra().min(1)}},({structuredContent:x,widgetId:e})=>hk(async()=>hP({rendered:!0,target:(await a.execute("render_widget",{structuredContent:x??{},widgetId:e},n)).target}),{rendered:!1})),hD(x,"submit_chat_query",{annotations:hw,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:ra().trim().min(1)}},({query:x})=>hk(async()=>hP({submitted:!0,...await a.execute("submit_chat_query",{query:x},n)}),{submitted:!1})),hD(x,"list_agent_trace_events",{annotations:hF,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:rc(ra()).optional(),event:ra().optional(),pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),requestId:ra().optional()}},e),hD(x,"list_agent_tool_calls",{annotations:hF,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:eD().int().min(0).optional(),pageSize:eD().int().min(1).max(200).optional(),query:ra().optional(),requestId:ra().optional(),status:rc(ra()).optional(),toolName:ra().optional()}},async x=>{var e;let t=hy(_);if(!t.stored)return hP(t);let r=hg((e=t.snapshot,(e.simulator?.tool_calls??[]).map(hN)).filter(e=>{let t,r,a,n;return t=x.requestId?.trim(),r=x.toolName?.trim(),a=x.status??[],n=x.query?.trim().toLowerCase(),(!t||e.requestId===t)&&(!r||e.toolName===r)&&(!(a.length>0)||!!a.includes(e.status))&&(!n||[e.toolName,e.serverId,e.appKey,e.status,e.message,"string"==typeof e.resultSummary?e.resultSummary:void 0].filter(x=>"string"==typeof x).some(x=>x.toLowerCase().includes(n)))}),x);return hP({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,toolCalls:r.items})}),x}),s=hs(A);try{await s(x,e)}catch(x){e.headersSent?e.destroy(x instanceof Error?x:void 0):fo(e,500,x instanceof Error?x.message:String(x))}finally{await A.close().catch(()=>void 0)}}let hT="/__web_sdk_debug_scenes",hR="/__web_sdk_widget_view_data_templates",h$={"Cache-Control":"no-cache"};async function hG(x,e){try{let t=await e?.()??{templatesByEntry:{},templatesByWidget:{}};fl(x,200,t,h$)}catch(e){d5.error("加载 Widget viewData 模板失败",{error:e}),fl(x,500,{templatesByEntry:{},templatesByWidget:{}},h$)}}let hO="Action HUB request failed or returned an invalid response",hX=x=>null!=x&&0!==x&&"0"!==x;async function hK(x,e){if(!function({request:x,response:e}){return!function(x){if(!["127.0.0.1","::1","::ffff:127.0.0.1"].includes(x.socket.remoteAddress??""))return!1;try{let e=x.headers.host;if(!e)return!1;let t=new URL(`http://${e}`);if(!["127.0.0.1","[::1]","localhost"].includes(t.hostname)||t.username||t.password||"/"!==t.pathname||t.search||t.hash)return!1;let r=x.headers.origin;return!r||r===t.origin}catch{return!1}}(x)?(fo(e,403,"Forbidden origin or host"),!1):"OPTIONS"===x.method?(e.writeHead(204).end(),!1):"POST"!==x.method?(fo(e,405,"Method not allowed"),!1):x.headers["content-type"]?.split(";")[0].trim().toLowerCase()==="application/json"||(fo(e,415,"Content-Type must be application/json"),!1)}(x))return;let{request:t,response:r}=x,a=new AbortController,n=()=>a.abort(),_=m0(()=>(function(x,e){let t=new mL({name:"doubao-action-hub",version:"1.0.0"},{capabilities:{tools:{}}});for(let r of["tools/list","tools/call"])t.setRequestHandler(r,(t,r)=>hZ(x,t,AbortSignal.any([e,r.mcpReq.signal])));return t})(e,a.signal)),A=setTimeout(()=>{a.abort(),r.headersSent||r.destroyed?(r.destroy(),t.destroy()):(r.once("finish",()=>t.destroy()),fo(r,504,"Action HUB request timed out"))},6e4);t.once("aborted",n),r.once("close",n);try{let e=await hQ(x);void 0===e||a.signal.aborted||await hs(_)(t,r,e)}finally{clearTimeout(A),t.off("aborted",n),r.off("close",n),a.abort(),await _.close()}}async function hQ({request:x,response:e}){let t;try{t=await fv(x,e,1048576)}catch{e.destroyed||e.writableEnded||fo(e,413,"Request body is too large or incomplete");return}try{return JSON.parse(t)}catch{fo(e,400,"Invalid JSON request");return}}async function hM(x){if(!x.ok||!x.body)throw await x.body?.cancel(),Error(hO);let e=[],t=0;for await(let r of x.body){if((t+=r.byteLength)>4194304)throw Error(hO);e.push(r)}return JSON.parse(Buffer.concat(e).toString("utf8"))}async function hZ(x,e,t){try{let r=await (x.fetcher??fetch)(`https://mcp.bytedance.net/mcp/proxy/${e.method}`,{method:"POST",redirect:"error",signal:t,headers:{...fI(),"Content-Type":"application/json","X-Access-Key":x.accessKey,"X-Client-Version":"doubao-web-simulator",...x.cluster?{cluster:x.cluster}:{}},body:JSON.stringify({mcp_server_names:[x.serverName],..."tools/call"===e.method?{name:e.params.name,arguments:JSON.stringify({...e.params.arguments,from_mcp_call:!0})}:{},...x.headers?{extra_info:{headers:JSON.stringify(x.headers)}}:{}})}),a=await hM(r);if(!oS(a))throw Error(hO);let n=a.result;if("string"==typeof n)try{n=JSON.parse(n)}catch{}for(let t of(n=function x(e,t){return"string"==typeof e?e.split(t).join("[redacted]"):Array.isArray(e)?e.map(e=>x(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e.split(t).join("[redacted]"),x(r,t)])):e}(n,x.accessKey),"tools/list"===e.method?[a,n]:[a]))if(!oS(t)||void 0!==t.base_resp&&!oS(t.base_resp)||[t.error_code,t.code,t.status_code,t.base_resp?.status_code].some(hX)||!1===t.success||t.error||void 0!==t.status&&![0,"0","success","ok"].includes(t.status))throw Error(hO);if("tools/call"===e.method&&"string"==typeof n)return{content:[{type:"text",text:n}],structuredContent:{result:n}};if(!oS(n)||void 0!==n.base_resp&&(!oS(n.base_resp)||hX(n.base_resp.status_code)))throw Error(hO);if("tools/list"===e.method){if(!Array.isArray(n.tools))throw Error(hO);return{tools:n.tools.map(x=>{if(!oS(x))throw Error(hO);let e=x.input_schema??x.inputSchema,t={name:x.name,...void 0===x.description?{}:{description:x.description},inputSchema:"string"==typeof e?JSON.parse(e):e};if(!uN.Tool(t))throw Error(hO);return t})}}return{content:Array.isArray(n.content)&&n.content.every(uN.ContentBlock)?n.content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n,...hX(n.error_code)||hX(n.errorCode)||!0===n.isError?{isError:!0}:{}}}catch{throw Error(hO)}}let hJ="/__dbx_real_device_debug",hV=`${hJ}/state`,hH=`${hJ}/start`,hU=`${hJ}/cancel`,hY=`${hJ}/qr`;class hz{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:hV,startEndpoint:hH,cancelEndpoint:hU,qrEndpoint:hY,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(x){this.provider=x,this.accessToken=x?ar.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:x=>x.pathname.startsWith(hJ),handle:({request:x,response:e,url:t})=>this.serveRequest(x,e,t)}]}async serveRequest(x,e,t){if(!this.validateRequest(x,e))return;let r=this.provider;if(!r)return this.writeError(e,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let a=await this.readJsonBody(x,e);if(a)try{if(t.pathname===hV||t.pathname===hH){if(Object.keys(a).length>0)return this.writeError(e,400,"INVALID_REQUEST","Unexpected request fields");let x=t.pathname===hV?await r.getState():await r.start();fl(e,200,x);return}if(t.pathname===hU){let x=a.operationId;if("string"!=typeof x||!x||1!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid operationId");fl(e,200,await r.cancel(x));return}if(t.pathname===hY){let{operationId:x,kind:t}=a;if("string"!=typeof x||!x||"modern"!==t&&"legacy"!==t||2!==Object.keys(a).length)return this.writeError(e,400,"INVALID_REQUEST","Invalid QR request");let n=await r.getQrImage(x,t);if(!n)return this.writeError(e,404,"QR_NOT_FOUND","QR image is unavailable");fi(e),e.writeHead(200,{"Content-Length":n.body.byteLength,"Content-Type":n.contentType}),e.end(n.body);return}return this.writeError(e,404,"NOT_FOUND","Not found")}catch{return this.writeError(e,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(x,e){var t,r;let a,n,_;if(!function(x){if(!x)return!1;try{let e=new URL(`http://${x}`).hostname.toLowerCase();return"127.0.0.1"===e||"[::1]"===e||"localhost"===e}catch{return!1}}(x.headers.host))return this.writeError(e,403,"FORBIDDEN_HOST","Forbidden host"),!1;let A=x.headers["x-dbx-real-device-token"];if("string"!=typeof A||!this.accessToken||(t=A,r=this.accessToken,n=(a=new TextEncoder).encode(t),_=a.encode(r),!(n.length===_.length&&ar.timingSafeEqual(n,_))))return this.writeError(e,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==x.method)return this.writeError(e,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(x.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(e,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let s=x.headers.origin;return!s||s===`http://${x.headers.host}`||(this.writeError(e,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(x,e){let t,r;try{t=await fv(x,e,4096)}catch{return this.writeError(e,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!t.trim())return{};try{r=JSON.parse(t)}catch{return this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body")}return!r||"object"!=typeof r||Array.isArray(r)?this.writeError(e,400,"INVALID_REQUEST","Invalid JSON body"):r}writeError(x,e,t,r){x.writableEnded||x.destroyed||fl(x,e,{error:{code:t,message:r}})}}let hW={"Cache-Control":"no-cache"},h0="/app_developer/api/sandbox/",h1=`${h0}session/business_info/update`,h2=new Set([`${h0}resources/notices/pull`,`${h0}resources/tasks/pull`]),h3={"Access-Control-Expose-Headers":fr},h6=new Set;function h4(x,e,t,r,a,n){if(!Z())return!1;let _=`${a[ft]??""} ${x} ${e.pathname}`,A=h2.has(e.pathname);if(A&&t>=500){if(h6.has(_))return!1;h6.add(_)}else A&&t<500&&h6.delete(_);let s=Number(process.hrtime.bigint()-r)/1e6;return d5.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:s,headers:a,logId:n}),!0}function h5({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){fu({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_})}function h7(x,e,t){return t&&!(h2.has(x.pathname)&&e>=500)}function h8(x,e){if(x.pathname!==h1||!e)return e;try{let x=JSON.parse(e);return JSON.stringify({...x,..."csr_pem"in x?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"Sandbox 业务信息请求无效"})}}async function h9({method:x,request:e,requestBody:t,requestHeaders:r,response:a,targetUrl:n,usePlatformFetch:_}){let A=process.hrtime.bigint(),s=fp(e,a);try{let e,i=_?await fF({internal:!0,path:`${n.pathname}${n.search}`,method:x,body:t,headers:r,signal:s}):await fetch(n,{body:"GET"===x||"HEAD"===x?void 0:t,headers:r,method:x,signal:s}),o=h4(x,n,i.status,A,r,i.headers.get(fr)??void 0);if(a.destroyed||a.writableEnded)return void i.body?.cancel().catch(()=>void 0);let l=await fd(i);return h7(n,i.status,o)&&h5({method:x,requestBody:h8(n,t),requestHeaders:r,responseBody:l,responseHeaders:i.headers,statusCode:i.status,targetUrl:n}),a.destroyed||a.writableEnded||(e=fs(i.headers,[fr]),fi(a,h3),a.writeHead(i.status,e),a.end(l)),{body:l,ok:i.ok}}catch(i){if(a.destroyed||a.writableEnded||s.aborted)return;let e=`代理 Sandbox 请求失败:${i instanceof Error?i.message:String(i)}`,_=h4(x,n,502,A,r);h7(n,502,_)&&h5({method:x,requestBody:h8(n,t),requestHeaders:r,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:n}),fo(a,502,e,h3)}}async function Ex(x,e,t={}){let r;if("POST"!==x.method)return void fo(e,405,"不支持的请求方法",h3);try{r=JSON.parse(await fv(x,e,0xa00000))}catch(x){fo(e,400,`Sandbox 代理请求内容无效:${x.message}`,h3);return}let a=function(x,e){if(!x.url)return;let t=new URL(x.url,e);if(!t.pathname.startsWith(h0))return;let r=new URL(`${t.pathname}${t.search}`,e);var a=x.params;if(a)for(let[x,e]of Object.entries(a))null!=e&&r.searchParams.set(x,String(e));return r}(r,t.targetOrigin??oN);if(!a)return void fo(e,404,"未找到 Sandbox endpoint",h3);if(!t.sandboxSessionId)return void fl(e,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},h3);let n=function(x,e,t,r){if(e.pathname.startsWith(`${h0}session/`)&&e.pathname!==`${h0}session/create`)return JSON.stringify({..."object"==typeof x.data&&null!==x.data?x.data:{},sandbox_session_id:r});if(void 0===x.data)return;if("object"!=typeof x.data||null===x.data||!t)return JSON.stringify(x.data);let a={...x.data};return e.pathname.startsWith(`${h0}jsb/`)&&"app_key"in a&&(a.app_key=t),e.pathname===`${h0}passport/open/auth`&&"client_key"in a&&(a.client_key=t),JSON.stringify(a)}(r,a,t.sandboxAppId,t.sandboxSessionId),_=r.method||"POST",A=function(x,e,t,r,a){let n=Object.fromEntries(Object.entries(f_({...x.headers,...t,...void 0===r?{}:{"content-length":String(Buffer.byteLength(r))},"content-type":"application/json"},e,{...fI(),...a?{[ft]:a}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]));for(let x of Object.keys(n))"accept-encoding"===x.toLowerCase()&&delete n[x];return n["accept-encoding"]="identity",n}(x,a,r.headers,n,t.sandboxSessionId),s=await h9({method:_,request:x,requestBody:n,requestHeaders:A,response:e,targetUrl:a,usePlatformFetch:!t.targetOrigin});if(a.pathname===h1&&s?.ok)try{let x=JSON.parse(s.body.toString("utf8"));(void 0===x.code||0===x.code)&&t.onBusinessInfoUpdated?.(function(x){if(!x||"object"!=typeof x||Array.isArray(x))return;let e="string"==typeof x.csr_pem?x.csr_pem.trim():"",t="string"==typeof x.phone_num?x.phone_num.trim():"";return t?{...e?{csrPem:e}:{},phoneNum:t}:void 0}(r.data))}catch{}}let Ee="/app_developer/api/sandbox/bridge/events",Et="/app_developer/api/sandbox/bridge/response",Er=new Set(["connection","content-length","host"]),Ea=new Set(["heartbeat"]),En=[500,1e3,2e3,5e3],E_=0;function EA(x){return x.length<=8?x:`${x.slice(0,4)}...${x.slice(-4)}`}function Es(x,e=new Headers,t=""){return{response:x,responseHeaders:Object.fromEntries(e),statusText:t}}async function Ei(x){let e,t,r=x.request_id||"";if(!r)return Es({error_message:"Bridge 请求缺少 request_id",http_status:0,request_id:r,success:!1});if(!x.path?.startsWith("/"))return Es({error_message:`Bridge 请求路径无效:${x.path??""}`,http_status:0,request_id:r,success:!1});let a=function(x){if(x.origin)try{var e;return new URL(x.path??"/",(e=x.origin).endsWith("/")?e:`${e}/`)}catch{return}}(x);if(!a)return Es({error_message:`Bridge 请求 origin 无效:${x.origin??""}`,http_status:0,request_id:r,success:!1});let n=(x.method||"GET").toUpperCase(),_=function(x){let e={};for(let[t,r]of Object.entries(x??{}))!t||Er.has(t.toLowerCase())||(e[t]=r);return e}(x.headers),A="GET"===n||"HEAD"===n?void 0:x.body??"",s=new AbortController,i=setTimeout(()=>s.abort(),(e="number"==typeof x.timeout_ms?x.timeout_ms:3e3,t="number"==typeof x.deadline_ms?x.deadline_ms-Date.now():e,Math.max(1,Math.min(e,t))));try{var o;let x=await fetch(a,{body:A,headers:_,method:n,redirect:"manual",signal:s.signal}),e=await x.text();return o={method:n,requestBody:A,requestHeaders:_,responseBody:e,responseHeaders:x.headers,statusCode:x.status,targetUrl:a},fu(o),Es({body:e,http_status:x.status,request_id:r,success:!0},x.headers,x.statusText)}catch(x){return fu({method:n,requestBody:A,requestHeaders:_,responseBody:x instanceof Error?x.message:String(x),responseHeaders:new Headers,statusCode:0,targetUrl:a}),Es({error_message:x instanceof Error?x.message:String(x),http_status:0,request_id:r,success:!1})}finally{clearTimeout(i)}}function Eo(x,e=new Set){if(Array.isArray(x)){for(let t of x)Eo(t,e);return[...e]}if(!x||"object"!=typeof x)return[...e];for(let[t,r]of Object.entries(x)){if(t.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof r&&r)e.add(r);else if(Array.isArray(r))for(let x of r)"string"==typeof x&&x&&e.add(x);continue}Eo(r,e)}return[...e]}function El(x,e){x.onLog?.(e)}function Ec(x){try{return JSON.parse(x)}catch{return}}function Ev({detail:x,requestHeaders:e,status:t,targetUrl:r}){if(Z()){if("number"==typeof t)return void d5.request({method:"CONNECT",url:r.pathname,statusCode:t,headers:e,context:{detail:x}});d5.info("Bridge 连接等待中",{url:r.pathname,detail:x,ppe:Q(e)})}}function Ed(x,e={}){Z()&&d5.info(x,e)}async function Ef(x,e){let t=JSON.stringify({sandbox_session_id:x.sandboxSessionId,...e}),r={"content-type":"application/json",[ft]:x.sandboxSessionId,...fI()};if(x.targetOrigin){let e=new URL(Et,x.targetOrigin),a=await fetch(e,{body:t,headers:r,method:"POST"}),n=await a.text();if(fu({method:"POST",requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:a.headers,statusCode:a.status,targetUrl:e}),!a.ok)throw Error(`上传 Bridge 响应失败:${a.status} ${n}`);return{responseBody:n,responseHeaders:Object.fromEntries(a.headers),responsePayload:Ec(n)}}let a=new URL(Et,oN),n=await fF({body:t,headers:r,internal:!0,method:"POST",path:Et}),_=await n.text();if(fu({method:"POST",requestBody:t,requestHeaders:r,responseBody:_,responseHeaders:n.headers,statusCode:n.status,targetUrl:a}),!n.ok)throw Error(`上传 Bridge 响应失败:${n.status} ${_}`);return{responseBody:_,responseHeaders:Object.fromEntries(n.headers),responsePayload:Ec(_)}}async function Eb(x,e){let t;try{t=JSON.parse(e)}catch(x){d5.warn("Sandbox Bridge 请求解析失败",{reason:x.message});return}let r=Date.now(),a=`bridge-${r}-${++E_}`,n=t.request_id||"",_={id:a,request:t,requestId:n,sandboxSessionId:x.sandboxSessionId,timestamp:r};El(x,{..._,logIds:Eo(t),status:"pending",updatedAtMs:r});let A=await Ei(t),s={...A.response,headers:A.responseHeaders,status_text:A.statusText};try{let e=await Ef(x,A.response);El(x,{..._,logIds:Eo([t,s,e]),response:s,status:A.response.success?"success":"error",updatedAtMs:Date.now()})}catch(e){throw El(x,{..._,errorMessage:e instanceof Error?e.message:String(e),logIds:Eo([t,s]),response:s,status:"error",updatedAtMs:Date.now()}),e}}async function Eu(x,e,t){let r={sandbox_session_id:x.sandboxSessionId},a=new URL(`${Ee}?sandbox_session_id=${encodeURIComponent(x.sandboxSessionId)}`,oN),n=(o=x.sandboxSessionId,{accept:"text/event-stream",host:a.host,[ft]:o,...fI()});Ev({detail:`host=${n.host} session=${EA(x.sandboxSessionId)}`,requestHeaders:n,status:"pending",targetUrl:a}),Ed("bridge/events request",{headers:{accept:n.accept,host:n.host,[ft]:EA(x.sandboxSessionId),"x-tt-env":n["x-tt-env"],"x-use-ppe":n["x-use-ppe"]},path:Ee,query:r});let _=await fF({headers:n,internal:!0,method:"GET",path:Ee,query:r,signal:e});if(Ev({detail:`content-type=${_.headers.get("content-type")??""}`,requestHeaders:n,status:_.status,targetUrl:a}),!_.ok||!_.body){let x=await _.text().catch(()=>"");fu({method:"GET",requestBody:void 0,requestHeaders:n,responseBody:x,responseHeaders:_.headers,statusCode:_.status,targetUrl:a}),d5.warn("Sandbox Bridge 事件请求失败",{status:_.status,body:x.slice(0,500)});let e=Error(`Sandbox Bridge SSE 请求失败:${_.status} ${x}`);throw e.status=_.status,e}fu({method:"GET",requestBody:void 0,requestHeaders:n,responseBody:"",responseHeaders:_.headers,statusCode:_.status,targetUrl:a}),t?.();let A=_.body.getReader(),s=new dW.TextDecoder,i="";for(;!e.aborted;){let{done:e,value:t}=await A.read();if(e){Ed("Bridge events 流已结束",{session:EA(x.sandboxSessionId)});break}let r=(i+=s.decode(t,{stream:!0})).search(/\r?\n\r?\n/);for(;r>=0;){let e=i.slice(0,r),t=i.slice(r).match(/^\r?\n\r?\n/);i=i.slice(r+(t?.[0].length??2));let A=function(x){let e="message",t=[];for(let r of x.split(/\r?\n/)){if(r.startsWith("event:")){e=r.slice(6).trim();continue}r.startsWith("data:")&&t.push(r.slice(5).trimStart())}return{data:t.join("\n"),name:e}}(e);if(!function(x,e){if(!Z()||Ea.has(x.name))return;let t=function(x){try{let e=JSON.parse(x);return"string"==typeof e.request_id?e.request_id:void 0}catch{return}}(x.data);d5.info("已收到 Bridge 事件",{event:x.name,requestId:t,ppe:Q(e)}),d5.info(`事件详情
402
+ ${x.data}`)}(A,n),"bridge_request"===A.name){var o,l,c=_.headers,v=_.status;fu({method:`EVENT ${A.name}`,requestBody:A.data,requestHeaders:n,responseBody:"",responseHeaders:c,statusCode:v,targetUrl:a}),Eb(x,A.data).catch(x=>{d5.warn("Sandbox Bridge 请求处理失败",{reason:x.message})})}else if("TOOL_CALL"===A.name){let e="object"==typeof(l=Ec(A.data))&&l?.tool_call?l:void 0;e?Promise.resolve(x.onSimulatorToolCall?.(e)).catch(x=>{d5.warn("Sandbox Tool 调用转发失败",{reason:x instanceof Error?x.message:String(x),requestId:e.request_id,toolCallId:e.tool_call.tool_call_id})}):d5.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===A.name){let e=function(x){let e=Ec(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.resource,a=t?.action,n=t?.resource_id,_=t?.revision;if(("notice"===r||"task"===r)&&("upsert"===a||"remove"===a)&&"string"==typeof n&&n&&("number"==typeof _||"string"==typeof _))return{action:a,eventId:"string"==typeof e.event_id?e.event_id:"",occurredAtMs:"number"==typeof e.occurred_at_ms?e.occurred_at_ms:void 0,resource:r,resourceId:n,revision:_}}(A.data);e?x.onResourceChanged?.(e):d5.warn("Sandbox 资源事件解析失败")}else if("card_delta"===A.name){let e=function(x){let e=Ec(x);if(!e||"object"!=typeof e||Array.isArray(e))return;let t=e.data&&"object"==typeof e.data&&!Array.isArray(e.data)?e.data:void 0,r=t?.card_delta;if(!("card_delta"!==e.type||!r||"object"!=typeof r||Array.isArray(r)))return r}(A.data);e?x.onSimulatorEvent?.({payload:e,type:"card_delta"}):d5.warn("Sandbox 模拟器事件解析失败",{event:A.name})}else if("get_simulator_card_snapshots"===A.name){let e=Ec(A.data);e&&"object"==typeof e&&!Array.isArray(e)?x.onSimulatorEvent?.({payload:e,type:A.name}):d5.warn("Sandbox 模拟器事件解析失败",{event:A.name})}r=i.search(/\r?\n\r?\n/)}}}async function Ep(x,e){let t=0,r=!1;for(;!e.aborted;){try{await Eu(x,e,()=>{r=!1,x.onConnectionStatusChange?.("connected")}),t=0}catch(t){if(e.aborted)return;let x=t.status;if(r||(d5.warn("无法接收来自平台服务的请求",{reason:t.message}),r=!0),401===x||403===x||404===x)return}x.onConnectionStatusChange?.("reconnecting"),await (0,D.setTimeout)(En[Math.min(t,En.length-1)],void 0,{signal:e}).catch(()=>void 0),t+=1}}let Em="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",Eh="/app_developer/api/sandbox/session/business_info/update";function EE(x){if(!x)return!1;try{return r5.statSync(x).isFile()}catch{return!1}}async function Ej({body:x,headers:e,method:t,sandboxPath:r,targetOrigin:a,targetUrl:n}){let _=new AbortController,A=setTimeout(()=>_.abort(),3e4);try{return a?await fetch(n,{body:x,headers:e,method:t,signal:_.signal}):await fF({internal:!0,path:r,body:x,headers:e,method:t,signal:_.signal})}catch(x){if(_.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${n}`);throw x}finally{clearTimeout(A)}}function Eg(x,e){return(x?.[e]??process.env[e])?.trim()??""}function Ey(x,e,t,r,a,n){if(!Z())return;let _=Number(process.hrtime.bigint()-r)/1e6;d5.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:_,headers:a,logId:n})}function ES({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_}){fu({method:x,requestBody:e,requestHeaders:t,responseBody:r,responseHeaders:a,statusCode:n,targetUrl:_})}async function EI(x,e,t,r,a,n){let _,A,s="/app_developer/api/sandbox/session/create",i="POST",o=function(){let x=new Set;for(let e of(process.env[Em]??"").split(",")){let t=e.trim();if(t)try{let e=new URL(t),r=e.hostname.replace(/^\[|\]$/g,"").toLowerCase(),a="localhost"===r||"::1"===r||4===(0,dz.isIP)(r)&&r.startsWith("127.");if("http:"!==e.protocol&&"https:"!==e.protocol||!a)throw Error("仅允许本机回环 HTTP(S) origin");x.add(e.origin)}catch(x){throw Error(`${Em} 包含无效 origin:${t}(${x instanceof Error?x.message:String(x)})`)}}return[...x]}(),l=JSON.stringify({sandbox_project_id:x,manifest:t?.()??(EE(e)?r5.readFileSync(e,"utf8"):""),business_templates:EE(r)?r5.readFileSync(r,"utf8"):"",...n?{app_id:n}:{},...o.length>0?{bridge_origins:o}:{}}),c={"content-type":"application/json",...fI()},v=new URL(s,a??oN),d=process.hrtime.bigint();try{_=await Ej({body:l,headers:c,method:i,sandboxPath:s,targetOrigin:a,targetUrl:v})}catch(e){let x=`创建 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw Ey(i,v,502,d,c),ES({method:i,requestBody:l,requestHeaders:c,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:v}),e}let f=_.headers.get(fr)||"",b=await _.text();Ey(i,v,_.status,d,c,f),ES({method:i,requestBody:l,requestHeaders:c,responseBody:b,responseHeaders:_.headers,statusCode:_.status,targetUrl:v});try{A=JSON.parse(b||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${_.status} ${_.statusText||b||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!_.ok||0!==A.code)throw Error(`创建 Sandbox session 失败:${A.message||_.statusText||_.status}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);let u=A.data?.sandbox_session_id,p=A.data?.sandbox_appid;if(!u||!p)throw Error(`创建 Sandbox session 失败:响应缺少 ${u?"sandbox_appid":"sandbox_session_id"}${A.log_id||f?`,log_id=${A.log_id||f}`:""}`);return{appId:p,sessionId:u}}async function EN(x,e,t,r,a,n){try{return await EI(x,e,t,r,a,n)}catch(x){return d5.warn(`Sandbox 平台服务模拟已跳过:${x instanceof Error?x.message:String(x)}`),{appId:"",sessionId:""}}}function EB(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function EF(x){return{csrUploaded:!!x,phoneNumberUploaded:!0}}async function Ew(x,e){let t,r,a="/app_developer/api/sandbox/session/business_info/get",n="POST",_=JSON.stringify({sandbox_session_id:x}),A={"content-type":"application/json",...fI()},s=new URL(a,e??oN),i=process.hrtime.bigint();try{t=await Ej({body:_,headers:A,method:n,sandboxPath:a,targetOrigin:e,targetUrl:s})}catch(x){throw Ey(n,s,502,i,A),x}let o=t.headers.get(fr)||"",l=await t.text();Ey(n,s,t.status,i,A,o);try{r=JSON.parse(l||"{}")}catch{throw ES({method:n,requestBody:_,requestHeaders:A,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),Error(`获取 Sandbox session 信息失败:HTTP ${t.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}let c={csrUploaded:!!r.data?.csr_pem?.trim(),phoneNumberUploaded:!!r.data?.phone_num?.trim()};if(ES({method:n,requestBody:_,requestHeaders:A,responseBody:JSON.stringify({code:r.code,data:c,log_id:r.log_id}),responseHeaders:t.headers,statusCode:t.status,targetUrl:s}),!t.ok||void 0!==r.code&&0!==r.code)throw Error(`获取 Sandbox session 信息失败:${r.message||t.statusText||t.status}${r.log_id||o?`,log_id=${r.log_id||o}`:""}`);return c}async function EC(x,e){if(!x)return EB();try{return await Ew(x,e)}catch(x){return d5.warn(`Sandbox session 信息查询已跳过:${x instanceof Error?x.message:String(x)}`),EB()}}async function EP(x,e,t){let r,a,n="POST",_=JSON.stringify({...x.csrPem?{csr_pem:x.csrPem}:{},phone_num:x.phoneNum,sandbox_session_id:e}),A={"content-type":"application/json",...fI(),[ft]:e},s=new URL(Eh,t??oN),i=process.hrtime.bigint();try{r=await Ej({body:_,headers:A,method:n,sandboxPath:Eh,targetOrigin:t,targetUrl:s})}catch(x){throw Ey(n,s,502,i,A),x}let o=r.headers.get(fr)||"",l=await r.text();Ey(n,s,r.status,i,A,o),ES({method:n,requestBody:JSON.stringify({...x.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:e}),requestHeaders:A,responseBody:l,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});try{a=JSON.parse(l||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${o?`,log_id=${o}`:""}`)}if(!r.ok||void 0!==a.code&&0!==a.code)throw Error(`更新 Sandbox session 信息失败:${a.message||r.statusText||r.status}${a.log_id||o?`,log_id=${a.log_id||o}`:""}`)}async function Ek(x,e,t,r){if(x&&e.phoneNum&&(!t||e.csrPem))try{return await EP({...e.csrPem?{csrPem:e.csrPem}:{},phoneNum:e.phoneNum},x,r),d5.info("Sandbox 业务信息已自动上传",{sessionId:x}),EF(e.csrPem)}catch(x){d5.warn(`Sandbox 业务信息自动上传已跳过:${x instanceof Error?x.message:String(x)}`);return}}async function ED(x,e){let t,r="/app_developer/api/sandbox/session/revoke",a="POST",n=JSON.stringify({sandbox_session_id:x}),_={"content-type":"application/json",...fI()},A=new URL(r,e??oN),s=process.hrtime.bigint();try{t=await Ej({body:n,headers:_,method:a,sandboxPath:r,targetOrigin:e,targetUrl:A})}catch(e){let x=`撤回 Sandbox session 请求失败:${e instanceof Error?e.message:String(e)}`;throw Ey(a,A,502,s,_),ES({method:a,requestBody:n,requestHeaders:_,responseBody:x,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:A}),e}let i=t.headers.get(fr)||"",o=await t.text();Ey(a,A,t.status,s,_,i),ES({method:a,requestBody:n,requestHeaders:_,responseBody:o,responseHeaders:t.headers,statusCode:t.status,targetUrl:A});let l=JSON.parse(o||"{}");if(!t.ok||0!==l.code)throw Error(`撤回 Sandbox session 失败:${l.message||t.statusText||t.status}${l.log_id||i?`,log_id=${l.log_id||i}`:""}`)}async function EL(x){if(x.recreatePromise)return x.recreatePromise;x.recreatePromise=(async()=>{var e;let t=x.sandboxSessionId;t&&await ED(t,x.sandboxTargetOrigin),x.bridge?.close(),x.bridge=void 0;let r=await EI(x.sandboxProjectId,x.simulatorManifestPath,x.simulatorManifestReader,x.simulatorBusinessTemplatesPath,x.sandboxTargetOrigin,x.sandboxSessionAppId),a=r.sessionId,n=!x.sandboxSessionAppId,_=await Ek(a,x.businessInfoInput,n,x.sandboxTargetOrigin)??await EC(a,x.sandboxTargetOrigin);return x.sandboxAppId=r.appId,x.sandboxSessionId=a,x.businessInfo=_,(e=x).resourceConnectionStatus="connecting",e.resourceEventSequence=0,e.resourceEvents.length=0,e.simulatorEventSequence=0,e.simulatorEvents.length=0,e.resourceGeneration+=1,ER(e),x.bridge=E$(x,a),d5.info("Sandbox session 已重建",{sessionId:a}),{...r,businessInfoUploaded:_.phoneNumberUploaded&&(!n||_.csrUploaded)}})();try{return await x.recreatePromise}finally{x.recreatePromise=void 0}}function Eq(x){return{bridgeLogs:x.bridgeLogs,bridgeLogsUpdatedAtMs:x.bridgeLogsUpdatedAtMs,connectionStatus:x.resourceConnectionStatus,events:x.resourceEvents,generation:x.resourceGeneration,instanceId:x.resourceInstanceId,simulatorEvents:x.simulatorEvents,updatedAtMs:x.resourceEventsUpdatedAtMs}}function ET(x){clearTimeout(x.logBroadcastTimer),x.logBroadcastTimer=void 0;let e=Eq(x);for(let t of x.eventListeners)t(e)}function ER(x){x.resourceEventsUpdatedAtMs=Math.max(Date.now(),x.resourceEventsUpdatedAtMs+1),ET(x)}function E$(x,e){var t={onConnectionStatusChange:e=>{x.resourceConnectionStatus!==e&&(x.resourceConnectionStatus=e,ER(x))},onLog:e=>{let t=x.bridgeLogs.findIndex(x=>x.id===e.id);t>=0?x.bridgeLogs[t]=e:(x.bridgeLogs.push(e),x.bridgeLogs.length>200&&x.bridgeLogs.splice(0,x.bridgeLogs.length-200)),x.bridgeLogsUpdatedAtMs=Math.max(Date.now(),x.bridgeLogsUpdatedAtMs+1),x.logBroadcastTimer??=setTimeout(()=>ET(x),50)},onResourceChanged:e=>{x.resourceEvents.push({...e,sequence:++x.resourceEventSequence}),x.resourceEvents.length>200&&x.resourceEvents.splice(0,x.resourceEvents.length-200),ER(x)},onSimulatorEvent:e=>{x.simulatorEvents.push({...e,sequence:++x.simulatorEventSequence}),x.simulatorEvents.length>200&&x.simulatorEvents.splice(0,x.simulatorEvents.length-200),ER(x)},onSimulatorToolCall:x.onSimulatorToolCall,sandboxSessionId:e,targetOrigin:x.sandboxTargetOrigin};if(!t.sandboxSessionId)return void d5.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let r=new AbortController;return Ed("正在启动 Sandbox Bridge",{session:EA(t.sandboxSessionId)}),t.onConnectionStatusChange?.("connecting"),Ep(t,r.signal),{close:()=>r.abort()}}async function EG(x,e,t,r){if("POST"!==x.method)return void fo(e,405,"不支持的请求方法");if(EO(x,e,r)){if(!t)return void fo(e,503,"Sandbox session 尚未初始化");try{let r=await fv(x,e,1048576);if(r){let x=JSON.parse(r);if(void 0!==x.csrPem&&"string"!=typeof x.csrPem||"string"!=typeof x.phoneNum)return void fo(e,400,"Sandbox 业务信息无效");t.businessInfoInput={..."string"==typeof x.csrPem&&x.csrPem.trim()?{csrPem:x.csrPem.trim()}:{},phoneNum:x.phoneNum.trim()}}let a=await EL(t);fl(e,200,{code:0,data:{sandbox_appid:a.appId,business_info_uploaded:a.businessInfoUploaded,sandbox_session_id:a.sessionId},message:"ok"})}catch(x){fo(e,500,x.message)}}}function EO(x,e,t){let r=x.headers.origin;return"string"==typeof r&&!!t.includes(r)||(fo(e,403,"Sandbox 控制请求来源无效"),!1)}function EX(x){let e=x.appId?.trim(),t=e&&!e.startsWith("doubao-sandbox-app-")?e:void 0,r=function(x){let e=r4.resolve(x??process.cwd()),t=e;try{t=r5.realpathSync.native(e)}catch{}return(0,ar.createHash)("sha256").update(t).digest("hex")}(x.appDirectory),a=function(x,e){let t=Eg(x,"DOUBAO_SANDBOX_PHONE_NUM"),r=Eg(x,"DOUBAO_SANDBOX_CSR_FILE"),a=function(x,e){if(!x)return;let t=r4.isAbsolute(x)?x:r4.resolve(e??process.cwd(),x);return EE(t)?t:void 0}(r,e),n="";if(r&&!a)d5.warn(`Sandbox CSR 文件不存在:${r}`);else if(a)try{n=r5.readFileSync(a,"utf8").trim()}catch(x){d5.warn(`Sandbox CSR 文件读取失败:${x instanceof Error?x.message:String(x)}`)}return{...t?{phoneNum:t}:{},...n?{csrPem:n}:{}}}(x.env,x.appDirectory),n=`${a.phoneNum??""}\0${a.csrPem??""}`;return{businessInfoInput:a,businessInfoInputKey:n,businessTemplatesPath:x.businessTemplatesPath,key:JSON.stringify([n,r,t,x.targetOrigin,x.businessTemplatesPath,x.manifestPath]),manifestReader:x.manifestReader,manifestPath:x.manifestPath,onSimulatorToolCall:x.onSimulatorToolCall,projectId:r,sessionAppId:t,targetOrigin:x.targetOrigin}}class EK{configKey;manifestReader;state;constructor(x,e,t){this.state=x,this.configKey=e,this.manifestReader=t}static async start(x){let e=EX(x),t=await EN(e.projectId,e.manifestPath,e.manifestReader,e.businessTemplatesPath,e.targetOrigin,e.sessionAppId),r=!e.sessionAppId,a={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await Ek(t.sessionId,e.businessInfoInput,r,e.targetOrigin)??await EC(t.sessionId,e.targetOrigin),businessInfoInput:e.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:e.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,ar.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:t.appId,sandboxProjectId:e.projectId,sandboxSessionAppId:e.sessionAppId,sandboxSessionId:t.sessionId,sandboxTargetOrigin:e.targetOrigin,simulatorBusinessTemplatesPath:e.businessTemplatesPath,simulatorManifestReader:e.manifestReader,simulatorManifestPath:e.manifestPath},n=new EK(a,e.key,e.manifestReader);return a.bridge=t.sessionId?E$(a,t.sessionId):void 0,n}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(x){return this.state.eventListeners.add(x),x(Eq(this.state)),()=>{this.state.eventListeners.delete(x)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),ET(this.state)}matches(x){let e=EX(x);return this.configKey===e.key&&this.manifestReader===e.manifestReader}getDebugContext(){var x;let e;return{fileSystemNamespace:(e=(x=this.state).sandboxSessionAppId?`real-app\0${x.sandboxSessionAppId}`:`virtual-app\0${x.sandboxAppId}\0${x.sandboxProjectId}`,`sandbox-v1:${(0,ar.createHash)("sha256").update(e).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(x=[]){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>{EO(e,t,x)&&Ex(e,t,{onBusinessInfoUpdated:x=>{this.state.businessInfo=EF(x?.csrPem),x&&(this.state.businessInfoInput=x)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})}},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>EG(e,t,this.state,x)}]}}function EQ(x,e){return x.relativePath<e.relativePath?-1:+(x.relativePath>e.relativePath)}let EM="/__tools/tools.json",EZ="/__events/events.json",EJ="manifest.yaml",EV="skill";function EH(x){if(!x)return!1;try{return r5.statSync(x).isFile()}catch{return!1}}function EU(x,e){if(!x)return;let t=r4.isAbsolute(x)?x:r4.resolve(e??process.cwd(),x);return EH(t)?t:void 0}function EY(x,e){if(x&&e)return r4.relative(e,x).split(r4.sep).join("/")||"."}function Ez(x){let e=r4.resolve(x);for(;;){if(EH(r4.join(e,EJ)))return e;let x=r4.dirname(e);if(x===e)return;e=x}}function EW(x){try{return r5.lstatSync(x),!0}catch{return!1}}function E0(x,e,t,r){let a;if(!e.reader&&EH(e.sourcePath)){var n;let t,a=r5.statSync(e.sourcePath);fi(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":a.size,"Content-Type":r}),n=e.sourcePath,(t=r5.createReadStream(n)).once("error",()=>x.destroy()),t.pipe(x);return}try{a=e.reader?.()}catch{a=void 0}void 0===a?fo(x,404,`未找到 ${t}`):(fi(x),x.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(a),"Content-Type":r}),x.end(a))}function E1(x,e){return function(x){let e,t;if(!x)return{layout:"missing",entries:[]};let r=r4.resolve(x);try{e=r5.lstatSync(r)}catch(x){if("ENOENT"===x.code)return{directory:r,layout:"missing",entries:[]};return{directory:r,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${r}: ${x.message}`}}if(e.isSymbolicLink()||!e.isDirectory())return{directory:r,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${r}`};try{var a;let x;a=r,x=[],function e(t){for(let r of r5.readdirSync(t,{withFileTypes:!0})){if(r.isSymbolicLink())continue;let n=r4.join(t,r.name);r.isDirectory()?e(n):r.isFile()&&"SKILL.md"===r.name&&x.push(function(x,e){let t=r4.relative(x,e).split(r4.sep).join("/");return{content:r5.readFileSync(e,"utf8"),relativePath:t}}(a,n))}}(a),t=x}catch(x){return{directory:r,layout:"invalid",entries:[],error:`skill directory is not readable: ${r}: ${x.message}`}}return t.sort(EQ),t.length>0?{directory:r,layout:"resolved",entries:t}:{directory:r,layout:"missing",entries:[]}}(function(x,e){if(e){if(!e)return;if(r4.isAbsolute(e))return e;let t=x?Ez(x):void 0,r=[x,t,process.cwd()].map(x=>r4.resolve(x??process.cwd(),e));return[...new Set(r)].find(EW)??r[0]}if(!x)return;let t=Ez(x);return[...new Set([t?r4.join(t,EV):void 0,r4.join(x,EV),r4.join(process.cwd(),EV)].filter(Boolean))].find(EW)}(x,e))}class E2{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(x){var e,t,r;this.appDirectory=x.appDirectory,this.manifestPath=x.manifestPath?EU(x.manifestPath,x.appDirectory):x.manifestSourcePath??(x.manifestReader?void 0:function(x){if(!x)return;let e=Ez(x);return[...new Set([e?r4.join(e,EJ):void 0,r4.join(process.cwd(),EJ)].filter(Boolean))].find(EH)}(x.appDirectory)),this.businessTemplatesPath=(e=this.manifestPath,t=x.businessTemplatesPath,r=x.appDirectory,t?EU(t,r):e?EU(r4.join(r4.dirname(e),"business-templates.yaml"),r):void 0),this.manifestReader=x.manifestReader,this.eventsConfigReader=x.eventsConfigReader,this.toolsConfigReader=x.toolsConfigReader,this.eventsConfigSource={reader:x.eventsConfigReader,sourcePath:x.eventsConfigSourcePath},this.skillsDirectory=x.skillsDirectory;let a=E1(x.appDirectory,this.skillsDirectory);if(x.skillsDirectory&&"resolved"!==a.layout)throw Error(a.error??`Simulator skills directory contains no runtime Skill: ${x.skillsDirectory}`);this.toolsConfigSource={reader:x.toolsConfigReader,sourcePath:x.toolsConfigSourcePath},this.manifestSource={reader:x.manifestReader,sourcePath:x.manifestSourcePath??this.manifestPath},this.sourceKey=JSON.stringify([this.appDirectory,this.businessTemplatesPath,this.manifestPath,this.eventsConfigSource.sourcePath,this.toolsConfigSource.sourcePath,this.manifestSource.sourcePath,this.skillsDirectory])}matches(x){let e=new E2(x);return this.sourceKey===e.sourceKey&&this.eventsConfigReader===e.eventsConfigReader&&this.toolsConfigReader===e.toolsConfigReader&&this.manifestReader===e.manifestReader}getDebugContext(){let x=E1(this.appDirectory,this.skillsDirectory),e="resolved"===x.layout?x.directory:void 0,t=EY(this.businessTemplatesPath,this.appDirectory),r=EY(this.eventsConfigSource.sourcePath,this.appDirectory),a=EY(this.toolsConfigSource.sourcePath,this.appDirectory),n=EY(this.manifestSource.sourcePath,this.appDirectory),_=EY(e,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:EZ,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...r?{eventsConfigRelativePath:r}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:EM,...a?{toolsConfigRelativePath:a}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...n?{simulatorManifestRelativePath:n}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...t?{simulatorBusinessTemplatesRelativePath:t}:{}}:{},...e?{simulatorSkillsDirectoryOriginalUrl:e,..._?{simulatorSkillsDirectoryRelativePath:_}:{}}:{}}}getRequestRoutes(){return[{match:EZ,handle:({response:x})=>E0(x,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:EM,handle:({response:x})=>E0(x,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:x})=>E0(x,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:x})=>{let e;"missing"===(e=E1(this.appDirectory,this.skillsDirectory)).layout?fo(x,404,"未找到模拟器 Skill 目录"):"invalid"===e.layout?fo(x,422,e.error??"模拟器 Skill 目录结构无效"):fl(x,200,{skills:e.entries},{"Cache-Control":"no-cache"})}}]}}let E3="/app_developer/api",E6=`${E3}/simulator/images/upload`,E4=new Set([`${E3}/simulator/chat`,E6,`${E3}/simulator/tool/report`]),E5={"Access-Control-Expose-Headers":fr};async function E7(x,e,t,r){if(!E4.has(t.pathname))return void fo(e,404,"未找到模拟器接口",E5);let a=r.targetOrigin??oN,n=new URL(`${t.pathname}${t.search}`,a),_=fp(x,e);try{var A;let a=x.method??"GET",s=process.hrtime.bigint(),i=function(x,e,t){return Object.fromEntries(Object.entries(f_(x.headers,e,{...fI(),...t?{[ft]:t}:{}})).filter(([x,e])=>"host"!==x.toLowerCase()&&void 0!==e).map(([x,e])=>[x,Array.isArray(e)?e.join(", "):String(e)]))}(x,n,r.getSandboxSessionId?.()),o=await E8(x,e,t,a),l=r.targetOrigin?await fetch(n,{body:o,headers:i,method:a,signal:_}):await fF({internal:!0,path:`${t.pathname}${t.search}`,method:a,body:o,headers:i,signal:_});if(function(x,e,t,r,a,n){if(!Z())return;let _=Number(process.hrtime.bigint()-r)/1e6;d5.request({method:x,url:`${e.pathname}${e.search}`,statusCode:t,durationMs:_,headers:a,logId:n})}(a,t,l.status,s,i,l.headers.get(fr)??void 0),e.destroyed||e.writableEnded)return void l.body?.cancel().catch(()=>void 0);await E9({method:a,requestBody:(A=o)instanceof Uint8Array?`(binary, ${A.byteLength} bytes)`:A,requestHeaders:i,requestUrl:t,response:e,upstreamResponse:l})}catch(x){if(e.destroyed||e.writableEnded||_.aborted)return;fo(e,502,`代理模拟器请求失败:${x instanceof Error?x.message:String(x)}`,E5)}}async function E8(x,e,t,r){if("GET"!==r&&"HEAD"!==r)return t.pathname===E6?await fc(x,e,0xb00000):await fv(x,e,0xb00000)}async function E9({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n}){var _,A;if(fi(a,E5),a.writeHead(n.status,fs(n.headers,[fr])),_=r,A=n,_.pathname===`${E3}/simulator/chat`||A.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await jx({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n});if(!Z())return n.body?void await (0,F.pipeline)(r3.Readable.fromWeb(n.body),a):void a.end();let s=await fd(n);fu({method:x,requestBody:e,requestHeaders:t,responseBody:s,responseHeaders:n.headers,statusCode:n.status,targetUrl:r}),a.end(s)}async function jx({method:x,requestBody:e,requestHeaders:t,requestUrl:r,response:a,upstreamResponse:n}){if(!n.body){fu({method:x,requestBody:e,requestHeaders:t,responseBody:"",responseHeaders:n.headers,statusCode:n.status,targetUrl:r}),a.end();return}let _=r3.Readable.fromWeb(n.body);if(!Z())return void await (0,F.pipeline)(_,a);fu({method:x,requestBody:e,requestHeaders:t,responseBody:"(event stream)",responseHeaders:n.headers,statusCode:n.status,targetUrl:r});let A=new r3.Transform({transform(x,e,t){let a;try{a=String(x).split("\n\n").filter(Boolean)}catch(e){return d5.error(`事件流分片解码失败:${e?.toString()}`),t(null,x)}for(let x of a)d5.info(`来自 ${r.pathname}${r.search} 的事件
403
+ ${x}`);t(null,x)}});await (0,F.pipeline)(_,A,a)}async function je(x,e){if("POST"!==x.method)return void fl(e,405,{message:"不支持的请求方法"});let t=fp(x,e);try{var r,a;let n,_,A=JSON.parse(await fv(x,e,0xa00000)),s=function(x){if("GET"!==x&&"POST"!==x)throw Error(`Unsupported request method: ${String(x)}`);return x}(A.method),i=fn(A.url),o=await fetch(i,{signal:t,body:"POST"===s?function(x){if(void 0!==x.data&&null!==x.data){if("base64"===x.dataEncoding&&"string"==typeof x.data){var e;let t;return t=new ArrayBuffer((e=Buffer.from(x.data,"base64")).byteLength),new Uint8Array(t).set(e),t}if(void 0===x.dataEncoding&&"string"==typeof x.data)return x.data;throw Error("Invalid prepared request body")}}(A):void 0,headers:(r=A.header,n=new Headers(r),["connection","content-length","host","origin","referer"].forEach(x=>n.delete(x)),n),method:s}),l=Buffer.from(await o.arrayBuffer()).toString("base64");fl(e,200,{data:l,dataEncoding:"base64",header:(a=o.headers,_={},a.forEach((x,e)=>{_[e]=x}),_),statusCode:o.status})}catch(x){if(t.aborted||e.destroyed)return;fl(e,500,{message:x instanceof Error?x.message:String(x)})}}let jt=I("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),jr="/__web_artifacts",ja="/assets/framework";function jn(x,e,t,r,a={}){fi(e,a.headers),jt(x,r,{root:t}).once("error",r=>{if(404===r.statusCode&&a.fallbackPath)return void jn(x,e,t,a.fallbackPath,{headers:a.headers});if(e.headersSent)return void e.destroy(r);let n=r.statusCode??500;fo(e,n,d7.STATUS_CODES[n]??"Internal Server Error")}).pipe(e)}let j_="/__webview",jA=`${j_}/client.js`,js=`${j_}/page`,ji=`${j_}/runtime`,jo=`${j_}/sw.js`,jl="x-doubao-web-view-target",jc="Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",jv=new URL(I("../../debugger-server/dist/web-view-proxy-bootstrap.js"),I.b),jd=new URL(I("../../debugger-server/dist/web-view-proxy-page-client.js"),I.b),jf=new URL(I("../../debugger-server/dist/web-view-proxy-service-worker.js"),I.b);function jb(x,e,t,r=!1){if("GET"!==x.method&&"HEAD"!==x.method)return void fo(e,405,"不支持的请求方法");let a=r5.readFileSync(t,"utf8");fi(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(a),"content-type":"text/javascript; charset=utf-8",...r?{"service-worker-allowed":"/"}:{}}),e.end("HEAD"===x.method?void 0:a)}function ju(x,e){let t=x.searchParams.get("parentOrigin")??e[0];if(!e.includes(t))throw Error("WebView 父级 origin 无效");return t}async function jp(x,e,t,r){if("GET"!==x.method&&"HEAD"!==x.method)return void fo(e,405,"不支持的请求方法");let a=fp(x,e);try{let n=ju(t,r),_=fn(t.searchParams.get("url")??void 0),A=await fetch(_,{signal:a,headers:{"user-agent":jc,..."string"==typeof x.headers.accept?{accept:x.headers.accept}:{},..."string"==typeof x.headers["accept-language"]?{"accept-language":x.headers["accept-language"]}:{}},method:x.method}),s=A.url?new URL(A.url):_;s.hash=_.hash;let i=A.headers.get("content-type")??"",o=fs(A.headers);if(o["cache-control"]="no-cache",o["cross-origin-resource-policy"]="cross-origin",o["x-doubao-web-view-parent-origin"]=n,"HEAD"===x.method||!i.includes("text/html")){let t="HEAD"===x.method?void 0:Buffer.from(await A.arrayBuffer());fi(e),e.writeHead(A.status,{...o,[jl]:s.toString(),...t?{"content-length":t.byteLength}:{}}),e.end(t);return}let l=function(x,e,t){let r=new URLSearchParams({mobileUserAgent:jc,originalPath:`${e.pathname}${e.search}${e.hash}`,parentOrigin:t}).toString().replaceAll("&","&amp;"),a=`<script src="${jA}?${r}"></script>`,n=/<head[^>]*>/i.exec(x);if(n){let e=n.index+n[0].length;return`${x.slice(0,e)}${a}${x.slice(e)}`}return`${a}${x}`}(await A.text(),s,n);fi(e),e.writeHead(A.status,{...o,[jl]:s.toString(),"content-length":Buffer.byteLength(l)}),e.end(l)}catch(x){if(a.aborted||e.destroyed)return;fo(e,502,`代理 web-view 页面失败: ${x instanceof Error?x.message:String(x)}`)}}let jm=/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;async function jh(x){let e=new URL(x).toString();try{await w(e)}catch(x){d5.error("打开 Web 模拟器失败",{error:x}),d5.info("请手动打开 Web 模拟器(本地)",{url:e})}}async function jE(x,e){await new Promise((t,r)=>{let a=e=>{x.off("listening",n),r(e)},n=()=>{x.off("error",a),t()};x.once("error",a),x.once("listening",n),x.listen(e,"127.0.0.1")})}async function jj(x){let e=await d4(9e3),t=[`http://127.0.0.1:${e}`,`http://localhost:${e}`],r=d7.createServer(fE([{match:`${j_}/bootstrap`,handle:({request:x,response:e,url:r})=>{if("GET"!==x.method&&"HEAD"!==x.method)return void fo(e,405,"不支持的请求方法");try{fn(r.searchParams.get("url")??void 0),ju(r,t)}catch{fo(e,400,"WebView URL 无效");return}fi(e,{"Cross-Origin-Resource-Policy":"cross-origin"}),e.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),e.end("HEAD"===x.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${j_}/bootstrap.js`,handle:({request:x,response:e})=>jb(x,e,jv)},{match:jo,handle:({request:x,response:e})=>jb(x,e,jf,!0)},{match:jA,handle:({request:x,response:e})=>jb(x,e,jd)},{match:ji,handle:({request:x,response:e,url:t})=>(function(x,e,t){let r;try{r=fn(t.searchParams.get("url")??void 0)}catch(x){fo(e,400,`无效的 web-view 请求地址: ${x instanceof Error?x.message:String(x)}`);return}let a=f_(x.headers,r,{"user-agent":jc});for(let x of Object.keys(a))x.startsWith("sec-fetch-")&&delete a[x];fm(x,e,{createResponseHeaders:x=>{let e=fA(x),t=Array.isArray(x.location)?x.location[0]:x.location;if(t&&URL.canParse(t,r)){let x=new URL(t,r);e.location=`${ji}?url=${encodeURIComponent(x.toString())}`}return e["cache-control"]="no-cache",e},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:a,targetUrl:r})})(x,e,t)},{match:js,handle:({request:x,response:e,url:r})=>jp(x,e,r,t)}],({response:x})=>{fo(x,404,"未找到 WebView 资源")}));await jE(r,0);let a=r.address(),n=`http://127.0.0.1:${a.port}`,_=d7.createServer(function({artifactOrigin:x,debugScenes:e,debuggerOrigins:t,debuggerProtocol:r,distPath:a,getWidgetViewDataTemplates:n,mcp:_,physicalDeviceDebugGateway:A,sandboxRuntime:s,simulatorAssets:i,simulatorTargetOrigin:o,webViewOrigin:l}){var c;let v={routes:[{match:x=>x.pathname.startsWith(jr),handle:({request:e,response:t,url:r})=>(function(x,e,t,r){let a=t.pathname.slice(jr.length)||"/";if(a.startsWith("//"))return void fo(e,400,"Web 产物路径无效");let n=new URL(r),_=a.startsWith("/")?a:`/${a}`,A=new URL(`${_}${t.search}`,n);A.origin!==n.origin?fo(e,400,"Web 产物路径无效"):fm(x,e,{createResponseHeaders:x=>({...fA(x),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:f_(x.headers,A),targetUrl:A})})(e,t,r,x)},{match:x=>x.pathname===ja||x.pathname.startsWith(`${ja}/`),handle:({request:x,response:e,url:t})=>{let r;!(r=t.pathname.slice(`${ja}/`.length))||r!==r4.basename(r)?fo(e,404,"未找到资源"):jn(x,e,r4.join(a,ja.slice(1)),r,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:x,response:e})=>je(x,e)},{match:"/__webview/page",handle:({request:x,response:e,url:t})=>{"GET"!==x.method&&"HEAD"!==x.method?fo(e,405,"不支持的请求方法"):(fi(e),e.writeHead(302,{"cache-control":"no-store",location:`${l}/__webview/bootstrap${t.search}`}),e.end())}},{match:"/__webview/sw.js",handle:({response:x})=>{fi(x),x.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),x.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
404
404
  self.addEventListener('activate', e => e.waitUntil((async () => {
405
405
  await self.clients.claim();
406
406
  await self.registration.unregister();
407
- })()));`)}},{match:x=>x.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:x,response:e,url:t})=>ja(x,e,a,t.pathname)},{match:x=>x.pathname.startsWith("/__"),handle:({response:x})=>fs(x,404,"未找到调试器资源")}],fallback:({request:x,response:e,url:t})=>ja(x,e,a,t.pathname,{fallbackPath:"/index.html"})};return fm([...(c={artifactOrigin:x,webViewOrigin:l,debugScenes:e,getWidgetViewDataTemplates:n,mcpEndpoint:_?.endpoint,physicalDeviceDebugGateway:A,sandboxRuntime:s,simulatorAssets:i},[{match:"/__web_sdk_debug_context",handle:({request:x,response:e})=>{let t,r;return r="string"==typeof(t=x.headers.host)&&t?`http://${t}`:void 0,void fi(e,200,{homeDir:ib.homedir(),webViewOrigin:c.webViewOrigin,launchDir:c.simulatorAssets.appDirectory,debugScenesEndpoint:hq,widgetViewDataTemplatesEndpoint:hT,debuggerMcpEndpoint:r?new URL(hD,r).toString():hD,manifestOriginalUrl:new URL("/base/manifest.json",c.artifactOrigin).toString(),...c.mcpEndpoint?{mcpOriginalEndpoint:c.mcpEndpoint,mcpProxyEndpoint:fC}:{},realDeviceDebug:c.physicalDeviceDebugGateway?.getDebugContext(),...c.simulatorAssets.getDebugContext(),...c.sandboxRuntime.getDebugContext()},hR)}},{match:hq,handle:({response:x})=>fi(x,200,c.debugScenes??{errors:[],scenes:[]},hR)},{match:hT,handle:({response:x})=>h$(x,c.getWidgetViewDataTemplates)}]),...A.getRequestRoutes(),...r,...function(x={}){return[{match:x=>x.pathname===E2||x.pathname.startsWith(`${E2}/`),handle:({request:e,response:t,url:r})=>E5(e,t,r,x)}]}({getSandboxSessionId:()=>s.sessionId,targetOrigin:o}),...s.getRequestRoutes(t),..._?.kind==="hub"?function(x){if(!x.serverName.trim()||!x.accessKey.trim())throw Error("Action HUB requires a server name and access key");return[{match:fC,handle:e=>hX(e,x)}]}({serverName:_.endpoint,accessKey:_.accessKey,cluster:_.cluster,headers:_.headers}):function(x={}){return[{match:fC,handle:({request:e,response:t,url:r})=>(function(x,e,t={},r=ft(x)){let a=og(t.targetEndpoint);if(!r)return void fs(e,400,"Bad request");if(!a)return void fs(e,404,"MCP endpoint not configured");let n=new URL(a);for(let[x,e]of new URLSearchParams(r.search))n.searchParams.append(x,e);fu(x,e,{createResponseHeaders:fn,errorMessage:"代理 MCP 请求失败",requestHeaders:fa(x.headers,n,{...fy(),...t.headers}),targetUrl:n})})(e,t,x,r)}]}({headers:_?.headers,targetEndpoint:_?.endpoint}),...i.getRequestRoutes(),...v.routes],v.fallback)}({...x,debuggerOrigins:t,webViewOrigin:n})),A=x.debuggerProtocol.attachConnection(_,x.sandboxRuntime);try{await jh(_,e)}catch(x){throw A(),await jj(r),x}return{origin:`http://127.0.0.1:${e}`,server:_,webViewServer:r,closeConnections:A}}async function jj(x){x.listening&&await new Promise((e,t)=>{x.close(x=>{x?t(x):e()}),x.closeIdleConnections(),x.closeAllConnections()})}async function jg(){if(!c)return;let{physicalDeviceDebugGateway:x,sandboxRuntime:e,server:t,webViewServer:r,closeConnections:a}=c;c=void 0,a(),x.dispose(),e.close(),await Promise.all([jj(t),jj(r)])}async function jy(x){let e,{targetOrigin:t,...r}=x.simulator??{},a={appDirectory:x.appDirectory,eventsConfigReader:x.eventsConfigReader,eventsConfigSourcePath:x.eventsConfigSourcePath,toolsConfigReader:x.toolsConfigReader,toolsConfigSourcePath:x.toolsConfigSourcePath,manifestReader:x.simulatorManifestReader,manifestSourcePath:x.simulatorManifestSourcePath,...r},n=new E1(a);try{var _,A;let r,s,i=function(x){let e=x.mcpEndpoint?.trim();if(!e)return;let t=x.mcpHeaders?{...x.mcpHeaders}:void 0,r=og(e);if(r)return{kind:"http",endpoint:r,headers:t};if(!1===x.allowActionHub)return void d6.warn("MCP endpoint 格式不受支持,请使用 HTTP(S) 地址。");if(!jp.test(e))return void d6.warn("MCP endpoint 格式不受支持,请使用 HTTP(S) 地址或 Action HUB Server 名称。");let a=(x.env?.MCP_ACCESS_KEY??process.env.MCP_ACCESS_KEY)?.trim();return a?{kind:"hub",endpoint:e,accessKey:a,cluster:(x.env?.MCP_CLUSTER??process.env.MCP_CLUSTER)?.trim()||void 0,headers:t}:void d6.warn("未配置 MCP_ACCESS_KEY,未启用 Action HUB 远程工具;本地端工具仍可使用。")}(x),o={appDirectory:x.appDirectory,appId:x.appId,businessTemplatesPath:n.businessTemplatesPath,env:x.env,manifestReader:x.simulatorManifestReader,manifestPath:n.manifestPath,targetOrigin:x.sandboxTargetOrigin};if(_=c,_?.server.listening){if(c?.artifactOrigin===x.artifactOrigin&&c.debuggerDistPath===r4.resolve(x.debuggerDistPath)&&(0,dY.isDeepStrictEqual)(c.mcp,i)&&c.simulatorAssets.matches(a)&&c.getWidgetViewDataTemplates===x.getWidgetViewDataTemplates&&c.sandboxRuntime.matches(o)&&c.simulatorTargetOrigin===t)return c;await jg()}let l={distPath:A=x.debuggerDistPath,indexPath:r4.join(A,"index.html")};if(!r5.existsSync(l.indexPath))return void d6.error("Web 模拟器资源缺失,请联系框架开发者。");let v=(r={},s=new hp(r),Object.assign([{match:"/__agent_trace",handle:x=>(function({request:x,response:e,url:t},r){let a;if("OPTIONS"===x.method){fA(e,hz),e.writeHead(204),e.end();return}"GET"!==x.method?fi(e,405,{error:"Method not allowed"},hz):fi(e,200,function(x,e){if(!x?.debug_snapshot)return x;let{debug_snapshot:t,...r}=x;return e?{...r,snapshot:t}:r}(r.snapshot,(a=t.searchParams.get("DEBUG"),null!=a&&"0"!==a&&"false"!==a.toLowerCase()))??{stored:!1},hz)})(x,r)},{match:hD,handle:x=>hL(x,r,s)}],{attachConnection:(x,e)=>{var t;let a,n,_,A;return t=x=>{var e,t;let a,n;return n=(t=e=x).snapshot.client_id??t.debug_snapshot?.client_id,a="string"==typeof n&&n.trim()?n.trim():void 0,void(e=function(x,e){let t=x?.snapshot,r=e.snapshot,a=t?.runtime_snapshot,n=r.runtime_snapshot;if(!t||!a||t.client_id!==r.client_id)return e;if(!n){var _;let x;if(_=a.target,x=function(x){let e=x.render_targets?.currentTarget;if(e)return e;let t=x.context;if(t){if(Object.hasOwn(t,"widget_id"))return{type:"widget"};if(Object.hasOwn(t,"page_id")||Object.hasOwn(t,"page_path"))return{type:"page"}}}(r),_&&x&&(1===Object.keys(x).length?x.type!==_.type:JSON.stringify(x)!==JSON.stringify(_)))return e;let{root:t,...n}=a;return{...e,snapshot:{...r,runtime_snapshot:a},...e.debug_snapshot?{debug_snapshot:{...e.debug_snapshot,runtime_snapshot:n}}:{}}}return Object.hasOwn(n,"root")||!Object.hasOwn(a,"root")||a.updatedAtMs!==n.updatedAtMs||JSON.stringify(a.target)!==JSON.stringify(n.target)?e:{...e,snapshot:{...r,runtime_snapshot:{...n,root:a.root}}}}(a?s.getSnapshotStore(a).snapshot:r.snapshot,e),r.snapshot=e,r.updatedAtMs=Date.now(),s.noteSnapshot(a))},a=new ho({noServer:!0,maxPayload:0xa00000}),n=new Set,_=(r,_,A)=>{let i,o=x.address().port,l=r.headers.host;try{i=new URL(r.url??"/","http://127.0.0.1")}catch{_.destroy();return}let c=i.searchParams.get("clientId")?.trim();l!==`127.0.0.1:${o}`&&l!==`localhost:${o}`||void 0!==r.headers.origin&&r.headers.origin!==`http://${l}`?_.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==i.pathname||!c||c.length>128?_.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):a.handleUpgrade(r,_,A,x=>{s.registerClient(c,x),n.add(x),x.on("pong",()=>n.add(x)),x.on("error",()=>x.close());let r=e.subscribeEvents(e=>hl(x,"sandbox",e));x.once("close",()=>{n.delete(x),r()}),x.on("message",(r,a)=>{try{let x=a?void 0:JSON.parse(r.toString());if(!oS(x))throw Error("Invalid debugger message");if("snapshot"===x.type&&oS(x.data)&&oS(x.data.snapshot))t({...x.data,...oS(x.data.debug_snapshot)?{debug_snapshot:{...x.data.debug_snapshot,client_id:c}}:{},snapshot:{...x.data.snapshot,client_id:c}});else if("control_result"===x.type&&oS(x.data))s.handleResult({...x.data,clientId:c});else if("clear_sandbox_logs"===x.type)e.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{x.close(1008,"Invalid debugger message")}})})},x.on("upgrade",_),(A=setInterval(()=>{for(let x of a.clients)n.delete(x)?x.ping():x.terminate()},3e4)).unref(),()=>{for(let e of(clearInterval(A),x.off("upgrade",_),a.clients))e.terminate();a.close()}},executeSandboxToolCall:x=>s.execute("execute_sandbox_tool_call",{toolCall:x})})),d=await EX.start({...o,onSimulatorToolCall:async x=>{await v.executeSandboxToolCall(x)}});e=d;let f=new hY,{origin:b,server:u,webViewServer:p,closeConnections:m}=await jE({artifactOrigin:x.artifactOrigin,debugScenes:x.debugScenes,debuggerProtocol:v,distPath:l.distPath,getWidgetViewDataTemplates:x.getWidgetViewDataTemplates,mcp:i,physicalDeviceDebugGateway:f,sandboxRuntime:d,simulatorAssets:n,simulatorTargetOrigin:t}),h=()=>{u.close(),p.close()};u.once("close",()=>{process.off("exit",h)}),process.once("exit",h);let E=new URL(b).toString(),j={debuggerDistPath:r4.resolve(x.debuggerDistPath),artifactOrigin:x.artifactOrigin,async close(){c===j&&await jg()},debuggerMcpEndpoint:new URL(hD,b).toString(),getWidgetViewDataTemplates:x.getWidgetViewDataTemplates,mcp:i,open:()=>jm(E),origin:b,physicalDeviceDebugGateway:f,sandboxRuntime:d,get sandboxSessionId(){return d.sessionId},server:u,webViewServer:p,closeConnections:m,setRealDeviceDebugProvider(x){f.setProvider(x)},simulatorAssets:n,simulatorTargetOrigin:t,url:E};return c=j,j}catch(x){e?.close(),d6.error("启动 Web SDK 调试器失败",{error:x});return}}async function jS(x,e){let t={errors:[],scenes:[]};if(!x)return t;for(let r of(await oB(x)).sort((x,e)=>x.name.localeCompare(e.name))){let x=await oF(r.path);x&&function(x,e){let t=ou(x);return"tool"!==t.type&&("widget"===t.type?e.widgetIds.has(t.id):0===t.unresolvedVariables.length)}(x,e)&&t.scenes.push({content:x,name:r.name})}return t}let jI="x-db-llm-modifiable",jN="x-db-is-entity-id",jB="x-db-is-refresh-key",jF=["entity_type"];function jw(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}function jC(x,e,t){if(!jw(x))throw Error(`Tool "${t}" 的 ${e} 必须是对象`);return x}function jP(x,e){let t;try{t=JSON.parse(x)}catch(x){throw Error(`解析 tools.json 失败:${e}`,{cause:x})}if(!jw(t)||!Array.isArray(t.tools)||0===t.tools.length)throw Error(`tools.json 必须包含非空的 tools 数组:${e}`);let r=new Set;return{tools:t.tools.map((x,t)=>{let a=function(x,e,t){if(!jw(x))throw Error(`索引为 ${e} 的 Tool 配置必须是对象:${t}`);let r="string"==typeof x.name?x.name.trim():"",a="string"==typeof x.description?x.description.trim():"";if(!r||!a)throw Error(`索引为 ${e} 的 Tool 配置必须提供 name 和 description:${t}`);if(void 0!==x.tool_type&&"client"!==x.tool_type&&"server"!==x.tool_type)throw Error(`Tool "${r}" 的 tool_type 必须为 "client" 或 "server"`);let n=function(x,e){if(void 0===x)return{};if(!jw(x))throw Error(`Tool "${e}" 的 _meta 必须是对象`);if(void 0===x.ui)return{};if(!jw(x.ui))throw Error(`Tool "${e}" 的 _meta.ui 必须是对象`);if("widgetPath"in x.ui)throw Error(`Tool "${e}" 必须使用 _meta.ui.widgetId,不能使用 widgetPath`);let t=x.ui.widgetId;if(void 0!==t&&("string"!=typeof t||!t.trim()))throw Error(`Tool "${e}" 的 _meta.ui.widgetId 必须是非空字符串`);let r=x.ui.expirePolicy;if(void 0!==r&&"same_conversation"!==r)throw Error(`Tool "${e}" 的 _meta.ui.expirePolicy 如有设置,必须为 "same_conversation"`);if("same_conversation"===r&&"string"!=typeof t)throw Error(`Tool "${e}" 设置 _meta.ui.expirePolicy 时必须提供 _meta.ui.widgetId`);return{..."string"==typeof t?{widgetId:t.trim()}:{},..."same_conversation"===r?{expirePolicy:r}:{}}}(x._meta,r);return{name:r,description:a,...n,inputSchema:jC(x.inputSchema,"inputSchema",r),outputSchema:jC(x.outputSchema,"outputSchema",r),permissions:function(x,e){if(void 0===x)return[];if(!Array.isArray(x)||x.some(x=>"string"!=typeof x||!x.trim()))throw Error(`Tool "${e}" 的 permissions 必须是由非空字符串组成的数组`);return x.map(x=>x.trim())}(x.permissions,r),toolType:"client"===x.tool_type?"client":"server"}}(x,t,e);if(r.has(a.name))throw Error(`Tool 名称重复:${a.name}`);return r.add(a.name),a})}}function jk(x,e,t,r,a=!1){let n=`Tool "${e}" 的 ${t} 属性 "${r}"`;if(!jw(x)||"string"!=typeof x.type||!x.type.trim())throw Error(`${n} 必须提供字符串类型的 type`);let _=x.type.trim(),A=x[jI];if(void 0!==A&&"boolean"!=typeof A)throw Error(`${n} 的 ${jI} 必须是布尔值`);if(A&&"outputSchema"!==t)throw Error(`${n} 的 ${jI} 仅支持在 outputSchema 中使用`);if(A&&"array"!==_)throw Error(`${n} 的 ${jI} 仅支持用于数组字段`);let s=x[jN];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${n} 的 ${jN} 必须是布尔值`);if(s&&!a)throw Error(`${n} 的 ${jN} 仅支持用于卡片输出的顶层字段`);let i=x[jB];if(void 0!==i&&"boolean"!=typeof i)throw Error(`${n} 的 ${jB} 必须是布尔值`);if(i&&!a)throw Error(`${n} 的 ${jB} 仅支持用于卡片输出的顶层字段`);let o={type:function(x,e){if("integer"===x)return"int";if("number"===x)return"float";if(["string","boolean","object","array"].includes(x))return x;throw Error(`${e} 使用了不支持的类型 "${x}"`)}(_,n),...A?{llm_modifiable:!0}:{},...s?{is_entity_id:!0}:{},..."string"==typeof x.description&&x.description.trim()?{description:x.description.trim()}:{}};if("object"===_){if(!jw(x.properties))throw Error(`${n} 必须提供对象类型的 properties`);if(o.properties=Object.fromEntries(Object.entries(x.properties).map(([x,a])=>[x,jk(a,e,t,`${r}.${x}`)])),void 0!==x.required){if(!Array.isArray(x.required)||x.required.some(x=>"string"!=typeof x))throw Error(`${n} 的 required 必须是字符串数组`);o.required=x.required}}if("array"===_){if(!jw(x.items))throw Error(`${n} 必须提供对象类型的数组项定义 items`);o.items=jk(x.items,e,t,`${r}[]`)}return o}function jD(x,e,t){let r=x[e];if(void 0===r)return{};if(!jw(r))throw Error(`manifest.yaml 的 ${e} 必须是对象:${t}`);return{...r}}function jL({tools:x,manifestPath:e,manifestText:t}){let r=function(x,e){let t;try{t=(0,sX.qg)(x)}catch(x){throw Error(`解析 manifest.yaml 失败:${e}`,{cause:x})}if(!jw(t))throw Error(`manifest.yaml 必须包含一个对象:${e}`);return t}(t,e),a=jD(r,"tools",e),n=jD(r,"entities",e);for(let e of x){if(e.name in a)throw Error(`Tool "${e.name}" 与 manifest.yaml 中的 Tool 重名`);if(a[e.name]={login_type:"no_login",description:e.description,..."client"===e.toolType?{is_client_tool:!0}:{},input_schema:function(x,e){if("object"!==x.type||!jw(x.properties))throw Error(`Tool "${e}" 的 inputSchema.type 必须为 object,且 properties 必须是对象`);let t=Object.fromEntries(Object.entries(x.properties).map(([x,t])=>[x,jk(t,e,"inputSchema",x)])),r=x.required;if(void 0!==r&&(!Array.isArray(r)||r.some(x=>"string"!=typeof x)))throw Error(`Tool "${e}" 的 inputSchema.required 必须是字符串数组`);return{type:"object",properties:t,...r&&r.length>0?{required:r}:{}}}(e.inputSchema,e.name),output:e.widgetId?{kind:"entities",entity_types:[e.name]}:{kind:"execution_result"},...e.permissions.length>0?{permissions:e.permissions}:{}},e.widgetId){if(e.name in n)throw Error(`Tool "${e.name}" 与 manifest.yaml 中的实体重名`);n[e.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(x,e){let t=e.name;if("array"!==x.type||!jw(x.items))throw Error(`Card Tool "${t}" 的 outputSchema.type 必须为 array,且 items 必须是对象`);if("object"!==x.items.type||!jw(x.items.properties))throw Error(`Card Tool "${t}" 的 outputSchema.items 必须是对象类型的定义`);let r=x.items.properties,a=jF.find(x=>x in r);if(a)throw Error(`Tool "${t}" 的 outputSchema 不能声明保留字段 "${a}"`);let n=Object.entries(r).filter(([x,e])=>{if(!jw(e)||void 0===e[jN])return!1;if("boolean"!=typeof e[jN])throw Error(`Tool "${t}" 的 outputSchema 属性 "${x}" 的 ${jN} 必须是布尔值`);return e[jN]});if(1!==n.length)throw Error(`Card Tool "${t}" 的 outputSchema 必须有且仅有一个 ${jN} 字段,当前有 ${n.length} 个`);let _=Object.entries(r).filter(([x,e])=>{if(!jw(e)||void 0===e[jB])return!1;if("boolean"!=typeof e[jB])throw Error(`Tool "${t}" 的 outputSchema 属性 "${x}" 的 ${jB} 必须是布尔值`);return e[jB]});if("same_conversation"===e.expirePolicy){let x=n[0]?.[0];if(1!==_.length||_[0]?.[0]!==x)throw Error(`Card Tool "${t}" 使用 expirePolicy "same_conversation" 时,必须在 ${jN} 字段上设置 ${jB}`)}return Object.fromEntries(Object.entries(r).map(([x,e])=>[x,jk(e,t,"outputSchema",x,!0)]))}(e.outputSchema,e)},tool_card_binding:{[e.name]:e.widgetId},..."same_conversation"===e.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,sX.As)({...r,tools:a,entities:n})}let jq=I("node:url"),jT=(0,k.createRequire)(import.meta.url),jR="DOUBAO_WEB_SDK_DEBUGGER_DIST_PATH";async function j$(x,e){let t=x.metadata.getData(),r=x.widgets,a=await jS(x.appDirectory,{widgetIds:new Set(Object.keys(r).map(x=>vd(r,t.widgets,x)))});return jy({...e,debuggerDistPath:e.debuggerDistPath??function(){let x=process.env[jR]?.trim();if(x){let e=r4.resolve(x);if(!r5.existsSync(r4.join(e,"index.html")))throw Error(`${jR} 必须指向已构建的 Web SDK 调试器目录,且目录中必须包含 index.html:${e}`);return e}let e=(0,jq.fileURLToPath)(new URL("../assets/web-sdk-debugger/",import.meta.url));if(r5.existsSync(r4.join(e,"index.html")))return e;try{return r4.resolve(r4.dirname(jT.resolve("@byted-doubao-apps/web-sdk-debugger-app/package.json")),"dist")}catch{return e}}(),debugScenes:a,getWidgetViewDataTemplates:x.getWidgetViewDataTemplates})}let jG=new WeakMap;function jO(x,e,t){let r=x.webDebuggerLaunchOptions,a=r?.simulator?.manifestPath,n=a?r4.resolve(x.appDirectory,a):void 0,_=x.toolsResources?.readManifestYaml;if(n){let e=jG.get(x);e?.path!==n&&(e={path:n,read:()=>(function(x,e=(0,r4.join)((0,r4.dirname)(x),"tools.json")){let t=(0,r5.readFileSync)(x,"utf8");if(!(0,r5.existsSync)(e))return t;let{tools:r}=jP((0,r5.readFileSync)(e,"utf8"),e);return jL({tools:r,manifestPath:x,manifestText:t})})(n)},jG.set(x,e)),_=e.read}return{appId:x.appId,appDirectory:x.appDirectory,artifactOrigin:e,env:{...x.env,...r?.env??{}},debuggerDistPath:r?.debuggerDistPath,allowActionHub:r?.allowActionHub,mcpEndpoint:r?.mcpEndpoint??t,mcpHeaders:r?.mcpHeaders,simulator:r?.simulator,eventsConfigReader:x.eventsResources?.readJson,eventsConfigSourcePath:x.eventsResources?.sourcePath,toolsConfigReader:x.toolsResources?.readToolsJson,toolsConfigSourcePath:x.toolsResources?.toolsSourcePath,simulatorManifestReader:_,simulatorManifestSourcePath:n??x.toolsResources?.manifestSourcePath}}let jX=x=>Y.bgHex("#9873b9")(Y.italic(Y.black(` ${x} `))),jK=x=>Y.bgBlueBright(Y.italic(Y.black(` ${x} `))),jQ=x=>Y.bold(Y.blueBright(x)),jM=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],jZ={page:"页面",scene:"调试场景",widget:"组件"};function jJ(x){console.log(` ${jQ(x.command.padEnd(21))} ${Y.gray(`- ${x.description}`)}`)}async function jV(x){let e=of(x);if(0!==e.length)return await H.prompt(e.map(([x,e])=>({type:"input",name:x,message:`请输入调试场景变量 "${x}" 的值:`,default:e??void 0})))}async function jH({matchedScene:x,appId:e,driver:t}){let r=await oF(x.path);if(!r)return;let a=await jV(r);await ow({matchedScene:x,appId:e,driver:t,variables:a},r)}async function jU(x,e,t,r,a,n,{interactive:_=!0}={}){if(await a.load({appletUrl:e,appId:x,isSigned:n}),!_)return;let A=await oB(process.cwd()),s=Object.values(t),i=Object.values(r),o=i.filter(({id:x})=>!i0(x));return s.length>0&&(console.log(`
408
-
409
- ${jK("可用 pages 列表")}
410
- `),s.forEach(x=>{console.log(` - ${jQ(x.path)}`)})),o.length>0&&(console.log(`
411
- ${jK("可用 widgets 列表")}
412
- `),o.forEach(x=>{let e=jQ(x.id);console.log(` - ${e}`)})),A.length>0&&(console.log(`
413
- ${jK("可用调试场景")}
414
- `),A.forEach(x=>console.log(` - ${jQ(x.name)}`))),console.log(`
415
- ${jK("可以继续执行以下命令:")}
416
- `),jM.forEach(jJ),console.log("\n"),dQ.instance.addListener(e=>{let t=e.trim();if("d"===t){let e=[...A.map(x=>({type:"scene",id:x.name})),...o.map(x=>({type:"widget",id:x.id})),...s.map(x=>({type:"page",id:x.path}))];if(0===e.length)return console.log(`
417
- ${jK("暂无可用的页面、组件或调试场景")}`),!0;dZ(async()=>{let{selectedEntry:t}=await H.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:x=>e.filter(e=>`${jZ[e.type]} ${e.type} ${e.id}`.toLowerCase().includes(x?.toLowerCase()??"")).map(x=>({name:`${Y.gray(jZ[x.type])}: ${x.id}`,short:`${jZ[x.type]} \xb7 ${x.id}`,value:x}))}]);if("scene"===t.type){let e=A.find(x=>x.name===t.id);e&&await jH({matchedScene:e,appId:x,driver:a})}else"widget"===t.type?a.pushWidget({appId:x,widgetId:t.id}):a.openPageUrl({appId:x,url:t.id})})}else{let e=A.find(x=>x.name===t);e?dZ(async()=>{await jH({matchedScene:e,appId:x,driver:a})}):i.some(x=>x.id===t)?a.pushWidget({appId:x,widgetId:t}):a.openPageUrl({appId:x,url:t})}return!0},"openPage")}async function jY({appId:x,appletUrl:e,pages:t,widgets:r,driver:a,isSigned:n,isDisposed:_}){let A=await oe();if(_())return;if(!A)return void os.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let s=await i9(A).catch(x=>(_()||os.error("重新启动应用失败",{error:x}),!1));if(_())return;if(!s)return void setTimeout(()=>{_()||os.info("请确认应用已经启动。\n")},1e3);if(await new Promise(x=>{setTimeout(x,5e3)}),_())return;if(!a)return void os.error("调试驱动尚未就绪。");let i=await jU(x,e,t,r,a,n);_()&&i?.()}async function jz({context:x,port:e,driver:t,isSigned:r,onCleanupReady:a}){let n,_,A,s,{host:i,artifactOrigin:o}=await x.resolveDevServer(e);x.devServerAbort.signal.throwIfAborted();let l=x.metadata.getData(),c=l.app.appId,v=(_=!1,A=[],{add(x){x&&(_?x():A.push(x))},cleanup:()=>{_=!0,A.splice(0).forEach(x=>x())},isDisposed:()=>_});v.add(()=>{n?.close()});let d=async()=>{if(v.isDisposed())return;let e=await j$(x,jO(x,o,vn()));if(e){if(n=e,v.isDisposed())return void await e.close();await e.open()}};if(x.devServerInteractive&&(s=function(x={}){let e={name:"Doubao Apps SDK",...x},t=e.name?`${e.name} 开发服务`:"",r=e.origin?`正在监听 ${Y.gray(e.origin)}。`:"已启动。";return`
418
- ${jQ(t)}${r}
407
+ })()));`)}},{match:x=>x.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:x,response:e,url:t})=>jn(x,e,a,t.pathname)},{match:x=>x.pathname.startsWith("/__"),handle:({response:x})=>fo(x,404,"未找到调试器资源")}],fallback:({request:x,response:e,url:t})=>jn(x,e,a,t.pathname,{fallbackPath:"/index.html"})};return fE([...(c={artifactOrigin:x,webViewOrigin:l,debugScenes:e,getWidgetViewDataTemplates:n,mcpEndpoint:_?.endpoint,physicalDeviceDebugGateway:A,sandboxRuntime:s,simulatorAssets:i},[{match:"/__web_sdk_debug_context",handle:({request:x,response:e})=>{let t,r;return r="string"==typeof(t=x.headers.host)&&t?`http://${t}`:void 0,void fl(e,200,{homeDir:ib.homedir(),webViewOrigin:c.webViewOrigin,launchDir:c.simulatorAssets.appDirectory,debugScenesEndpoint:hT,widgetViewDataTemplatesEndpoint:hR,debuggerMcpEndpoint:r?new URL(hL,r).toString():hL,manifestOriginalUrl:new URL("/base/manifest.json",c.artifactOrigin).toString(),...c.mcpEndpoint?{mcpOriginalEndpoint:c.mcpEndpoint,mcpProxyEndpoint:fk}:{},realDeviceDebug:c.physicalDeviceDebugGateway?.getDebugContext(),...c.simulatorAssets.getDebugContext(),...c.sandboxRuntime.getDebugContext()},h$)}},{match:hT,handle:({response:x})=>fl(x,200,c.debugScenes??{errors:[],scenes:[]},h$)},{match:hR,handle:({response:x})=>hG(x,c.getWidgetViewDataTemplates)}]),...A.getRequestRoutes(),...r,...function(x={}){return[{match:x=>x.pathname===E3||x.pathname.startsWith(`${E3}/`),handle:({request:e,response:t,url:r})=>E7(e,t,r,x)}]}({getSandboxSessionId:()=>s.sessionId,targetOrigin:o}),...s.getRequestRoutes(t),..._?.kind==="hub"?function(x){if(!x.serverName.trim()||!x.accessKey.trim())throw Error("Action HUB requires a server name and access key");return[{match:fk,handle:e=>hK(e,x)}]}({serverName:_.endpoint,accessKey:_.accessKey,cluster:_.cluster,headers:_.headers}):function(x={}){return[{match:fk,handle:({request:e,response:t,url:r})=>(function(x,e,t={},r=fa(x)){let a=og(t.targetEndpoint);if(!r)return void fo(e,400,"Bad request");if(!a)return void fo(e,404,"MCP endpoint not configured");let n=new URL(a);for(let[x,e]of new URLSearchParams(r.search))n.searchParams.append(x,e);fm(x,e,{createResponseHeaders:fA,errorMessage:"代理 MCP 请求失败",requestHeaders:f_(x.headers,n,{...fI(),...t.headers}),targetUrl:n})})(e,t,x,r)}]}({headers:_?.headers,targetEndpoint:_?.endpoint}),...i.getRequestRoutes(),...v.routes],v.fallback)}({...x,debuggerOrigins:t,webViewOrigin:n})),A=x.debuggerProtocol.attachConnection(_,x.sandboxRuntime);try{await jE(_,e)}catch(x){throw A(),await jg(r),x}return{origin:`http://127.0.0.1:${e}`,server:_,webViewServer:r,closeConnections:A}}async function jg(x){x.listening&&await new Promise((e,t)=>{x.close(x=>{x?t(x):e()}),x.closeIdleConnections(),x.closeAllConnections()})}async function jy(){if(!c)return;let{physicalDeviceDebugGateway:x,sandboxRuntime:e,server:t,webViewServer:r,closeConnections:a}=c;c=void 0,a(),x.dispose(),e.close(),await Promise.all([jg(t),jg(r)])}async function jS(x){let e,{targetOrigin:t,...r}=x.simulator??{},a={appDirectory:x.appDirectory,eventsConfigReader:x.eventsConfigReader,eventsConfigSourcePath:x.eventsConfigSourcePath,toolsConfigReader:x.toolsConfigReader,toolsConfigSourcePath:x.toolsConfigSourcePath,manifestReader:x.simulatorManifestReader,manifestSourcePath:x.simulatorManifestSourcePath,...r},n=new E2(a);try{var _,A;let r,s,i=function(x){let e=x.mcpEndpoint?.trim();if(!e)return;let t=x.mcpHeaders?{...x.mcpHeaders}:void 0,r=og(e);if(r)return{kind:"http",endpoint:r,headers:t};if(!1===x.allowActionHub)return void d5.warn("MCP endpoint 格式不受支持,请使用 HTTP(S) 地址。");if(!jm.test(e))return void d5.warn("MCP endpoint 格式不受支持,请使用 HTTP(S) 地址或 Action HUB Server 名称。");let a=(x.env?.MCP_ACCESS_KEY??process.env.MCP_ACCESS_KEY)?.trim();return a?{kind:"hub",endpoint:e,accessKey:a,cluster:(x.env?.MCP_CLUSTER??process.env.MCP_CLUSTER)?.trim()||void 0,headers:t}:void d5.warn("未配置 MCP_ACCESS_KEY,未启用 Action HUB 远程工具;本地端工具仍可使用。")}(x),o={appDirectory:x.appDirectory,appId:x.appId,businessTemplatesPath:n.businessTemplatesPath,env:x.env,manifestReader:x.simulatorManifestReader,manifestPath:n.manifestPath,targetOrigin:x.sandboxTargetOrigin};if(_=c,_?.server.listening){if(c?.artifactOrigin===x.artifactOrigin&&c.debuggerDistPath===r4.resolve(x.debuggerDistPath)&&(0,dW.isDeepStrictEqual)(c.mcp,i)&&c.simulatorAssets.matches(a)&&c.getWidgetViewDataTemplates===x.getWidgetViewDataTemplates&&c.sandboxRuntime.matches(o)&&c.simulatorTargetOrigin===t)return c;await jy()}let l={distPath:A=x.debuggerDistPath,indexPath:r4.join(A,"index.html")};if(!r5.existsSync(l.indexPath))return void d5.error("Web 模拟器资源缺失,请联系框架开发者。");let v=(r={},s=new hm(r),Object.assign([{match:"/__agent_trace",handle:x=>(function({request:x,response:e,url:t},r){let a;if("OPTIONS"===x.method){fi(e,hW),e.writeHead(204),e.end();return}"GET"!==x.method?fl(e,405,{error:"Method not allowed"},hW):fl(e,200,function(x,e){if(!x?.debug_snapshot)return x;let{debug_snapshot:t,...r}=x;return e?{...r,snapshot:t}:r}(r.snapshot,(a=t.searchParams.get("DEBUG"),null!=a&&"0"!==a&&"false"!==a.toLowerCase()))??{stored:!1},hW)})(x,r)},{match:hL,handle:x=>hq(x,r,s)}],{attachConnection:(x,e)=>{var t;let a,n,_,A;return t=x=>{var e,t;let a,n;return n=(t=e=x).snapshot.client_id??t.debug_snapshot?.client_id,a="string"==typeof n&&n.trim()?n.trim():void 0,void(e=function(x,e){let t=x?.snapshot,r=e.snapshot,a=t?.runtime_snapshot,n=r.runtime_snapshot;if(!t||!a||t.client_id!==r.client_id)return e;if(!n){var _;let x;if(_=a.target,x=function(x){let e=x.render_targets?.currentTarget;if(e)return e;let t=x.context;if(t){if(Object.hasOwn(t,"widget_id"))return{type:"widget"};if(Object.hasOwn(t,"page_id")||Object.hasOwn(t,"page_path"))return{type:"page"}}}(r),_&&x&&(1===Object.keys(x).length?x.type!==_.type:JSON.stringify(x)!==JSON.stringify(_)))return e;let{root:t,...n}=a;return{...e,snapshot:{...r,runtime_snapshot:a},...e.debug_snapshot?{debug_snapshot:{...e.debug_snapshot,runtime_snapshot:n}}:{}}}return Object.hasOwn(n,"root")||!Object.hasOwn(a,"root")||a.updatedAtMs!==n.updatedAtMs||JSON.stringify(a.target)!==JSON.stringify(n.target)?e:{...e,snapshot:{...r,runtime_snapshot:{...n,root:a.root}}}}(a?s.getSnapshotStore(a).snapshot:r.snapshot,e),r.snapshot=e,r.updatedAtMs=Date.now(),s.noteSnapshot(a))},a=new hl({noServer:!0,maxPayload:0xa00000}),n=new Set,_=(r,_,A)=>{let i,o=x.address().port,l=r.headers.host;try{i=new URL(r.url??"/","http://127.0.0.1")}catch{_.destroy();return}let c=i.searchParams.get("clientId")?.trim();l!==`127.0.0.1:${o}`&&l!==`localhost:${o}`||void 0!==r.headers.origin&&r.headers.origin!==`http://${l}`?_.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==i.pathname||!c||c.length>128?_.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):a.handleUpgrade(r,_,A,x=>{s.registerClient(c,x),n.add(x),x.on("pong",()=>n.add(x)),x.on("error",()=>x.close());let r=e.subscribeEvents(e=>hc(x,"sandbox",e));x.once("close",()=>{n.delete(x),r()}),x.on("message",(r,a)=>{try{let x=a?void 0:JSON.parse(r.toString());if(!oS(x))throw Error("Invalid debugger message");if("snapshot"===x.type&&oS(x.data)&&oS(x.data.snapshot))t({...x.data,...oS(x.data.debug_snapshot)?{debug_snapshot:{...x.data.debug_snapshot,client_id:c}}:{},snapshot:{...x.data.snapshot,client_id:c}});else if("control_result"===x.type&&oS(x.data))s.handleResult({...x.data,clientId:c});else if("clear_sandbox_logs"===x.type)e.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{x.close(1008,"Invalid debugger message")}})})},x.on("upgrade",_),(A=setInterval(()=>{for(let x of a.clients)n.delete(x)?x.ping():x.terminate()},3e4)).unref(),()=>{for(let e of(clearInterval(A),x.off("upgrade",_),a.clients))e.terminate();a.close()}},executeSandboxToolCall:x=>s.execute("execute_sandbox_tool_call",{toolCall:x})})),d=await EK.start({...o,onSimulatorToolCall:async x=>{await v.executeSandboxToolCall(x)}});e=d;let f=new hz,{origin:b,server:u,webViewServer:p,closeConnections:m}=await jj({artifactOrigin:x.artifactOrigin,debugScenes:x.debugScenes,debuggerProtocol:v,distPath:l.distPath,getWidgetViewDataTemplates:x.getWidgetViewDataTemplates,mcp:i,physicalDeviceDebugGateway:f,sandboxRuntime:d,simulatorAssets:n,simulatorTargetOrigin:t}),h=()=>{u.close(),p.close()};u.once("close",()=>{process.off("exit",h)}),process.once("exit",h);let E=new URL(b).toString(),j={debuggerDistPath:r4.resolve(x.debuggerDistPath),artifactOrigin:x.artifactOrigin,async close(){c===j&&await jy()},debuggerMcpEndpoint:new URL(hL,b).toString(),getWidgetViewDataTemplates:x.getWidgetViewDataTemplates,mcp:i,open:()=>jh(E),origin:b,physicalDeviceDebugGateway:f,sandboxRuntime:d,get sandboxSessionId(){return d.sessionId},server:u,webViewServer:p,closeConnections:m,setRealDeviceDebugProvider(x){f.setProvider(x)},simulatorAssets:n,simulatorTargetOrigin:t,url:E};return c=j,j}catch(x){e?.close(),d5.error("启动 Web SDK 调试器失败",{error:x});return}}async function jI(x,e){let t={errors:[],scenes:[]};if(!x)return t;for(let r of(await oB(x)).sort((x,e)=>x.name.localeCompare(e.name))){let x=await oF(r.path);x&&function(x,e){let t=ou(x);return"tool"!==t.type&&("widget"===t.type?e.widgetIds.has(t.id):0===t.unresolvedVariables.length)}(x,e)&&t.scenes.push({content:x,name:r.name})}return t}let jN="x-db-llm-modifiable",jB="x-db-is-entity-id",jF="x-db-is-refresh-key",jw=["entity_type"];function jC(x){return"object"==typeof x&&null!==x&&!Array.isArray(x)}function jP(x,e,t){if(!jC(x))throw Error(`Tool "${t}" 的 ${e} 必须是对象`);return x}function jk(x,e){let t;try{t=JSON.parse(x)}catch(x){throw Error(`解析 tools.json 失败:${e}`,{cause:x})}if(!jC(t)||!Array.isArray(t.tools)||0===t.tools.length)throw Error(`tools.json 必须包含非空的 tools 数组:${e}`);let r=new Set;return{tools:t.tools.map((x,t)=>{let a=function(x,e,t){if(!jC(x))throw Error(`索引为 ${e} 的 Tool 配置必须是对象:${t}`);let r="string"==typeof x.name?x.name.trim():"",a="string"==typeof x.description?x.description.trim():"";if(!r||!a)throw Error(`索引为 ${e} 的 Tool 配置必须提供 name 和 description:${t}`);if(void 0!==x.tool_type&&"client"!==x.tool_type&&"server"!==x.tool_type)throw Error(`Tool "${r}" 的 tool_type 必须为 "client" 或 "server"`);let n=function(x,e){if(void 0===x)return{};if(!jC(x))throw Error(`Tool "${e}" 的 _meta 必须是对象`);if(void 0===x.ui)return{};if(!jC(x.ui))throw Error(`Tool "${e}" 的 _meta.ui 必须是对象`);if("widgetPath"in x.ui)throw Error(`Tool "${e}" 必须使用 _meta.ui.widgetId,不能使用 widgetPath`);let t=x.ui.widgetId;if(void 0!==t&&("string"!=typeof t||!t.trim()))throw Error(`Tool "${e}" 的 _meta.ui.widgetId 必须是非空字符串`);let r=x.ui.expirePolicy;if(void 0!==r&&"same_conversation"!==r)throw Error(`Tool "${e}" 的 _meta.ui.expirePolicy 如有设置,必须为 "same_conversation"`);if("same_conversation"===r&&"string"!=typeof t)throw Error(`Tool "${e}" 设置 _meta.ui.expirePolicy 时必须提供 _meta.ui.widgetId`);return{..."string"==typeof t?{widgetId:t.trim()}:{},..."same_conversation"===r?{expirePolicy:r}:{}}}(x._meta,r);return{name:r,description:a,...n,inputSchema:jP(x.inputSchema,"inputSchema",r),outputSchema:jP(x.outputSchema,"outputSchema",r),permissions:function(x,e){if(void 0===x)return[];if(!Array.isArray(x)||x.some(x=>"string"!=typeof x||!x.trim()))throw Error(`Tool "${e}" 的 permissions 必须是由非空字符串组成的数组`);return x.map(x=>x.trim())}(x.permissions,r),toolType:"client"===x.tool_type?"client":"server"}}(x,t,e);if(r.has(a.name))throw Error(`Tool 名称重复:${a.name}`);return r.add(a.name),a})}}function jD(x,e,t,r,a=!1){let n=`Tool "${e}" 的 ${t} 属性 "${r}"`;if(!jC(x)||"string"!=typeof x.type||!x.type.trim())throw Error(`${n} 必须提供字符串类型的 type`);let _=x.type.trim(),A=x[jN];if(void 0!==A&&"boolean"!=typeof A)throw Error(`${n} 的 ${jN} 必须是布尔值`);if(A&&"outputSchema"!==t)throw Error(`${n} 的 ${jN} 仅支持在 outputSchema 中使用`);if(A&&"array"!==_)throw Error(`${n} 的 ${jN} 仅支持用于数组字段`);let s=x[jB];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${n} 的 ${jB} 必须是布尔值`);if(s&&!a)throw Error(`${n} 的 ${jB} 仅支持用于卡片输出的顶层字段`);let i=x[jF];if(void 0!==i&&"boolean"!=typeof i)throw Error(`${n} 的 ${jF} 必须是布尔值`);if(i&&!a)throw Error(`${n} 的 ${jF} 仅支持用于卡片输出的顶层字段`);let o={type:function(x,e){if("integer"===x)return"int";if("number"===x)return"float";if(["string","boolean","object","array"].includes(x))return x;throw Error(`${e} 使用了不支持的类型 "${x}"`)}(_,n),...A?{llm_modifiable:!0}:{},...s?{is_entity_id:!0}:{},..."string"==typeof x.description&&x.description.trim()?{description:x.description.trim()}:{}};if("object"===_){if(!jC(x.properties))throw Error(`${n} 必须提供对象类型的 properties`);if(o.properties=Object.fromEntries(Object.entries(x.properties).map(([x,a])=>[x,jD(a,e,t,`${r}.${x}`)])),void 0!==x.required){if(!Array.isArray(x.required)||x.required.some(x=>"string"!=typeof x))throw Error(`${n} 的 required 必须是字符串数组`);o.required=x.required}}if("array"===_){if(!jC(x.items))throw Error(`${n} 必须提供对象类型的数组项定义 items`);o.items=jD(x.items,e,t,`${r}[]`)}return o}function jL(x,e,t){let r=x[e];if(void 0===r)return{};if(!jC(r))throw Error(`manifest.yaml 的 ${e} 必须是对象:${t}`);return{...r}}function jq({tools:x,manifestPath:e,manifestText:t}){let r=function(x,e){let t;try{t=(0,sX.qg)(x)}catch(x){throw Error(`解析 manifest.yaml 失败:${e}`,{cause:x})}if(!jC(t))throw Error(`manifest.yaml 必须包含一个对象:${e}`);return t}(t,e),a=jL(r,"tools",e),n=jL(r,"entities",e);for(let e of x){if(e.name in a)throw Error(`Tool "${e.name}" 与 manifest.yaml 中的 Tool 重名`);if(a[e.name]={login_type:"no_login",description:e.description,..."client"===e.toolType?{is_client_tool:!0}:{},input_schema:function(x,e){if("object"!==x.type||!jC(x.properties))throw Error(`Tool "${e}" 的 inputSchema.type 必须为 object,且 properties 必须是对象`);let t=Object.fromEntries(Object.entries(x.properties).map(([x,t])=>[x,jD(t,e,"inputSchema",x)])),r=x.required;if(void 0!==r&&(!Array.isArray(r)||r.some(x=>"string"!=typeof x)))throw Error(`Tool "${e}" 的 inputSchema.required 必须是字符串数组`);return{type:"object",properties:t,...r&&r.length>0?{required:r}:{}}}(e.inputSchema,e.name),output:e.widgetId?{kind:"entities",entity_types:[e.name]}:{kind:"execution_result"},...e.permissions.length>0?{permissions:e.permissions}:{}},e.widgetId){if(e.name in n)throw Error(`Tool "${e.name}" 与 manifest.yaml 中的实体重名`);n[e.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(x,e){let t=e.name;if("array"!==x.type||!jC(x.items))throw Error(`Card Tool "${t}" 的 outputSchema.type 必须为 array,且 items 必须是对象`);if("object"!==x.items.type||!jC(x.items.properties))throw Error(`Card Tool "${t}" 的 outputSchema.items 必须是对象类型的定义`);let r=x.items.properties,a=jw.find(x=>x in r);if(a)throw Error(`Tool "${t}" 的 outputSchema 不能声明保留字段 "${a}"`);let n=Object.entries(r).filter(([x,e])=>{if(!jC(e)||void 0===e[jB])return!1;if("boolean"!=typeof e[jB])throw Error(`Tool "${t}" 的 outputSchema 属性 "${x}" 的 ${jB} 必须是布尔值`);return e[jB]});if(1!==n.length)throw Error(`Card Tool "${t}" 的 outputSchema 必须有且仅有一个 ${jB} 字段,当前有 ${n.length} 个`);let _=Object.entries(r).filter(([x,e])=>{if(!jC(e)||void 0===e[jF])return!1;if("boolean"!=typeof e[jF])throw Error(`Tool "${t}" 的 outputSchema 属性 "${x}" 的 ${jF} 必须是布尔值`);return e[jF]});if("same_conversation"===e.expirePolicy){let x=n[0]?.[0];if(1!==_.length||_[0]?.[0]!==x)throw Error(`Card Tool "${t}" 使用 expirePolicy "same_conversation" 时,必须在 ${jB} 字段上设置 ${jF}`)}return Object.fromEntries(Object.entries(r).map(([x,e])=>[x,jD(e,t,"outputSchema",x,!0)]))}(e.outputSchema,e)},tool_card_binding:{[e.name]:e.widgetId},..."same_conversation"===e.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,sX.As)({...r,tools:a,entities:n})}let jT=I("node:url"),jR=(0,k.createRequire)(import.meta.url),j$="DOUBAO_WEB_SDK_DEBUGGER_DIST_PATH";async function jG(x,e){let t=x.metadata.getData(),r=x.widgets,a=await jI(x.appDirectory,{widgetIds:new Set(Object.keys(r).map(x=>vp(r,t.widgets,x)))});return jS({...e,debuggerDistPath:e.debuggerDistPath??function(){let x=process.env[j$]?.trim();if(x){let e=r4.resolve(x);if(!r5.existsSync(r4.join(e,"index.html")))throw Error(`${j$} 必须指向已构建的 Web SDK 调试器目录,且目录中必须包含 index.html:${e}`);return e}let e=(0,jT.fileURLToPath)(new URL("../assets/web-sdk-debugger/",import.meta.url));if(r5.existsSync(r4.join(e,"index.html")))return e;try{return r4.resolve(r4.dirname(jR.resolve("@byted-doubao-apps/web-sdk-debugger-app/package.json")),"dist")}catch{return e}}(),debugScenes:a,getWidgetViewDataTemplates:x.getWidgetViewDataTemplates})}let jO=new WeakMap;function jX(x,e,t){let r=x.webDebuggerLaunchOptions,a=r?.simulator?.manifestPath,n=a?r4.resolve(x.appDirectory,a):void 0,_=x.toolsResources?.readManifestYaml;if(n){let e=jO.get(x);e?.path!==n&&(e={path:n,read:()=>(function(x,e=(0,r4.join)((0,r4.dirname)(x),"tools.json")){let t=(0,r5.readFileSync)(x,"utf8");if(!(0,r5.existsSync)(e))return t;let{tools:r}=jk((0,r5.readFileSync)(e,"utf8"),e);return jq({tools:r,manifestPath:x,manifestText:t})})(n)},jO.set(x,e)),_=e.read}return{appId:x.appId,appDirectory:x.appDirectory,artifactOrigin:e,env:{...x.env,...r?.env??{}},debuggerDistPath:r?.debuggerDistPath,allowActionHub:r?.allowActionHub,mcpEndpoint:r?.mcpEndpoint??t,mcpHeaders:r?.mcpHeaders,simulator:r?.simulator,eventsConfigReader:x.eventsResources?.readJson,eventsConfigSourcePath:x.eventsResources?.sourcePath,toolsConfigReader:x.toolsResources?.readToolsJson,toolsConfigSourcePath:x.toolsResources?.toolsSourcePath,simulatorManifestReader:_,simulatorManifestSourcePath:n??x.toolsResources?.manifestSourcePath}}let jK=x=>Y.bgHex("#9873b9")(Y.italic(Y.black(` ${x} `))),jQ=x=>Y.bgBlueBright(Y.italic(Y.black(` ${x} `))),jM=x=>Y.bold(Y.blueBright(x)),jZ=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],jJ={page:"页面",scene:"调试场景",widget:"组件"};function jV(x){console.log(` ${jM(x.command.padEnd(21))} ${Y.gray(`- ${x.description}`)}`)}async function jH(x){let e=of(x);if(0!==e.length)return await H.prompt(e.map(([x,e])=>({type:"input",name:x,message:`请输入调试场景变量 "${x}" 的值:`,default:e??void 0})))}async function jU({matchedScene:x,appId:e,driver:t}){let r=await oF(x.path);if(!r)return;let a=await jH(r);await ow({matchedScene:x,appId:e,driver:t,variables:a},r)}async function jY(x,e,t,r,a,n,{interactive:_=!0}={}){if(await a.load({appletUrl:e,appId:x,isSigned:n}),!_)return;let A=await oB(process.cwd()),s=Object.values(t),i=Object.values(r),o=i.filter(({id:x})=>!i0(x));return s.length>0&&(console.log(`
408
+
409
+ ${jQ("可用 pages 列表")}
410
+ `),s.forEach(x=>{console.log(` - ${jM(x.path)}`)})),o.length>0&&(console.log(`
411
+ ${jQ("可用 widgets 列表")}
412
+ `),o.forEach(x=>{let e=jM(x.id);console.log(` - ${e}`)})),A.length>0&&(console.log(`
413
+ ${jQ("可用调试场景")}
414
+ `),A.forEach(x=>console.log(` - ${jM(x.name)}`))),console.log(`
415
+ ${jQ("可以继续执行以下命令:")}
416
+ `),jZ.forEach(jV),console.log("\n"),dZ.instance.addListener(e=>{let t=e.trim();if("d"===t){let e=[...A.map(x=>({type:"scene",id:x.name})),...o.map(x=>({type:"widget",id:x.id})),...s.map(x=>({type:"page",id:x.path}))];if(0===e.length)return console.log(`
417
+ ${jQ("暂无可用的页面、组件或调试场景")}`),!0;dV(async()=>{let{selectedEntry:t}=await H.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:x=>e.filter(e=>`${jJ[e.type]} ${e.type} ${e.id}`.toLowerCase().includes(x?.toLowerCase()??"")).map(x=>({name:`${Y.gray(jJ[x.type])}: ${x.id}`,short:`${jJ[x.type]} \xb7 ${x.id}`,value:x}))}]);if("scene"===t.type){let e=A.find(x=>x.name===t.id);e&&await jU({matchedScene:e,appId:x,driver:a})}else"widget"===t.type?a.pushWidget({appId:x,widgetId:t.id}):a.openPageUrl({appId:x,url:t.id})})}else{let e=A.find(x=>x.name===t);e?dV(async()=>{await jU({matchedScene:e,appId:x,driver:a})}):i.some(x=>x.id===t)?a.pushWidget({appId:x,widgetId:t}):a.openPageUrl({appId:x,url:t})}return!0},"openPage")}async function jz({appId:x,appletUrl:e,pages:t,widgets:r,driver:a,isSigned:n,isDisposed:_}){let A=await oe();if(_())return;if(!A)return void os.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let s=await i9(A).catch(x=>(_()||os.error("重新启动应用失败",{error:x}),!1));if(_())return;if(!s)return void setTimeout(()=>{_()||os.info("请确认应用已经启动。\n")},1e3);if(await new Promise(x=>{setTimeout(x,5e3)}),_())return;if(!a)return void os.error("调试驱动尚未就绪。");let i=await jY(x,e,t,r,a,n);_()&&i?.()}async function jW({context:x,port:e,driver:t,isSigned:r,onCleanupReady:a}){let n,_,A,s,{host:i,artifactOrigin:o}=await x.resolveDevServer(e);x.devServerAbort.signal.throwIfAborted();let l=x.metadata.getData(),c=l.app.appId,v=(_=!1,A=[],{add(x){x&&(_?x():A.push(x))},cleanup:()=>{_=!0,A.splice(0).forEach(x=>x())},isDisposed:()=>_});v.add(()=>{n?.close()});let d=async()=>{if(v.isDisposed())return;let e=await jG(x,jX(x,o,vi()));if(e){if(n=e,v.isDisposed())return void await e.close();await e.open()}};if(x.devServerInteractive&&(s=function(x={}){let e={name:"Doubao Apps SDK",...x},t=e.name?`${e.name} 开发服务`:"",r=e.origin?`正在监听 ${Y.gray(e.origin)}。`:"已启动。";return`
418
+ ${jM(t)}${r}
419
419
  `}(),Z()||console.clear(),console.log(s),console.log(((x,e)=>{if(x&&e){let t=[{title:"\uD83C\uDF10 服务地址",content:e},{title:"\uD83D\uDCE6 应用 ID",content:x}].map(({title:x,titleHighlighter:e,content:t})=>{let r=e?e(x):Y.bold(Y.gray(x));return` - ${Y.bgWhiteBright(Y.italic(Y.black(` ${r} `)))}: ${Y.gray(t.startsWith("http")?Y.underline(t):t)}`}).join("\n");return`
420
- ${jX("豆包应用服务信息")}:
420
+ ${jK("豆包应用服务信息")}:
421
421
 
422
422
  ${t}
423
423
 
424
424
  `}return`
425
- ${jX("豆包应用服务信息")}:
425
+ ${jK("豆包应用服务信息")}:
426
426
 
427
- 调试服务未运行。`})(c,i))),x.devServerInteractive){let e={context:x,appId:c,appletUrl:i,pages:l.pages,widgets:l.widgets,driver:t,isSigned:r,openWebDebugger:d,isDisposed:v.isDisposed};v.add(dQ.instance.addListener(x=>{let t=x.trim().toLowerCase();return("r"===t||"web"===t)&&(process.stdout.write((()=>{let x="";for(let e=0;e<2;e++)x+="\x1b[2K"+(e<1?dV():"");return x+"\x1b[G"})()),"r"===t?jY(e).catch(dM):e.openWebDebugger(),!0)},"devCommands",-1))}a(v.cleanup);try{if(!t){x.devServerInteractive&&os.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}v.add(await jU(c,i,l.pages,l.widgets,t,r,{interactive:x.devServerInteractive}))}catch(x){throw v.cleanup(),x}}let jW=(x,e,t)=>{if(!Z())return void t();let r=process.hrtime.bigint(),a=x.method,n=x.url;e.on("finish",()=>{let x=Number(process.hrtime.bigint()-r)/1e6,t=n?new URL(n,"http://localhost").pathname:"",_=e.statusCode;os.request({method:a||"UNKNOWN",url:t,statusCode:_,durationMs:x})}),t()},j0=new Set(["EACCES","EPERM"]),j1=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),j2=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),j3=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),j6=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),j4={SyntaxError:"syntax_error",TypeError:"type_error",ModuleNotFoundError:"dependency_error",ModuleBuildError:"compilation_error",ValidationError:"config_error",TimeoutError:"timeout_error",FetchError:"network_error",LoaderError:"loader_error",PluginError:"plugin_error"};function j5(x,e){if(!x||"object"!=typeof x||!(e in x))return;let t=x[e];return"string"==typeof t?t:void 0}function j7(x){if(!x||"object"!=typeof x)return[];if(Array.isArray(x.errors)&&x.errors.length>0)return x.errors;if(Array.isArray(x.stats))return x.stats.flatMap(j7);let e=x.stats&&"object"==typeof x.stats?x.stats:x;try{let x=e.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(x)?x:[]}catch{return[]}}function j8(x){return!!(x&&!/<%=?\s*appId\s*%>/.test(x))}function j9(x){return{scene:void 0,commandStartTime:x,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function gx(x,e){Object.assign(x,j9(e))}function ge(x,{scene:e,commandStartTime:t,compileStartTime:r}){let a=x.commandStartTime===t,n=x.prepareDurations,_=x.builderInitStartTime,A=x.appInfoDurationMs,s=x.appInfoMeasured;a&&void 0!==_&&(n.builderInitMs=Math.max(0,r-_)),gx(x,t),x.scene=e,x.compileStartTime=r,a&&(x.prepareDurations=n,x.appInfoDurationMs=A,x.appInfoMeasured=s)}function gt(x,e,t){x.compilePhaseEndTimes[e]=Math.max(x.compilePhaseEndTimes[e]??0,t)}function gr(x){return Math.max(0,Math.round(Number.isFinite(x)?x:0))}let ga=new class{uploader;constructor(x){this.uploader=x}async reportEvent(x){try{await (this.uploader??=new G).upload({name:x.name,params:{...x.params,kit_version:"0.6.0",kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:(process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL").toLowerCase()}})}catch{}}async report(x){try{var e,t;let r,a,n,_,A,s,i,o=x.context?.compileLifecycle;if(o){if(o.reported)return;o.reported=!0}let l="dev_initial"===x.scene||"hot_update"===x.scene?"dev":x.scene,c={appDirectory:x.appDirectory,targetAppId:function(x){try{let e=x?.appId;return j8(e)?e:void 0}catch{return}}(x.context),scene:x.scene,command:l},v="failed"===x.status?{...c,status:x.status,errorStage:x.errorStage,error:j7(x.error)[0]??x.error}:{...c,status:x.status,pageCount:Object.keys(x.context.pages).length,widgetCount:Object.keys(x.context.widgets).length,securityMode:(r=x.context.signingEncryptionOptions,a=!!r?.signing.enabled,n=!!r?.encryption.enabled,a&&n?"signing_and_encryption":a?"signing":n?"encryption":"none"),durations:(e=x.context.compileLifecycle,t=x.compileEndTime,_=e.commandStartTime??t,A=e.compileStartTime??t,s=Math.min(t,Math.max(A,e.compilePhaseEndTimes.moduleProcess??t)),i=Math.min(t,Math.max(s,e.compilePhaseEndTimes.assetProcess??t)),{totalMs:t-_,prepareMs:A-_,compileMs:t-A,...e.prepareDurations,appInfoMs:e.appInfoDurationMs,appTemplateProcessMs:e.appTemplateProcessDurationMs,viewTemplateProcessMs:e.viewTemplateProcessDurationMs,moduleProcessMs:s-A,assetProcessMs:i-s,outputWriteMs:t-i})};await this.upload(v)}catch{}}async flush(x=3e3){try{await this.uploader?.flush?.(x)}catch{}}async upload(x){let{appDirectory:e,...t}=x;await this.reportEvent(function(x,e){let t={kit_compile_id:function(){let x="unknown";try{x=(0,ib.userInfo)().username||x}catch{}return`${Date.now()}_${x}_${(0,ar.randomUUID)()}`}(),kit_compile_scene:x.scene,kit_command:x.command,kit_status:x.status};if(x.targetAppId&&(t.kit_appId=x.targetAppId),"success"===x.status)t.kit_page_count=x.pageCount,t.kit_widget_count=x.widgetCount,t.kit_security_mode=x.securityMode,t.kit_duration_ms_total=gr(x.durations.totalMs),t.kit_prepare_ms=gr(x.durations.prepareMs),t.kit_compile_ms=gr(x.durations.compileMs),t.kit_config_load_ms=gr(x.durations.configLoadMs),t.kit_project_scan_ms=gr(x.durations.projectScanMs),t.kit_context_bootstrap_ms=gr(x.durations.contextBootstrapMs),t.kit_app_info_ms=gr(x.durations.appInfoMs),t.kit_app_template_process_ms=gr(x.durations.appTemplateProcessMs),t.kit_view_template_process_ms=gr(x.durations.viewTemplateProcessMs),t.kit_plugin_bootstrap_ms=gr(x.durations.pluginBootstrapMs),t.kit_builder_init_ms=gr(x.durations.builderInitMs),t.kit_module_process_ms=gr(x.durations.moduleProcessMs),t.kit_asset_process_ms=gr(x.durations.assetProcessMs),t.kit_output_write_ms=gr(x.durations.outputWriteMs);else{t.kit_error_type=function(x){let e=j5(x,"code")?.toUpperCase();if(e){if(j0.has(e))return"permission_error";if(j1.has(e))return"dependency_error";if(j2.has(e))return"timeout_error";if(j3.has(e))return"network_error";if(j6.has(e))return"filesystem_error"}let t="string"==typeof x?x:j5(x,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(t))return"dependency_error";if(/permission denied|operation not permitted/i.test(t))return"permission_error";if(/timed out|timeout/i.test(t))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(t))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(t))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(t))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(t))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(t))return"config_error";if(/loader|加载器/i.test(t))return"loader_error";if(/plugin/i.test(t))return"plugin_error";let r=j5(x,"name");return r&&j4[r]||"unknown_error"}(x.error),x.errorStage&&(t.kit_error_stage=x.errorStage);let a=function(x){if("string"==typeof x)return x;if(!x||"object"!=typeof x||!("message"in x))return;let e=x.message;return"string"==typeof e?e:void 0}(x.error);if(a){var r;let x=(r=e.appDirectory,(0,dY.stripVTControlCharacters)(a).replaceAll(r4.resolve(r),"<project>").replaceAll((0,ib.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));x&&(t.kit_error_message=x)}}return{name:"kit_compile",params:t}}(t,{appDirectory:e}))}};function gn(x,e,t){t?.hasErrors()?ga.report({appDirectory:x.appDirectory,context:x,scene:e,status:"failed",errorStage:"compile",error:j7(t)[0]}):ga.report({appDirectory:x.appDirectory,context:x,scene:e,status:"success",compileEndTime:Date.now()})}class g_{constructor(x,e,t){this._content=e,this._hashCode=t,this.source=x}get content(){return this._content}get hashCode(){var x;return this._hashCode||(x=this.content,m0.createHash("sha256").update("string"==typeof x?x:new DataView(x.buffer,x.byteOffset,x.byteLength)).digest("hex").substring(0,8))}}class gA extends g_{constructor(x,e){super(x,e),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=dg(this._manifest,JSON.parse(e))}catch(x){}this.destination=x}get manifest(){return this._manifest}get content(){return JSON.stringify({manifestVersion:this._manifest.manifestVersion,packageName:this._manifest.packageName,appId:this._manifest.appId,scmVersion:this._manifest.scmVersion,versionName:this._manifest.versionName,versionTag:this._manifest.versionTag,versionCode:this._manifest.versionCode,runtimeVersion:this._manifest.runtimeVersion,sourceType:this._manifest.sourceType,permissions:this._manifest.permissions,settings:this._manifest.settings,applet:this._manifest.applet,widgets:this._manifest.widgets},null,2)}setManifestVersion(x){this._manifest.manifestVersion=x}setRuntimeVersion(x){this._manifest.runtimeVersion=x}setPackageName(x){this._manifest.packageName=x}setVersionName(x){this._manifest.versionName=x}assignBasicManifest(x){Object.assign(this._manifest,x)}mergeBasicManifest(x){dg(this._manifest,x)}setSCMVersion(x){this._manifest.scmVersion=x}setVersionCode(x){this._manifest.versionCode=x}setAppletManifest(x){this._manifest.applet=x}mergeAppletManifest(x){dg(this._manifest.applet,x)}setRenderType(x=om.REACT_LYNX){this._manifest.renderType=x}appendWidget(x){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(x)}appendPage(x){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(x)}toString(){return JSON.stringify(this._manifest,null,2)}}class gs{constructor(){this.assets={}}addAsset(x,e){this.assets[x]=e}deleteAsset(x){delete this.assets[x]}getAsset(x){return this.assets[x]}getAssets(){return this.assets}getManifestAsset(x){return this.getAsset(x)||(this.assets[x]=new gA(x,JSON.stringify({}))),this.getAsset(x)}}class gi{options;constructor(x){this.options=x}apply(x){let e,{pluginSystem:t}=this.options;x.hooks.thisCompilation.tap({name:gi.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},r=>{r.hooks.processAssets.tapPromise({name:gi.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{e=new gs,r.getAssets().forEach(x=>{let t=new g_(x.name,x.source.source(),x.info.contenthash?.[0]);e.addAsset(x.name,t)});let{entrypoints:a}=r,n={};a.forEach((x,t)=>{n[t]=x.getFiles().map(x=>{let t=e.getAsset(x);if(!t)throw Error(`未找到构建产物 ${x}`);return new g_(t.source,t.content,t.hashCode)})});let _=this.options.context.appId;_&&r5.mkdirSync(r4.join(this.options.context.rootPath,_),{recursive:!0}),await t.callAssetsHooks("beforeEmit",{assets:e,chunks:n}),Object.keys(e.getAssets()).forEach(t=>{let a=e.getAsset(t);if(!a)return;let{source:n,destination:_}=a;if(!n||!_)return;r.getAsset(n)?r.renameAsset(n,_):r.emitAsset(_,new x.rspack.sources.RawSource(a.content));let A=r.getAsset(`${n}.map`);A&&r.renameAsset(A.name,`${_}.map`)}),await t.callAssetsHooks("afterEmit",{assets:{...e.getAssets()}})})})}}let go=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class gl{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(gl.name,x=>{x.hooks.finishModules.tap(gl.name,()=>{let e=new Map,t=r=>{if(!r)return!1;let a=e.get(r);if(void 0!==a)return a;if(function(x){var e;let t=x.resourceResolveData?.descriptionFileData?.name;if("string"==typeof t&&go.has(t))return!0;let r=(e=x.resource,e?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...go].some(x=>r?.includes(`/node_modules/${x}/`))}(r))return e.set(r,!0),!0;for(let a of(e.set(r,!1),x.moduleGraph.getOutgoingConnections(r)))if(t(a.module))return e.set(r,!0),!0;return!1};x.entries.forEach((e,r)=>{e.dependencies.some(e=>t(x.moduleGraph.getModule(e)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(r)??r)})})})}}class gc{options;constructor(x){this.options=x}apply(x){x.hooks.make.tapPromise(gc.name,async x=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(gc.name,x=>{x.hooks.optimizeTree.tapPromise(gc.name,async e=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:x.fileDependencies}).catch(e=>x.errors.push(e))})}),x.hooks.done.tapPromise(gc.name,async x=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:x})})}}function gv(x){return x.replaceAll("\\","/")}function gd(x,e,t,r=`${e}.map`){return e!==t&&!!x.getAsset(e)&&(x.renameAsset(e,t),x.getAsset(r)&&x.renameAsset(r,`${t}.map`),!0)}class gf{context;constructor(x){this.context=x}apply(x){x.hooks.thisCompilation.tap(gf.name,e=>{e.hooks.processAssets.tapPromise({name:gf.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var x,t;let r=this.context.metadata.getData(),a=this.context.command===rV.DEV?"all":"configured",n=vb(this.context.pages,this.context.normalizedAppConfig.pages.entries,a),_=vb(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,a),A=r.app.appId||this.context.appId;if(!A&&Object.keys(n).length>0)throw Error("解析 Web 页面入口路径需要 appId");A&&(x=r.pages,Object.keys(n).forEach(t=>{let r=gv(t),a=vv(r);gd(e,`${a}/template.js`,lH(A,x[t]?.path??lV(r),vo),`${a}/background.js.map`)})),t=r.widgets,Object.keys(_).forEach(x=>{var r;let a=vv(gv(x));gd(e,`${a}/template.js`,(r=vd(_,t,x),`${r}/${vo}`),`${a}/background.js.map`)})})})}}class gb{entry;constructor(x){this.entry=x}apply(x){let e=new x.webpack.experiments.VirtualModulesPlugin;e.apply(x),x.hooks.thisCompilation.tap(gb.name,()=>{e.writeModule(iK,""),e.writeModule(iQ,iM),Object.values(this.entry).forEach(x=>{e.writeModule(x.filename,x.toString())})})}}function gu(x,e){return x.isIdentifier(e)?e.text:x.isPropertyAccessExpression(e)?e.name.text:void 0}let gp={templatesByEntry:{},templatesByWidget:{}},gm="/doubao-apps-framework.template.js",gh="/doubao-apps-api.template.js",gE=(x,e,t="/assets/framework/")=>{let r=e?t.replace(/\/+$/,""):"",a=(x,t,a)=>({libraryName:a,url:`${r}${x}`,background:{sectionPath:t},mainThread:{sectionPath:`${t}__main-thread`},async:!!e});return{"@byted-doubao-apps/bridge-base":a(gh,"api"),"@byted-doubao-apps/open-api":a(gh,"api"),...Object.fromEntries(Object.entries(iz).map(([e,t])=>[e,a(x?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",t])])),[`${c0}/api`]:a(gh,"api"),[`${c1}/api`]:a(gh,"api"),[c0]:a(gm,"framework"),[c1]:a(gm,"framework"),"@byted-doubao-apps/components":a(gm,"components"),[c3(c0)]:a(gm,"components"),[c3(c1)]:a(gm,"components")}},gj=(0,k.createRequire)(import.meta.url);function gg(x,e){for(let t of x)try{return gj.resolve(t,{paths:e})}catch{}throw Error(`无法解析以下候选包:${x.join(", ")}`)}class gy{pluginSystem;constructor(x){this.pluginSystem=x}async createEntry(){let{entry:x}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return x}async createConfig({config:x}){var e,t,r,a,n;let{appDirectory:_,command:A,metadata:s,rootPath:i}=x.context,o=x.context.environment,l="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:o}),x.context.setEnvironment(o);let c=A===rV.DEV,v=await this.createEntry(),d=c4(_),f=[_,r4.dirname((0,jq.fileURLToPath)(import.meta.url))],b=gj.resolve("@lynx-js/react/transform"),u=c?"all":"configured",h=vb(x.context.pages,x.context.normalizedAppConfig.pages.entries,u),S=new Set([...Object.keys(vb(x.context.widgets,x.context.normalizedAppConfig.widgets.entries,u)),...Object.keys(h)]),I=S.size>0;I&&await du({widgets:x.context.widgets,pages:x.context.pages,entries:v,collector:s,normalizedAppConfig:x.context.normalizedAppConfig,define:x.context.userConfig?.source?.define});let N={include:x.options.source?.include,exclude:x.options.source?.exclude,decorators:x.options.source?.decorators,define:{...x.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(x.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},B=x=>[iK,iQ,x.filename],F={...N,entry:Object.fromEntries(Object.entries(v).map(([x,e])=>[x,B(e)]))},w=Object.fromEntries(Object.entries(v).filter(([x])=>S.has(x))),C=new Map(Object.keys(w).map(x=>[vv(x),x])),P={...F,entry:Object.fromEntries(Object.entries(w).map(([x,e])=>[vv(x),B(e)])),define:{...F.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},D=[...vr()?[]:[v5({externals:gE(c),globalObject:"lynx"})]],L=[function({metadata:x,resolveAppInfo:e,resolveVersionTag:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,a)=>{let n=a?.environment?.name==="web"?vs:vA;r.plugin(vi.name).use(vi,[{metadata:x,resolveAppInfo:e,resolveVersionTag:t,isNative:a?.environment?.name!=="web",shouldInjectAsset:n}])})}}}({metadata:s,resolveAppInfo:()=>x.context.resolveAppInfo(),resolveVersionTag:()=>x.context.versionTag})],q={source:{...F,define:{...F.define,...vr()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(gj(gj.resolve(`${d}/package.json`,{paths:[_]})).version)}:{}}},output:{distPath:{image:"base/static/image",svg:"base/static/svg"}},...!c?{tools:{rspack:{output:{publicPath:"/"}}}}:{},plugins:D},T=[function x({metadata:e,entry:t,lynxConfigs:r,resolveSigningEncryptionOptions:a,onProcessDuration:n}){return{name:x.name,setup(x){x.modifyBundlerChain((_,A)=>{if(A?.environment?.name==="web")return;let s=x.useExposed(Symbol.for("LynxTemplatePlugin"));_.plugin(dy.name).use(dy,[s.LynxTemplatePlugin,e,t,a,n,r])})}}}({metadata:s,entry:v,lynxConfigs:{internal:x.context.internal,config:x.context.appConfig.lynxConfig,entries:Object.fromEntries(Object.entries({...x.context.normalizedAppConfig.pages.entries,...x.context.normalizedAppConfig.widgets.entries}).map(([x,e])=>[x,e.lynxConfig]))},resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(x.context.compileLifecycle.viewTemplateProcessDurationMs,e)}}),function({context:x,normalizeEntryName:e}){return{name:"template-widget-entry-plugin",setup(t){t.modifyBundlerChain((t,r)=>{let a=r?.environment?.name;t.plugin("template-widget-entry-plugin").use(gl,[{markTemplateWidgetEntry:e=>{x.addTemplateWidgetEntry(e)},normalizeEntryName:x=>e?.(x,a)}])})}}}({context:x.context,normalizeEntryName:(x,e)=>"web"===e?C.get(x):x}),(e=this.pluginSystem,t=x.context,{name:"output-plugin",setup(x){let r={pluginSystem:e,context:t};x.modifyBundlerChain((x,e)=>{e?.environment?.name!=="web"&&x.plugin("output-plugin").use(gi,[r])})}}),...A===rV.DEV&&I?[function({context:x}){let e;return x.getWidgetViewDataTemplates=async()=>{if(e)return e;try{e=function(x,e,t){let r=function(x){let e,t=(0,k.createRequire)(r4.join(x,"package.json"));try{e=t.resolve("typescript")}catch(x){return}return t(e)}(x);if(!r)return{templatesByEntry:{},templatesByWidget:{}};let a=[...new Set(Object.values(e).map(({filename:x})=>x))],n=r.createProgram({options:function(x,e){let t={allowJs:!0,checkJs:!1,jsx:x.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:x.ScriptTarget.ESNext},r=x.findConfigFile(e,r5.existsSync);if(!r)return t;let a=x.readConfigFile(r,x.sys.readFile);return a.error?t:{...x.parseJsonConfigFileContent(a.config,x.sys,r4.dirname(r)).options,...t}}(r,x),rootNames:a}),_=n.getTypeChecker(),A=Object.fromEntries(Object.entries(e).map(([x,{filename:e}])=>{let t,a=n.getSourceFile(e);return[op(x),a?(t={},!function x(e){if(r.isCallExpression(e)&&("getViewData"===gu(r,e.expression)||"useViewData"===gu(r,e.expression))&&e.typeArguments?.[0]){let x=_.getTypeFromTypeNode(e.typeArguments[0]);for(let a of _.getPropertiesOfType(x)){let n=a.valueDeclaration??a.declarations?.[0]??e;t[a.getName()]=function x(e,t,r,a,n){let _=(t.isUnion()?t.types:[t]).filter(x=>!(x.flags&(e.TypeFlags.Undefined|e.TypeFlags.Never)));if(_.some(x=>x.flags&e.TypeFlags.Null))return null;if(_.some(x=>x.flags&e.TypeFlags.StringLike))return"";if(_.some(x=>x.flags&(e.TypeFlags.NumberLike|e.TypeFlags.BigIntLike)))return 0;if(_.some(x=>x.flags&e.TypeFlags.BooleanLike))return!1;if(_.some(x=>r.isArrayType(x)||r.isTupleType(x)))return[];let A=_.find(x=>x.flags&e.TypeFlags.Object);if(!A||n.has(A))return{};n.add(A);let s=Object.fromEntries(r.getPropertiesOfType(A).map(t=>{let _=t.valueDeclaration??t.declarations?.[0]??a;return[t.getName(),x(e,r.getTypeOfSymbolAtLocation(t,_),r,_,n)]}));return n.delete(A),s}(r,_.getTypeOfSymbolAtLocation(a,n),_,n,new Set([x]))}}r.forEachChild(e,x)}(a),t):{}]})),s=Object.fromEntries(Object.keys(e).map(x=>{let r=op(x);return[vd(e,t,x),A[r]??{}]}));return{templatesByEntry:A,templatesByWidget:s}}(x.appDirectory,x.widgets,x.metadata.getData().widgets)}catch{e=gp}return e},{name:"WidgetViewDataPlugin",setup(x){x.onAfterDevCompile(({stats:x})=>{x.hasErrors()||(e=void 0)})}}}({context:x.context})]:[],(({context:x})=>({name:"DevServerLogPlugin",setup(e){let t,r=!1,a=!1,n=process.env.DEV_SERVER_HOST;if("dev"===e.context.action&&void 0!==n){let x=new URL(n),t="https:"===x.protocol?"wss":"ws";e.modifyEnvironmentConfig({order:"post",handler:(e,{mergeEnvironmentConfig:r})=>r(e,{dev:{assetPrefix:n,client:{host:x.hostname,port:x.port,protocol:t}},output:{assetPrefix:n}})}),e.modifyBundlerChain({order:"post",handler(e){let r=e.resolve.alias.get("@lynx-js/webpack-dev-transport/client");if("string"!=typeof r)return;let[a,n]=r.split("?"),_=new URLSearchParams(n);_.set("hostname",x.hostname),_.set("port",x.port),_.set("protocol",t),e.resolve.alias.set("@lynx-js/webpack-dev-transport/client",`${a}?${_}`)}})}e.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{setup({server:x}){x.middlewares.use(jW)}}})),e.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DevServerLogPlugin",e=>x.finishInitialDevCompile(e))}),e.onAfterDevCompile(async({stats:n})=>{if(n.hasErrors())return void x.finishInitialDevCompile(Error(n.toString({all:!1,errors:!0,colors:!1})));if(r)return;let{devServer:_}=e.context;if(!_)return;r=!0;let A=await ol({debugDriver:x.userConfig.debugDriver,skipAdbForegroundAppWatch:x.userConfig.skipAdbForegroundAppWatch}).catch(dM);a||(x.finishInitialDevCompile(),jz({context:x,port:_.port,driver:A,isSigned:x.isSignedEncryption,onCleanupReady(x){a?x():t=x}}).catch(x=>{a||os.error("初始化开发服务操作失败",{error:x})}))}),e.onCloseDevServer(()=>{a=!0,x.devServerAbort.abort(),t?.(),t=void 0})}}))({context:x.context}),function({context:x}){let e="KitMonitorPlugin";return{name:e,setup(t){if(t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.finishMake.tap(e,()=>{gt(x.compileLifecycle,"moduleProcess",Date.now())}),r.hooks.emit.tap(e,()=>{gt(x.compileLifecycle,"assetProcess",Date.now())}),r.hooks.failed.tap(e,e=>{ga.report({appDirectory:x.appDirectory,context:x,scene:x.compileLifecycle.scene??(x.command===rV.DEV?"dev_initial":x.command),status:"failed",errorStage:"compile",error:e})})}),x.command!==rV.DEV){let e=x.command;t.onBeforeBuild(()=>{let t=Date.now();ge(x.compileLifecycle,{scene:e,commandStartTime:x.compileLifecycle.commandStartTime??t,compileStartTime:t})}),t.onAfterBuild(({stats:t})=>{gn(x,e,t)})}else t.onBeforeDevCompile(({isFirstCompile:e})=>{let t=Date.now();ge(x.compileLifecycle,{scene:e?"dev_initial":"hot_update",commandStartTime:e?x.compileLifecycle.commandStartTime??t:t,compileStartTime:t})}),t.onAfterDevCompile(({stats:e})=>{gn(x,x.compileLifecycle.scene??"dev_initial",e)})}}}({context:x.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(x){x.onBeforeCreateCompiler(({bundlerConfigs:x})=>{let{BytedRsdoctorPlugin:e}=gj(gg(["@byted/rsdoctor"],f));for(let t of x){let x=r4.join(t.output?.path??"",`.rsdoctor-${t.name}`);t.plugins??=[],t.plugins.push(new e({disableClientServer:!0,supports:{banner:!0},output:{reportDir:x}}))}})}}]:[],(r=this.pluginSystem,a=x.context,{name:"view-hooks-plugin",setup(x){x.modifyBundlerChain((x,e)=>{e?.environment?.name==="web"||x.plugin("view-hooks-plugin").use(gc,[{pluginSystem:r,context:a}])})}}),(({getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:n})=>({name:"lynx:encode-worker",async setup(_){va()||_.modifyBundlerChain((_,A)=>{A?.environment?.name!=="web"&&_.plugin(dj.name).use(dj,[{getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:n}]).end()})}}))({getAppAssetPath:()=>x.context.appAssetPath,getAppMapAssetPath:()=>x.context.appMapAssetPath,metadata:x.context.metadata,resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.appTemplateProcessDurationMs+=e}}),...x.rsbuildPlugins||[]],R=[{name:"web-virtual-entry-plugin",setup(x){x.modifyBundlerChain((x,{environment:e})=>{"web"===e.name&&x.plugin(gb.name).use(gb,[w])})}},(n=x.context,{name:"web-output-plugin",setup(x){x.modifyBundlerChain({order:"post",handler(x,{environment:e}){if("web"===e.name){let e=".rspeedy/";for(let t of Object.keys(x.plugins.entries()??{}))t.startsWith("lynx:template-")&&x.plugin(t).tap(x=>{let t=x[0];return t?.intermediate?.startsWith(e)&&(t.intermediate=t.intermediate.slice(e.length)),x});x.plugins.has("lynx:sourcemap")&&x.plugin("lynx:sourcemap").tap(x=>{var e;let t,r=x[0];return r.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],e=n.appDirectory,t=r4.resolve(e),r.moduleFilenameTemplate=({absoluteResourcePath:x,query:e=""})=>{let r=r4.relative(t,x),a=".."!==r&&!r.startsWith(`..${r4.sep}`)&&!r4.isAbsolute(r),n=a?gv(r):gv(x).replace(/^\/+/,"");return`${a?"file":"webpack"}:///${n}${e}`},x}),x.plugin(gf.name).use(gf,[n])}}})}})],$=E({mode:A===rV.DEV?"development":"production",environments:I?{lynx:q,web:{source:P,output:{distPath:{css:"base/web-common",js:"base/web-common",image:"base/web-static/image",svg:"base/web-static/svg",font:"base/web-static/font",media:"base/web-static/media"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!c&&"cheap-module-source-map",css:!1}},plugins:[v5({externals:gE(A===rV.DEV,!0,x.options.frameworkPrefix),globalObject:"lynx"})]}}:{lynx:q},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(x,e,t=r4.join(r4.dirname((0,jq.fileURLToPath)(import.meta.url)),"components-loader.js"),r=gg){for(let x of[r4.join(r4.dirname((0,jq.fileURLToPath)(import.meta.url)),"../loader/components-loader/index.js"),t])if((0,r5.existsSync)(x))return x;return r(e===c1?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],x)}(f,d),options:{frameworkPackage:d,widgetEntryPaths:Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>r4.resolve(_,x))}}]},plugins:[new dK(Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>r4.resolve(_,x))),new j.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:j.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...N,entry:{}},server:{cors:!0,host:x.context.devServerHost,port:c&&process.env.DEV_SERVER_PORT?Number(process.env.DEV_SERVER_PORT):void 0},dev:{writeToDisk:Z(),hmr:A===rV.DEV},output:{distPath:{js:"base/common",root:i||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...x.options.resolve?.alias||{}}},performance:{printFileSize:Z(),...vr()&&!l?{chunkSplit:{strategy:"split-by-experience"}}:{}},...l?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(x){(function(x){let{LAYERS:e,lazy:t,rootPath:r,elementTemplate:a}=x??{};return{name:"lynx:react-alias",setup(x){let n=(0,k.createRequire)(import.meta.url),_=n.resolve("@lynx-js/react/package.json",{paths:[r??x.context.rootPath]}),{version:A}=n(_),s=r4.dirname(_);x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{source:{include:[s]}})),x.modifyBundlerChain(async(n,{isProd:_,rspack:i})=>{if(Object.hasOwn(n,dt))return;let o=dr(i,r??x.context.rootPath,t?["lazy","import"]:["import"]),l=dr(i,s,["import"]);x.expose(Symbol.for("@lynx-js/react/internal:resolve"),{resolve:o,version:A}),Object.defineProperty(n,dt,{value:!0});let[c,v,d,f,b,u,p,m,h,E,j,g,y,S]=await Promise.all([o("@lynx-js/react/jsx-runtime"),o("@lynx-js/react/lepus/jsx-runtime"),o("@lynx-js/react/jsx-dev-runtime"),o("@lynx-js/react/lepus/jsx-dev-runtime"),a?o("@lynx-js/react/element-template/jsx-runtime"):Promise.resolve(null),a?o("@lynx-js/react/element-template/jsx-dev-runtime"):Promise.resolve(null),l("preact/hooks"),o("@lynx-js/react/hooks"),o("@lynx-js/react/lepus/hooks"),o("@lynx-js/react"),o("@lynx-js/react/lepus"),de()(A,"0.111.9999")?o("@lynx-js/react/compat"):Promise.resolve(null),a?o("@lynx-js/react/element-template"):Promise.resolve(null),a?o("@lynx-js/react/element-template/internal"):Promise.resolve(null)]),I={background:c,mainThread:b??v},N={background:d,mainThread:u??f};n.module.rule("react:jsx-runtime:main-thread").issuerLayer(e.MAIN_THREAD).resolve.alias.set("react/jsx-runtime",I.mainThread).set("react/jsx-dev-runtime",N.mainThread).set("@lynx-js/react/jsx-runtime",I.mainThread).set("@lynx-js/react/jsx-dev-runtime",N.mainThread).set("@lynx-js/react/lepus$",j).set("@lynx-js/react/lepus/jsx-runtime",I.mainThread).set("@lynx-js/react/lepus/jsx-dev-runtime",N.mainThread).set("preact/hooks",h).set("@lynx-js/react/hooks",h).set("@lynx-js/react/lepus/hooks",h).set("@lynx-js/react-signals$","@lynx-js/react-signals/lepus").end().end().end().rule("react:jsx-runtime:background").issuerLayer(e.BACKGROUND).resolve.alias.set("react/jsx-runtime",I.background).set("react/jsx-dev-runtime",N.background).set("@lynx-js/react/jsx-runtime",I.background).set("@lynx-js/react/jsx-dev-runtime",N.background).set("@lynx-js/react/lepus$",y??E).set("preact/hooks",p).set("@lynx-js/react/hooks",m).end().end().end().end();let B=new Map;for(let[x,e]of(a&&B.set("experimental/lazy/import",r4.join(s,"runtime/lazy/element-template-import.js")),await Promise.all(["experimental/lazy/import","internal","legacy-react-runtime","runtime-components","worklet-runtime/bindings"].map(async x=>{let e=`@lynx-js/react/${x}`,t=B.get(x)??await o(e);return[`${e}$`,t]}))))n.resolve.alias.set(x,e);_&&(n.resolve.alias.set("@lynx-js/react/debug$",!1),process.env.REACT_DEVTOOL||n.resolve.alias.set("@lynx-js/preact-devtools$",!1)),n.resolve.alias.has("react$")||n.resolve.alias.set("react$",E),n.resolve.alias.set("@lynx-js/react$",y??E).set("@lynx-js/react/internal$",S??n.resolve.alias.get("@lynx-js/react/internal$")).set("@lynx-js/react/jsx-runtime",I.background).set("@lynx-js/react/jsx-dev-runtime",N.background),a&&n.resolve.alias.set("@lynx-js/react/element-template$",y).set("@lynx-js/react/element-template/internal$",S).set("@lynx-js/react/element-template/jsx-runtime",b).set("@lynx-js/react/element-template/jsx-dev-runtime",u),g&&n.resolve.alias.set("@lynx-js/react/compat$",g),await Promise.all(["preact","preact/compat","preact/debug","preact/devtools","preact/test-utils","preact/jsx-runtime","preact/jsx-dev-runtime","preact/compat","preact/compat/client","preact/compat/server","preact/compat/jsx-runtime","preact/compat/jsx-dev-runtime","preact/compat/scheduler"].map(x=>l(x).then(e=>{n.resolve.alias.set(`${x}$`,e)})))})}}})({LAYERS:p,lazy:!1,rootPath:r4.dirname((0,jq.fileURLToPath)(import.meta.url))}).setup(x)}},{name:"set-server.printUrls-false",setup(x){x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{printUrls:!1}}))}},m({compat:{componentsPkg:[],newRuntimePkg:d,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...c2]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(x){x.modifyBundlerChain((x,{CHAIN_ID:e})=>{let t=x.module.rule(e.RULE.JS).oneOf(e.ONE_OF.JS_MAIN);for(let x of[p.BACKGROUND,p.MAIN_THREAD]){let e=t.oneOfs.get(x)?.uses.get(x);if(!e)throw Error(`未找到该层的 React 转换加载器:${x}`);e.tap(x=>({...x,transformPath:b}))}})}},function(x){let{compilerOptionsKeys:e=vg.compilerOptionsKeys,configKeys:t=vg.configKeys,validate:r=vM,dslPluginName2PkgName:a=vZ,upgradeRspeedyLink:n="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return r(x),{name:"lynx:config",async setup(r){r.expose(Symbol.for("lynx.config"),{config:x}),"rstest"!==r.context.callerName&&r.modifyBundlerChain(_=>{let A=r.useExposed(Symbol.for("LynxTemplatePlugin"));if(!A){let x="Rspeedy and plugins";throw Object.entries(a).forEach(([e,t])=>{r.isPluginExists(e)&&(x=t)}),Error(`\
428
- [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${vq("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
427
+ 调试服务未运行。`})(c,i))),x.devServerInteractive){let e={context:x,appId:c,appletUrl:i,pages:l.pages,widgets:l.widgets,driver:t,isSigned:r,openWebDebugger:d,isDisposed:v.isDisposed};v.add(dZ.instance.addListener(x=>{let t=x.trim().toLowerCase();return("r"===t||"web"===t)&&(process.stdout.write((()=>{let x="";for(let e=0;e<2;e++)x+="\x1b[2K"+(e<1?dU():"");return x+"\x1b[G"})()),"r"===t?jz(e).catch(dJ):e.openWebDebugger(),!0)},"devCommands",-1))}a(v.cleanup);try{if(!t){x.devServerInteractive&&os.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}v.add(await jY(c,i,l.pages,l.widgets,t,r,{interactive:x.devServerInteractive}))}catch(x){throw v.cleanup(),x}}let j0=(x,e,t)=>{if(!Z())return void t();let r=process.hrtime.bigint(),a=x.method,n=x.url;e.on("finish",()=>{let x=Number(process.hrtime.bigint()-r)/1e6,t=n?new URL(n,"http://localhost").pathname:"",_=e.statusCode;os.request({method:a||"UNKNOWN",url:t,statusCode:_,durationMs:x})}),t()},j1=new Set(["EACCES","EPERM"]),j2=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),j3=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),j6=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),j4=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),j5={SyntaxError:"syntax_error",TypeError:"type_error",ModuleNotFoundError:"dependency_error",ModuleBuildError:"compilation_error",ValidationError:"config_error",TimeoutError:"timeout_error",FetchError:"network_error",LoaderError:"loader_error",PluginError:"plugin_error"};function j7(x,e){if(!x||"object"!=typeof x||!(e in x))return;let t=x[e];return"string"==typeof t?t:void 0}function j8(x){if(!x||"object"!=typeof x)return[];if(Array.isArray(x.errors)&&x.errors.length>0)return x.errors;if(Array.isArray(x.stats))return x.stats.flatMap(j8);let e=x.stats&&"object"==typeof x.stats?x.stats:x;try{let x=e.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(x)?x:[]}catch{return[]}}function j9(x){return!!(x&&!/<%=?\s*appId\s*%>/.test(x))}function gx(x){return{scene:void 0,commandStartTime:x,compileStartTime:void 0,builderInitStartTime:void 0,compilePhaseEndTimes:{moduleProcess:void 0,assetProcess:void 0},prepareDurations:{configLoadMs:0,projectScanMs:0,contextBootstrapMs:0,pluginBootstrapMs:0,builderInitMs:0},appInfoDurationMs:0,appInfoMeasured:!1,appTemplateProcessDurationMs:0,viewTemplateProcessDurationMs:0,reported:!1}}function ge(x,e){Object.assign(x,gx(e))}function gt(x,{scene:e,commandStartTime:t,compileStartTime:r}){let a=x.commandStartTime===t,n=x.prepareDurations,_=x.builderInitStartTime,A=x.appInfoDurationMs,s=x.appInfoMeasured;a&&void 0!==_&&(n.builderInitMs=Math.max(0,r-_)),ge(x,t),x.scene=e,x.compileStartTime=r,a&&(x.prepareDurations=n,x.appInfoDurationMs=A,x.appInfoMeasured=s)}function gr(x,e,t){x.compilePhaseEndTimes[e]=Math.max(x.compilePhaseEndTimes[e]??0,t)}function ga(x){return Math.max(0,Math.round(Number.isFinite(x)?x:0))}let gn=new class{uploader;constructor(x){this.uploader=x}async reportEvent(x){try{await (this.uploader??=new G).upload({name:x.name,params:{...x.params,kit_version:"0.6.0",kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:(process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL").toLowerCase()}})}catch{}}async report(x){try{var e,t;let r,a,n,_,A,s,i,o=x.context?.compileLifecycle;if(o){if(o.reported)return;o.reported=!0}let l="dev_initial"===x.scene||"hot_update"===x.scene?"dev":x.scene,c={appDirectory:x.appDirectory,targetAppId:function(x){try{let e=x?.appId;return j9(e)?e:void 0}catch{return}}(x.context),scene:x.scene,command:l},v="failed"===x.status?{...c,status:x.status,errorStage:x.errorStage,error:j8(x.error)[0]??x.error}:{...c,status:x.status,pageCount:Object.keys(x.context.pages).length,widgetCount:Object.keys(x.context.widgets).length,securityMode:(r=x.context.signingEncryptionOptions,a=!!r?.signing.enabled,n=!!r?.encryption.enabled,a&&n?"signing_and_encryption":a?"signing":n?"encryption":"none"),durations:(e=x.context.compileLifecycle,t=x.compileEndTime,_=e.commandStartTime??t,A=e.compileStartTime??t,s=Math.min(t,Math.max(A,e.compilePhaseEndTimes.moduleProcess??t)),i=Math.min(t,Math.max(s,e.compilePhaseEndTimes.assetProcess??t)),{totalMs:t-_,prepareMs:A-_,compileMs:t-A,...e.prepareDurations,appInfoMs:e.appInfoDurationMs,appTemplateProcessMs:e.appTemplateProcessDurationMs,viewTemplateProcessMs:e.viewTemplateProcessDurationMs,moduleProcessMs:s-A,assetProcessMs:i-s,outputWriteMs:t-i})};await this.upload(v)}catch{}}async flush(x=3e3){try{await this.uploader?.flush?.(x)}catch{}}async upload(x){let{appDirectory:e,...t}=x;await this.reportEvent(function(x,e){let t={kit_compile_id:function(){let x="unknown";try{x=(0,ib.userInfo)().username||x}catch{}return`${Date.now()}_${x}_${(0,ar.randomUUID)()}`}(),kit_compile_scene:x.scene,kit_command:x.command,kit_status:x.status};if(x.targetAppId&&(t.kit_appId=x.targetAppId),"success"===x.status)t.kit_page_count=x.pageCount,t.kit_widget_count=x.widgetCount,t.kit_security_mode=x.securityMode,t.kit_duration_ms_total=ga(x.durations.totalMs),t.kit_prepare_ms=ga(x.durations.prepareMs),t.kit_compile_ms=ga(x.durations.compileMs),t.kit_config_load_ms=ga(x.durations.configLoadMs),t.kit_project_scan_ms=ga(x.durations.projectScanMs),t.kit_context_bootstrap_ms=ga(x.durations.contextBootstrapMs),t.kit_app_info_ms=ga(x.durations.appInfoMs),t.kit_app_template_process_ms=ga(x.durations.appTemplateProcessMs),t.kit_view_template_process_ms=ga(x.durations.viewTemplateProcessMs),t.kit_plugin_bootstrap_ms=ga(x.durations.pluginBootstrapMs),t.kit_builder_init_ms=ga(x.durations.builderInitMs),t.kit_module_process_ms=ga(x.durations.moduleProcessMs),t.kit_asset_process_ms=ga(x.durations.assetProcessMs),t.kit_output_write_ms=ga(x.durations.outputWriteMs);else{t.kit_error_type=function(x){let e=j7(x,"code")?.toUpperCase();if(e){if(j1.has(e))return"permission_error";if(j2.has(e))return"dependency_error";if(j3.has(e))return"timeout_error";if(j6.has(e))return"network_error";if(j4.has(e))return"filesystem_error"}let t="string"==typeof x?x:j7(x,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(t))return"dependency_error";if(/permission denied|operation not permitted/i.test(t))return"permission_error";if(/timed out|timeout/i.test(t))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(t))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(t))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(t))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(t))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(t))return"config_error";if(/loader|加载器/i.test(t))return"loader_error";if(/plugin/i.test(t))return"plugin_error";let r=j7(x,"name");return r&&j5[r]||"unknown_error"}(x.error),x.errorStage&&(t.kit_error_stage=x.errorStage);let a=function(x){if("string"==typeof x)return x;if(!x||"object"!=typeof x||!("message"in x))return;let e=x.message;return"string"==typeof e?e:void 0}(x.error);if(a){var r;let x=(r=e.appDirectory,(0,dW.stripVTControlCharacters)(a).replaceAll(r4.resolve(r),"<project>").replaceAll((0,ib.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));x&&(t.kit_error_message=x)}}return{name:"kit_compile",params:t}}(t,{appDirectory:e}))}};function g_(x,e,t){t?.hasErrors()?gn.report({appDirectory:x.appDirectory,context:x,scene:e,status:"failed",errorStage:"compile",error:j8(t)[0]}):gn.report({appDirectory:x.appDirectory,context:x,scene:e,status:"success",compileEndTime:Date.now()})}class gA{constructor(){this.assets={}}addAsset(x,e){this.assets[x]=e}deleteAsset(x){delete this.assets[x]}getAsset(x){return this.assets[x]}getAssets(){return this.assets}getManifestAsset(x){return this.getAsset(x)||(this.assets[x]=new cY(x,JSON.stringify({}))),this.getAsset(x)}}class gs{options;constructor(x){this.options=x}apply(x){let e,{pluginSystem:t}=this.options;x.hooks.thisCompilation.tap({name:gs.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},r=>{r.hooks.processAssets.tapPromise({name:gs.name,stage:x.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{e=new gA,r.getAssets().forEach(x=>{let t=new cU(x.name,x.source.source(),x.info.contenthash?.[0]);e.addAsset(x.name,t)});let{entrypoints:a}=r,n={};a.forEach((x,t)=>{n[t]=x.getFiles().map(x=>{let t=e.getAsset(x);if(!t)throw Error(`未找到构建产物 ${x}`);return new cU(t.source,t.content,t.hashCode)})});let _=this.options.context.appId;_&&r5.mkdirSync(r4.join(this.options.context.rootPath,_),{recursive:!0}),await t.callAssetsHooks("beforeEmit",{assets:e,chunks:n}),Object.keys(e.getAssets()).forEach(t=>{let a=e.getAsset(t);if(!a)return;let{source:n,destination:_}=a;if(!n||!_)return;r.getAsset(n)?r.renameAsset(n,_):r.emitAsset(_,new x.rspack.sources.RawSource(a.content));let A=r.getAsset(`${n}.map`);A&&r.renameAsset(A.name,`${_}.map`)}),await t.callAssetsHooks("afterEmit",{assets:{...e.getAssets()}})})})}}let gi=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class go{options;constructor(x){this.options=x}apply(x){x.hooks.thisCompilation.tap(go.name,x=>{x.hooks.finishModules.tap(go.name,()=>{let e=new Map,t=r=>{if(!r)return!1;let a=e.get(r);if(void 0!==a)return a;if(function(x){var e;let t=x.resourceResolveData?.descriptionFileData?.name;if("string"==typeof t&&gi.has(t))return!0;let r=(e=x.resource,e?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...gi].some(x=>r?.includes(`/node_modules/${x}/`))}(r))return e.set(r,!0),!0;for(let a of(e.set(r,!1),x.moduleGraph.getOutgoingConnections(r)))if(t(a.module))return e.set(r,!0),!0;return!1};x.entries.forEach((e,r)=>{e.dependencies.some(e=>t(x.moduleGraph.getModule(e)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(r)??r)})})})}}class gl{options;constructor(x){this.options=x}apply(x){x.hooks.make.tapPromise(gl.name,async x=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata}).catch(e=>x.errors.push(e))}),x.hooks.thisCompilation.tap(gl.name,x=>{x.hooks.optimizeTree.tapPromise(gl.name,async e=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:x.fileDependencies}).catch(e=>x.errors.push(e))})}),x.hooks.done.tapPromise(gl.name,async x=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:x})})}}function gc(x){return x.replaceAll("\\","/")}function gv(x,e,t,r=`${e}.map`){return e!==t&&!!x.getAsset(e)&&(x.renameAsset(e,t),x.getAsset(r)&&x.renameAsset(r,`${t}.map`),!0)}class gd{context;constructor(x){this.context=x}apply(x){x.hooks.thisCompilation.tap(gd.name,e=>{e.hooks.processAssets.tapPromise({name:gd.name,stage:x.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var x,t;let r=this.context.metadata.getData(),{pages:a,widgets:n}=this.context,_=r.app.appId||this.context.appId;if(!_&&Object.keys(a).length>0)throw Error("解析 Web 页面入口路径需要 appId");_&&(x=r.pages,Object.keys(a).forEach(t=>{let r=gc(t),a=vu(r);gv(e,`${a}/template.js`,c0(_,x[t]?.path??cW(r),vd),`${a}/background.js.map`)})),t=r.widgets,Object.keys(n).forEach(x=>{var r;let a=vu(gc(x));gv(e,`${a}/template.js`,(r=vp(n,t,x),`${r}/${vd}`),`${a}/background.js.map`)})})})}}class gf{entry;constructor(x){this.entry=x}apply(x){let e=new x.webpack.experiments.VirtualModulesPlugin;e.apply(x),x.hooks.thisCompilation.tap(gf.name,()=>{e.writeModule(iK,""),e.writeModule(iQ,iM),Object.values(this.entry).forEach(x=>{e.writeModule(x.filename,x.toString())})})}}function gb(x,e){return x.isIdentifier(e)?e.text:x.isPropertyAccessExpression(e)?e.name.text:void 0}let gu={templatesByEntry:{},templatesByWidget:{}},gp="/doubao-apps-framework.template.js",gm="/doubao-apps-api.template.js",gh=(x,e,t="/assets/framework/")=>{let r=e?t.replace(/\/+$/,""):"",a=(x,t,a)=>({libraryName:a,url:`${r}${x}`,background:{sectionPath:t},mainThread:{sectionPath:`${t}__main-thread`},async:!!e});return{"@byted-doubao-apps/bridge-base":a(gm,"api"),"@byted-doubao-apps/open-api":a(gm,"api"),...Object.fromEntries(Object.entries(iz).map(([e,t])=>[e,a(x?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",t])])),[`${c6}/api`]:a(gm,"api"),[`${c4}/api`]:a(gm,"api"),[c6]:a(gp,"framework"),[c4]:a(gp,"framework"),"@byted-doubao-apps/components":a(gp,"components"),[c7(c6)]:a(gp,"components"),[c7(c4)]:a(gp,"components")}},gE=(0,k.createRequire)(import.meta.url);function gj(x,e){for(let t of x)try{return gE.resolve(t,{paths:e})}catch{}throw Error(`无法解析以下候选包:${x.join(", ")}`)}class gg{pluginSystem;constructor(x){this.pluginSystem=x}async createEntry(x){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return x.setPages(Object.fromEntries(Object.entries(x.pages).filter(([x])=>x in e))),x.setWidgets(Object.fromEntries(Object.entries(x.widgets).filter(([x])=>x in e))),e}async createConfig({config:x}){var e,t,r,a,n;let{context:_}=x,{appDirectory:A,command:s,metadata:i,rootPath:o}=_,l=x.context.environment,c="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:l}),x.context.setEnvironment(l);let v=s===rV.DEV,d=await this.createEntry(_),f=c9(A),b=[A,r4.dirname((0,jT.fileURLToPath)(import.meta.url))],u=gE.resolve("@lynx-js/react/transform"),h=new Set([...Object.keys(x.context.widgets),...Object.keys(x.context.pages)]),S=h.size>0||_.normalizedAppConfig.tools.entryNames.length>0;S&&await dh({widgets:x.context.widgets,pages:x.context.pages,entries:d,collector:i,normalizedAppConfig:x.context.normalizedAppConfig,define:x.context.userConfig?.source?.define});let I={include:x.options.source?.include,exclude:x.options.source?.exclude,decorators:x.options.source?.decorators,define:{...x.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(x.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},N=x=>[iK,iQ,x.filename],B={...I,entry:Object.fromEntries(Object.entries(d).map(([x,e])=>[x,N(e)]))},F=Object.fromEntries(Object.entries(d).filter(([x])=>h.has(x))),w=new Map(Object.keys(F).map(x=>[vu(x),x])),C={...B,entry:Object.fromEntries(Object.entries(F).map(([x,e])=>[vu(x),N(e)])),define:{...B.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},P=[...vA()?[]:[v9({externals:gh(v),globalObject:"lynx"})]],D=[function({metadata:x,resolveAppInfo:e,resolveVersionTag:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,a)=>{let n=a?.environment?.name==="web"?vc:vl;r.plugin(vv.name).use(vv,[{metadata:x,resolveAppInfo:e,resolveVersionTag:t,isNative:a?.environment?.name!=="web",shouldInjectAsset:n}])})}}}({metadata:i,resolveAppInfo:()=>x.context.resolveAppInfo(),resolveVersionTag:()=>x.context.versionTag})],L={source:{...B,define:{...B.define,...vA()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(gE(gE.resolve(`${f}/package.json`,{paths:[A]})).version)}:{}}},output:{distPath:{image:"base/static/image",svg:"base/static/svg"}},...!v?{tools:{rspack:{output:{publicPath:"/"}}}}:{},plugins:P},q=[function x({metadata:e,entry:t,lynxConfigs:r,resolveSigningEncryptionOptions:a,onProcessDuration:n}){return{name:x.name,setup(x){x.modifyBundlerChain((_,A)=>{if(A?.environment?.name==="web")return;let s=x.useExposed(Symbol.for("LynxTemplatePlugin"));_.plugin(dI.name).use(dI,[s.LynxTemplatePlugin,e,t,a,n,r])})}}}({metadata:i,entry:d,lynxConfigs:{internal:x.context.internal,config:x.context.appConfig.lynxConfig,entries:Object.fromEntries(Object.entries({...x.context.normalizedAppConfig.pages.entries,...x.context.normalizedAppConfig.widgets.entries}).map(([x,e])=>[x,e.lynxConfig]))},resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(x.context.compileLifecycle.viewTemplateProcessDurationMs,e)}}),function({context:x,normalizeEntryName:e}){return{name:"template-widget-entry-plugin",setup(t){t.modifyBundlerChain((t,r)=>{let a=r?.environment?.name;t.plugin("template-widget-entry-plugin").use(go,[{markTemplateWidgetEntry:e=>{x.addTemplateWidgetEntry(e)},normalizeEntryName:x=>e?.(x,a)}])})}}}({context:x.context,normalizeEntryName:(x,e)=>"web"===e?w.get(x):x}),(e=this.pluginSystem,t=x.context,{name:"output-plugin",setup(x){let r={pluginSystem:e,context:t};x.modifyBundlerChain((x,e)=>{e?.environment?.name!=="web"&&x.plugin("output-plugin").use(gs,[r])})}}),...s===rV.DEV&&S?[function({context:x}){let e;return x.getWidgetViewDataTemplates=async()=>{if(e)return e;try{e=function(x,e,t){let r=function(x){let e,t=(0,k.createRequire)(r4.join(x,"package.json"));try{e=t.resolve("typescript")}catch(x){return}return t(e)}(x);if(!r)return{templatesByEntry:{},templatesByWidget:{}};let a=[...new Set(Object.values(e).map(({filename:x})=>x))],n=r.createProgram({options:function(x,e){let t={allowJs:!0,checkJs:!1,jsx:x.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:x.ScriptTarget.ESNext},r=x.findConfigFile(e,r5.existsSync);if(!r)return t;let a=x.readConfigFile(r,x.sys.readFile);return a.error?t:{...x.parseJsonConfigFileContent(a.config,x.sys,r4.dirname(r)).options,...t}}(r,x),rootNames:a}),_=n.getTypeChecker(),A=Object.fromEntries(Object.entries(e).map(([x,{filename:e}])=>{let t,a=n.getSourceFile(e);return[op(x),a?(t={},!function x(e){if(r.isCallExpression(e)&&("getViewData"===gb(r,e.expression)||"useViewData"===gb(r,e.expression))&&e.typeArguments?.[0]){let x=_.getTypeFromTypeNode(e.typeArguments[0]);for(let a of _.getPropertiesOfType(x)){let n=a.valueDeclaration??a.declarations?.[0]??e;t[a.getName()]=function x(e,t,r,a,n){let _=(t.isUnion()?t.types:[t]).filter(x=>!(x.flags&(e.TypeFlags.Undefined|e.TypeFlags.Never)));if(_.some(x=>x.flags&e.TypeFlags.Null))return null;if(_.some(x=>x.flags&e.TypeFlags.StringLike))return"";if(_.some(x=>x.flags&(e.TypeFlags.NumberLike|e.TypeFlags.BigIntLike)))return 0;if(_.some(x=>x.flags&e.TypeFlags.BooleanLike))return!1;if(_.some(x=>r.isArrayType(x)||r.isTupleType(x)))return[];let A=_.find(x=>x.flags&e.TypeFlags.Object);if(!A||n.has(A))return{};n.add(A);let s=Object.fromEntries(r.getPropertiesOfType(A).map(t=>{let _=t.valueDeclaration??t.declarations?.[0]??a;return[t.getName(),x(e,r.getTypeOfSymbolAtLocation(t,_),r,_,n)]}));return n.delete(A),s}(r,_.getTypeOfSymbolAtLocation(a,n),_,n,new Set([x]))}}r.forEachChild(e,x)}(a),t):{}]})),s=Object.fromEntries(Object.keys(e).map(x=>{let r=op(x);return[vp(e,t,x),A[r]??{}]}));return{templatesByEntry:A,templatesByWidget:s}}(x.appDirectory,x.widgets,x.metadata.getData().widgets)}catch{e=gu}return e},{name:"WidgetViewDataPlugin",setup(x){x.onAfterDevCompile(({stats:x})=>{x.hasErrors()||(e=void 0)})}}}({context:x.context})]:[],(({context:x})=>({name:"DevServerLogPlugin",setup(e){let t,r=!1,a=!1,n=process.env.DEV_SERVER_HOST;if("dev"===e.context.action&&void 0!==n){let x=new URL(n),t="https:"===x.protocol?"wss":"ws";e.modifyEnvironmentConfig({order:"post",handler:(e,{mergeEnvironmentConfig:r})=>r(e,{dev:{assetPrefix:n,client:{host:x.hostname,port:x.port,protocol:t}},output:{assetPrefix:n}})}),e.modifyBundlerChain({order:"post",handler(e){let r=e.resolve.alias.get("@lynx-js/webpack-dev-transport/client");if("string"!=typeof r)return;let[a,n]=r.split("?"),_=new URLSearchParams(n);_.set("hostname",x.hostname),_.set("port",x.port),_.set("protocol",t),e.resolve.alias.set("@lynx-js/webpack-dev-transport/client",`${a}?${_}`)}})}e.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{setup({server:x}){x.middlewares.use(j0)}}})),e.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DevServerLogPlugin",e=>x.finishInitialDevCompile(e))}),e.onAfterDevCompile(async({stats:n})=>{if(n.hasErrors())return void x.finishInitialDevCompile(Error(n.toString({all:!1,errors:!0,colors:!1})));if(r)return;let{devServer:_}=e.context;if(!_)return;r=!0;let A=await ol({debugDriver:x.userConfig.debugDriver,skipAdbForegroundAppWatch:x.userConfig.skipAdbForegroundAppWatch}).catch(dJ);a||(x.finishInitialDevCompile(),jW({context:x,port:_.port,driver:A,isSigned:x.isSignedEncryption,onCleanupReady(x){a?x():t=x}}).catch(x=>{a||os.error("初始化开发服务操作失败",{error:x})}))}),e.onCloseDevServer(()=>{a=!0,x.devServerAbort.abort(),t?.(),t=void 0})}}))({context:x.context}),function({context:x}){let e="KitMonitorPlugin";return{name:e,setup(t){if(t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.finishMake.tap(e,()=>{gr(x.compileLifecycle,"moduleProcess",Date.now())}),r.hooks.emit.tap(e,()=>{gr(x.compileLifecycle,"assetProcess",Date.now())}),r.hooks.failed.tap(e,e=>{gn.report({appDirectory:x.appDirectory,context:x,scene:x.compileLifecycle.scene??(x.command===rV.DEV?"dev_initial":x.command),status:"failed",errorStage:"compile",error:e})})}),x.command!==rV.DEV){let e=x.command;t.onBeforeBuild(()=>{let t=Date.now();gt(x.compileLifecycle,{scene:e,commandStartTime:x.compileLifecycle.commandStartTime??t,compileStartTime:t})}),t.onAfterBuild(({stats:t})=>{g_(x,e,t)})}else t.onBeforeDevCompile(({isFirstCompile:e})=>{let t=Date.now();gt(x.compileLifecycle,{scene:e?"dev_initial":"hot_update",commandStartTime:e?x.compileLifecycle.commandStartTime??t:t,compileStartTime:t})}),t.onAfterDevCompile(({stats:e})=>{g_(x,x.compileLifecycle.scene??"dev_initial",e)})}}}({context:x.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(x){x.onBeforeCreateCompiler(({bundlerConfigs:x})=>{let{BytedRsdoctorPlugin:e}=gE(gj(["@byted/rsdoctor"],b));for(let t of x){let x=r4.join(t.output?.path??"",`.rsdoctor-${t.name}`);t.plugins??=[],t.plugins.push(new e({disableClientServer:!0,supports:{banner:!0},output:{reportDir:x}}))}})}}]:[],(r=this.pluginSystem,a=x.context,{name:"view-hooks-plugin",setup(x){x.modifyBundlerChain((x,e)=>{e?.environment?.name==="web"||x.plugin("view-hooks-plugin").use(gl,[{pluginSystem:r,context:a}])})}}),(({getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:n})=>({name:"lynx:encode-worker",async setup(_){vs()||_.modifyBundlerChain((_,A)=>{A?.environment?.name!=="web"&&_.plugin(dS.name).use(dS,[{getAppAssetPath:x,getAppMapAssetPath:e,engineVersion:t,metadata:r,resolveSigningEncryptionOptions:a,onProcessDuration:n}]).end()})}}))({getAppAssetPath:()=>x.context.appAssetPath,getAppMapAssetPath:()=>x.context.appMapAssetPath,metadata:x.context.metadata,resolveSigningEncryptionOptions:()=>x.context.resolveSigningEncryptionOptions(),onProcessDuration:e=>{x.context.compileLifecycle.appTemplateProcessDurationMs+=e}}),...x.rsbuildPlugins||[]],T=[{name:"web-virtual-entry-plugin",setup(x){x.modifyBundlerChain((x,{environment:e})=>{"web"===e.name&&x.plugin(gf.name).use(gf,[F])})}},(n=x.context,{name:"web-output-plugin",setup(x){x.modifyBundlerChain({order:"post",handler(x,{environment:e}){if("web"===e.name){let e=".rspeedy/";for(let t of Object.keys(x.plugins.entries()??{}))t.startsWith("lynx:template-")&&x.plugin(t).tap(x=>{let t=x[0];return t?.intermediate?.startsWith(e)&&(t.intermediate=t.intermediate.slice(e.length)),x});x.plugins.has("lynx:sourcemap")&&x.plugin("lynx:sourcemap").tap(x=>{var e;let t,r=x[0];return r.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],e=n.appDirectory,t=r4.resolve(e),r.moduleFilenameTemplate=({absoluteResourcePath:x,query:e=""})=>{let r=r4.relative(t,x),a=".."!==r&&!r.startsWith(`..${r4.sep}`)&&!r4.isAbsolute(r),n=a?gc(r):gc(x).replace(/^\/+/,"");return`${a?"file":"webpack"}:///${n}${e}`},x}),x.plugin(gd.name).use(gd,[n])}}})}})],R=E({mode:s===rV.DEV?"development":"production",environments:S?{lynx:L,web:{source:C,output:{distPath:{css:"base/web-common",js:"base/web-common",image:"base/web-static/image",svg:"base/web-static/svg",font:"base/web-static/font",media:"base/web-static/media"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!v&&"cheap-module-source-map",css:!1}},plugins:[v9({externals:gh(s===rV.DEV,!0,x.options.frameworkPrefix),globalObject:"lynx"})]}}:{lynx:L},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(x,e,t=r4.join(r4.dirname((0,jT.fileURLToPath)(import.meta.url)),"components-loader.js"),r=gj){for(let x of[r4.join(r4.dirname((0,jT.fileURLToPath)(import.meta.url)),"../loader/components-loader/index.js"),t])if((0,r5.existsSync)(x))return x;return r(e===c4?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],x)}(b,f),options:{frameworkPackage:f,widgetEntryPaths:Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>r4.resolve(A,x))}}]},plugins:[new dM(Object.values(x.context.widgets??{}).filter(({internal:x})=>!x).map(({filename:x})=>r4.resolve(A,x))),new j.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:j.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...I,entry:{}},server:{cors:!0,host:x.context.devServerHost,port:v&&process.env.DEV_SERVER_PORT?Number(process.env.DEV_SERVER_PORT):void 0},dev:{writeToDisk:Z(),hmr:s===rV.DEV},output:{distPath:{js:"base/common",root:o||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...x.options.resolve?.alias||{}}},performance:{printFileSize:Z(),...vA()&&!c?{chunkSplit:{strategy:"split-by-experience"}}:{}},...c?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(x){(function(x){let{LAYERS:e,lazy:t,rootPath:r,elementTemplate:a}=x??{};return{name:"lynx:react-alias",setup(x){let n=(0,k.createRequire)(import.meta.url),_=n.resolve("@lynx-js/react/package.json",{paths:[r??x.context.rootPath]}),{version:A}=n(_),s=r4.dirname(_);x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{source:{include:[s]}})),x.modifyBundlerChain(async(n,{isProd:_,rspack:i})=>{if(Object.hasOwn(n,dn))return;let o=d_(i,r??x.context.rootPath,t?["lazy","import"]:["import"]),l=d_(i,s,["import"]);x.expose(Symbol.for("@lynx-js/react/internal:resolve"),{resolve:o,version:A}),Object.defineProperty(n,dn,{value:!0});let[c,v,d,f,b,u,p,m,h,E,j,g,y,S]=await Promise.all([o("@lynx-js/react/jsx-runtime"),o("@lynx-js/react/lepus/jsx-runtime"),o("@lynx-js/react/jsx-dev-runtime"),o("@lynx-js/react/lepus/jsx-dev-runtime"),a?o("@lynx-js/react/element-template/jsx-runtime"):Promise.resolve(null),a?o("@lynx-js/react/element-template/jsx-dev-runtime"):Promise.resolve(null),l("preact/hooks"),o("@lynx-js/react/hooks"),o("@lynx-js/react/lepus/hooks"),o("@lynx-js/react"),o("@lynx-js/react/lepus"),da()(A,"0.111.9999")?o("@lynx-js/react/compat"):Promise.resolve(null),a?o("@lynx-js/react/element-template"):Promise.resolve(null),a?o("@lynx-js/react/element-template/internal"):Promise.resolve(null)]),I={background:c,mainThread:b??v},N={background:d,mainThread:u??f};n.module.rule("react:jsx-runtime:main-thread").issuerLayer(e.MAIN_THREAD).resolve.alias.set("react/jsx-runtime",I.mainThread).set("react/jsx-dev-runtime",N.mainThread).set("@lynx-js/react/jsx-runtime",I.mainThread).set("@lynx-js/react/jsx-dev-runtime",N.mainThread).set("@lynx-js/react/lepus$",j).set("@lynx-js/react/lepus/jsx-runtime",I.mainThread).set("@lynx-js/react/lepus/jsx-dev-runtime",N.mainThread).set("preact/hooks",h).set("@lynx-js/react/hooks",h).set("@lynx-js/react/lepus/hooks",h).set("@lynx-js/react-signals$","@lynx-js/react-signals/lepus").end().end().end().rule("react:jsx-runtime:background").issuerLayer(e.BACKGROUND).resolve.alias.set("react/jsx-runtime",I.background).set("react/jsx-dev-runtime",N.background).set("@lynx-js/react/jsx-runtime",I.background).set("@lynx-js/react/jsx-dev-runtime",N.background).set("@lynx-js/react/lepus$",y??E).set("preact/hooks",p).set("@lynx-js/react/hooks",m).end().end().end().end();let B=new Map;for(let[x,e]of(a&&B.set("experimental/lazy/import",r4.join(s,"runtime/lazy/element-template-import.js")),await Promise.all(["experimental/lazy/import","internal","legacy-react-runtime","runtime-components","worklet-runtime/bindings"].map(async x=>{let e=`@lynx-js/react/${x}`,t=B.get(x)??await o(e);return[`${e}$`,t]}))))n.resolve.alias.set(x,e);_&&(n.resolve.alias.set("@lynx-js/react/debug$",!1),process.env.REACT_DEVTOOL||n.resolve.alias.set("@lynx-js/preact-devtools$",!1)),n.resolve.alias.has("react$")||n.resolve.alias.set("react$",E),n.resolve.alias.set("@lynx-js/react$",y??E).set("@lynx-js/react/internal$",S??n.resolve.alias.get("@lynx-js/react/internal$")).set("@lynx-js/react/jsx-runtime",I.background).set("@lynx-js/react/jsx-dev-runtime",N.background),a&&n.resolve.alias.set("@lynx-js/react/element-template$",y).set("@lynx-js/react/element-template/internal$",S).set("@lynx-js/react/element-template/jsx-runtime",b).set("@lynx-js/react/element-template/jsx-dev-runtime",u),g&&n.resolve.alias.set("@lynx-js/react/compat$",g),await Promise.all(["preact","preact/compat","preact/debug","preact/devtools","preact/test-utils","preact/jsx-runtime","preact/jsx-dev-runtime","preact/compat","preact/compat/client","preact/compat/server","preact/compat/jsx-runtime","preact/compat/jsx-dev-runtime","preact/compat/scheduler"].map(x=>l(x).then(e=>{n.resolve.alias.set(`${x}$`,e)})))})}}})({LAYERS:p,lazy:!1,rootPath:r4.dirname((0,jT.fileURLToPath)(import.meta.url))}).setup(x)}},{name:"set-server.printUrls-false",setup(x){x.modifyRsbuildConfig((x,{mergeRsbuildConfig:e})=>e(x,{server:{printUrls:!1}}))}},m({compat:{componentsPkg:[],newRuntimePkg:f,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...c5]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(x){x.modifyBundlerChain((x,{CHAIN_ID:e})=>{let t=x.module.rule(e.RULE.JS).oneOf(e.ONE_OF.JS_MAIN);for(let x of[p.BACKGROUND,p.MAIN_THREAD]){let e=t.oneOfs.get(x)?.uses.get(x);if(!e)throw Error(`未找到该层的 React 转换加载器:${x}`);e.tap(x=>({...x,transformPath:u}))}})}},function(x){let{compilerOptionsKeys:e=vI.compilerOptionsKeys,configKeys:t=vI.configKeys,validate:r=vV,dslPluginName2PkgName:a=vH,upgradeRspeedyLink:n="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return r(x),{name:"lynx:config",async setup(r){r.expose(Symbol.for("lynx.config"),{config:x}),"rstest"!==r.context.callerName&&r.modifyBundlerChain(_=>{let A=r.useExposed(Symbol.for("LynxTemplatePlugin"));if(!A){let x="Rspeedy and plugins";throw Object.entries(a).forEach(([e,t])=>{r.isPluginExists(e)&&(x=t)}),Error(`\
428
+ [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${v$("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
429
429
 
430
430
  Please upgrade ${x} to latest version.
431
431
 
432
- See ${vq(vK().yellow("Upgrade Rspeedy"),n)} for more details.
433
- `)}let{LynxTemplatePlugin:s}=A;_.plugin("lynx:config").use(v$,[{LynxTemplatePlugin:s,config:x,compilerOptionsKeys:e,configKeys:t}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableReloadLifecycle:!0}),y(),g(),...I?[]:D,...L,...T,...I?R:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:$}),$}}async function gS(x,e){let t=new gy(e),r=await t.createConfig({config:x}),a=await h({rspeedyConfig:r,cwd:x.context.appDirectory});return a.removePlugins(["lynx:react-alias"]),a}async function gI(x,e){var t;let{entry:r}=await ve({config:x,pluginSystem:e});return await gS({...x,rsbuildPlugins:[...x.rsbuildPlugins||[],(t={context:x.context,entry:r,pluginSystem:e},{name:"worker-in-view-plugin",setup(x){x.modifyRspackConfig((x,{environment:e})=>{var r,a,n;let _;("lynx"===e.name||"web"===e.name)&&(r=x,a=t,n=e.name,r.entry??={},_=r.entry,Object.entries(a.entry).forEach(([x,e])=>{_[x]={filename:"web"===n?`${x}.js`:`base/${x}${va()?".js":".template.js"}`,import:"web"===n&&"development"===r.mode&&"app"===x?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",e.filename]:e.filename,layer:p.BACKGROUND}}),x.plugins.push(new vE(t,"lynx"===e.name)),"web"===e.name&&x.plugins.push(new vu))})}})]},e)}function gN(x){if(x instanceof Error)return x.message;if("string"==typeof x)return x;try{return JSON.stringify(x)??String(x)}catch{return String(x)}}let gB=x=>{try{return r5.statSync(x,{throwIfNoEntry:!1})?.isFile()}catch(x){return!1}};async function gF({internal:x,appKey:e}){try{return await fB({internal:x,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/dek/public_key`})}catch(x){throw on.error("获取 KEK 失败",{error:x,appKey:e,operation:"get-kek"}),x}}async function gw(x,e,t,r){if(!(r||vt("DISABLE_SIGNING_ENCRYPTION")||vt("LEGACY_FRAMEWORK"))){if(x)return x;if("production"===process.env.NODE_ENV&&e===rV.DEPLOY){if(!t)throw Error("获取 KEK 需要 appId");let{data:x}=await gF({internal:!1,appKey:t}),e=Number(Object.keys(x.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:x.keys[e],key_id:e,salt:""}}}}}let gC=r4.join("node_modules",".doubao-dev","config.json");function gP(x,e,t){if(t){let e=r4.isAbsolute(t)?t:r4.resolve(x,t);if(r5.existsSync(e))return e;oa.warn("未找到配置文件",{path:e})}for(let t of i2.map(t=>r4.resolve(x,`${e}${t}`)))if(gB(t))return t;return!1}async function gk(x){let e=(0,C.createJiti)((0,jq.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await e.import(x,{default:!0})}async function gD({cwd:x=process.cwd(),customConfigFile:e}){let t=gP(x,"doubao.config",e);if(!t)return{};try{return await gk(t)}catch(x){throw oa.error("加载配置文件失败",{path:t}),x}}async function gL({cwd:x=process.cwd()}={}){let e=gP(r4.resolve(x,"src"),i1);if(e)try{return await gk(e)}catch(x){throw oa.error("加载应用配置文件失败",{path:e}),x}}async function gq(x){let e=globalThis,t=Object.prototype.hasOwnProperty.call(e,"defineAppConfig"),r=e.defineAppConfig;e.defineAppConfig=x=>x;try{return await gk(x)}finally{t?e.defineAppConfig=r:delete e.defineAppConfig}}async function gT({cwd:x=process.cwd()}={}){let e=gP(r4.resolve(x,"src"),i1);if(e)try{let x=await gq(e);return{...void 0!==x.darkMode?{darkMode:x.darkMode}:{},...void 0!==x.chat?{chat:x.chat}:{},...Array.isArray(x.pages)?{pages:x.pages}:{},...Array.isArray(x.widgets)?{widgets:x.widgets}:{}}}catch(x){throw oa.error("加载 Taro 应用配置文件失败",{path:e}),x}}let gR=async(x,e=r4.basename(x))=>{if(!r5.existsSync(x))return{};let t={};for(let r of(await aa.readdir(x))){let a=r4.resolve(x,r);if(!r5.statSync(a).isDirectory())continue;let n=r4.resolve(a,"index.tsx");r5.existsSync(n)&&(t[`${e}/${r}/index`]={folderName:`${r}/index`,renderType:om.REACT_LYNX,filename:n})}return t},g$=async(x,e=r4.basename(x))=>{if(!r5.existsSync(x))return{viewEntries:{},apiEntries:{}};let t=await gR(x,e),r={},a=r4.resolve(x,"login.ts");r5.existsSync(a)&&(r[`${e}/login`]={filename:a,folderName:x});let n=r4.resolve(x,"privacy.ts");return r5.existsSync(n)&&(r[`${e}/privacy`]={filename:n,folderName:x}),{viewEntries:t,apiEntries:r}},gG=async(x,e)=>r5.existsSync(x)?(await aa.readdir(x)).reduce((t,r)=>{let a=r4.resolve(x,r);return r5.statSync(a).isDirectory()&&r5.existsSync(r4.resolve(a,e))&&(t[r]=r4.resolve(a,e)),t},{}):{};function gO(x,e){return cW(x,e).replace(/\.(?:t|j)sx?$/i,"")}function gX(x){return r4.resolve(x,"app.ts")}function gK(x,e,t,r){let a=`${t}/`;if(!e.startsWith(a))throw Error(`${t} 配置键必须以 "${a}" 开头:${e}`);let n=e.slice(a.length),_=r4.resolve(x,t,`${n}${r}`);if(!r5.existsSync(_))throw Error(`配置的入口文件不存在:${_}(入口:${e})`);return{relativeEntry:n,filename:_}}function gQ(x,e){let t=e.entries[x]?.name;if(void 0===t)return lJ(x);if("string"!=typeof t||!t.trim())throw Error(`配置的 Tool 名称必须是非空字符串:${x}`);return t.trim()}let gM=async(x,e={entryNames:[],entries:{}})=>{let t=r4.resolve(x,"tools"),r={...await gG(t,"index.ts")};e.entryNames.forEach(t=>{let{filename:a}=gK(x,t,"tools",".ts"),n=gQ(t,e),_=r[n];if(_&&_!==a)throw Error(`Tool 名称 "${n}" 已被其他入口使用:${_}`);r[n]=a});let a=gX(x);return{tools:r,app:r5.existsSync(a)?a:void 0}},gZ=async(x,e)=>{let t=r4.resolve(x,"pages"),r=r4.resolve(x,"widgets"),a=r4.resolve(x,"auth"),n=r4.resolve(x,"mcp-ui"),[_,A,s,i]=await Promise.all([gR(t),gR(r),g$(n),g$(a)]),o=Object.keys(i.viewEntries).length>0||Object.keys(i.apiEntries).length>0?i:s,l=e.pages,c=e.widgets,v=(e,t,r)=>{let a={...e};return t.forEach(e=>{if(a[e])return;let{relativeEntry:t,filename:n}=gK(x,e,r,".tsx");a[e]={folderName:t,renderType:om.REACT_LYNX,filename:n,isVirtualFile:!1}}),a},d=v(_,l.entryNames,"pages");return{widgets:v(A,c.entryNames,"widgets"),pages:d,auth:o}};function gJ(x,e,t=!1,r=!1){let a=c4(e);return Object.keys(x).reduce((n,_)=>{let{filename:A}=x[_],s=r&&x[_].isLoginPage?"defineLoginPage":r?"definePage":"defineWidget",i=`${iX}${r4.sep}${_}${r4.extname(A)}`,o=cW(r4.join(e,i,".."),A);return n[_]=new c5(i),n[_].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:a,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:s,name:s},{propertyName:"getViewContext",name:"getViewContext"}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]}),n[_].appendContent(`
432
+ See ${v$(vZ().yellow("Upgrade Rspeedy"),n)} for more details.
433
+ `)}let{LynxTemplatePlugin:s}=A;_.plugin("lynx:config").use(vX,[{LynxTemplatePlugin:s,config:x,compilerOptionsKeys:e,configKeys:t}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableReloadLifecycle:!0}),y(),g(),...S?[]:P,...D,...q,...S?T:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:R}),R}}async function gy(x,e){let t=new gg(e),r=await t.createConfig({config:x}),a=await h({rspeedyConfig:r,cwd:x.context.appDirectory});return a.removePlugins(["lynx:react-alias"]),a}async function gS(x,e){var t;let{entry:r}=await vn({config:x,pluginSystem:e});return await gy({...x,rsbuildPlugins:[...x.rsbuildPlugins||[],(t={context:x.context,entry:r,pluginSystem:e},{name:"worker-in-view-plugin",setup(x){x.modifyRspackConfig((x,{environment:e})=>{var r,a,n;let _;("lynx"===e.name||"web"===e.name)&&(r=x,a=t,n=e.name,r.entry??={},_=r.entry,Object.entries(a.entry).forEach(([x,e])=>{_[x]={filename:"web"===n?`${x}.js`:`base/${x}${vs()?".js":".template.js"}`,import:"web"===n&&"development"===r.mode&&"app"===x?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",e.filename]:e.filename,layer:p.BACKGROUND}}),x.plugins.push(new vy(t,"lynx"===e.name)),"web"===e.name&&x.plugins.push(new vh))})}})]},e)}function gI(x){if(x instanceof Error)return x.message;if("string"==typeof x)return x;try{return JSON.stringify(x)??String(x)}catch{return String(x)}}let gN=x=>{try{return r5.statSync(x,{throwIfNoEntry:!1})?.isFile()}catch(x){return!1}};async function gB({internal:x,appKey:e}){try{return await fw({internal:x,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/dek/public_key`})}catch(x){throw on.error("获取 KEK 失败",{error:x,appKey:e,operation:"get-kek"}),x}}async function gF(x,e,t,r){if(!(r||v_("DISABLE_SIGNING_ENCRYPTION")||v_("LEGACY_FRAMEWORK"))){if(x)return x;if("production"===process.env.NODE_ENV&&e===rV.DEPLOY){if(!t)throw Error("获取 KEK 需要 appId");let{data:x}=await gB({internal:!1,appKey:t}),e=Number(Object.keys(x.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:x.keys[e],key_id:e,salt:""}}}}}let gw=r4.join("node_modules",".doubao-dev","config.json");function gC(x,e,t){if(t){let e=r4.isAbsolute(t)?t:r4.resolve(x,t);if(r5.existsSync(e))return e;oa.warn("未找到配置文件",{path:e})}for(let t of i2.map(t=>r4.resolve(x,`${e}${t}`)))if(gN(t))return t;return!1}async function gP(x){let e=(0,C.createJiti)((0,jT.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await e.import(x,{default:!0})}async function gk({cwd:x=process.cwd(),customConfigFile:e}){let t=gC(x,"doubao.config",e);if(!t)return{};try{return await gP(t)}catch(x){throw oa.error("加载配置文件失败",{path:t}),x}}async function gD({cwd:x=process.cwd()}={}){let e=gC(r4.resolve(x,"src"),i1);if(e)try{return await gP(e)}catch(x){throw oa.error("加载应用配置文件失败",{path:e}),x}}async function gL(x){let e=globalThis,t=Object.prototype.hasOwnProperty.call(e,"defineAppConfig"),r=e.defineAppConfig;e.defineAppConfig=x=>x;try{return await gP(x)}finally{t?e.defineAppConfig=r:delete e.defineAppConfig}}async function gq({cwd:x=process.cwd()}={}){let e=gC(r4.resolve(x,"src"),i1);if(e)try{let x=await gL(e);return{...void 0!==x.darkMode?{darkMode:x.darkMode}:{},...void 0!==x.chat?{chat:x.chat}:{},...Array.isArray(x.pages)?{pages:x.pages}:{},...Array.isArray(x.widgets)?{widgets:x.widgets}:{}}}catch(x){throw oa.error("加载 Taro 应用配置文件失败",{path:e}),x}}let gT=async(x,e=r4.basename(x))=>{if(!r5.existsSync(x))return{};let t={};for(let r of(await aa.readdir(x))){let a=r4.resolve(x,r);if(!r5.statSync(a).isDirectory())continue;let n=r4.resolve(a,"index.tsx");r5.existsSync(n)&&(t[`${e}/${r}/index`]={folderName:`${r}/index`,renderType:om.REACT_LYNX,filename:n})}return t},gR=async(x,e=r4.basename(x))=>{if(!r5.existsSync(x))return{viewEntries:{},apiEntries:{}};let t=await gT(x,e),r={},a=r4.resolve(x,"login.ts");r5.existsSync(a)&&(r[`${e}/login`]={filename:a,folderName:x});let n=r4.resolve(x,"privacy.ts");return r5.existsSync(n)&&(r[`${e}/privacy`]={filename:n,folderName:x}),{viewEntries:t,apiEntries:r}},g$=async(x,e)=>r5.existsSync(x)?(await aa.readdir(x)).reduce((t,r)=>{let a=r4.resolve(x,r);return r5.statSync(a).isDirectory()&&r5.existsSync(r4.resolve(a,e))&&(t[r]=r4.resolve(a,e)),t},{}):{};function gG(x,e){return c3(x,e).replace(/\.(?:t|j)sx?$/i,"")}function gO(x){return r4.resolve(x,"app.ts")}function gX(x,e,t,r){let a=`${t}/`;if(!e.startsWith(a))throw Error(`${t} 配置键必须以 "${a}" 开头:${e}`);let n=e.slice(a.length),_=r4.resolve(x,t,`${n}${r}`);if(!r5.existsSync(_))throw Error(`配置的入口文件不存在:${_}(入口:${e})`);return{relativeEntry:n,filename:_}}function gK(x,e){let t=e.entries[x]?.name;if(void 0===t)return cz(x);if("string"!=typeof t||!t.trim())throw Error(`配置的 Tool 名称必须是非空字符串:${x}`);return t.trim()}let gQ=async(x,e)=>{let t=r4.resolve(x,"tools"),r=e?{}:await g$(t,"index.ts");e?.entryNames.forEach(t=>{let{filename:a}=gX(x,t,"tools",".ts"),n=gK(t,e),_=r[n];if(_&&_!==a)throw Error(`Tool 名称 "${n}" 已被其他入口使用:${_}`);r[n]=a});let a=gO(x);return{tools:r,app:r5.existsSync(a)?a:void 0}},gM=async(x,e)=>{let t=r4.resolve(x,"pages"),r=r4.resolve(x,"widgets"),a=r4.resolve(x,"auth"),n=r4.resolve(x,"mcp-ui"),[_,A,s,i]=await Promise.all([e?{}:gT(t),e?{}:gT(r),gR(n),gR(a)]),o=Object.keys(i.viewEntries).length>0||Object.keys(i.apiEntries).length>0?i:s,l=e?.pages,c=e?.widgets,v=(e,t,r)=>{let a={...e};return t.forEach(e=>{let{relativeEntry:t,filename:n}=gX(x,e,r,".tsx");a[e]={folderName:t,renderType:om.REACT_LYNX,filename:n,isVirtualFile:!1}}),a},d=v(_,l?.entryNames??[],"pages");return{widgets:v(A,c?.entryNames??[],"widgets"),pages:d,auth:o}};function gZ(x,e,t=!1,r=!1){let a=c9(e);return Object.keys(x).reduce((n,_)=>{let{filename:A}=x[_],s=r&&x[_].isLoginPage?"defineLoginPage":r?"definePage":"defineWidget",i=`${iX}${r4.sep}${_}${r4.extname(A)}`,o=c3(r4.join(e,i,".."),A);return n[_]=new vx(i),n[_].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:a,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:s,name:s},{propertyName:"getViewContext",name:"getViewContext"}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]}),n[_].appendContent(`
434
434
  lynx.__DOUBAO_VIEW_TYPE__ = ${JSON.stringify(r?"page":"widget")};
435
435
 
436
436
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -450,7 +450,7 @@ root.render(<FC />);
450
450
  if (import.meta.webpackHot) {
451
451
  import.meta.webpackHot.accept()
452
452
  }
453
- `),n},{})}let gV={name:"AuthPlugin",async setup(x){vt("DISABLE_GENERATE_LOGIN_CARD")||vt("LEGACY_FRAMEWORK")||(x.view.hooks.modifyEnvironment.tapPromise(gV.name,async({environment:x})=>{x.useAuth=!0}),x.view.hooks.modifyEntryOption.tapPromise({name:gV.name,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:e})=>{let t,r,a,n,_,A,s,{isDev:i,auth:o,appDirectory:l}=x.context,c={},v=Object.keys(o.viewEntries).reduce((x,e)=>(x[e]={...o.viewEntries[e],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===e||"auth/mcp-login-page/index"===e||"mcp-ui/mcp-login-page/index"===e},x),{});return x.context.appendPages(v),e=Object.assign(e,(t=c4(l),r=`${iX}${r4.sep}${iZ}${r4.sep}${iH}.tsx`,c[a=`${iZ}/${iH}`]={filename:r,renderType:om.REACT_LYNX,folderName:iH,isVirtualFile:!0,isSpecial:!0,internal:!0},n=new c5(r),_=r4.join(l,r4.dirname(r)),A=Object.values(o.apiEntries).find(x=>"login"===r4.parse(x.filename).name),s=Object.values(o.apiEntries).find(x=>"privacy"===r4.parse(x.filename).name),n.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:t,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${t}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),A&&n.appendImports({moduleSpecifier:cW(_,A.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),s&&n.appendImports({moduleSpecifier:cW(_,s.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),n.appendContent(`
453
+ `),n},{})}let gJ={name:"AuthPlugin",async setup(x){v_("DISABLE_GENERATE_LOGIN_CARD")||v_("LEGACY_FRAMEWORK")||(x.view.hooks.modifyEnvironment.tapPromise(gJ.name,async({environment:x})=>{x.useAuth=!0}),x.view.hooks.modifyEntryOption.tapPromise({name:gJ.name,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:e})=>{let t,r,a,n,_,A,s,{isDev:i,auth:o,appDirectory:l}=x.context,c={},v=Object.keys(o.viewEntries).reduce((x,e)=>(x[e]={...o.viewEntries[e],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===e||"auth/mcp-login-page/index"===e||"mcp-ui/mcp-login-page/index"===e},x),{});return x.context.appendPages(v),e=Object.assign(e,(t=c9(l),r=`${iX}${r4.sep}${iZ}${r4.sep}${iH}.tsx`,c[a=`${iZ}/${iH}`]={filename:r,renderType:om.REACT_LYNX,folderName:iH,isVirtualFile:!0,isSpecial:!0,internal:!0},n=new vx(r),_=r4.join(l,r4.dirname(r)),A=Object.values(o.apiEntries).find(x=>"login"===r4.parse(x.filename).name),s=Object.values(o.apiEntries).find(x=>"privacy"===r4.parse(x.filename).name),n.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:t,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${t}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),A&&n.appendImports({moduleSpecifier:c3(_,A.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),s&&n.appendImports({moduleSpecifier:c3(_,s.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),n.appendContent(`
454
454
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
455
455
 
456
456
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -474,7 +474,7 @@ root.render(<FC />);
474
474
  if (import.meta.webpackHot) {
475
475
  import.meta.webpackHot.accept()
476
476
  }
477
- `:""),{[a]:n}),gJ(v,l,i,!0)),x.context.appendWidgets(c),{entry:e}}))}},gH="AppletDoubaoAppInfoPlugin",gU={name:gH,setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:gH,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:e})=>{let t="manifest"===x.context.permissionSource,r=x.context.command===rV.DEV||x.context.command===rV.BUILD||x.context.command===rV.DEPLOY;if(!t&&!r)return;let a=x.context.appId;if(!a&&!t)return;let n=t?function(x){let e,t=r4.join(x,"manifest.yaml");try{e=(0,sX.qg)(r5.readFileSync(t,"utf8"))}catch(x){throw Error(`无法读取权限配置:${t}`,{cause:x})}if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`manifest.yaml 必须是对象:${t}`);let r=e.permissions;if(void 0===r)return[];if(!Array.isArray(r))throw Error(`manifest.yaml 的 permissions 必须是数组:${t}`);return r.map((x,e)=>{if(!x||"string"!=typeof x.scope_name||!x.scope_name.trim()||void 0!==x.description&&"string"!=typeof x.description)throw Error(`manifest.yaml 的 permissions[${e}] 必须包含非空 scope_name 和可选的字符串 description:${t}`);return{scope_name:x.scope_name.trim(),description:x.description||x.scope_name.trim()}})}(x.context.appDirectory):x.context.permissions,_=a&&r?await x.context.resolveAppInfo():void 0;if(_||t){var A=e.getManifestAsset(x.context.manifestAssetPath);(void 0!==n||_)&&A.assignBasicManifest({permissions:Object.fromEntries((n??[]).filter(x=>"string"==typeof x?.scope_name&&!!x.scope_name.trim()).map(x=>{let e=x.scope_name.trim();return[e,{desc:"string"==typeof x.description&&x.description?x.description:e,apis:[]}]}))}),_?.appName&&A.mergeAppletManifest({name:_.appName}),_?.iconUrl&&A.mergeAppletManifest({icons:oP(_.iconUrl)})}})}},gY={name:"ExpiredWidgetPlugin",async setup(x){x.view.hooks.modifyEntryOption.tapPromise({name:gY.name,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:e})=>{let t,r,a,n,{isDev:_,appDirectory:A}=x.context,s={};return e=Object.assign(e,(t=c4(A),r=`${iX}${r4.sep}${iZ}${r4.sep}${iU}.tsx`,s[a=`${iZ}/${iU}`]={filename:r,renderType:om.REACT_LYNX,folderName:iU,isVirtualFile:!0,isSpecial:!0,internal:!0},(n=new c5(r)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:t,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${t}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),n.appendContent(`
477
+ `:""),{[a]:n}),gZ(v,l,i,!0)),x.context.appendWidgets(c),{entry:e}}))}},gV="AppletDoubaoAppInfoPlugin",gH={name:gV,setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:gV,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:e})=>{let t="manifest"===x.context.permissionSource,r=x.context.command===rV.DEV||x.context.command===rV.BUILD||x.context.command===rV.DEPLOY;if(!t&&!r)return;let a=x.context.appId;if(!a&&!t)return;let n=t?function(x){let e,t=r4.join(x,"manifest.yaml");try{e=(0,sX.qg)(r5.readFileSync(t,"utf8"))}catch(x){throw Error(`无法读取权限配置:${t}`,{cause:x})}if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`manifest.yaml 必须是对象:${t}`);let r=e.permissions;if(void 0===r)return[];if(!Array.isArray(r))throw Error(`manifest.yaml 的 permissions 必须是数组:${t}`);return r.map((x,e)=>{if(!x||"string"!=typeof x.scope_name||!x.scope_name.trim()||void 0!==x.description&&"string"!=typeof x.description)throw Error(`manifest.yaml 的 permissions[${e}] 必须包含非空 scope_name 和可选的字符串 description:${t}`);return{scope_name:x.scope_name.trim(),description:x.description||x.scope_name.trim()}})}(x.context.appDirectory):x.context.permissions,_=a&&r?await x.context.resolveAppInfo():void 0;if(_||t){var A=e.getManifestAsset(x.context.manifestAssetPath);(void 0!==n||_)&&A.assignBasicManifest({permissions:Object.fromEntries((n??[]).filter(x=>"string"==typeof x?.scope_name&&!!x.scope_name.trim()).map(x=>{let e=x.scope_name.trim();return[e,{desc:"string"==typeof x.description&&x.description?x.description:e,apis:[]}]}))}),_?.appName&&A.mergeAppletManifest({name:_.appName}),_?.iconUrl&&A.mergeAppletManifest({icons:oP(_.iconUrl)})}})}},gU={name:"ExpiredWidgetPlugin",async setup(x){x.view.hooks.modifyEntryOption.tapPromise({name:gU.name,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:e})=>{let t,r,a,n,{isDev:_,appDirectory:A}=x.context,s={};return e=Object.assign(e,(t=c9(A),r=`${iX}${r4.sep}${iZ}${r4.sep}${iU}.tsx`,s[a=`${iZ}/${iU}`]={filename:r,renderType:om.REACT_LYNX,folderName:iU,isVirtualFile:!0,isSpecial:!0,internal:!0},(n=new vx(r)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:t,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${t}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),n.appendContent(`
478
478
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
479
479
 
480
480
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -493,7 +493,7 @@ root.render(<FC />);
493
493
  if (import.meta.webpackHot) {
494
494
  import.meta.webpackHot.accept()
495
495
  }
496
- `:""),{[a]:n})),x.context.appendWidgets(s),{entry:e}})}},gz="LynxPlugin",gW={name:gz,async setup(x){x.view.hooks.modifyEnvironment.tapPromise(gz,async({environment:x})=>{x.useLynx=!0});let e={};x.view.hooks.modifyEntryOption.tapPromise({name:gz,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let{appDirectory:r,isDev:a,widgets:n,pages:_}=x.context;return e=t=Object.assign(t,gJ(n,r,a),gJ(_,r,a,!0)),{entry:t}}),x.view.hooks.collectMetaData.tapPromise({name:gz,stage:x.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{normalizedAppConfig:r,userConfig:a,widgets:n,pages:_}=x.context;await du({widgets:n,pages:_,entries:e,collector:t,normalizedAppConfig:r,define:a.source?.define})}),x.assets.hooks.beforeEmit.tapPromise({name:gz,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:e})=>{let{widgets:t,pages:r,app:a}=x.context.metadata.getInstance(),n=x.context.templateWidgetEntries;Object.keys(t).forEach(r=>{let a=t[r],_=`${r}/template.js`,A=e.getAsset(_);if(a&&A){let t=`${a.metadata.id}/template.js`;A.destination=t;let _=e.getManifestAsset(x.context.manifestAssetPath),s=a.toManifest(t,A.hashCode,om.LYNX);n.has(r)&&(s.titleType=oh.NONE),_.appendWidget(s)}}),Object.keys(r).forEach(t=>{let n=r[t],_=`${t}/template.js`,A=e.getAsset(_);if(n&&A){let t=lH(a.metadata.appId,n.metadata.path,"template.js");A.destination=t,e.getManifestAsset(x.context.manifestAssetPath).appendPage(n.toManifest(t,A.hashCode,om.LYNX))}})}),x.assets.hooks.afterEmit.tapPromise(gz,async({assets:x})=>{}),x.view.hooks.afterBuild.tapPromise(gz,async({stats:x})=>{})}},g0=`function toAppRuntimeTool(tool, id, key) {
496
+ `:""),{[a]:n})),x.context.appendWidgets(s),{entry:e}})}},gY="LynxPlugin",gz={name:gY,async setup(x){x.view.hooks.modifyEnvironment.tapPromise(gY,async({environment:x})=>{x.useLynx=!0});let e={};x.view.hooks.modifyEntryOption.tapPromise({name:gY,stage:x.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let{appDirectory:r,isDev:a,widgets:n,pages:_}=x.context;return e=t=Object.assign(t,gZ(n,r,a),gZ(_,r,a,!0)),{entry:t}}),x.view.hooks.collectMetaData.tapPromise({name:gY,stage:x.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{normalizedAppConfig:r,userConfig:a,widgets:n,pages:_}=x.context;await dh({widgets:n,pages:_,entries:e,collector:t,normalizedAppConfig:r,define:a.source?.define})}),x.assets.hooks.beforeEmit.tapPromise({name:gY,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:e})=>{let{widgets:t,pages:r,app:a}=x.context.metadata.getInstance(),n=x.context.templateWidgetEntries;Object.keys(t).forEach(r=>{let a=t[r],_=`${r}/template.js`,A=e.getAsset(_);if(a&&A){let t=`${a.metadata.id}/template.js`;A.destination=t;let _=e.getManifestAsset(x.context.manifestAssetPath),s=a.toManifest(t,A.hashCode,om.LYNX);n.has(r)&&(s.titleType=oh.NONE),_.appendWidget(s)}}),Object.keys(r).forEach(t=>{let n=r[t],_=`${t}/template.js`,A=e.getAsset(_);if(n&&A){let t=c0(a.metadata.appId,n.metadata.path,"template.js");A.destination=t,e.getManifestAsset(x.context.manifestAssetPath).appendPage(n.toManifest(t,A.hashCode,om.LYNX))}})}),x.assets.hooks.afterEmit.tapPromise(gY,async({assets:x})=>{}),x.view.hooks.afterBuild.tapPromise(gY,async({stats:x})=>{})}},gW=`function toAppRuntimeTool(tool, id, key) {
497
497
  const normalizedTool = typeof tool === 'object' &&
498
498
  tool !== null &&
499
499
  '__FUNCTIONAL__' in tool &&
@@ -515,20 +515,20 @@ if (import.meta.webpackHot) {
515
515
  return Object.defineProperty(normalizedTool, '__runtimeEntry', {
516
516
  value: Object.freeze({ type: 'functional_tool', key, id: normalizedTool.aiMeta.id })
517
517
  });
518
- }`;async function g1(x,e,t){let{app:r,tools:a,collector:n,define:_}=t,A=a[e],s=x;(A||r===e)&&(_&&Object.keys(_).length>0&&(s=Object.keys(_).reduce((x,e)=>{let t=_[e];if("string"==typeof t)return x.replaceAll(e,t);throw Error(`define 配置项 ${e} 的值必须是字符串`)},x)),T((0,dv.parseSync)(s,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(x){if(da(x.callee)&&["defineTool","defineApp"].includes(x.callee.value)){let e=x.arguments[0]?.expression;if(ds(e)){for(let x of e.properties)if(dl(x)&&da(x.key)&&"aiMeta"===x.key.value){let e=dc(x.value);A?n.addToolMeta(A,e):n.addAppMeta({...e,appId:e.appId??e.package})}}}}}))}async function g2({tools:x,app:e,collector:t,define:r,appConfig:a}){let n={collector:t,tools:Object.fromEntries(Object.entries(x).map(([x,e])=>[e,x])),app:e,define:r};Object.entries(x).forEach(([x])=>{t.addToolMeta(x,{id:x})}),r5.existsSync(e)?await Promise.all(Object.values({...x,app:e}).filter(x=>/\.(ts|tsx|jsx|js)$/i.test(x)&&r5.existsSync(x)).map(x=>g1(r5.readFileSync(x,"utf-8"),x,n))):oa.warn("应用入口文件不存在",{path:e});let _=t.app,A=a?.appId??_.appId;if(!A)throw Error("请在应用配置或 AI 元数据中提供 appId");t.addAppMeta({..._,name:a?.name??_.name,description:a?.description??_.description,icons:a?.icons??_.icons,keywords:a?.keywords??_.keywords,version:a?.version??_.version,darkMode:a?.darkMode??_.darkMode,chat:a?.chat??_.chat,appId:A})}let g3={name:"AppletMainPlugin",setup:async x=>{x.context.app&&(x.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:e})=>{var t;let{app:r,srcDirectory:a,tools:n}=x.context,_=Object.fromEntries((t=x.context.normalizedAppConfig.tools).entryNames.map(x=>{let e=gQ(x,t),r=n[e];if(!r)throw Error(`未解析到配置的 Tool 入口:${x}`);return[e,r]}));return Object.assign(e,{app:((x,e,t,r=r4.dirname(e))=>{let a=r4.dirname(x),n=c4(r4.resolve(e,"..","..")),_=[],A=[];Object.entries(t).forEach(([x,e],t)=>{let n=gO(r,e);_.push(`import Tool${t} from "${cW(a,e)}";`),A.push(`toAppRuntimeTool(Tool${t}, ${JSON.stringify(x)}, ${JSON.stringify(n)})`)});let s=A.length>0;return new c5(x,`
518
+ }`;async function g0(x,e,t){let{app:r,tools:a,collector:n,define:_}=t,A=a[e],s=x;(A||r===e)&&(_&&Object.keys(_).length>0&&(s=Object.keys(_).reduce((x,e)=>{let t=_[e];if("string"==typeof t)return x.replaceAll(e,t);throw Error(`define 配置项 ${e} 的值必须是字符串`)},x)),T((0,db.parseSync)(s,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(x){if(dA(x.callee)&&["defineTool","defineApp"].includes(x.callee.value)){let e=x.arguments[0]?.expression;if(dc(e)){for(let x of e.properties)if(dd(x)&&dA(x.key)&&"aiMeta"===x.key.value){let e=df(x.value);A?n.addToolMeta(A,e):n.addAppMeta({...e,appId:e.appId??e.package})}}}}}))}async function g1({tools:x,app:e,collector:t,define:r,appConfig:a}){let n={collector:t,tools:Object.fromEntries(Object.entries(x).map(([x,e])=>[e,x])),app:e,define:r};Object.entries(x).forEach(([x])=>{t.addToolMeta(x,{id:x})}),r5.existsSync(e)?await Promise.all(Object.values({...x,app:e}).filter(x=>/\.(ts|tsx|jsx|js)$/i.test(x)&&r5.existsSync(x)).map(x=>g0(r5.readFileSync(x,"utf-8"),x,n))):oa.warn("应用入口文件不存在",{path:e});let _=t.app,A=a?.appId??_.appId;if(!A)throw Error("请在应用配置或 AI 元数据中提供 appId");t.addAppMeta({..._,name:a?.name??_.name,description:a?.description??_.description,icons:a?.icons??_.icons,keywords:a?.keywords??_.keywords,version:a?.version??_.version,darkMode:a?.darkMode??_.darkMode,chat:a?.chat??_.chat,appId:A})}let g2={name:"AppletMainPlugin",setup:async x=>{x.context.app&&(x.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:e})=>{var t;let{app:r,srcDirectory:a,tools:n}=x.context,_=Object.fromEntries((t=x.context.normalizedAppConfig.tools).entryNames.map(x=>{let e=gK(x,t),r=n[e];if(!r)throw Error(`未解析到配置的 Tool 入口:${x}`);return[e,r]}));return Object.assign(e,{app:((x,e,t,r=r4.dirname(e))=>{let a=r4.dirname(x),n=c9(r4.resolve(e,"..","..")),_=[],A=[];Object.entries(t).forEach(([x,e],t)=>{let n=gG(r,e);_.push(`import Tool${t} from "${c3(a,e)}";`),A.push(`toAppRuntimeTool(Tool${t}, ${JSON.stringify(x)}, ${JSON.stringify(n)})`)});let s=A.length>0;return new vx(x,`
519
519
  import { ${s?"Applet, defineTool":"Applet"} } from "${n}";
520
- import App from "${cW(a,e)}";
520
+ import App from "${c3(a,e)}";
521
521
  ${_.join("\n")}
522
522
 
523
- ${s?g0:""}
523
+ ${s?gW:""}
524
524
 
525
525
  new Applet(App, [${A.join(", ")}]).bootstrap();
526
- `)})(`${x.context.appDirectory}${r4.sep}${iX}${r4.sep}app.js`,r,n,a)}),Object.keys(_).length>0&&(e[iW]=function(x,e,t,r=r4.resolve(t,"src")){let a=r4.dirname(x),n=c4(t),_=[],A=[];return Object.entries(e).forEach(([x,e],t)=>{let n={type:"client_tool",key:gO(r,e),id:x};_.push(`import ClientTool${t} from "${cW(a,e)}";`),A.push(`{ name: ${JSON.stringify(x)}, handler: ClientTool${t}, entry: Object.freeze(${JSON.stringify(n)}) }`)}),new c5(x,`
526
+ `)})(`${x.context.appDirectory}${r4.sep}${iX}${r4.sep}app.js`,r,n,a)}),Object.keys(_).length>0&&(e[iW]=function(x,e,t,r=r4.resolve(t,"src")){let a=r4.dirname(x),n=c9(t),_=[],A=[];return Object.entries(e).forEach(([x,e],t)=>{let n={type:"client_tool",key:gG(r,e),id:x};_.push(`import ClientTool${t} from "${c3(a,e)}";`),A.push(`{ name: ${JSON.stringify(x)}, handler: ClientTool${t}, entry: Object.freeze(${JSON.stringify(n)}) }`)}),new vx(x,`
527
527
  import { bootstrapClientToolRuntime } from "${n}";
528
528
  ${_.join("\n")}
529
529
 
530
530
  bootstrapClientToolRuntime([${A.join(", ")}]);
531
- `)}(`${x.context.appDirectory}${r4.sep}${iX}${r4.sep}${iW}.js`,_,x.context.appDirectory,a)),{entry:e}}),x.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:x})=>{}),x.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:x.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:e})=>{let{app:t,appConfig:r,tools:a,userConfig:n}=x.context;await g2({appConfig:r,tools:a,app:t,collector:e,define:n.source?.define}),x.context.setVersionTag(x.context.metadata.app.version)}),x.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e,chunks:t})=>{var r,a;let n=process.env.DOUBAO_VERSION_CODE?.trim();if(n&&!/^\d+$/.test(n))throw Error("DOUBAO_VERSION_CODE must contain only digits");let{app:_,pages:A,tools:s}=x.context.metadata.getInstance(),i=e.getAsset(x.context.appAssetPath),o=t[iW]?.find(({source:x})=>x.endsWith(".js")),l=e.getManifestAsset(x.context.manifestAssetPath),{manifest:c}=l,v=[];c.applet.pages.forEach(x=>{v.push(x.digest)});let d=_.metadata.appId,f=x.context.versionTag;l.assignBasicManifest({manifestVersion:"3.0",packageName:d,appId:d,versionName:f,versionTag:f,scmVersion:process.env.BUILD_VERSION,versionCode:n||Date.now().toString(),runtimeVersion:"1.0",sourceType:x.context.internal?1:2,settings:x.context.manifestSettings});let b=x.context.appAssetPath,u=x.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(x.context.pages)[0],p=u?A[u]?.metadata.path:void 0,m=_.toManifest({toolsMetadata:s,hashCode:i?.hashCode??(r=i?.hashCode??c?.applet?.digest,a=v.join(""),m0.createHash("sha256").update(r+a).digest("hex").substring(0,8)),appRuntimeEntry:b,appRuntimeType:x.context.environment.useLynx?"lynx":"js"});o&&(m.toolRuntimeEntry=o.source),l.mergeAppletManifest(m),p&&l.mergeAppletManifest({appletEntry:p})}),x.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:x.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:x})=>{}),x.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:x})=>{}))}},g6={name:"AppletMainEntryCheckPlugin",setup:async x=>{let{srcDirectory:e}=x.context,t=gX(e);if(!r5.existsSync(t))throw Error("ENOENT: no such file or directory")}},g4={name:"AppletManifestPlugin",setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:x.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:e})=>{let{signing:t}=await x.context.resolveSigningEncryptionOptions()||{};if(t?.enabled){let{signData:r}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),a=e.getManifestAsset(x.context.manifestAssetPath),{manifest:n}=a,{buffer:_,status:A,error_msg:s}=await r(Buffer.from(a.content),cz(t,{extra_config:{app_id:n.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==A)throw Error(s);let i=new g_(iV,_);i.destination=iV,e.addAsset(iV,i)}})}},g5="AppletWebManifestPlugin",g7={name:g5,setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:g5,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:e})=>{var t,r;let a=x.context.metadata.getData(),n=a.app.appId||x.context.appId,_=x.context.command===rV.DEV?"all":"configured",A=vb(x.context.pages,x.context.normalizedAppConfig.pages.entries,_),s=vb(x.context.widgets,x.context.normalizedAppConfig.widgets.entries,_);if(!n&&Object.keys(A).length>0)throw Error("解析 Web 页面入口路径需要 appId");let i=n?(t=a.pages,Object.keys(A).map(x=>{let e=t[x]??{},r=e.path??lV(x),a={entry:lH(n,r,vo)},_=vf(A[x]);return{path:r,entryName:x,web:a,debugHidden:_,manifest:{...e,path:r,digest:"",entry:"",renderType:om.LYNX,web:a,..._?{debugHidden:!0}:{}}}})):[],o=(r=a.widgets,Object.keys(s).map(x=>{let{id:e,...t}=r[x]??{},a=e??vd(s,r,x),n={entry:`${a}/${vo}`},_=vf(s[x]);return{id:a,entryName:x,web:n,debugHidden:_,manifest:{...t,widgetId:a,digest:"",entry:"",renderType:om.LYNX,web:n,..._?{debugHidden:!0}:{}}}}));if(0===i.length&&0===o.length&&0===x.context.normalizedAppConfig.tools.entryNames.length)return;let l=e.getManifestAsset(x.context.manifestAssetPath),c=new Map(i.map(x=>[x.path,x])),v=new Set(l.manifest.applet.pages?.map(x=>x.path));for(let x of(l.manifest.applet.pages?.forEach(x=>{let e=c.get(x.path);e&&(x.web=e.web,e.debugHidden&&(x.debugHidden=!0))}),i))v.has(x.path)||l.appendPage(x.manifest);let d=new Map(o.map(x=>[x.id,x])),f=new Set(l.manifest.widgets?.map(x=>x.widgetId));for(let e of(l.manifest.widgets?.forEach(x=>{let e=d.get(x.widgetId);e&&(x.web=e.web,e.debugHidden&&(x.debugHidden=!0))}),o))if(!f.has(e.id)){let t=e.manifest;x.context.templateWidgetEntries.has(e.entryName)&&(t.titleType=oh.NONE),l.appendWidget(t)}x.context.app&&(l.manifest.applet.web={appRuntimeEntry:vl,...x.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:vc}:{}})})}};function g8(x,e){let t;if(!x)return{entryNames:[],entries:{}};if(Array.isArray(x))t=x;else if("object"==typeof x)e&&oa.warn(`${e} 的对象映射配置已弃用,请改用由字符串或 { entry, ...metadata } 对象组成的数组。`),t=Object.entries(x).map(([x,e])=>{let t;return{...e,entry:(t=x.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?t:`${t}/index`}});else throw Error("入口配置必须是数组或对象映射。");let r=[],a={},n=new Set,_=[],A=new Set;return t.forEach(x=>{let e,t;if("string"==typeof x)e=x,t={};else{let{entry:r,...a}=x;if(!r)throw Error('入口配置对象必须包含 "entry"。');e=r,t=a}n.has(e)?A.has(e)||(_.push(e),A.add(e)):(r.push(e),n.add(e)),a[e]=t}),e&&_.length>0&&oa.warn(`${e} 配置中存在重复入口:${_.join(", ")}。已合并重复入口,以最后一次的元数据配置为准。`),{entryNames:r,entries:a}}class g9{constructor(){this.deploy={},this._isInitialized=!1,this._environment={useLynx:!1,useAuth:!1},this._srcDirectory="",this._virtualEntryDir="",this._appDirectory=process.cwd(),this._rootPath="",this._appAssetPath="",this._appMapAssetPath="",this._manifestPath="",this._widgets={},this._app="",this._tools={},this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:x,metadata:e,versionTag:t,srcDirectory:r="",virtualEntryDir:a="",appDirectory:n=process.cwd(),rootPath:_="",manifestPath:A="",pages:s={},widgets:i={},auth:o,mcpUI:l,app:c="",tools:v={},environment:d={useLynx:!1,useAuth:!1},viewEntriesByType:f={}}){this._command=x,this._metadata=e,this._versionTag=t,this._srcDirectory=r,this._virtualEntryDir=a,this._appDirectory=n,this._rootPath=_,this._manifestPath=A,this._pages={...s},this._widgets={...i};let b=o??l??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=c,this._tools={...v},this._environment={useLynx:d.useLynx,useAuth:!!(d.useAuth||d.useMcpUI)},this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([x,e])=>[x,{pages:{...e.pages},widgets:{...e.widgets}}])),this._isInitialized=!0}assertInitialized(x){if(!this._isInitialized)throw Error(`BuildContext.${x} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===rV.DEV}get command(){return this.assertInitialized("command"),this._command}get metadata(){return this.assertInitialized("metadata"),this._metadata}get manifestPath(){return this.assertInitialized("manifestPath"),this._manifestPath}get appDirectory(){return this._appDirectory}get virtualEntryDir(){return this.assertInitialized("virtualEntryDir"),this._virtualEntryDir}get srcDirectory(){return this.assertInitialized("srcDirectory"),this._srcDirectory}get rootPath(){return this.assertInitialized("rootPath"),this._rootPath}get manifest(){if(this._manifest)return{...this._manifest};try{return this._manifest=JSON.parse(r5.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(x){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return iJ}get appAssetPath(){return this._appAssetPath}get appMapAssetPath(){return this._appMapAssetPath}get environment(){return{...this._environment}}get widgets(){return{...this._widgets}}get pages(){return{...this._pages}}get auth(){return{viewEntries:{...this._auth.viewEntries},apiEntries:{...this._auth.apiEntries}}}get mcpUI(){return this.auth}get viewEntriesByType(){return Object.fromEntries(Object.entries(this._viewEntriesByType).map(([x,e])=>[x,{pages:{...e.pages},widgets:{...e.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}get appId(){return this._appId||this._metadata.appId}setAppId(x){this._appId=x}setApp(x){this._app=x}setTools(x){this._tools=x}setEnvironment(x){this._environment={...x}}mergeEnvironment(x){this._environment={...this._environment,...x}}setPages(x){this._pages=x}setWidgets(x){this._widgets=x}appendPages(x){Object.assign(this._pages,x)}appendWidgets(x){Object.assign(this._widgets,x)}getViewEntriesByType(x){let e=this._viewEntriesByType[x];return e?{pages:{...e.pages},widgets:{...e.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(x,e){this._viewEntriesByType[x]={pages:{...e.pages},widgets:{...e.widgets}}}setAppAssetPath(x){this._appAssetPath=x}setAppMapAssetPath(x){this._appMapAssetPath=x}setManifest(x){this._manifest=x}setVersionTag(x){return this.assertInitialized("versionTag"),!this._versionTag&&x&&(this._versionTag=x),this._versionTag}setAuthApi(x){this._auth={viewEntries:{...x.viewEntries},apiEntries:{...x.apiEntries}}}setMcpUIApi(x){this.setAuthApi(x)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function yx({internal:x,domainId:e,appLimit:t,appOffset:r,keyWord:a,appKey:n}){return await fB({internal:x,domainId:e,path:"/app_developer/api/apps",query:{app_limit:t,app_offset:r,key_word:a,app_key:n},method:"GET"})}function ye(x,e){Z()&&oa.info(x,e)}async function yt({appKey:x}){ye("[app-info] 开始获取应用信息",{appKey:x});let e=await yx({internal:!1,appLimit:1,appOffset:0,appKey:x}).then(({data:e,log_id:t})=>{let r=e?.app_list||[],a=r.find(e=>e.app_key===x);return ye("[app-info] MGetApps 请求完成",{appKey:x,appCount:r.length,exactMatch:!!a,logId:t}),a}).catch(e=>{throw ye("[app-info] MGetApps 请求失败",{appKey:x,reason:gN(e)}),e});if(!e)throw ye("[app-info] 应用信息查询结束,未找到可用结果",{appKey:x}),Error(`未找到应用 ${x}`);return{appKey:x,appName:e.name,iconUrl:e.icon_url}}function yr(){return function({fetch:x,getCacheKey:e,ttl:t,timeout:r,cacheFailures:a=!1,now:n=Date.now}){let _=new Map;return function(...A){var s,i;let o,l="string"==typeof(s=e(...A))?s:JSON.stringify(s),c=n(),v=_.get(l);if(v&&v.expiresAt>c)return v.promise;let d=(i=x(...A),void 0===r?i:Promise.race([i,new Promise((x,e)=>{o=setTimeout(()=>{e(Error(`Request timed out after ${r}ms`))},r)})]).finally(()=>{o&&clearTimeout(o)})).catch(x=>{throw a||_.get(l)?.promise!==d||_.delete(l),x});return _.set(l,{expiresAt:c+t,promise:d}),d}}({fetch:yt,getCacheKey:({appKey:x})=>x,ttl:6e4,timeout:1e4,cacheFailures:!0})}async function ya(x="0.0.0.0"){if(!x||x.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");if("0.0.0.0"===x&&void 0!==process.env.DEV_SERVER_HOST)return x;let{address:e}=await (0,P.lookup)(x,{family:4});if("0.0.0.0"!==e)return e;let t=xa()[0];return t||(os.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function yn(x,e,t){let r=await fetch(`${x}/base/manifest.json`,{signal:AbortSignal.any([t,AbortSignal.timeout(1500)]),redirect:"error"}),a=await r.json();if(!r.ok||e&&a?.appId!==e)throw Error(`开发服务器返回的 manifest 无效:${x}(HTTP ${r.status},appId:${e})`)}async function y_(x,e,t,r){let a,n=xt(x,"0.0.0.0"===e?"127.0.0.1":e),_=AbortSignal.any([r,AbortSignal.timeout(5e3)]);try{for(;;)try{await yn(n,t,_);break}catch(x){a=x,await (0,D.setTimeout)(200,void 0,{signal:_})}}catch{throw r.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${n}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:a})}return{host:process.env.DEV_SERVER_HOST??n,artifactOrigin:n}}class yA extends g9{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(x=>{this.finishInitialDevCompile=x,this.devServerAbort.signal.addEventListener("abort",()=>x(void 0),{once:!0})});devServerResolution;resolveDevServer(x){return this.devServerResolution??=this.initialDevCompile.then(e=>{if(e)throw e;return this.devServerAbort.signal.throwIfAborted(),y_(x,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=j9();eventsResources;toolsResources;manifestSettings;_userConfig={};_env={};_appConfig={};_normalizedAppConfig={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}};_signingEncryptionOptions;_rawSigningEncryptionOptions;_signingEncryptionOptionsPromise;_disableSigningEncryption=!1;_dek=Buffer.from("");_internal=!1;_fetchCachedAppInfo=yr();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;_permissionSource;get permissionSource(){return this._permissionSource}get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){var x;return{pages:{entryNames:[...(x=this._normalizedAppConfig).pages.entryNames],entries:Object.fromEntries(Object.entries(x.pages.entries).map(([x,e])=>[x,{...e}]))},tools:{entryNames:[...x.tools.entryNames],entries:Object.fromEntries(Object.entries(x.tools.entries).map(([x,e])=>[x,{...e}]))},widgets:{entryNames:[...x.widgets.entryNames],entries:Object.fromEntries(Object.entries(x.widgets.entries).map(([x,e])=>[x,{...e}]))}}}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(x=>({...x}))}get signingEncryptionOptions(){if(this._signingEncryptionOptions)return{...this._signingEncryptionOptions,encryption:{...this._signingEncryptionOptions?.encryption,dek:this.dek}}}get dek(){return this._dek}get isSignedEncryption(){return this.signingEncryptionOptions?.signing.enabled||this.signingEncryptionOptions?.encryption.enabled}get internal(){return this.assertInitialized("internal"),this._internal}setSigningEncryptionOptions(x){this._rawSigningEncryptionOptions=x,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0}disableSigningEncryption(){this._disableSigningEncryption=!0,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._dek=Buffer.from("")}addTemplateWidgetEntry(x){this._templateWidgetEntries.add(x)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let x=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==x&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-x))}}async resolveAppInfoInternal(){var x;let e=this.appId;if(!j8(e))return;let t="string"==typeof(x=this._appConfig.icons)?x.length>0?x:void 0:x?.["3x"]||x?.["2x"]||x?.["1x"],r={appKey:e,...this._appConfig.name?{appName:this._appConfig.name}:{},...t?{iconUrl:t}:{}};if(this._skipAppInfoFetch)return r;try{let x=await this._fetchCachedAppInfo({appKey:e});return{...r,...x,appName:x.appName||r.appName,iconUrl:x.iconUrl||r.iconUrl}}catch(x){if(this.command!==rV.DEV&&this.command!==rV.BUILD)throw x;if(function(x){if(!(x instanceof Error))return!1;try{let e=JSON.parse(x.message);return e?.code===0x2fb1799}catch{return!1}}(x))return r;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,oa.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:gN(x)})),r}}async bootstrap({srcDirectory:x,appDirectory:e,rootPath:t,userConfig:r,appConfig:a={},normalizedAppConfig:n={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:_,metadata:A,signingEncryptionOptions:s,disableSigningEncryption:i,appId:o,versionTag:l,pages:c,widgets:v,auth:d,app:f,tools:b,internal:u,skipAppInfoFetch:p,permissions:m,permissionSource:h,devServerInteractive:E=!0,env:j={}}){await super.bootstrap({srcDirectory:x,appDirectory:e,virtualEntryDir:r4.resolve(e,iX),rootPath:t,manifestPath:r4.resolve(`${t}/${iJ}`),command:_,metadata:A,versionTag:l,pages:c,widgets:v,auth:d,app:f,tools:b});let{icons:g,...y}=a??{};this._userConfig=r,this.devServerInteractive=E,this._env={...j},this._appConfig={...y,...void 0!==o?{appId:o}:{},...void 0!==g?{icons:oP(g)}:{}},this._normalizedAppConfig=n,this._internal=u??((x=process.cwd())=>c6(x)===c0)(e),this._skipAppInfoFetch=!!p,this._permissionSource=h,this._permissions=m?.map(x=>({...x})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=s,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!i,this._appId=o??a?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=yr()}async resolveSigningEncryptionOptionsOnce(){let x=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await gw(this._rawSigningEncryptionOptions,this.command,x,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:x}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=x(),Z()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function ys({appId:x,versionTag:e,versionCode:t,packagePath:r,internal:a,domainId:n,cookie:_,token:A,cardCheckJSON:s,cloudBuildJobID:i,needAuth:o=!0}){let l=new FormData,c=new Blob([new Uint8Array(r5.readFileSync(r))],{type:"application/zip"});l.append("applet_file",c,"doubao_app.zip"),l.append("applet_version_code",t.toString()),s&&l.append("card_check",s),i&&l.append("cloud_build_job_id",i);let v=`/developer/${o?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(x)}/versions/${encodeURIComponent(e)}/package/upload_applet`;return await fB({internal:a,domainId:A?"sms-external":n,path:v,method:"POST",body:l,headers:{..._?{Cookie:_}:{},...A?{"X-Developer-Open-Build-Token":A}:{}},auth:o&&!A})}function yi(x){if(x)return{token:x};let e=process.env.DOUBAO_DEPLOY_COOKIE?.trim();if(!e)throw Error("Doubao Apps Platform 部署需要 Developer Open Build Token(--token);本地测试可设置 DOUBAO_DEPLOY_COOKIE。");return{cookie:e}}async function yo({versionTag:x,appKey:e,manifest:t,rootPath:r,token:a,cookie:n,cardCheckJSON:_,cloudBuildJobID:A}){process.env.NODE_ENV="production";let{appId:s,packageName:i,versionCode:o}=t;if(e&&s!==e)throw Error(`部署目标 ${e} 与构建产物 appId ${s||"(missing)"} 不一致。`);let l=function(x,e){let t=x||e.versionTag||e.versionName;if(!t)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return t}(x,t),{packageResource:c}=await lQ({channelName:"doubao_app",manifest:t,rootPath:r});if(!c)throw Error("Failed to archive package");let v=await ys({appId:e||s||i,versionTag:l,versionCode:o,packagePath:c.resource,internal:!1,needAuth:!0,...n?{cookie:n}:{},token:a,cardCheckJSON:_,cloudBuildJobID:A});return console.log("Deploy success:",v),v}function yl(x,e){if(!r5.existsSync(x)||!r5.statSync(x).isFile())throw Error(`${e} 文件不存在:${x}`);return r5.readFileSync(x,"utf8")}class yc{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(x=process.cwd()){this.appDirectory=x}async prepare(x,e={},t){let r=this.context;try{let r=Date.now(),a=await this.getUserConfig(e),n={...await this.getAppConfig(),...e.appName?{name:e.appName}:{},...e.appIcon?{icons:oP(e.appIcon)}:{}},_={pages:g8(n?.pages,"pages"),tools:g8(n?.tools,"tools"),widgets:g8(n?.widgets,"widgets")},A=function(x){let e=r4.join(x,"events.json");if(r5.existsSync(e)&&r5.statSync(e).isFile())return{readJson:()=>r5.readFileSync(e,"utf8"),sourcePath:e}}(this.appDirectory),s=function({appDirectory:x,normalizedAppConfig:e}){let t=r4.join(x,"tools.json");if(!r5.existsSync(t))return;let r=r4.join(x,"manifest.yaml"),a=()=>yl(t,"tools.json"),n=()=>jL({tools:(()=>{let x=jP(a(),t);var r=x.tools;let n=new Set(e.widgets.entryNames.map(x=>e.widgets.entries[x]?.id??lJ(x)));for(let x of r)if(x.widgetId&&!n.has(x.widgetId))throw Error(`Tool "${x.name}" 引用的 widgetId "${x.widgetId}" 未在 app.config.ts 中声明`);return x})().tools,manifestPath:r,manifestText:yl(r,"manifest.yaml")});return n(),{manifestSourcePath:r,readManifestYaml:n,readToolsJson:a,toolsSourcePath:t}}({appDirectory:this.appDirectory,normalizedAppConfig:_}),i=function(x){if(x)return!0===x?{mcpEndpoint:vn()}:{...x,mcpEndpoint:vn({mcpEndpoint:x.mcpEndpoint})}}(e.openWebDebugger),o=Date.now()-r;this.rootPath=r4.resolve(this.appDirectory,"dist"),r5.existsSync(r4.resolve(this.rootPath))&&r5.rmSync(r4.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new yA,gx(this.context.compileLifecycle,r),this.context.compileLifecycle.prepareDurations.configLoadMs=o;let l=r4.resolve(this.appDirectory,"src"),c=Date.now(),{pages:v,widgets:d,auth:f,app:b,tools:u}=await this.analyzeConvention(l,_);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-c;let p=new o$,m=((x=process.cwd())=>c6(x)===c0)(this.appDirectory),h=Date.now();await this.context.bootstrap({srcDirectory:l,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:a,env:this._env,appConfig:n,normalizedAppConfig:_,command:x,metadata:p,signingEncryptionOptions:e.signingEncryptionOptions,skipAppInfoFetch:x===rV.DEPLOY||!!e.token||!!e.skipAppInfoFetch,permissions:e.permissions,permissionSource:e.permissionSource,appId:e.appId,versionTag:e.versionTag,pages:v,widgets:d,auth:f,app:b,tools:u,internal:m,devServerInteractive:e.interactive}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-h,(x===rV.DEV||void 0!==e.host)&&(this.context.devServerHost=await ya(e.host)),this.context.webDebuggerLaunchOptions=i,this.context.eventsResources=A,this.context.toolsResources=s,this.pluginSystem=new lX(this.context,[g3,gW,g6,gV,g7,gU,g4,gY,...a.experiments?.taro?[function({name:x,appId:e,icons:t,widgets:r}){return{name:c9,setup:a=>{let n=(0,c8.createRequire)(import.meta.url);a.view.hooks.modifyEntryOption.tapPromise({name:c9,stage:a.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:x})=>{let{appDirectory:e,isDev:t,pages:r,widgets:n}=a.context,_=c7(r,e,!1,t);return{entry:x=Object.assign(x,_,c7(n,e,!0,t))}}),a.view.hooks.beforeBuild.tapPromise({name:c9,stage:a.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:x})=>{let{appDirectory:e}=a.context;cz(x,{resolve:{alias:{"@tarojs/components":n.resolve("@doubao-dev/taro-runtime/components",{paths:[e]}),"@tarojs/taro":(0,r7.dirname)(n.resolve("@doubao-dev/taro-runtime/package.json",{paths:[e]}))}}})}),a.worker.hooks.modifyEntryOption.tapPromise({name:c9,stage:a.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:t})=>{let{appDirectory:r,isDev:n}=a.context,{app:_}=a.context;return _&&(t.app=function(x,e,t,r,a=!1){var n;let _=`${iX}${r4.sep}app.js`,A=(n=cW(r4.dirname(_),x)).startsWith(".")?n:`./${n}`,s=c4(e);return new c5(_,`
531
+ `)}(`${x.context.appDirectory}${r4.sep}${iX}${r4.sep}${iW}.js`,_,x.context.appDirectory,a)),{entry:e}}),x.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:x})=>{}),x.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:x.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:e})=>{let{app:t,appConfig:r,tools:a,userConfig:n}=x.context;await g1({appConfig:r,tools:a,app:t,collector:e,define:n.source?.define}),x.context.setVersionTag(x.context.metadata.app.version)}),x.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e,chunks:t})=>{var r,a;let n=process.env.DOUBAO_VERSION_CODE?.trim();if(n&&!/^\d+$/.test(n))throw Error("DOUBAO_VERSION_CODE must contain only digits");let{app:_,pages:A,tools:s}=x.context.metadata.getInstance(),i=e.getAsset(x.context.appAssetPath),o=t[iW]?.find(({source:x})=>x.endsWith(".js")),l=e.getManifestAsset(x.context.manifestAssetPath),{manifest:c}=l,v=[];c.applet.pages.forEach(x=>{v.push(x.digest)});let d=_.metadata.appId,f=x.context.versionTag;l.assignBasicManifest({manifestVersion:"3.0",packageName:d,appId:d,versionName:f,versionTag:f,scmVersion:process.env.BUILD_VERSION,versionCode:n||Date.now().toString(),runtimeVersion:"1.0",sourceType:x.context.internal?1:2,settings:x.context.manifestSettings});let b=x.context.appAssetPath,u=x.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(x.context.pages)[0],p=u?A[u]?.metadata.path:void 0,m=_.toManifest({toolsMetadata:s,hashCode:i?.hashCode??(r=i?.hashCode??c?.applet?.digest,a=v.join(""),cH.createHash("sha256").update(r+a).digest("hex").substring(0,8)),appRuntimeEntry:b,appRuntimeType:x.context.environment.useLynx?"lynx":"js"});o&&(m.toolRuntimeEntry=o.source),l.mergeAppletManifest(m),p&&l.mergeAppletManifest({appletEntry:p})}),x.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:x.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:x})=>{}),x.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:x})=>{}))}},g3={name:"AppletMainEntryCheckPlugin",setup:async x=>{let{srcDirectory:e}=x.context,t=gO(e);if(!r5.existsSync(t))throw Error("ENOENT: no such file or directory")}},g6={name:"AppletManifestPlugin",setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:x.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:e})=>{let{signing:t}=await x.context.resolveSigningEncryptionOptions()||{};if(t?.enabled){let{signData:r}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),a=e.getManifestAsset(x.context.manifestAssetPath),{manifest:n}=a,{buffer:_,status:A,error_msg:s}=await r(Buffer.from(a.content),c2(t,{extra_config:{app_id:n.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==A)throw Error(s);let i=new cU(iV,_);i.destination=iV,e.addAsset(iV,i)}})}},g4="AppletWebManifestPlugin";function g5(x,e,t,r){let a=x.metadata.getData(),n=a.app.appId||x.appId,_=x.normalizedAppConfig.tools.entryNames.length>0;if(0===Object.keys(t).length&&0===Object.keys(r).length&&!_)return;let{manifest:A}=e;for(let[x,r]of Object.entries(t)){if(!n)throw Error("解析 Web 页面入口路径需要 appId");let t=a.pages[x]??{},_=t.path??cW(x),s={web:{entry:c0(n,_,vd)},...r.internal?{debugHidden:!0}:{}},i=A.applet.pages.find(x=>x.path===_);i?Object.assign(i,s):e.appendPage({...t,path:_,digest:"",entry:"",renderType:om.LYNX,...s})}let s=x.templateWidgetEntries;for(let[x,t]of Object.entries(r)){let{id:n,..._}=a.widgets[x]??{},i=vp(r,a.widgets,x),o={web:{entry:`${i}/${vd}`},...t.internal?{debugHidden:!0}:{}},l=A.widgets.find(x=>x.widgetId===i);l?Object.assign(l,o):e.appendWidget({..._,widgetId:i,digest:"",entry:"",renderType:om.LYNX,...s.has(x)?{titleType:oh.NONE}:{},...o})}x.app&&(A.applet.web={appRuntimeEntry:vf,..._?{toolRuntimeEntry:vb}:{}})}let g7={name:g4,setup:async x=>{x.assets.hooks.beforeEmit.tapPromise({name:g4,stage:x.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:e})=>{let{command:t,pages:r,widgets:a,normalizedAppConfig:n}=x.context,_=t===rV.DEV;g5(x.context,e.getManifestAsset(x.context.manifestAssetPath),_?r:vm(r,n.pages.entries),_?a:vm(a,n.widgets.entries))})}};function g8(x,e){let t;if(!x)return{entryNames:[],entries:{}};if(Array.isArray(x))t=x;else if("object"==typeof x)e&&oa.warn(`${e} 的对象映射配置已弃用,请改用由字符串或 { entry, ...metadata } 对象组成的数组。`),t=Object.entries(x).map(([x,e])=>{let t;return{...e,entry:(t=x.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?t:`${t}/index`}});else throw Error("入口配置必须是数组或对象映射。");let r=[],a={},n=new Set,_=[],A=new Set;return t.forEach(x=>{let e,t;if("string"==typeof x)e=x,t={};else{let{entry:r,...a}=x;if(!r)throw Error('入口配置对象必须包含 "entry"。');e=r,t=a}n.has(e)?A.has(e)||(_.push(e),A.add(e)):(r.push(e),n.add(e)),a[e]=t}),e&&_.length>0&&oa.warn(`${e} 配置中存在重复入口:${_.join(", ")}。已合并重复入口,以最后一次的元数据配置为准。`),{entryNames:r,entries:a}}class g9{constructor(){this.deploy={},this._isInitialized=!1,this._environment={useLynx:!1,useAuth:!1},this._srcDirectory="",this._virtualEntryDir="",this._appDirectory=process.cwd(),this._rootPath="",this._appAssetPath="",this._appMapAssetPath="",this._manifestPath="",this._widgets={},this._app="",this._tools={},this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:x,metadata:e,versionTag:t,srcDirectory:r="",virtualEntryDir:a="",appDirectory:n=process.cwd(),rootPath:_="",manifestPath:A="",pages:s={},widgets:i={},auth:o,mcpUI:l,app:c="",tools:v={},environment:d={useLynx:!1,useAuth:!1},viewEntriesByType:f={}}){this._command=x,this._metadata=e,this._versionTag=t,this._srcDirectory=r,this._virtualEntryDir=a,this._appDirectory=n,this._rootPath=_,this._manifestPath=A,this._pages={...s},this._widgets={...i};let b=o??l??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=c,this._tools={...v},this._environment={useLynx:d.useLynx,useAuth:!!(d.useAuth||d.useMcpUI)},this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([x,e])=>[x,{pages:{...e.pages},widgets:{...e.widgets}}])),this._isInitialized=!0}assertInitialized(x){if(!this._isInitialized)throw Error(`BuildContext.${x} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===rV.DEV}get command(){return this.assertInitialized("command"),this._command}get metadata(){return this.assertInitialized("metadata"),this._metadata}get manifestPath(){return this.assertInitialized("manifestPath"),this._manifestPath}get appDirectory(){return this._appDirectory}get virtualEntryDir(){return this.assertInitialized("virtualEntryDir"),this._virtualEntryDir}get srcDirectory(){return this.assertInitialized("srcDirectory"),this._srcDirectory}get rootPath(){return this.assertInitialized("rootPath"),this._rootPath}get manifest(){if(this._manifest)return{...this._manifest};try{return this._manifest=JSON.parse(r5.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(x){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return iJ}get appAssetPath(){return this._appAssetPath}get appMapAssetPath(){return this._appMapAssetPath}get environment(){return{...this._environment}}get widgets(){return{...this._widgets}}get pages(){return{...this._pages}}get auth(){return{viewEntries:{...this._auth.viewEntries},apiEntries:{...this._auth.apiEntries}}}get mcpUI(){return this.auth}get viewEntriesByType(){return Object.fromEntries(Object.entries(this._viewEntriesByType).map(([x,e])=>[x,{pages:{...e.pages},widgets:{...e.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}get appId(){return this._appId||this._metadata.appId}setAppId(x){this._appId=x}setApp(x){this._app=x}setTools(x){this._tools=x}setEnvironment(x){this._environment={...x}}mergeEnvironment(x){this._environment={...this._environment,...x}}setPages(x){this._pages=x}setWidgets(x){this._widgets=x}appendPages(x){Object.assign(this._pages,x)}appendWidgets(x){Object.assign(this._widgets,x)}getViewEntriesByType(x){let e=this._viewEntriesByType[x];return e?{pages:{...e.pages},widgets:{...e.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(x,e){this._viewEntriesByType[x]={pages:{...e.pages},widgets:{...e.widgets}}}setAppAssetPath(x){this._appAssetPath=x}setAppMapAssetPath(x){this._appMapAssetPath=x}setManifest(x){this._manifest=x}setVersionTag(x){return this.assertInitialized("versionTag"),!this._versionTag&&x&&(this._versionTag=x),this._versionTag}setAuthApi(x){this._auth={viewEntries:{...x.viewEntries},apiEntries:{...x.apiEntries}}}setMcpUIApi(x){this.setAuthApi(x)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function yx({internal:x,domainId:e,appLimit:t,appOffset:r,keyWord:a,appKey:n}){return await fw({internal:x,domainId:e,path:"/app_developer/api/apps",query:{app_limit:t,app_offset:r,key_word:a,app_key:n},method:"GET"})}function ye(x,e){Z()&&oa.info(x,e)}async function yt({appKey:x}){ye("[app-info] 开始获取应用信息",{appKey:x});let e=await yx({internal:!1,appLimit:1,appOffset:0,appKey:x}).then(({data:e,log_id:t})=>{let r=e?.app_list||[],a=r.find(e=>e.app_key===x);return ye("[app-info] MGetApps 请求完成",{appKey:x,appCount:r.length,exactMatch:!!a,logId:t}),a}).catch(e=>{throw ye("[app-info] MGetApps 请求失败",{appKey:x,reason:gI(e)}),e});if(!e)throw ye("[app-info] 应用信息查询结束,未找到可用结果",{appKey:x}),Error(`未找到应用 ${x}`);return{appKey:x,appName:e.name,iconUrl:e.icon_url}}function yr(){return function({fetch:x,getCacheKey:e,ttl:t,timeout:r,cacheFailures:a=!1,now:n=Date.now}){let _=new Map;return function(...A){var s,i;let o,l="string"==typeof(s=e(...A))?s:JSON.stringify(s),c=n(),v=_.get(l);if(v&&v.expiresAt>c)return v.promise;let d=(i=x(...A),void 0===r?i:Promise.race([i,new Promise((x,e)=>{o=setTimeout(()=>{e(Error(`Request timed out after ${r}ms`))},r)})]).finally(()=>{o&&clearTimeout(o)})).catch(x=>{throw a||_.get(l)?.promise!==d||_.delete(l),x});return _.set(l,{expiresAt:c+t,promise:d}),d}}({fetch:yt,getCacheKey:({appKey:x})=>x,ttl:6e4,timeout:1e4,cacheFailures:!0})}async function ya(x="0.0.0.0"){if(!x||x.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");if("0.0.0.0"===x&&void 0!==process.env.DEV_SERVER_HOST)return x;let{address:e}=await (0,P.lookup)(x,{family:4});if("0.0.0.0"!==e)return e;let t=xa()[0];return t||(os.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function yn(x,e,t){let r=await fetch(`${x}/base/manifest.json`,{signal:AbortSignal.any([t,AbortSignal.timeout(1500)]),redirect:"error"}),a=await r.json();if(!r.ok||e&&a?.appId!==e)throw Error(`开发服务器返回的 manifest 无效:${x}(HTTP ${r.status},appId:${e})`)}async function y_(x,e,t,r){let a,n=xt(x,"0.0.0.0"===e?"127.0.0.1":e),_=AbortSignal.any([r,AbortSignal.timeout(5e3)]);try{for(;;)try{await yn(n,t,_);break}catch(x){a=x,await (0,D.setTimeout)(200,void 0,{signal:_})}}catch{throw r.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${n}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:a})}return{host:process.env.DEV_SERVER_HOST??n,artifactOrigin:n}}class yA extends g9{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(x=>{this.finishInitialDevCompile=x,this.devServerAbort.signal.addEventListener("abort",()=>x(void 0),{once:!0})});devServerResolution;resolveDevServer(x){return this.devServerResolution??=this.initialDevCompile.then(e=>{if(e)throw e;return this.devServerAbort.signal.throwIfAborted(),y_(x,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=gx();eventsResources;toolsResources;manifestSettings;_userConfig={};_env={};_appConfig={};_normalizedAppConfig={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}};_signingEncryptionOptions;_rawSigningEncryptionOptions;_signingEncryptionOptionsPromise;_disableSigningEncryption=!1;_dek=Buffer.from("");_internal=!1;_fetchCachedAppInfo=yr();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;_permissionSource;get permissionSource(){return this._permissionSource}get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){var x;return{pages:{entryNames:[...(x=this._normalizedAppConfig).pages.entryNames],entries:Object.fromEntries(Object.entries(x.pages.entries).map(([x,e])=>[x,{...e}]))},tools:{entryNames:[...x.tools.entryNames],entries:Object.fromEntries(Object.entries(x.tools.entries).map(([x,e])=>[x,{...e}]))},widgets:{entryNames:[...x.widgets.entryNames],entries:Object.fromEntries(Object.entries(x.widgets.entries).map(([x,e])=>[x,{...e}]))}}}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(x=>({...x}))}get signingEncryptionOptions(){if(this._signingEncryptionOptions)return{...this._signingEncryptionOptions,encryption:{...this._signingEncryptionOptions?.encryption,dek:this.dek}}}get dek(){return this._dek}get isSignedEncryption(){return this.signingEncryptionOptions?.signing.enabled||this.signingEncryptionOptions?.encryption.enabled}get internal(){return this.assertInitialized("internal"),this._internal}setSigningEncryptionOptions(x){this._rawSigningEncryptionOptions=x,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0}disableSigningEncryption(){this._disableSigningEncryption=!0,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._dek=Buffer.from("")}addTemplateWidgetEntry(x){this._templateWidgetEntries.add(x)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let x=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==x&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-x))}}async resolveAppInfoInternal(){var x;let e=this.appId;if(!j9(e))return;let t="string"==typeof(x=this._appConfig.icons)?x.length>0?x:void 0:x?.["3x"]||x?.["2x"]||x?.["1x"],r={appKey:e,...this._appConfig.name?{appName:this._appConfig.name}:{},...t?{iconUrl:t}:{}};if(this._skipAppInfoFetch)return r;try{let x=await this._fetchCachedAppInfo({appKey:e});return{...r,...x,appName:x.appName||r.appName,iconUrl:x.iconUrl||r.iconUrl}}catch(x){if(this.command!==rV.DEV&&this.command!==rV.BUILD)throw x;if(function(x){if(!(x instanceof Error))return!1;try{let e=JSON.parse(x.message);return e?.code===0x2fb1799}catch{return!1}}(x))return r;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,oa.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:gI(x)})),r}}async bootstrap({srcDirectory:x,appDirectory:e,rootPath:t,userConfig:r,appConfig:a={},normalizedAppConfig:n={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:_,metadata:A,signingEncryptionOptions:s,disableSigningEncryption:i,appId:o,versionTag:l,pages:c,widgets:v,auth:d,app:f,tools:b,internal:u,skipAppInfoFetch:p,permissions:m,permissionSource:h,devServerInteractive:E=!0,env:j={}}){await super.bootstrap({srcDirectory:x,appDirectory:e,virtualEntryDir:r4.resolve(e,iX),rootPath:t,manifestPath:r4.resolve(`${t}/${iJ}`),command:_,metadata:A,versionTag:l,pages:c,widgets:v,auth:d,app:f,tools:b});let{icons:g,...y}=a??{};this._userConfig=r,this.devServerInteractive=E,this._env={...j},this._appConfig={...y,...void 0!==o?{appId:o}:{},...void 0!==g?{icons:oP(g)}:{}},this._normalizedAppConfig=n,this._internal=u??((x=process.cwd())=>c8(x)===c6)(e),this._skipAppInfoFetch=!!p,this._permissionSource=h,this._permissions=m?.map(x=>({...x})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=s,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!i,this._appId=o??a?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=yr()}async resolveSigningEncryptionOptionsOnce(){let x=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await gF(this._rawSigningEncryptionOptions,this.command,x,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:x}=await import("node:module").then(function(x){return I.t(x.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=x(),Z()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function ys({appId:x,versionTag:e,versionCode:t,packagePath:r,internal:a,domainId:n,cookie:_,token:A,cardCheckJSON:s,cloudBuildJobID:i,needAuth:o=!0}){let l=new FormData,c=new Blob([new Uint8Array(r5.readFileSync(r))],{type:"application/zip"});l.append("applet_file",c,"doubao_app.zip"),l.append("applet_version_code",t.toString()),s&&l.append("card_check",s),i&&l.append("cloud_build_job_id",i);let v=`/developer/${o?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(x)}/versions/${encodeURIComponent(e)}/package/upload_applet`;return await fw({internal:a,domainId:A?"sms-external":n,path:v,method:"POST",body:l,headers:{..._?{Cookie:_}:{},...A?{"X-Developer-Open-Build-Token":A}:{}},auth:o&&!A})}function yi(x){if(x)return{token:x};let e=process.env.DOUBAO_DEPLOY_COOKIE?.trim();if(!e)throw Error("Doubao Apps Platform 部署需要 Developer Open Build Token(--token);本地测试可设置 DOUBAO_DEPLOY_COOKIE。");return{cookie:e}}async function yo({versionTag:x,appKey:e,manifest:t,rootPath:r,token:a,cookie:n,cardCheckJSON:_,cloudBuildJobID:A}){process.env.NODE_ENV="production";let{appId:s,packageName:i,versionCode:o}=t;if(e&&s!==e)throw Error(`部署目标 ${e} 与构建产物 appId ${s||"(missing)"} 不一致。`);let l=function(x,e){let t=x||e.versionTag||e.versionName;if(!t)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return t}(x,t),{packageResource:c}=await lQ({channelName:"doubao_app",manifest:t,rootPath:r});if(!c)throw Error("Failed to archive package");let v=await ys({appId:e||s||i,versionTag:l,versionCode:o,packagePath:c.resource,internal:!1,needAuth:!0,...n?{cookie:n}:{},token:a,cardCheckJSON:_,cloudBuildJobID:A});return console.log("Deploy success:",v),v}function yl(x,e){if(!r5.existsSync(x)||!r5.statSync(x).isFile())throw Error(`${e} 文件不存在:${x}`);return r5.readFileSync(x,"utf8")}class yc{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(x=process.cwd()){this.appDirectory=x}async prepare(x,e={},t){let r=this.context;try{let r=Date.now(),a=await this.getUserConfig(e),n=await this.getAppConfig(),_={...n,...e.appName?{name:e.appName}:{},...e.appIcon?{icons:oP(e.appIcon)}:{}},A={pages:g8(_?.pages,"pages"),tools:g8(_?.tools,"tools"),widgets:g8(_?.widgets,"widgets")},s=function(x){let e=r4.join(x,"events.json");if(r5.existsSync(e)&&r5.statSync(e).isFile())return{readJson:()=>r5.readFileSync(e,"utf8"),sourcePath:e}}(this.appDirectory),i=function({appDirectory:x,normalizedAppConfig:e}){let t=r4.join(x,"tools.json");if(!r5.existsSync(t))return;let r=r4.join(x,"manifest.yaml"),a=()=>yl(t,"tools.json"),n=()=>jq({tools:(()=>{let x=jk(a(),t);var r=x.tools;let n=new Set(e.widgets.entryNames.map(x=>e.widgets.entries[x]?.id??cz(x)));for(let x of r)if(x.widgetId&&!n.has(x.widgetId))throw Error(`Tool "${x.name}" 引用的 widgetId "${x.widgetId}" 未在 app.config.ts 中声明`);return x})().tools,manifestPath:r,manifestText:yl(r,"manifest.yaml")});return n(),{manifestSourcePath:r,readManifestYaml:n,readToolsJson:a,toolsSourcePath:t}}({appDirectory:this.appDirectory,normalizedAppConfig:A}),o=function(x){if(x)return!0===x?{mcpEndpoint:vi()}:{...x,mcpEndpoint:vi({mcpEndpoint:x.mcpEndpoint})}}(e.openWebDebugger),l=Date.now()-r;this.rootPath=r4.resolve(this.appDirectory,"dist"),r5.existsSync(r4.resolve(this.rootPath))&&r5.rmSync(r4.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new yA,ge(this.context.compileLifecycle,r),this.context.compileLifecycle.prepareDurations.configLoadMs=l;let c=r4.resolve(this.appDirectory,"src"),v=Date.now(),{pages:d,widgets:f,auth:b,app:u,tools:p}=await this.analyzeConvention(c,void 0===n?void 0:A);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-v;let m=new o$,h=((x=process.cwd())=>c8(x)===c6)(this.appDirectory),E=Date.now();await this.context.bootstrap({srcDirectory:c,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:a,env:this._env,appConfig:_,normalizedAppConfig:A,command:x,metadata:m,signingEncryptionOptions:e.signingEncryptionOptions,skipAppInfoFetch:x===rV.DEPLOY||!!e.token||!!e.skipAppInfoFetch,permissions:e.permissions,permissionSource:e.permissionSource,appId:e.appId,versionTag:e.versionTag,pages:d,widgets:f,auth:b,app:u,tools:p,internal:h,devServerInteractive:e.interactive}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-E,(x===rV.DEV||void 0!==e.host)&&(this.context.devServerHost=await ya(e.host)),this.context.webDebuggerLaunchOptions=o,this.context.eventsResources=s,this.context.toolsResources=i,this.pluginSystem=new lX(this.context,[g2,gz,g3,gJ,g7,gH,g6,gU,...a.experiments?.taro?[function({name:x,appId:e,icons:t,widgets:r}){return{name:vr,setup:a=>{let n=(0,vt.createRequire)(import.meta.url);a.view.hooks.modifyEntryOption.tapPromise({name:vr,stage:a.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:x})=>{let{appDirectory:e,isDev:t,pages:r,widgets:n}=a.context,_=ve(r,e,!1,t);return{entry:x=Object.assign(x,_,ve(n,e,!0,t))}}),a.view.hooks.beforeBuild.tapPromise({name:vr,stage:a.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:x})=>{let{appDirectory:e}=a.context;c2(x,{resolve:{alias:{"@tarojs/components":n.resolve("@doubao-dev/taro-runtime/components",{paths:[e]}),"@tarojs/taro":(0,r7.dirname)(n.resolve("@doubao-dev/taro-runtime/package.json",{paths:[e]}))}}})}),a.worker.hooks.modifyEntryOption.tapPromise({name:vr,stage:a.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:t})=>{let{appDirectory:r,isDev:n}=a.context,{app:_}=a.context;return _&&(t.app=function(x,e,t,r,a=!1){var n;let _=`${iX}${r4.sep}app.js`,A=(n=c3(r4.dirname(_),x)).startsWith(".")?n:`./${n}`,s=c9(e);return new vx(_,`
532
532
  import { Applet } from "${s}";
533
533
  import { defineApp } from '${s}';
534
534
  import { APP_ID, getLifecycle, setCurrentId } from '@doubao-dev/taro-runtime/internal';
@@ -573,4 +573,4 @@ if (import.meta.webpackHot) {
573
573
  import.meta.webpackHot.accept()
574
574
  }
575
575
  `:""}
576
- `)}(_,r,x,e,n)),{entry:t}}),a.worker.hooks.collectMetaData.tapPromise(c9,async({collector:r})=>{r.addAppMeta({name:x,appId:e,icons:t})}),a.view.hooks.collectMetaData.tapPromise({name:c9,stage:a.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:x})=>{let{pages:e,widgets:t}=a.context;Object.entries(e).forEach(([e,t])=>{let{folderName:r}=t;x.addPageMeta(e,{id:lJ(e,r),path:lV(e)})}),Object.entries(t).forEach(([e,t])=>{let a,{folderName:n}=t;x.addWidgetMeta(e,(a=lJ(e,n),{...r?.[n]??r?.[e]??r?.[a]??{},id:a}))})})}}}(a.experiments.taro)]:[],...a.plugins||[]]);let E=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-E,this.context.setVersionTag(n.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let j=await gI({options:a,commandType:x,context:this.context,rsbuildPlugins:t},this.pluginSystem);return{userConfig:a,builder:j}}catch(e){throw ga.report({appDirectory:this.appDirectory,context:this.context===r?void 0:this.context,scene:x===rV.DEV?"dev_initial":x,status:"failed",errorStage:"prepare",error:e}),e}}async dev(x){let e,t,{builder:r}=await this.prepare(rV.DEV,{...x,openWebDebugger:x.openWebDebugger??x.web},x.rsbuildPlugins);this.context.manifestSettings=function({cwd:x=process.cwd()}={}){let e=r4.resolve(x,gC);if(r5.existsSync(e))try{let x=JSON.parse(r5.readFileSync(e,"utf-8"));if(!oS(x))throw TypeError("开发配置必须是 JSON 对象");return x}catch(x){oa.warn("加载开发配置文件失败,已忽略该文件",{path:e,reason:gN(x)});return}}({cwd:this.appDirectory});let a=await r.startDevServer(),n=this.context.webDebuggerLaunchOptions;try{let r=await this.context.resolveDevServer(a.port);e=r.host,t=n?await j$(this.context,jO(this.context,r.artifactOrigin)):void 0,x.web&&t&&(os.info("Web 模拟器已就绪",{url:t.url}),!1!==x.autoBrowser&&await t.open())}catch(x){throw await t?.close(),await a.server.close(),x}let _=async()=>{os.info("正在关闭开发服务…");try{await t?.close(),await a.server.close()}finally{await ga.flush()}os.info("开发服务已关闭")};return{host:e,devServerReady:!0,...t?{webDebugger:t}:{},closeServer:_}}async build(x){let{builder:e}=await this.prepare(rV.BUILD,x,x.rsbuildPlugins);try{if(await e.build(),this.copyWebAssetsToRoot(),(x.skipCleanupRootPath||Z())&&x.archive&&x.channel){let{packageResource:e}=await lQ({channelName:x.channel,manifest:this.context.manifest,rootPath:this.rootPath});if(!e)throw Error("Failed to archive package");return{archivePath:e.resource}}}finally{x.skipCleanupRootPath||Z()||r5.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(x){let{builder:e}=await this.prepare(rV.ANALYZE,x);await e.build()}async perf(x){let{builder:e}=await this.prepare(rV.PERF,x);await e.build()}async deploy(x){let e=iO(),t={DOUBAO_CLOUD_BUILD_JOB_ID:process.env.DOUBAO_CLOUD_BUILD_JOB_ID,platform_info_source_digest:process.env.platform_info_source_digest},{builder:r}=await this.prepare(rV.DEPLOY,x,[...x.rsbuildPlugins??[],{name:"CloudCardCheckReport",setup(x){x.onAfterBuild(({stats:x})=>{e=iO(x)})}}]),a=x.deployType||lZ.NORMAL;if(this.context.deploy={...this.context.deploy,...x.appId?{appId:x.appId}:{},...x.versionCode?{versionCode:x.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.selfBuilt){if(a!==lZ.NORMAL)return void oA.error("请在 doubao.config.ts 中配置部署插件");let n=function(x,e=process.env){let t=e.DOUBAO_CLOUD_BUILD_JOB_ID?.trim(),r=e.platform_info_source_digest?.trim();if(!t&&!r)return x=>({});if(!x||!t||!r||!/^sha256:[a-f0-9]{64}$/.test(r))throw Error("Cloud card check upload requires a build token, worker job ID and source SHA-256.");return x=>({cloudBuildJobID:t,cardCheckJSON:JSON.stringify({...x,source_digest:r})})}(x.token,t),_=yi(x.token);await r.build(),this.copyWebAssetsToRoot();let A=x.appId;return await yo({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...A?{appKey:A}:{},manifest:this.context.manifest,rootPath:this.rootPath,...n(e),..._})}(x.build||a===lZ.NORMAL)&&(await r.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:a})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(x,e){switch(x){case oG.DEV:return await this.dev(e);case oG.BUILD:return await this.build(e);case oG.ANALYZE:return await this.analyze(e);case oG.PERF:return await this.perf(e);case oG.DEPLOY:return await this.deploy(e)}}async getUserConfig(x){if(!this._userConfig){let e=(0,N.loadEnv)({cwd:this.appDirectory,mode:x.envMode}),t=await gD({cwd:this.appDirectory,customConfigFile:x.config});this._env=Object.fromEntries(Object.entries(e.parsed).filter(([x])=>"DOUBAO_DEPLOY_COOKIE"!==x)),t.source||={},t.source.define={...e.publicVars,...t.source.define},x.debugDriver&&(t.debugDriver=x.debugDriver),void 0!==x.skipAdbForegroundAppWatch&&(t.skipAdbForegroundAppWatch=x.skipAdbForegroundAppWatch),this._userConfig=t}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let x=[this.context.manifest?.applet.web?.appRuntimeEntry,...this.context.manifest?.applet.pages?.map(x=>x.web?.entry)??[],...this.context.manifest?.widgets?.map(x=>x.web?.entry)??[]].filter(x=>!!x);if(0===x.length)return;let e=r4.resolve(this.appDirectory,"dist");for(let t of(r5.existsSync(r4.join(e,"base"))&&x.push("base"),x)){let x=r4.resolve(e,t);if(x!==e&&!x.startsWith(`${e}${r4.sep}`))throw Error(`Web 构建产物路径超出输出根目录:${t}`);if(!r5.existsSync(x))throw Error(`构建完成后未找到 Web 构建产物:${x}`);let r=r4.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`,t);r5.mkdirSync(r4.dirname(r),{recursive:!0}),r5.cpSync(x,r,{recursive:!0})}let t=r4.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`),r=r4.resolve(t,"base","manifest.json");r5.mkdirSync(r4.dirname(r),{recursive:!0}),r5.writeFileSync(r,JSON.stringify(this.context.manifest),"utf-8")}async getAppConfig(){if(!this._appConfigLoaded){let x=await this.getUserConfig({});if(x.experiments?.taro)return this._appConfig=await gT({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await gL({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(x,e){let{pages:t,widgets:r,auth:a}=await gZ(x,e),{app:n,tools:_}=await gM(x,e.tools);return{pages:t,widgets:r,auth:a,app:n,tools:_}}}async function yv(x){let e=await ol(x);if(!e)throw Error("未检测到可用的 Android 设备。");return e}function yd({compileHooks:x,output:e,onCardCheck:t}){let r=new Map,a={percentage:0},n=()=>{if(0===r.size)return;let x=[...r.values()].reduce((x,e)=>e.percentage<x.percentage?e:x);(x.percentage!==a.percentage||x.stage!==a.stage)&&(a=x,e?.onProgress?.(x))},_=x=>{for(let e of(r.clear(),x))r.set(e,{percentage:0});a={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(a){t&&a.onAfterBuild(({stats:x})=>t(iO(x))),e?.printLogs===!1&&(a.logger.level="silent"),e?.progressBar!==void 0&&a.modifyRsbuildConfig(x=>((x.dev??={}).progressBar=e.progressBar,x)),e?.onProgress&&(a.modifyRspackConfig((x,{appendPlugins:e,environment:t,environments:a})=>{0===r.size&&_(Object.keys(a)),e(new N.rspack.ProgressPlugin((x,e)=>{r.set(t.name,{percentage:Math.max(0,Math.min(1,x)),...e?{stage:e}:{}}),n()}))}),a.onBeforeDevCompile(({environments:x})=>{_(Object.keys(x))})),a.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DoubaoAppsDevPlugin",e=>x?.onDevCompileFailed?.(e))}),a.onAfterDevCompile(({stats:e})=>{if(r.size>0){for(let x of r.keys())r.set(x,{percentage:1,stage:"done"});n()}x?.onAfterDevCompile?.(j7(e))})}}]}class yf{appDirectory;launcher;constructor(x,e=yc){this.appDirectory=x,this.launcher=new e(x)}async create(x){await ry(x)}async dev(x={}){let{compileHooks:e,output:t,simulator:r,rsbuildPlugins:a=[],...n}=x,_=r;if("object"==typeof r){let{businessTemplatesPath:x,manifestPath:e,skillsDirectory:t,targetOrigin:a,...n}=r;_={...n,simulator:{businessTemplatesPath:x,manifestPath:e,skillsDirectory:t,targetOrigin:a}}}let A=()=>this.launcher.dev({...n,...void 0!==_?{openWebDebugger:_}:{},rsbuildPlugins:[...yd({compileHooks:e,output:t}),...a],signingEncryptionOptions:x.signingEncryptionOptions});return t?await M(t,A):await A()}async build(x={}){process.env.NODE_ENV="production";let{compileHooks:e,rsbuildPlugins:t=[],...r}=x,a=iO(),n=await this.launcher.build({...r,rsbuildPlugins:[...yd({compileHooks:e,onCardCheck:x=>{a=x}}),...t],signingEncryptionOptions:x.signingEncryptionOptions,versionTag:x.versionTag});return{cardCheck:a,...n}}getAppId(){let x=this.launcher.context;return x?.metadata.appId??x?.appId}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:x})=>!i0(x))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(x){let{widgetId:e,deviceId:t,botId:r,widgetData:a,debugDriver:n,skipAdbForegroundAppWatch:_}=x,A=await yv({debugDriver:n,deviceId:t,skipAdbForegroundAppWatch:_}),s=this.launcher.context.metadata.appId;await A.pushWidget({appId:s,widgetId:e,widgetData:a,botId:r})}async openPage(x){let{pageId:e,pageData:t,pageSettings:r,mode:a,debugDriver:n,deviceId:_,skipAdbForegroundAppWatch:A}=x,s=await yv({debugDriver:n,deviceId:_,skipAdbForegroundAppWatch:A}),i=this.launcher.context.metadata.appId;await s.openPage({appId:i,pageId:e,pageData:t,pageSettings:r,mode:a})}async openPageUrl(x){let{url:e,debugDriver:t,deviceId:r,skipAdbForegroundAppWatch:a}=x,n=await yv({debugDriver:t,deviceId:r,skipAdbForegroundAppWatch:a});await n.openPageUrl({appId:this.launcher.context.metadata.appId,url:e})}async callTool(x){let{toolId:e,toolData:t,debugDriver:r,deviceId:a,skipAdbForegroundAppWatch:n}=x,_=await yv({debugDriver:r,deviceId:a,skipAdbForegroundAppWatch:n}),A=this.launcher.context.metadata.appId;await _.callTool({appId:A,toolId:e,toolData:t})}async executeDebugScene(x){let{matchedScene:e,variables:t,deviceId:r,debugDriver:a,skipAdbForegroundAppWatch:n}=x,_=this.launcher.context.metadata.appId,A=await yv({debugDriver:a,deviceId:r,skipAdbForegroundAppWatch:n});await ow({matchedScene:e,appId:_,driver:A,variables:t})}async getDebugScenes(){let x=await oB(this.appDirectory||process.cwd());return await Promise.all(x.map(async x=>({...x,content:await oF(x.path)})))}async cloudPackage(x={}){let e=this.appDirectory||process.cwd(),t=r4.resolve(e,x.appDir||".");(0,N.loadEnv)({cwd:t,mode:x.envMode});let r=await iF({appDir:t,outputDir:x.outputDir?r4.resolve(e,x.outputDir):void 0});for(let x of r.warnings)o_.warn(x);if(r.blockers.length>0)throw Error(r.blockers.join("\n"));return r.archivePath}async deploy(x={}){let{versionTag:e,token:t,appKey:r,signingEncryptionOptions:a}=x,n=yi(t);process.env.NODE_ENV="production";try{await this.launcher.build({skipCleanupRootPath:!0,...r?{appId:r}:{},signingEncryptionOptions:a,skipAppInfoFetch:!0,token:t,versionTag:e});let{manifest:x}=this.launcher.context;return await yo({versionTag:this.launcher.context.versionTag,...r?{appKey:r}:{},manifest:x,rootPath:this.launcher.rootPath,...n})}finally{!Z()&&r4.isAbsolute(this.launcher.rootPath)&&r5.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{yf as DoubaoAppsSDK,iS as getRootDependencyOptions};
576
+ `)}(_,r,x,e,n)),{entry:t}}),a.worker.hooks.collectMetaData.tapPromise(vr,async({collector:r})=>{r.addAppMeta({name:x,appId:e,icons:t})}),a.view.hooks.collectMetaData.tapPromise({name:vr,stage:a.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:x})=>{let{pages:e,widgets:t}=a.context;Object.entries(e).forEach(([e,t])=>{let{folderName:r}=t;x.addPageMeta(e,{id:cz(e,r),path:cW(e)})}),Object.entries(t).forEach(([e,t])=>{let a,{folderName:n}=t;x.addWidgetMeta(e,(a=cz(e,n),{...r?.[n]??r?.[e]??r?.[a]??{},id:a}))})})}}}(a.experiments.taro)]:[],...a.plugins||[]]);let j=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-j,this.context.setVersionTag(_.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let g=await gS({options:a,commandType:x,context:this.context,rsbuildPlugins:t},this.pluginSystem);return{userConfig:a,builder:g}}catch(e){throw gn.report({appDirectory:this.appDirectory,context:this.context===r?void 0:this.context,scene:x===rV.DEV?"dev_initial":x,status:"failed",errorStage:"prepare",error:e}),e}}async dev(x){let e,t,{builder:r}=await this.prepare(rV.DEV,{...x,openWebDebugger:x.openWebDebugger??x.web},x.rsbuildPlugins);this.context.manifestSettings=function({cwd:x=process.cwd()}={}){let e=r4.resolve(x,gw);if(r5.existsSync(e))try{let x=JSON.parse(r5.readFileSync(e,"utf-8"));if(!oS(x))throw TypeError("开发配置必须是 JSON 对象");return x}catch(x){oa.warn("加载开发配置文件失败,已忽略该文件",{path:e,reason:gI(x)});return}}({cwd:this.appDirectory});let a=await r.startDevServer(),n=this.context.webDebuggerLaunchOptions;try{let r=await this.context.resolveDevServer(a.port);e=r.host,t=n?await jG(this.context,jX(this.context,r.artifactOrigin)):void 0,x.web&&t&&(os.info("Web 模拟器已就绪",{url:t.url}),!1!==x.autoBrowser&&await t.open())}catch(x){throw await t?.close(),await a.server.close(),x}let _=async()=>{os.info("正在关闭开发服务…");try{await t?.close(),await a.server.close()}finally{await gn.flush()}os.info("开发服务已关闭")};return{host:e,devServerReady:!0,...t?{webDebugger:t}:{},closeServer:_}}async build(x){let{builder:e}=await this.prepare(rV.BUILD,x,x.rsbuildPlugins);try{if(await e.build(),this.copyWebAssetsToRoot(),(x.skipCleanupRootPath||Z())&&x.archive&&x.channel){let{packageResource:e}=await lQ({channelName:x.channel,manifest:this.context.manifest,rootPath:this.rootPath});if(!e)throw Error("Failed to archive package");return{archivePath:e.resource}}}finally{x.skipCleanupRootPath||Z()||r5.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(x){let{builder:e}=await this.prepare(rV.ANALYZE,x);await e.build()}async perf(x){let{builder:e}=await this.prepare(rV.PERF,x);await e.build()}async deploy(x){let e=iO(),t={DOUBAO_CLOUD_BUILD_JOB_ID:process.env.DOUBAO_CLOUD_BUILD_JOB_ID,platform_info_source_digest:process.env.platform_info_source_digest},{builder:r}=await this.prepare(rV.DEPLOY,x,[...x.rsbuildPlugins??[],{name:"CloudCardCheckReport",setup(x){x.onAfterBuild(({stats:x})=>{e=iO(x)})}}]),a=x.deployType||lZ.NORMAL;if(this.context.deploy={...this.context.deploy,...x.appId?{appId:x.appId}:{},...x.versionCode?{versionCode:x.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.selfBuilt){if(a!==lZ.NORMAL)return void oA.error("请在 doubao.config.ts 中配置部署插件");let n=function(x,e=process.env){let t=e.DOUBAO_CLOUD_BUILD_JOB_ID?.trim(),r=e.platform_info_source_digest?.trim();if(!t&&!r)return x=>({});if(!x||!t||!r||!/^sha256:[a-f0-9]{64}$/.test(r))throw Error("Cloud card check upload requires a build token, worker job ID and source SHA-256.");return x=>({cloudBuildJobID:t,cardCheckJSON:JSON.stringify({...x,source_digest:r})})}(x.token,t),_=yi(x.token);await r.build(),this.copyWebAssetsToRoot();let A=x.appId;return await yo({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...A?{appKey:A}:{},manifest:this.context.manifest,rootPath:this.rootPath,...n(e),..._})}(x.build||a===lZ.NORMAL)&&(await r.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:a})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(x,e){switch(x){case oG.DEV:return await this.dev(e);case oG.BUILD:return await this.build(e);case oG.ANALYZE:return await this.analyze(e);case oG.PERF:return await this.perf(e);case oG.DEPLOY:return await this.deploy(e)}}async getUserConfig(x){if(!this._userConfig){let e=(0,N.loadEnv)({cwd:this.appDirectory,mode:x.envMode}),t=await gk({cwd:this.appDirectory,customConfigFile:x.config});this._env=Object.fromEntries(Object.entries(e.parsed).filter(([x])=>"DOUBAO_DEPLOY_COOKIE"!==x)),t.source||={},t.source.define={...e.publicVars,...t.source.define},x.debugDriver&&(t.debugDriver=x.debugDriver),void 0!==x.skipAdbForegroundAppWatch&&(t.skipAdbForegroundAppWatch=x.skipAdbForegroundAppWatch),this._userConfig=t}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let x=this.context.manifest;if(!x)return;let e=new cY(this.context.manifestAssetPath,JSON.stringify(x));g5(this.context,e,this.context.pages,this.context.widgets);let t=[["web",x],["preview",e.manifest]],r=r4.resolve(this.appDirectory,"dist");for(let[x,e]of t){let t=[e.applet.web?.appRuntimeEntry,e.applet.web?.toolRuntimeEntry,...e.applet.pages?.map(x=>x.web?.entry)??[],...e.widgets?.map(x=>x.web?.entry)??[]].filter(x=>!!x);if(0===t.length)continue;r5.existsSync(r4.join(r,"base"))&&t.push("base");let a=r4.resolve(this.rootPath,`${x}_${e.versionCode}`);for(let x of t){let e=r4.resolve(r,x);if(e!==r&&!e.startsWith(`${r}${r4.sep}`))throw Error(`Web 构建产物路径超出输出根目录:${x}`);if(!r5.existsSync(e))throw Error(`构建完成后未找到 Web 构建产物:${e}`);let t=r4.resolve(a,x);r5.mkdirSync(r4.dirname(t),{recursive:!0}),r5.cpSync(e,t,{recursive:!0})}let n=r4.resolve(a,"base","manifest.json");r5.mkdirSync(r4.dirname(n),{recursive:!0}),r5.writeFileSync(n,JSON.stringify(e),"utf-8")}}async getAppConfig(){if(!this._appConfigLoaded){let x=await this.getUserConfig({});if(x.experiments?.taro)return this._appConfig=await gq({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await gD({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(x,e){let{pages:t,widgets:r,auth:a}=await gM(x,e),{app:n,tools:_}=await gQ(x,e?.tools);return{pages:t,widgets:r,auth:a,app:n,tools:_}}}async function yv(x){let e=await ol(x);if(!e)throw Error("未检测到可用的 Android 设备。");return e}function yd({compileHooks:x,output:e,onCardCheck:t}){let r=new Map,a={percentage:0},n=()=>{if(0===r.size)return;let x=[...r.values()].reduce((x,e)=>e.percentage<x.percentage?e:x);(x.percentage!==a.percentage||x.stage!==a.stage)&&(a=x,e?.onProgress?.(x))},_=x=>{for(let e of(r.clear(),x))r.set(e,{percentage:0});a={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(a){t&&a.onAfterBuild(({stats:x})=>t(iO(x))),e?.printLogs===!1&&(a.logger.level="silent"),e?.progressBar!==void 0&&a.modifyRsbuildConfig(x=>((x.dev??={}).progressBar=e.progressBar,x)),e?.onProgress&&(a.modifyRspackConfig((x,{appendPlugins:e,environment:t,environments:a})=>{0===r.size&&_(Object.keys(a)),e(new N.rspack.ProgressPlugin((x,e)=>{r.set(t.name,{percentage:Math.max(0,Math.min(1,x)),...e?{stage:e}:{}}),n()}))}),a.onBeforeDevCompile(({environments:x})=>{_(Object.keys(x))})),a.onAfterCreateCompiler(({compiler:e})=>{for(let t of"compilers"in e?e.compilers:[e])t.hooks.failed.tap("DoubaoAppsDevPlugin",e=>x?.onDevCompileFailed?.(e))}),a.onAfterDevCompile(({stats:e})=>{if(r.size>0){for(let x of r.keys())r.set(x,{percentage:1,stage:"done"});n()}x?.onAfterDevCompile?.(j8(e))})}}]}class yf{appDirectory;launcher;constructor(x,e=yc){this.appDirectory=x,this.launcher=new e(x)}async create(x){await ry(x)}async dev(x={}){let{compileHooks:e,output:t,simulator:r,rsbuildPlugins:a=[],...n}=x,_=r;if("object"==typeof r){let{businessTemplatesPath:x,manifestPath:e,skillsDirectory:t,targetOrigin:a,...n}=r;_={...n,simulator:{businessTemplatesPath:x,manifestPath:e,skillsDirectory:t,targetOrigin:a}}}let A=()=>this.launcher.dev({...n,...void 0!==_?{openWebDebugger:_}:{},rsbuildPlugins:[...yd({compileHooks:e,output:t}),...a],signingEncryptionOptions:x.signingEncryptionOptions});return t?await M(t,A):await A()}async build(x={}){process.env.NODE_ENV="production";let{compileHooks:e,rsbuildPlugins:t=[],...r}=x,a=iO(),n=await this.launcher.build({...r,rsbuildPlugins:[...yd({compileHooks:e,onCardCheck:x=>{a=x}}),...t],signingEncryptionOptions:x.signingEncryptionOptions,versionTag:x.versionTag});return{cardCheck:a,...n}}getAppId(){let x=this.launcher.context;return x?.metadata.appId??x?.appId}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:x})=>!i0(x))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(x){let{widgetId:e,deviceId:t,botId:r,widgetData:a,debugDriver:n,skipAdbForegroundAppWatch:_}=x,A=await yv({debugDriver:n,deviceId:t,skipAdbForegroundAppWatch:_}),s=this.launcher.context.metadata.appId;await A.pushWidget({appId:s,widgetId:e,widgetData:a,botId:r})}async openPage(x){let{pageId:e,pageData:t,pageSettings:r,mode:a,debugDriver:n,deviceId:_,skipAdbForegroundAppWatch:A}=x,s=await yv({debugDriver:n,deviceId:_,skipAdbForegroundAppWatch:A}),i=this.launcher.context.metadata.appId;await s.openPage({appId:i,pageId:e,pageData:t,pageSettings:r,mode:a})}async openPageUrl(x){let{url:e,debugDriver:t,deviceId:r,skipAdbForegroundAppWatch:a}=x,n=await yv({debugDriver:t,deviceId:r,skipAdbForegroundAppWatch:a});await n.openPageUrl({appId:this.launcher.context.metadata.appId,url:e})}async callTool(x){let{toolId:e,toolData:t,debugDriver:r,deviceId:a,skipAdbForegroundAppWatch:n}=x,_=await yv({debugDriver:r,deviceId:a,skipAdbForegroundAppWatch:n}),A=this.launcher.context.metadata.appId;await _.callTool({appId:A,toolId:e,toolData:t})}async executeDebugScene(x){let{matchedScene:e,variables:t,deviceId:r,debugDriver:a,skipAdbForegroundAppWatch:n}=x,_=this.launcher.context.metadata.appId,A=await yv({debugDriver:a,deviceId:r,skipAdbForegroundAppWatch:n});await ow({matchedScene:e,appId:_,driver:A,variables:t})}async getDebugScenes(){let x=await oB(this.appDirectory||process.cwd());return await Promise.all(x.map(async x=>({...x,content:await oF(x.path)})))}async cloudPackage(x={}){let e=this.appDirectory||process.cwd(),t=r4.resolve(e,x.appDir||".");(0,N.loadEnv)({cwd:t,mode:x.envMode});let r=await iF({appDir:t,outputDir:x.outputDir?r4.resolve(e,x.outputDir):void 0});for(let x of r.warnings)o_.warn(x);if(r.blockers.length>0)throw Error(r.blockers.join("\n"));return r.archivePath}async deploy(x={}){let{versionTag:e,token:t,appKey:r,signingEncryptionOptions:a}=x,n=yi(t);process.env.NODE_ENV="production";try{await this.launcher.build({skipCleanupRootPath:!0,...r?{appId:r}:{},signingEncryptionOptions:a,skipAppInfoFetch:!0,token:t,versionTag:e});let{manifest:x}=this.launcher.context;return await yo({versionTag:this.launcher.context.versionTag,...r?{appKey:r}:{},manifest:x,rootPath:this.launcher.rootPath,...n})}finally{!Z()&&r4.isAbsolute(this.launcher.rootPath)&&r5.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{yf as DoubaoAppsSDK,iS as getRootDependencyOptions};