@doubao-dev/cli 0.0.34 → 0.0.36

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.
Files changed (142) hide show
  1. package/dist/1232.js +1 -0
  2. package/dist/1264.js +1 -0
  3. package/dist/1611.js +2 -0
  4. package/dist/2232.js +60 -0
  5. package/dist/2507.js +1 -0
  6. package/dist/275.js +5 -8
  7. package/dist/2932.js +1 -1
  8. package/dist/4525.js +1 -1
  9. package/dist/4880.js +1 -1
  10. package/dist/4931.js +1 -1
  11. package/dist/{3688.js → 5887.js} +3 -3
  12. package/dist/6438.js +140 -0
  13. package/dist/6976.js +280 -0
  14. package/dist/{8981.js.LICENSE.txt → 6976.js.LICENSE.txt} +108 -0
  15. package/dist/7410.js +1 -2
  16. package/dist/@byted-doubao-apps/create.js +1 -1
  17. package/dist/@byted-doubao-apps/kit.js +1 -1
  18. package/dist/@byted-doubao-apps/login.js +2 -2
  19. package/dist/@byted-doubao-apps/login~1.js +2 -2
  20. package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
  21. package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
  22. package/dist/@byted-hdt/cli.js +1 -1
  23. package/dist/@inquirer/select.js +1 -1
  24. package/dist/{assets/web-sdk-debugger/static/wasm/eaf690f2cd.module.wasm → @lynx-js/static/wasm/77fb77f77f.module.wasm} +0 -0
  25. package/dist/@lynx-js/{web-core-canary.js → web-core.js} +2 -2
  26. package/dist/app.js +1 -1
  27. package/dist/assets/web-sdk-debugger/__doubao_web_sdk_native_modules/applet-bridge-module-core.js +1 -1
  28. package/dist/assets/web-sdk-debugger/index.html +1 -1
  29. package/dist/assets/web-sdk-debugger/preact-devtools/index.js +4 -1
  30. package/dist/assets/web-sdk-debugger/static/css/index.ef5d8bc5ad.css +1 -0
  31. package/dist/assets/web-sdk-debugger/static/js/{682.de47e82f6b.js → 426.53c43a8594.js} +2 -2
  32. package/dist/assets/web-sdk-debugger/static/js/479.26e0b1d922.js +1829 -0
  33. package/dist/assets/web-sdk-debugger/static/js/async/503.259fed5610.js +1 -0
  34. package/dist/assets/web-sdk-debugger/static/js/async/{legacy-wasm-js.bacc8b5564.js → legacy-wasm-js.9b9367f818.js} +2 -2
  35. package/dist/assets/web-sdk-debugger/static/js/async/lynx-core-chunk.7f5e94dfae.js +5 -0
  36. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.f78260697f.js +1 -0
  37. package/dist/assets/web-sdk-debugger/static/js/async/web-core-markup-encoder.33c43c480e.js +4 -0
  38. package/dist/assets/web-sdk-debugger/static/js/async/web-core-template-loader-thread.ba290b32d7.js +4 -0
  39. package/dist/assets/web-sdk-debugger/static/js/async/web-core-worker-chunk.9a5989b104.js +1 -0
  40. package/dist/assets/web-sdk-debugger/static/js/async/web-elements.3fbd53918e.js +365 -0
  41. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.efd0ffb051.js +5 -0
  42. package/dist/assets/web-sdk-debugger/static/js/async/{xmarkdown-deps.3ea5672b2c.js.LICENSE.txt → xmarkdown-deps.efd0ffb051.js.LICENSE.txt} +1 -1
  43. package/dist/assets/web-sdk-debugger/static/js/index.b6e5c76345.js +44 -0
  44. package/dist/assets/web-sdk-debugger/static/js/lib-polyfill.c91181f230.js +1 -0
  45. package/dist/assets/web-sdk-debugger/static/wasm/{69a8ba8eb9.module.wasm → 4c402c7981.module.wasm} +0 -0
  46. package/dist/assets/web-sdk-debugger/static/wasm/{03b02f9e5a.module.wasm → 72aaf7d0aa.module.wasm} +0 -0
  47. package/dist/{@lynx-js/static/wasm/eaf690f2cd.module.wasm → assets/web-sdk-debugger/static/wasm/77fb77f77f.module.wasm} +0 -0
  48. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
  49. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
  50. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-react-dev.template.js +0 -0
  51. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-react.template.js +0 -0
  52. package/dist/browser.js +1 -1
  53. package/dist/build.js +1 -1
  54. package/dist/build~1.js +10 -10
  55. package/dist/check.js +1 -1
  56. package/dist/client.js +1 -0
  57. package/dist/client~1.js +1 -0
  58. package/dist/components-loader.js +1 -1
  59. package/dist/demo-server.js +2 -2
  60. package/dist/demo.js +2 -2
  61. package/dist/dev-config.js +2 -2
  62. package/dist/dev-shell.js +1 -1
  63. package/dist/dev.js +19 -16
  64. package/dist/explore.js +10 -0
  65. package/dist/gen-explore.js +1 -1
  66. package/dist/gen-trajectory.js +1 -1
  67. package/dist/info.js +2 -2
  68. package/dist/init.js +4 -4
  69. package/dist/ink.js +1 -1
  70. package/dist/inquirer.js +1 -1
  71. package/dist/json-file.js +2 -2
  72. package/dist/legacy-status.js +1 -1
  73. package/dist/legacy-upload.js +1 -1
  74. package/dist/lepus.js +1 -1
  75. package/dist/login.js +2 -1
  76. package/dist/main.js +1 -1
  77. package/dist/{manifest-mcp-config.js → manifest-headers.js} +1 -1
  78. package/dist/ora.js +1 -1
  79. package/dist/portal.js +1 -1
  80. package/dist/project-layout.js +1 -1
  81. package/dist/project.js +1 -1
  82. package/dist/prompt.js +8 -8
  83. package/dist/prompts.js +1 -1
  84. package/dist/qrcode.js +1 -0
  85. package/dist/report.js +1 -1
  86. package/dist/run-registry.js +1 -1
  87. package/dist/run.js +321 -321
  88. package/dist/sandbox.js +1 -1
  89. package/dist/scan.js +1 -1
  90. package/dist/sdk.js +192 -59
  91. package/dist/sdk~1.js +66 -58
  92. package/dist/server.js +10 -10
  93. package/dist/skill.js +1 -1
  94. package/dist/skills.js +1 -1
  95. package/dist/skills~1.js +1 -1
  96. package/dist/status.js +1 -1
  97. package/dist/status~1.js +2 -2
  98. package/dist/stop.js +1 -1
  99. package/dist/sync.js +1 -1
  100. package/dist/trajectory.js +3 -0
  101. package/dist/update.js +1 -1
  102. package/dist/upgrade.js +1 -1
  103. package/dist/workspace.js +1 -1
  104. package/dist/yaml.js +1 -1
  105. package/package.json +7 -7
  106. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +2 -2
  107. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/06-/350/267/257/347/224/261.md +4 -0
  108. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/07-/347/225/214/351/235/242.md +8 -0
  109. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/26-/345/237/272/347/241/200/344/277/241/346/201/257.md +2 -1
  110. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/33-/345/261/217/345/271/225.md +124 -8
  111. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/groups.md +1 -1
  112. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +2 -1
  113. package/skills/doubao-agentic-service-development/references/frontend/examples/page-widget-basics.md +1 -0
  114. package/skills/doubao-agentic-service-development/references/frontend/guides/client-tools-and-events.md +209 -0
  115. package/skills/doubao-agentic-service-development/references/frontend/guides/component-development.md +7 -1
  116. package/skills/doubao-agentic-service-development/references/frontend/guides/debugger-mcp.md +1 -1
  117. package/skills/doubao-agentic-service-development/references/frontend/widget-templates/overview.md +13 -9
  118. package/skills/doubao-agentic-service-development/references/frontend/widget-templates/props.md +26 -1
  119. package/skills/doubao-agentic-service-development/references/frontend-dev.md +2 -0
  120. package/dist/2168.js +0 -60
  121. package/dist/318.js +0 -1
  122. package/dist/3974.js +0 -151
  123. package/dist/6427.js +0 -126
  124. package/dist/7417.js +0 -204
  125. package/dist/7417.js.LICENSE.txt +0 -107
  126. package/dist/7945.js +0 -1
  127. package/dist/8981.js +0 -78
  128. package/dist/assets/web-sdk-debugger/static/css/index.7c65607402.css +0 -1
  129. package/dist/assets/web-sdk-debugger/static/js/670.8a8f0f7d57.js +0 -1829
  130. package/dist/assets/web-sdk-debugger/static/js/async/503.cf61731bba.js +0 -1
  131. package/dist/assets/web-sdk-debugger/static/js/async/lynx-core-chunk.afc1ded023.js +0 -5
  132. package/dist/assets/web-sdk-debugger/static/js/async/web-core-main-chunk.7fe9af852c.js +0 -1
  133. package/dist/assets/web-sdk-debugger/static/js/async/web-core-markup-encoder.f81d6d2cae.js +0 -4
  134. package/dist/assets/web-sdk-debugger/static/js/async/web-core-template-loader-thread.4a49f8a286.js +0 -4
  135. package/dist/assets/web-sdk-debugger/static/js/async/web-core-worker-chunk.c315fd6753.js +0 -1
  136. package/dist/assets/web-sdk-debugger/static/js/async/web-elements.43d1e29387.js +0 -365
  137. package/dist/assets/web-sdk-debugger/static/js/async/xmarkdown-deps.3ea5672b2c.js +0 -5
  138. package/dist/assets/web-sdk-debugger/static/js/index.9f626ba3a2.js +0 -44
  139. package/dist/assets/web-sdk-debugger/static/js/lib-polyfill.9daa7c863e.js +0 -1
  140. package/dist/simulator-client.js +0 -1
  141. /package/dist/{7410.js.LICENSE.txt → 1611.js.LICENSE.txt} +0 -0
  142. /package/dist/assets/web-sdk-debugger/static/js/{670.8a8f0f7d57.js.LICENSE.txt → 479.26e0b1d922.js.LICENSE.txt} +0 -0
package/dist/sdk.js CHANGED
@@ -1,5 +1,130 @@
1
1
  /*! LICENSE: sdk.js.LICENSE.txt */
2
- let e,t,n,r,o,i,a;import"node:module";import{LAYERS as s,pluginReactLynx as l}from"@lynx-js/react-rsbuild-plugin";import{createRspeedy as p,mergeRspeedyConfig as d,rspack as c}from"@lynx-js/rspeedy";import{pluginLess as u}from"@rsbuild/plugin-less";import{pluginSass as m}from"@rsbuild/plugin-sass";import h from"tinypool";import{__webpack_require__ as f}from"./rslib-runtime.js";import{external_node_stream_promises_namespaceObject as g,external_node_tty_namespaceObject as y,external_node_https_namespaceObject as b,external_node_timers_promises_namespaceObject as _,core_namespaceObject as v,external_node_process_namespaceObject as w,external_better_opn_namespaceObject as S,promises_namespaceObject as E}from"./7945.js";import{schemas_number as x,schemas_enum as A,McpServer as T,unknown as C,dist_esm as I,schemas_string as P,schemas_object as O,createMcpHandler as D,pluginReactAlias as k,schemas_boolean as $,toNodeHandler as R,lodash_es_get as N,lodash_es_merge as L,schemas_array as M,record as j,getWebSdkDebuggerDistPath as B,eraseLines as U,lodash_es_mergeWith as F,pluginExternalBundle as H}from"./7417.js";import{external_node_module_namespaceObject as W}from"./3551.js";import{parseDebugScene as V,isRecord as G,getDebugSceneVariableEntries as q,BoxType as J,normalizeHttpEndpoint as K,parseSandboxSimulatorToolCallEvent as z,TitleType as Y,RenderType as X,AUTH_META as Z,normalizeWidgetSourceEntry as Q,resolveDebugScene as ee,execaCommand as et,APP_DEVELOPER_ORIGIN as en}from"./8981.js";import{walk_simple as er}from"./7526.js";import"./4525.js";import"./yaml.js";import{VIRTUAL_INJECTED_FILE as eo,DEPLOY_PACKAGE as ei,getPPEEnvironmentHeader as ea,deployLogger as es,VIRTUAL_INJECTED_STYLE_FILE as el,CONVENTIONAL_FILE_NAME_PRIVACY as ep,isExternalBundleDisabled as ed,isInternal as ec,isDebugMode as eu,ENTRY_FILE_TSX as em,configLogger as eh,loggers_buildLogger as ef,isAppTemplateJsDisabled as eg,CONVENTIONAL_FILE_NAME_LOGIN as ey,MANIFEST_FILE as eb,resolveCachedLoginCookie as e_,resolveWebDebuggerMcpEndpoint as ev,ENTRY_FILE_TS as ew,APP_PACKAGE_NAME as eS,MANIFEST_SIGN_FILE as eE,VIRTUAL_INJECTED_STYLE_CONTENT as ex,isDebugDriverName as eA,loadAppConfig as eT,CONVENTIONAL_DIR_NAME_WIDGET as eC,getErrorMessage as eI,FRAMEWORK_REACT_EXTERNAL_LIBRARY_NAMES as eP,resolveFrameworkPackage as eO,command_ECommand as eD,AI_MANIFEST as ek,CLIENT_TOOL_RUNTIME_ENTRY_KEY as e$,isDebugLogEnabled as eR,buildLogger as eN,SCM_DEPLOY_PACKAGE_FOLDER as eL,MCP_PRIVACY_LOGIN_CARD as eM,CloudBuildLauncher as ej,requestDoubaoAppsPlatform as eB,runWithLoggerOutput as eU,resolveLoginCookie as eF,fetchDoubaoAppsPlatform as eH,resolveConfigFile as eW,logger as eV,WIDGETS as eG,TMP_DIR as eq,DebugDriverType as eJ,DEBUG_DRIVER_NAMES as eK,devServerLogger as ez,cloneNormalizedAppConfig as eY,EXPIRED_WIDGET as eX,INTERNAL_FRAMEWORK_PACKAGE as eZ,isGenerateLoginCardDisabled as eQ,Command as e0,loadConfig as e1,DEK_FILE_NAME as e2,PUBLIC_FRAMEWORK_PACKAGE as e3,getLocalAreaNetworkUrl as e4,isInternalWidgetId as e5,PRIVACY as e9,isSelfContainedBuild as e8,FRAMEWORK_PACKAGE_NAMES as e7,importConfig as e6,APP_CONFIG_NAME as te,loadDevSettings as tt,DOUBAO_APP_OUTPUT_FOLDER as tn,getFrameworkComponentsPackage as tr,getSigningEncryptionOptions as to,getRequestPPELane as ti,getLocalAreaNetworkAddress as ta,getFrameworkApiPackage as ts}from"./6427.js";import tl from"./inquirer.js";import{source as tp,TeaUploader as td}from"./3688.js";import{wrapper as tc}from"./wrapper.js";import{create as tu}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"(e,t,n){e.exports=n.p+"static/assets/web-view-proxy-bootstrap.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"(e,t,n){e.exports=n.p+"static/assets/web-view-proxy-page-client.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"(e,t,n){e.exports=n.p+"static/assets/web-view-proxy-service-worker.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js+t_74cfcecd4de87dca5f35abdf10f99dcc/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"(e,t,n){e.exports=n.p+"static/assets/encode-worker.js"}});class tm{}function th(e,t=3e3){return et(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function tf(e,t){return th(`adb -s ${e} ${t}`)}async function tg(e){let t=(await th(`adb -s ${e} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return t?.[1]}async function ty(e,t){let n=(await tf(e,`shell pidof ${t}`)).stdout.trim();return n?n.split(/\s+/)[0]:void 0}async function tb(e){let t=await tg(e);return(t===eS.DOUBAO||t===eS.PLAYGROUND)&&(await th(`adb -s ${e} shell am force-stop ${t}`),await th(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function t_(){return(await th("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function tv(){let e=await t_();if(e.length>1){let{device:t}=await tl.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class tw extends tm{deviceId;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(e,t={}){if(super(),this.deviceId=e,t.skipForegroundAppWatch)return;let n=setInterval(()=>{this.watchAppProcess()},500);process.once("exit",()=>clearInterval(n))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let e=await ty(this.deviceId,eS.DOUBAO);void 0!==this.lastAppProcessId&&void 0!==e&&this.lastAppProcessId!==e&&await this.reloadOnAppRestart(e),void 0!==e&&(this.lastAppProcessId=e)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(e){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(e=>setTimeout(e,5e3)),await ty(this.deviceId,eS.DOUBAO)!==e)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(e){this.latestLoadParams=e;let{appletUrl:t,appId:n,isSigned:r}=e,o=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${n} --es appletHost ${t} --es appletType 1 --es isSigned ${r}`;eu()&&console.log(tp.dim(`adb -s ${this.deviceId} ${o}`)),await tf(this.deviceId,o)}async openPage(e){let{appId:t,pageId:n,pageData:r,pageSettings:o,mode:i}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${n} --es appletPageData '${r}' --es appletPageSettings '${o}' --es mode '${i}'`;eu()&&console.log(tp.dim(`adb -s ${this.deviceId} ${a}`)),await tf(this.deviceId,a)}async openPageUrl(e){let{appId:t,url:n}=e,r=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageUrl '${n}'`;eu()&&console.log(tp.dim(`adb -s ${this.deviceId} ${r}`)),await tf(this.deviceId,r)}async pushWidget(e){let{appId:t,widgetId:n,widgetData:r,botId:o}=e,i=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${t} --es widgetName ${n} --es widgetData '${r}' --es botId ${o||process.env.DEBUG_BOT_ID}`;eu()&&console.log(tp.dim(`adb -s ${this.deviceId} ${i}`)),await tf(this.deviceId,i)}async callTool(e){let{appId:t,toolId:n,toolData:r}=e,o=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${t} --es toolName '${n}' --es toolData '${r}'`;eu()&&console.log(tp.dim(`adb -s ${this.deviceId} ${o}`)),await tf(this.deviceId,o)}}class tS extends tm{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}class tE{options;currentUrl=null;debugDriver=null;appId=null;constructor(e){this.options=e}async start(e,t,n){if(null!==this.currentUrl){this.currentUrl=e,this.debugDriver?.getAllAppClients().forEach(e=>this.onConnect(e,n));return}this.currentUrl=e,this.appId=t;let{getDebugDriver:r,toolkitExecutor:o}=await import("./@byted-hdt/cli.js").then(f.bind(f,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_debug@4.4.3/node_modules/@byted-hdt/cli/dist/es/index.js"));await o({runType:"rspeedy",openWebview:this.options.devtool});let i=r();this.debugDriver=i,i.getAllAppClients().forEach(e=>this.onConnect(e,n)),i.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(e){this.debugDriver?.getAllAppClients().forEach(t=>{try{t.sendCustomizedMessage(e.method,e.params,-1,"CDP")}catch(e){ez.error("向 HDT 客户端发送消息失败",{error:e})}})}onConnect=(e,t)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:t}})}}class tx extends tm{server;constructor(){super(),this.server=new tE({devtool:!0,open:!0})}async load(e){let{appletUrl:t,appId:n,isSigned:r}=e;this.server.start(t,n,r)}async openPage(e){let{appId:t,pageId:n,pageData:r,pageSettings:o,mode:i}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:n,appletPageData:r,appletPageSettings:o,mode:i}})}async openPageUrl(e){let{appId:t,url:n}=e;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:t,url:n}})}async pushWidget(e){let{appId:t,widgetId:n,widgetData:r,botId:o}=e;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:t,widgetName:n,widgetData:r,botId:o||process.env.DEBUG_BOT_ID}})}async callTool(e){let{appId:t,toolId:n,toolData:r}=e;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:t,toolName:n,toolData:r}})}}async function tA(t={}){if(!e){let n=t.debugDriver??eJ.Adb;if(!eA(n))throw Error(`无效的调试驱动 "${n}",可选值:${eK.join(", ")}。`);switch(n){case eJ.Hdt:e=new tx;break;case eJ.DevTools:e=new tS;break;case eJ.Adb:{let n=t.deviceId??await tv();n&&(e=new tw(n,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${n}",可选值:${eK.join(", ")}。`)}}return e}let tT=f("node:fs/promises"),tC=f("node:path");async function tI(e){let t=(0,tC.join)(e,"debug-scene");try{return(await (0,tT.readdir)(t,{withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(".json")).map(e=>({name:e.name.slice(0,-5),path:(0,tC.join)(t,e.name)}))}catch{return[]}}async function tP(e){try{return V(JSON.parse(await (0,tT.readFile)(e,"utf8")))}catch(t){return eu()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function tO(e,t){let{matchedScene:n,appId:r,driver:o,variables:i}=e,a=t??await tP(n.path);if(!a)return;let s=ee(a,i);if("page"===s.type){var l,p;l=n.name,0!==(p=s.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${p.map(e=>`{{${e}}}`).join(", ")}`),await o.openPageUrl({appId:r,url:s.url})}else if("widget"===s.type){let e=JSON.stringify(s.resolvedInput),t={appId:r,widgetId:s.id,widgetData:e,botId:s.botId};await o.pushWidget(t)}else{let e=JSON.stringify(s.resolvedInput),t={appId:r,toolId:s.id,toolData:e};await o.callTool(t)}}let tD="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tk(e){if("string"==typeof e){let t=e.length>0?e:tD;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||tD,"2x":e?.["2x"]||tD,"3x":e?.["3x"]||tD}}function t$(e){let t=Object.keys(e);return t.sort(),t.reduce((t,n)=>(t[n]=e[n],t),{})}class tR{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tN extends tR{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,n){let r=this._metadata;return{id:r.id,name:r.name,path:r.path,description:r.description,keywords:r.keywords,digest:t,prop:r.prop,entry:e,renderType:n,title:r.title,chat:r.chat}}}class tL extends tR{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,n,r=[]){let o=this._metadata;return{widgetId:o.id,name:o.name,description:o.description,keywords:o.keywords,digest:t,prop:o.prop,entry:e,renderType:n,border:o.border,appSettings:r,boxType:"full_box"===o.boxType?J.FULL_BOX:J.INBOX,titleType:o.titleType?tL.TITLE_TYPE_MAP[o.titleType]:void 0}}}tL.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tM extends tR{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(){let e=this._metadata;return{id:e.id,name:e.name,description:e.description,timeout:e.timeout}}}class tj extends tR{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest({toolsMetadata:e,hashCode:t,appRuntimeEntry:n,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:tk(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:n,appRuntimeType:r}}}class tB{constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(e){this.metadata.app.metadata?this.metadata.app.assign(e):this.metadata.app=new tj(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tM(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tN(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tL(t)}getData(){let{tools:e,pages:t,widgets:n,app:r}=this.metadata;return{app:r.metadata??{},tools:t$(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:t$(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:t$(Object.fromEntries(Object.keys(n).map(e=>[e,n[e].metadata])))}}getInstance(){let{tools:e,pages:t,widgets:n,app:r}=this.metadata;return{app:r,tools:t$(e),pages:t$(t),widgets:t$(n)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}let tU={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tF={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tH={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tW={...tU,...tF,...tH},tV={...tU,...tF,...tH};(nP=nD||(nD={}))[nP.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",nP[nP.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",nP[nP.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",nP[nP.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",nP[nP.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",nP[nP.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",nP[nP.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tG=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tq(){return{modifyEnvironment:new tG.FU(["arg0"]),modifyEntryOption:new tG.BD(["arg0"]),beforeBuild:new tG.FU(["arg0"]),collectMetaData:new tG.FU(["arg0"]),build:new tG.FU(["arg0"]),afterBuild:new tG.FU(["arg0"])}}function tJ({hooks:e,stages:t}){return{hooks:e,...t}}class tK{constructor(e,t=[]){this.plugins=[],this.api={...{worker:tJ({hooks:tq(),stages:tV}),view:tJ({hooks:tq(),stages:tW}),assets:tJ({hooks:{beforeEmit:new tG.FU(["arg0"]),afterEmit:new tG.FU(["arg0"])},stages:nD}),deploy:tJ({hooks:{beforeDeploy:new tG.FU(["arg0"]),deploy:new tG.FU(["arg0"]),afterDeploy:new tG.FU(["arg0"])},stages:{}})},context:e},this.addPlugins(t)}getScopeHooks(e){return this.api[e].hooks}addPlugins(e){this.plugins.push(...e)}async bootstrap(){for await(let e of this.plugins)await e.setup(this.api)}async callScopeHooks(e,t,...n){let r=N(this.getScopeHooks(e),t);return await r.promise(...n)}async callWorkerHooks(e,...t){return this.callScopeHooks("worker",e,...t)}async callViewHooks(e,...t){return this.callScopeHooks("view",e,...t)}async callAssetsHooks(e,...t){return this.callScopeHooks("assets",e,...t)}async callDeployHooks(e,...t){return this.callScopeHooks("deploy",e,...t)}}let tz=f("fs"),tY=f("path"),tX=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function tZ(e,t,n,r){return new Promise((o,i)=>{let a=tz.createWriteStream(e),s=tX("zip",{zlib:{level:9}});s.pipe(a),s.directory(t,n??!1),a.on("close",()=>{r?.deleteResource&&tz.rmSync(t,{recursive:!0}),eN.success("Compiled artifacts packaged",{file:tY.basename(e)}),o("")}),s.on("error",e=>{eN.error("An error occurred during packaging",{error:e}),i(e)}),s.finalize()})}let tQ=f("node:fs");async function t0({channelName:e,manifest:t,rootPath:n}){let r=tC.resolve(n),o=tC.resolve(n,tn),i=tC.resolve(o,t.packageName),a={outputFolder:o,transformFolder:i,manifest:t};tQ.existsSync(o)&&tQ.rmSync(o,{recursive:!0}),tQ.mkdirSync(o),tQ.mkdirSync(i),function(e,t){let{transformFolder:n,manifest:r}=t,{applet:o,widgets:i}=r,a=tC.resolve(e,"base"),s=tC.resolve(n,"base");tQ.mkdirSync(s),tQ.cpSync(a,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=tC.resolve(e,o.appletId),p=tC.resolve(n,o.appletId);tQ.mkdirSync(p),o.pages.length>0&&tQ.cpSync(l,p,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),i.forEach(t=>{let r=tC.resolve(e,t.widgetId),o=tC.resolve(n,t.widgetId);tQ.mkdirSync(o),tQ.cpSync(r,o,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})});let d=tC.resolve(e,`web_${r.versionCode}`);if(tQ.existsSync(d)){let e=tC.resolve(n,`web_${r.versionCode}`);tQ.cpSync(d,e,{recursive:!0})}}(r,a);let s=await t1(e,a);return eN.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function t1(e,t){if(!/([a-z0-9_-]+)/.test(e))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:n,outputFolder:r,transformFolder:o}=t,{applet:i,widgets:a,packageName:s,versionCode:l}=n,p=tC.resolve(r,ei),d=tC.resolve(p,e),c=tC.resolve(d,s);tQ.mkdirSync(p),tQ.mkdirSync(d),tQ.mkdirSync(c),tQ.cpSync(o,c,{recursive:!0});let u={},m=tQ.readdirSync(c).filter(e=>tQ.statSync(tC.resolve(c,e)).isDirectory()),h=tC.resolve(p,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if(e===`web_${l}`)return Promise.resolve();if("base"===e)return tZ(tC.resolve(c,`${e}_${l}.zip`),tC.resolve(c,e),e,{deleteResource:!0});if(e===i.appletId){let t=`${e}_${i.digest}.zip`;return u[i.appletId]=t,tZ(tC.resolve(c,t),tC.resolve(c,e),e,{deleteResource:!0})}let t=a.find(t=>t.widgetId===e);if(t){let n=`${e}_${t.digest}.zip`;return u[t.widgetId]=n,tZ(tC.resolve(c,n),tC.resolve(c,e),e,{deleteResource:!0})}return eN.error("Invalid package directory",{directory:e}),Promise.resolve()})),await tZ(h,d,e),process.env.BUILD_VERSION){let e=tC.resolve(r,eL),t=tC.resolve(e,s);tQ.mkdirSync(e),tQ.mkdirSync(t),tQ.cpSync(c,t,{recursive:!0})}return eN.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(nO=nk||(nk={})).NORMAL="normal",nO.SELF_BUILT_CREATE="selfBuiltCreate",nO.SELF_BUILT_PUBLISH="selfBuiltPublish",nO.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",nO.SELF_BUILT_STOP="selfBuiltStop",nO.SELF_BUILT_ROLLBACK="selfBuiltRollback";let t2={NORMAL:nk.NORMAL,SELF_BUILT_CREATE:nk.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:nk.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:nk.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:nk.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:nk.SELF_BUILT_ROLLBACK};function t3(e,t){let n=(t||e).replace(/^\/+/,"").split("/").filter(Boolean);return n.length>1&&"index"===n[n.length-1]?n[n.length-2]||"index":n[n.length-1]||"index"}function t4(e,t){let[n]=(t??e).split(/[?#]/,1),r=n.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return r?`/${r}`:"/"}function t5(e,t,n){let r=t4(t).slice(1);return`${e}/${r}/${n}`}function t9(e,...t){return F(e,...t,(e,t,n)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let t8=(e,t)=>tC.relative(e,t).replaceAll(tC.sep,"/");class t7{constructor(e,t=""){this.imports=[],this.contents=[],this._filename=e,t&&this.appendContent(t)}appendImports(...e){this.imports.push(...e)}appendContent(...e){this.contents.push(...e)}unshiftContent(...e){this.contents.unshift(...e)}get filename(){return this._filename}toString(){return[this.imports.map(e=>{if(e.importSpecifiers&&e.importSpecifiers.length>0){let t="",n=e.importSpecifiers.find(e=>"default"===e.propertyName),r=e.importSpecifiers.filter(e=>"default"!==e.propertyName);return n&&(t+=`${n.name}`),r.length&&(n&&(t+=", "),t+=`{ ${r.map(e=>e.name===e.propertyName?e.name:`${e.propertyName} as ${e.name}`).join(", ")} }`),`import ${t} from "${e.moduleSpecifier}";`}return`import "${e.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(e){if(this._filename){let t=tY.dirname(this._filename);(0,tz.existsSync)(t)||(0,tz.mkdirSync)(t,{recursive:!0}),(0,tz.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function t6(e,t,n=!1,r=!1){return Object.keys(e).reduce((o,i)=>{let{filename:a,isVirtualFile:s,isSpecial:l}=e[i];if(s||l)return o;let p=`${eq}${tC.sep}${i}${tC.extname(a)}`,d=t8(tC.join(t,p,".."),a),c=eO(t),u=n?"defineWidget":"definePage";return o[i]=new t7(p),o[i].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:c,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:u,name:u}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),o[i].appendContent(`
2
+ let e,t,r,n,i,a,o;import"node:module";import{LAYERS as s,pluginReactLynx as l}from"@lynx-js/react-rsbuild-plugin";import{createRspeedy as c,mergeRspeedyConfig as p,rspack as d}from"@lynx-js/rspeedy";import{pluginLess as u}from"@rsbuild/plugin-less";import{pluginSass as m}from"@rsbuild/plugin-sass";import h from"tinypool";import{__webpack_require__ as f}from"./rslib-runtime.js";import{external_node_stream_promises_namespaceObject as g,core_namespaceObject as y,external_node_tty_namespaceObject as b,external_node_https_namespaceObject as _,external_node_timers_promises_namespaceObject as v,external_jiti_namespaceObject as E,external_node_process_namespaceObject as w,external_better_opn_namespaceObject as S,promises_namespaceObject as x}from"./1264.js";import{external_node_module_namespaceObject as A}from"./3551.js";import{parseDebugScene as T,schemas_enum as I,schemas_number as O,unknown as P,TokenExpiredError as C,AUTH_META as R,normalizeWidgetSourceEntry as $,resolveDebugScene as k,schemas_object as N,createMcpHandler as L,prepareCloudBuildSource as D,withAuth as j,ExternalsLoadingPlugin as M,schemas_boolean as U,lodash_es_get as B,TitleType as F,RenderType as H,schemas_record as W,getWebSdkDebuggerDistPath as G,eraseLines as V,NotLoggedInError as q,parseSandboxSimulatorToolCallEvent as J,lodash_es_mergeWith as z,isRecord as K,getDebugSceneVariableEntries as Y,McpServer as X,dist_esm as Z,schemas_string as Q,APP_DEVELOPER_ORIGIN as ee,execaCommand as et,normalizeHttpEndpoint as er,toNodeHandler as en,schemas_array as ei,lodash_es_merge as ea,BoxType as eo,APP_DEVELOPER_DOMAIN as es}from"./6976.js";import{walk_simple as el}from"./7526.js";import"./4525.js";import"./yaml.js";import{source as ec,TeaUploader as ep}from"./5887.js";import ed from"./inquirer.js";import{DebugDriverType as eu,DEBUG_DRIVER_NAMES as em,getLocalAreaNetworkUrl as eh,isDebugDriverName as ef,getLocalAreaNetworkAddress as eg}from"./2507.js";import{wrapper as ey}from"./wrapper.js";import{create as eb}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-bootstrap.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-page-client.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"(e,t,r){e.exports=r.p+"static/assets/web-view-proxy-service-worker.js"},"../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js+t_e17ab80716e3a051afc8527cc96a064b/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"(e,t,r){e.exports=r.p+"static/assets/encode-worker.js"}});let e_=f("node:async_hooks"),ev=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),eE=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,ew=new e_.AsyncLocalStorage;function eS(){return(process.env.DEBUG??"").toLocaleLowerCase().split(",").includes("applet0930")}function ex(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function eA(e,t=new WeakSet){if(null==e)return String(e);if("string"==typeof e)return/^[\w./:@-]+$/.test(e)&&e.length>0?e:JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(e instanceof Error)return eA(e.message,t);if("object"!=typeof e)return String(e);if(t.has(e))return'"[Circular]"';t.add(e);let r=Array.isArray(e)?`[${e.map(e=>eA(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>{let n=eE.test(ex(e))?'"[REDACTED]"':eA(r,t);return`${JSON.stringify(e)}:${n}`}).join(",")}}`;return t.delete(e),r}function eT(e){return ec.cyan(`[${e}]`.padEnd(ev))}function eI(e={}){let t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),r=t["x-tt-env"],n=t["x-use-ppe"],i=Array.isArray(r)?r.join(","):r;return n&&i?String(i):void 0}function eO(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[ex(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let r=eE.test(e)?"[REDACTED]":eA(t);return ec.dim(`${e}=${r}`)}).join(" ")}let eP=new class e{constructor(e={}){this.sink=e.sink??y.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??eS}child(t,r={}){return new e({sink:this.sink,tag:t,context:{...this.context,...r},isDebug:this.isDebugEnabled})}withContext(t){return new e({sink:this.sink,tag:this.tag,context:{...this.context,...t},isDebug:this.isDebugEnabled})}info(e,t){this.emit("info",e,t)&&this.sink.info(this.formatMessage(e,t))}success(e,t){this.emit("info",e,t)&&this.sink.success(this.formatMessage(e,t))}start(e,t){this.emit("info",e,t)&&this.sink.start(this.formatMessage(e,t))}ready(e,t){this.emit("info",e,t)&&this.sink.ready(this.formatMessage(e,t))}warn(e,t){this.emit("warn",e,t)&&this.sink.warn(this.formatMessage(e,t))}debug(e,t){if(this.isDebugEnabled()&&this.emit("debug",e,t)){let r=this.formatMessage(e,t);this.sink===y.logger?y.logger.log(r):this.sink.debug(r)}}error(e,t={}){let r,{error:n,...i}=t,a=this.tag?`${eT(this.tag)} `:"",o=e instanceof Error?e.message:String(e),s=`${a}${o}`;if(void 0!==n)s+=`: ${n instanceof Error?n.message:eA(n)}`,this.isDebugEnabled()&&n instanceof Error&&n.stack&&(r=n.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(r=e.stack);let l=eO({...this.context,...i});l&&(s+=` ${l}`),r&&(s+=`
3
+ ${r}`),this.emit("error",o,{...i,...void 0!==n?{error:n}:{}})&&this.sink.error(s)}greet(e){this.emit("info",e)&&this.sink.greet(e)}request(e){var t;let r,n,i,a,o,s,l,c=e.timestamp??new Date,p=ec.gray(`[${(r=c.getFullYear(),n=String(c.getMonth()+1).padStart(2,"0"),i=String(c.getDate()).padStart(2,"0"),a=String(c.getHours()).padStart(2,"0"),o=String(c.getMinutes()).padStart(2,"0"),s=String(c.getSeconds()).padStart(2,"0"),l=String(c.getMilliseconds()).padStart(3,"0"),`${r}-${n}-${i} ${a}:${o}:${s}.${l}`)}]`),d=ec.bold(e.method),u=void 0===e.durationMs?"":` ${ec.dim(`${e.durationMs.toFixed(1)}ms`)}`,m=eI(e.headers),h=Array.isArray(e.logId)?e.logId.join(","):e.logId,f=[m?eO({ppe:m}):"",h?eO({logid:h}):"",eO({...this.context,...e.context})].filter(Boolean).join(" "),g=`${this.tag?`${eT(this.tag)} `:""}${p} ${d} ${e.url} ${((t=e.statusCode)>=500?ec.red:t>=400?ec.yellow:ec.green)(String(t))}${u}${f?` ${f}`:""}`,y=e.statusCode>=500?"error":e.statusCode>=400?"warn":"info";this.emit(y,`${e.method} ${e.url} ${e.statusCode}`,{...e.context,durationMs:e.durationMs,logId:h,ppe:m},c.getTime())&&("error"===y?this.sink.error(g):"warn"===y?this.sink.warn(g):this.sink.info(g))}formatMessage(e,t={}){let r=eO({...this.context,...t}),n=this.tag?`${eT(this.tag)} `:"",i=e instanceof Error?e.message:String(e);return`${n}${i}${r?` ${r}`:""}`}emit(e,t,r={},n=Date.now()){let i=ew.getStore(),a=i?.onLog;if(a)try{a({timestamp:n,level:e,scope:this.tag,message:t instanceof Error?t.message:String(t),context:function(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[ex(e),t]).sort(([e],[t])=>e.localeCompare(t));if(0!==t.length)return Object.fromEntries(t.map(([e,t])=>[e,eE.test(e)?"[REDACTED]":function e(t,r=new WeakSet){if(t instanceof Error)return t.message;if(null===t||"object"!=typeof t)return"bigint"==typeof t?String(t):t;if(r.has(t))return"[Circular]";r.add(t);let n=Array.isArray(t)?t.map(t=>e(t,r)):Object.fromEntries(Object.entries(t).map(([t,n])=>[t,eE.test(ex(t))?"[REDACTED]":e(n,r)]));return r.delete(t),n}(t)]))}({...this.context,...r})})}catch{}return i?.printLogs!==!1}},eC=eP.child("build"),eR=f("path"),e$="./node_modules/.doubao",ek="./node_modules/.injected.js",eN="./node_modules/.injected.css",eL=`.doubao-apps-style-anchor{display:none}
4
+ :root {
5
+ --doubao-picker-view-height: 108px;
6
+ --doubao-picker-view-indicator-radius: 12px;
7
+ --doubao-picker-view-item-height: 36px;
8
+ --doubao-picker-view-item-padding: 0 8px;
9
+ --doubao-picker-view-item-font-size: 15px;
10
+ --doubao-picker-view-item-line-height: 21px;
11
+ --doubao-picker-view-item-font-weight: 500;
12
+ --doubao-picker-view-z-index: 1000;
13
+ }
14
+
15
+ .doubao-picker-view {
16
+ --doubao-picker-view-bg: var(--bg-base-2);
17
+ --doubao-picker-view-indicator-bg: var(--bg-base-3-overlay);
18
+ --doubao-picker-view-item-text-color: var(--neutral-50);
19
+ --doubao-picker-view-item-disabled-color: var(--neutral-30);
20
+ --doubao-picker-view-item-selected-color: var(--neutral-100);
21
+ height: var(--doubao-picker-view-height);
22
+ background: var(--doubao-picker-view-bg);
23
+ flex-direction: row;
24
+ display: flex;
25
+ position: relative;
26
+ overflow: hidden;
27
+ }
28
+
29
+ .doubao-picker-view--embedded {
30
+ z-index: auto;
31
+ width: 100%;
32
+ position: static;
33
+ bottom: auto;
34
+ left: auto;
35
+ right: auto;
36
+ }
37
+
38
+ .doubao-picker-view--fixed {
39
+ position: fixed;
40
+ bottom: 0;
41
+ left: 0;
42
+ right: 0;
43
+ }
44
+
45
+ .doubao-picker-view__columns {
46
+ flex-direction: row;
47
+ flex: 1;
48
+ height: 100%;
49
+ display: flex;
50
+ position: relative;
51
+ }
52
+
53
+ .doubao-picker-view__indicator {
54
+ height: var(--doubao-picker-view-item-height);
55
+ background: var(--doubao-picker-view-indicator-bg);
56
+ border-radius: var(--doubao-picker-view-indicator-radius);
57
+ pointer-events: none;
58
+ z-index: 0;
59
+ position: absolute;
60
+ top: 50%;
61
+ left: 0;
62
+ right: 0;
63
+ transform: translateY(-50%);
64
+ }
65
+
66
+ .doubao-picker-column {
67
+ perspective: 300px;
68
+ flex: 1;
69
+ height: 100%;
70
+ overflow: hidden;
71
+ }
72
+
73
+ .doubao-picker-column__content {
74
+ transform-style: preserve-3d;
75
+ flex-direction: column;
76
+ justify-content: flex-start;
77
+ align-items: center;
78
+ display: flex;
79
+ }
80
+
81
+ .doubao-picker-column__item {
82
+ height: var(--doubao-picker-view-item-height);
83
+ box-sizing: border-box;
84
+ width: 100%;
85
+ padding: var(--doubao-picker-view-item-padding);
86
+ backface-visibility: hidden;
87
+ justify-content: center;
88
+ align-items: center;
89
+ display: flex;
90
+ }
91
+
92
+ .doubao-picker-column__item-text {
93
+ font-size: var(--doubao-picker-view-item-font-size);
94
+ line-height: var(--doubao-picker-view-item-line-height);
95
+ font-weight: var(--doubao-picker-view-item-font-weight);
96
+ color: var(--doubao-picker-view-item-text-color);
97
+ text-overflow: ellipsis;
98
+ white-space: nowrap;
99
+ text-align: center;
100
+ max-width: 100%;
101
+ overflow: hidden;
102
+ }
103
+
104
+ .doubao-picker-column__item--disabled .doubao-picker-column__item-text {
105
+ color: var(--doubao-picker-view-item-disabled-color);
106
+ }
107
+
108
+ .doubao-picker-column__item--selected .doubao-picker-column__item-text {
109
+ color: var(--doubao-picker-view-item-selected-color);
110
+ }
111
+
112
+ .doubao-picker-divider {
113
+ height: var(--doubao-picker-view-item-height);
114
+ flex: none;
115
+ justify-content: center;
116
+ align-self: center;
117
+ align-items: center;
118
+ padding: 0 4px;
119
+ display: flex;
120
+ }
121
+
122
+ .doubao-picker-divider__text {
123
+ font-size: var(--doubao-picker-view-item-font-size);
124
+ line-height: var(--doubao-picker-view-item-line-height);
125
+ font-weight: var(--doubao-picker-view-item-font-weight);
126
+ color: var(--doubao-picker-view-item-selected-color);
127
+ }`,eD="widgets";eR.sep;let ej=`base${eR.sep}manifest.json`,eM=`base${eR.sep}manifest.sign`,eU="mcp-privacy-login-card",eB="__doubao_apps__expired-widget",eF="bundle.keystore",eH={"@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"},eW="client-tool",eG=e=>e===eU||e===eB,eV="app.config",eq=[".js",".ts",".mjs"],eJ="com.larus.nova";class ez{}function eK(e,t=3e3){return et(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function eY(e,t){return eK(`adb -s ${e} ${t}`)}async function eX(e){let t=(await eK(`adb -s ${e} shell dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity' | tail -n 1`)).stdout.match(/\su\d+\s+([^\s\/]+)\//);return t?.[1]}async function eZ(e,t){let r=(await eY(e,`shell pidof ${t}`)).stdout.trim();return r?r.split(/\s+/)[0]:void 0}async function eQ(e){let t=await eX(e);return(t===eJ||"com.flow.aisdk.example"===t)&&(await eK(`adb -s ${e} shell am force-stop ${t}`),await eK(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function e0(){return(await eK("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function e1(){let e=await e0();if(e.length>1){let{device:t}=await ed.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class e2 extends ez{deviceId;latestLoadParams;lastAppProcessId;isWatchingAppProcess=!1;isAutoReloading=!1;constructor(e,t={}){if(super(),this.deviceId=e,t.skipForegroundAppWatch)return;let r=setInterval(()=>{this.watchAppProcess()},500);process.once("exit",()=>clearInterval(r))}async watchAppProcess(){if(!this.isWatchingAppProcess){this.isWatchingAppProcess=!0;try{let e=await eZ(this.deviceId,eJ);void 0!==this.lastAppProcessId&&void 0!==e&&this.lastAppProcessId!==e&&await this.reloadOnAppRestart(e),void 0!==e&&(this.lastAppProcessId=e)}finally{this.isWatchingAppProcess=!1}}}async reloadOnAppRestart(e){if(void 0!==this.latestLoadParams&&!this.isAutoReloading){this.isAutoReloading=!0;try{if(await new Promise(e=>setTimeout(e,5e3)),await eZ(this.deviceId,eJ)!==e)return;await this.load(this.latestLoadParams)}finally{this.isAutoReloading=!1}}}async load(e){this.latestLoadParams=e;let{appletUrl:t,appId:r,isSigned:n}=e,i=`shell am broadcast -a com.bytedance.applet.SET_APPLET_DEBUG_HOST --es appletName ${r} --es appletHost ${t} --es appletType 1 --es isSigned ${n}`;eS()&&console.log(ec.dim(`adb -s ${this.deviceId} ${i}`)),await eY(this.deviceId,i)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:a}=e,o=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${r} --es appletPageData '${n}' --es appletPageSettings '${i}' --es mode '${a}'`;eS()&&console.log(ec.dim(`adb -s ${this.deviceId} ${o}`)),await eY(this.deviceId,o)}async openPageUrl(e){let{appId:t,url:r}=e,n=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageUrl '${r}'`;eS()&&console.log(ec.dim(`adb -s ${this.deviceId} ${n}`)),await eY(this.deviceId,n)}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET_WIDGET --es appletName ${t} --es widgetName ${r} --es widgetData '${n}' --es botId ${i||process.env.DEBUG_BOT_ID}`;eS()&&console.log(ec.dim(`adb -s ${this.deviceId} ${a}`)),await eY(this.deviceId,a)}async callTool(e){let{appId:t,toolId:r,toolData:n}=e,i=`shell am broadcast -a com.bytedance.applet.CALL_TOOL --es appletName ${t} --es toolName '${r}' --es toolData '${n}'`;eS()&&console.log(ec.dim(`adb -s ${this.deviceId} ${i}`)),await eY(this.deviceId,i)}}class e3 extends ez{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}eP.child("cli");let e4=eP.child("config"),e5=eP.child("security"),e9=eP.child("build"),e8=eP.child("deploy"),e7=eP.child("dev-server");class e6{options;currentUrl=null;debugDriver=null;appId=null;constructor(e){this.options=e}async start(e,t,r){if(null!==this.currentUrl){this.currentUrl=e,this.debugDriver?.getAllAppClients().forEach(e=>this.onConnect(e,r));return}this.currentUrl=e,this.appId=t;let{getDebugDriver:n,toolkitExecutor:i}=await import("./@byted-hdt/cli.js").then(f.bind(f,"../../../node_modules/.pnpm/@byted-hdt+cli@0.0.71_debug@4.4.3/node_modules/@byted-hdt/cli/dist/es/index.js"));await i({runType:"rspeedy",openWebview:this.options.devtool});let a=n();this.debugDriver=a,a.getAllAppClients().forEach(e=>this.onConnect(e,r)),a.on("app-client-connected",this.onConnect)}stop(){this.currentUrl=null,this.debugDriver?.off("app-client-connected",this.onConnect)}sendMessage(e){this.debugDriver?.getAllAppClients().forEach(t=>{try{t.sendCustomizedMessage(e.method,e.params,-1,"CDP")}catch(e){e7.error("向 HDT 客户端发送消息失败",{error:e})}})}onConnect=(e,t)=>{null!==this.currentUrl&&null!==this.debugDriver&&null!==this.appId&&this.sendMessage({method:"Applet_AppReload",params:{appletName:this.appId,appletHost:this.currentUrl,appletType:1,isSigned:t}})}}class te extends ez{server;constructor(){super(),this.server=new e6({devtool:!0,open:!0})}async load(e){let{appletUrl:t,appId:r,isSigned:n}=e;this.server.start(t,r,n)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:a}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:r,appletPageData:n,appletPageSettings:i,mode:a}})}async openPageUrl(e){let{appId:t,url:r}=e;this.server.sendMessage({method:"Applet_OpenPageUrl",params:{appletName:t,url:r}})}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e;this.server.sendMessage({method:"Applet_OpenWidget",params:{appletName:t,widgetName:r,widgetData:n,botId:i||process.env.DEBUG_BOT_ID}})}async callTool(e){let{appId:t,toolId:r,toolData:n}=e;this.server.sendMessage({method:"Applet_CallTool",params:{appletName:t,toolName:r,toolData:n}})}}async function tt(t={}){if(!e){let r=t.debugDriver??eu.Adb;if(!ef(r))throw Error(`无效的调试驱动 "${r}",可选值:${em.join(", ")}。`);switch(r){case eu.Hdt:e=new te;break;case eu.DevTools:e=new e3;break;case eu.Adb:{let r=t.deviceId??await e1();r&&(e=new e2(r,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${r}",可选值:${em.join(", ")}。`)}}return e}let tr=f("node:fs/promises"),tn=f("node:path");async function ti(e){let t=(0,tn.join)(e,"debug-scene");try{return(await (0,tr.readdir)(t,{withFileTypes:!0})).filter(e=>e.isFile()&&e.name.endsWith(".json")).map(e=>({name:e.name.slice(0,-5),path:(0,tn.join)(t,e.name)}))}catch{return[]}}async function ta(e){try{return T(JSON.parse(await (0,tr.readFile)(e,"utf8")))}catch(t){return eS()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function to(e,t){let{matchedScene:r,appId:n,driver:i,variables:a}=e,o=t??await ta(r.path);if(!o)return;let s=k(o,a);if("page"===s.type){var l,c;l=r.name,0!==(c=s.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${c.map(e=>`{{${e}}}`).join(", ")}`),await i.openPageUrl({appId:n,url:s.url})}else if("widget"===s.type){let e=JSON.stringify(s.resolvedInput),t={appId:n,widgetId:s.id,widgetData:e,botId:s.botId};await i.pushWidget(t)}else{let e=JSON.stringify(s.resolvedInput),t={appId:n,toolId:s.id,toolData:e};await i.callTool(t)}}let ts="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tl(e){if("string"==typeof e){let t=e.length>0?e:ts;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||ts,"2x":e?.["2x"]||ts,"3x":e?.["3x"]||ts}}function tc(e){let t=Object.keys(e);return t.sort(),t.reduce((t,r)=>(t[r]=e[r],t),{})}class tp{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class td extends tp{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r){let n=this._metadata;return{id:n.id,name:n.name,path:n.path,description:n.description,keywords:n.keywords,digest:t,prop:n.prop,entry:e,renderType:r,title:n.title,chat:n.chat}}}class tu extends tp{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(e,t,r,n=[]){let i=this._metadata;return{widgetId:i.id,name:i.name,description:i.description,keywords:i.keywords,digest:t,prop:i.prop,entry:e,renderType:r,border:i.border,appSettings:n,boxType:tu.BOX_TYPE_MAP[i.boxType??"inbox"]??eo.INBOX,titleType:i.titleType?tu.TITLE_TYPE_MAP[i.titleType]:void 0}}}tu.BOX_TYPE_MAP={inbox:eo.INBOX,full_box:eo.FULL_BOX,custom_box:eo.CUSTOM_BOX},tu.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tm extends tp{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest(){let e=this._metadata;return{id:e.id,name:e.name,description:e.description,timeout:e.timeout}}}class th extends tp{constructor(e){super(),this._metadata=e}assign(e){this._metadata={...this._metadata,...e}}toManifest({toolsMetadata:e,hashCode:t,appRuntimeEntry:r,appRuntimeType:n}){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:tl(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:r,appRuntimeType:n}}}class tf{constructor(){this.metadata={app:{},widgets:{},pages:{},tools:{}}}get app(){return this.metadata.app.metadata??{}}get appId(){return this.app.appId}addAppMeta(e){this.metadata.app.metadata?this.metadata.app.assign(e):this.metadata.app=new th(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tm(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new td(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tu(t)}getData(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n.metadata??{},tools:tc(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tc(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tc(Object.fromEntries(Object.keys(r).map(e=>[e,r[e].metadata])))}}getInstance(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n,tools:tc(e),pages:tc(t),widgets:tc(r)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}(rf=rb||(rb={})).DEV="dev",rf.BUILD="build",rf.PERF="perf",rf.DEPLOY="deploy",rf.ANALYZE="analyze";let tg={DEV:rb.DEV,BUILD:rb.BUILD,PERF:rb.PERF,DEPLOY:rb.DEPLOY,ANALYZE:rb.ANALYZE},ty={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tb={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},t_={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tv={...ty,...tb,...t_},tE={...ty,...tb,...t_};(rg=r_||(r_={}))[rg.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",rg[rg.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",rg[rg.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",rg[rg.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",rg[rg.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",rg[rg.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",rg[rg.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tw=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tS(){return{modifyEnvironment:new tw.FU(["arg0"]),modifyEntryOption:new tw.BD(["arg0"]),beforeBuild:new tw.FU(["arg0"]),collectMetaData:new tw.FU(["arg0"]),build:new tw.FU(["arg0"]),afterBuild:new tw.FU(["arg0"])}}function tx({hooks:e,stages:t}){return{hooks:e,...t}}class tA{constructor(e,t=[]){this.plugins=[],this.api={...{worker:tx({hooks:tS(),stages:tE}),view:tx({hooks:tS(),stages:tv}),assets:tx({hooks:{beforeEmit:new tw.FU(["arg0"]),afterEmit:new tw.FU(["arg0"])},stages:r_}),deploy:tx({hooks:{beforeDeploy:new tw.FU(["arg0"]),deploy:new tw.FU(["arg0"]),afterDeploy:new tw.FU(["arg0"])},stages:{}})},context:e},this.addPlugins(t)}getScopeHooks(e){return this.api[e].hooks}addPlugins(e){this.plugins.push(...e)}async bootstrap(){for await(let e of this.plugins)await e.setup(this.api)}async callScopeHooks(e,t,...r){let n=B(this.getScopeHooks(e),t);return await n.promise(...r)}async callWorkerHooks(e,...t){return this.callScopeHooks("worker",e,...t)}async callViewHooks(e,...t){return this.callScopeHooks("view",e,...t)}async callAssetsHooks(e,...t){return this.callScopeHooks("assets",e,...t)}async callDeployHooks(e,...t){return this.callScopeHooks("deploy",e,...t)}}let tT=f("fs"),tI=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function tO(e,t,r,n){return new Promise((i,a)=>{let o=tT.createWriteStream(e),s=tI("zip",{zlib:{level:9}});s.pipe(o),s.directory(t,r??!1),o.on("close",()=>{n?.deleteResource&&tT.rmSync(t,{recursive:!0}),eC.success("Compiled artifacts packaged",{file:eR.basename(e)}),i("")}),s.on("error",e=>{eC.error("An error occurred during packaging",{error:e}),a(e)}),s.finalize()})}let tP=f("node:fs");async function tC({channelName:e,manifest:t,rootPath:r}){let n=tn.resolve(r),i=tn.resolve(r,"doubao_app_output"),a=tn.resolve(i,t.packageName),o={outputFolder:i,transformFolder:a,manifest:t};tP.existsSync(i)&&tP.rmSync(i,{recursive:!0}),tP.mkdirSync(i),tP.mkdirSync(a),function(e,t){let{transformFolder:r,manifest:n}=t,{applet:i,widgets:a}=n,o=tn.resolve(e,"base"),s=tn.resolve(r,"base");tP.mkdirSync(s),tP.cpSync(o,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=tn.resolve(e,i.appletId),c=tn.resolve(r,i.appletId);tP.mkdirSync(c),i.pages.length>0&&tP.cpSync(l,c,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),a.forEach(t=>{let n=tn.resolve(e,t.widgetId),i=tn.resolve(r,t.widgetId);tP.mkdirSync(i),tP.cpSync(n,i,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})});let p=tn.resolve(e,`web_${n.versionCode}`);if(tP.existsSync(p)){let e=tn.resolve(r,`web_${n.versionCode}`);tP.cpSync(p,e,{recursive:!0})}}(n,o);let s=await tR(e,o);return eC.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function tR(e,t){if(!/([a-z0-9_-]+)/.test(e))throw Error("Channel name is invalid, only support /[a-z0-9_-]+/. archive gecko package failed. ");let{manifest:r,outputFolder:n,transformFolder:i}=t,{applet:a,widgets:o,packageName:s,versionCode:l}=r,c=tn.resolve(n,"deploy-package"),p=tn.resolve(c,e),d=tn.resolve(p,s);tP.mkdirSync(c),tP.mkdirSync(p),tP.mkdirSync(d),tP.cpSync(i,d,{recursive:!0});let u={},m=tP.readdirSync(d).filter(e=>tP.statSync(tn.resolve(d,e)).isDirectory()),h=tn.resolve(c,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if(e===`web_${l}`)return Promise.resolve();if("base"===e)return tO(tn.resolve(d,`${e}_${l}.zip`),tn.resolve(d,e),e,{deleteResource:!0});if(e===a.appletId){let t=`${e}_${a.digest}.zip`;return u[a.appletId]=t,tO(tn.resolve(d,t),tn.resolve(d,e),e,{deleteResource:!0})}let t=o.find(t=>t.widgetId===e);if(t){let r=`${e}_${t.digest}.zip`;return u[t.widgetId]=r,tO(tn.resolve(d,r),tn.resolve(d,e),e,{deleteResource:!0})}return eC.error("Invalid package directory",{directory:e}),Promise.resolve()})),await tO(h,p,e),process.env.BUILD_VERSION){let e=tn.resolve(n,"scm-deploy-package"),t=tn.resolve(e,s);tP.mkdirSync(e),tP.mkdirSync(t),tP.cpSync(d,t,{recursive:!0})}return eC.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(ry=rv||(rv={})).NORMAL="normal",ry.SELF_BUILT_CREATE="selfBuiltCreate",ry.SELF_BUILT_PUBLISH="selfBuiltPublish",ry.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",ry.SELF_BUILT_STOP="selfBuiltStop",ry.SELF_BUILT_ROLLBACK="selfBuiltRollback";let t$={NORMAL:rv.NORMAL,SELF_BUILT_CREATE:rv.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:rv.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:rv.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:rv.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:rv.SELF_BUILT_ROLLBACK};function tk(e,t){let r=(t||e).replace(/^\/+/,"").split("/").filter(Boolean);return r.length>1&&"index"===r[r.length-1]?r[r.length-2]||"index":r[r.length-1]||"index"}function tN(e,t){let[r]=(t??e).split(/[?#]/,1),n=r.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function tL(e,t,r){let n=tN(t).slice(1);return`${e}/${n}/${r}`}function tD(e,...t){return z(e,...t,(e,t,r)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let tj=(e,t)=>tn.relative(e,t).replaceAll(tn.sep,"/"),tM="@byted-doubao-apps/framework",tU="@doubao-dev/framework",tB=[tM,tU];function tF(e){return`${e}/components`}function tH(e){let t=tn.resolve(e,"package.json");if(tP.existsSync(t))try{let e=JSON.parse(tP.readFileSync(t,"utf8")),r={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(r[tU])return tU;if(r[tM])return tM}catch{}}function tW(e){return tH(e)??tM}class tG{constructor(e,t=""){this.imports=[],this.contents=[],this._filename=e,t&&this.appendContent(t)}appendImports(...e){this.imports.push(...e)}appendContent(...e){this.contents.push(...e)}unshiftContent(...e){this.contents.unshift(...e)}get filename(){return this._filename}toString(){return[this.imports.map(e=>{if(e.importSpecifiers&&e.importSpecifiers.length>0){let t="",r=e.importSpecifiers.find(e=>"default"===e.propertyName),n=e.importSpecifiers.filter(e=>"default"!==e.propertyName);return r&&(t+=`${r.name}`),n.length&&(r&&(t+=", "),t+=`{ ${n.map(e=>e.name===e.propertyName?e.name:`${e.propertyName} as ${e.name}`).join(", ")} }`),`import ${t} from "${e.moduleSpecifier}";`}return`import "${e.moduleSpecifier}";`}).join("\n"),...this.contents].join("\n").trim()}write(e){if(this._filename){let t=eR.dirname(this._filename);(0,tT.existsSync)(t)||(0,tT.mkdirSync)(t,{recursive:!0}),(0,tT.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function tV(e,t,r=!1,n=!1){return Object.keys(e).reduce((i,a)=>{let{filename:o,isVirtualFile:s,isSpecial:l}=e[a];if(s||l)return i;let c=`${e$}${tn.sep}${a}${tn.extname(o)}`,p=tj(tn.join(t,c,".."),o),d=tW(t),u=r?"defineWidget":"definePage";return i[a]=new tG(c),i[a].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"getViewData",name:"getViewData"},{propertyName:u,name:u}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"TaroView"}]}),i[a].appendContent(`
3
128
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
4
129
 
5
130
  const View = ${u}({
@@ -8,61 +133,67 @@ const View = ${u}({
8
133
  }
9
134
  });
10
135
 
11
- const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(!n)});
136
+ const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(!r)});
12
137
 
13
- root.render(<FC />);`,r?`
138
+ root.render(<FC />);`,n?`
14
139
  if (import.meta.webpackHot) {
15
140
  import.meta.webpackHot.accept()
16
141
  }
17
- `:""),o},{})}let ne=f("module"),nt="doubao:plugin:taro";class nn extends t7{toString(){return this.contents.join("\n").trim()}}async function nr({config:e,pluginSystem:t}){let n=e.context.environment;await t.callWorkerHooks("modifyEnvironment",{environment:n}),e.context.setEnvironment(n);let{entry:r}=await t.callWorkerHooks("modifyEntryOption",{entry:{app:new nn(`.${tC.sep}app.js`,"")}});return{entry:r}}async function no({compiler:e,compilation:t,assets:n,metadata:r,resolveAppInfo:o,shouldInjectAsset:i}){let a=Object.keys(n).reduce((e,n)=>{if(!i(n))return e;let r=t.getAsset(n);return r&&e.push(r),e},[]);if(0===a.length)return;let s=r.app,l=await o?.(),p=`globalThis.${ek} = ${JSON.stringify({package:l?.appKey||s.appId,appId:l?.appKey||s.appId,name:l?.appName||s.name,icons:l?.iconUrl?tk(l.iconUrl):s.icons})};
18
- `;a.forEach(n=>{if(n.source.source().toString().startsWith(p))return;let r=new e.webpack.sources.ReplaceSource(n.source,n.name);r.insert(0,p),t.updateAsset(n.name,r,n.info)})}function ni(e){let t=tC.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function na(e){let t=e.replaceAll("\\","/");return t.split("/").some(e=>e.startsWith("__doubao_web__"))&&ni(t)}class ns{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(ns.name,t=>{t.hooks.processAssets.tapPromise({name:ns.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async n=>{await no({compiler:e,compilation:t,assets:n,...this.options})})})}}let nl="index.web.bundle",np="base/app.web.bundle",nd="base/client-tool/index.web.bundle";function nc(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function nu(e,t,n){return t[n]?.id??t3(n,e[n]?.folderName)}function nm(e){return!!e?.internal}function nh(e={},t={},n="configured"){return"all"===n?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e,n])=>nm(n)||!!t[e]?.web))}(e,t)}class nf{apply(e){e.hooks.thisCompilation.tap(nf.name,t=>{t.hooks.processAssets.tapPromise({name:nf.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let n=ng(t,"app"),r=n?t.getAsset(n):void 0;if(!n||!r)throw Error("Worker entry asset was not emitted.");await ny(t,e,n,np);let o=ng(t,e$);o&&await ny(t,e,o,nd)})})}}function ng(e,t){let n=e.entrypoints.get(t)?.getEntrypointChunk();return[...n?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function ny(e,t,n,r){let o=e.getAsset(n);if(!o)throw Error(`Worker entry asset was not emitted: ${n}`);e.emitAsset(r,new t.webpack.sources.RawSource(await nb(o.source.source().toString())));let i=e.getAsset(`${n}.map`);i&&e.emitAsset(`${r}.map`,i.source,i.info),e.deleteAsset(n)}async function nb(e){let{encode:t}=await import("./@lynx-js/web-core-canary.js");return Buffer.from(t({styleInfo:{},manifest:{"/app-service.js":e},cardType:"react",appType:"card",pageConfig:{enableFiberArch:!0,useLepusNG:!0,enableReuseContext:!0,bundleModuleMode:"ReturnByFunction",targetSdkVersion:"3.2"},lepusCode:{root:"void 0;"},customSections:{},elementTemplates:{}}))}class n_{options;recordNativeAppAssetPaths;constructor(e,t){this.options=e,this.recordNativeAppAssetPaths=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[eo]:"",[el]:ex,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(n_.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(n_.name,t=>{t.hooks.optimizeTree.tapPromise(n_.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:n_.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async n=>{var r,o,i;let a,s=ng(t,"app");if(!s||!t.getAsset(s))throw Error("Worker entry asset was not emitted.");this.recordNativeAppAssetPaths&&(r=t,o=this.options.context,i=s,o.setAppAssetPath(i),a=`${i}.map`,r.getAsset(a)&&o.setAppMapAssetPath(a)),await no({compiler:e,compilation:t,assets:n,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),shouldInjectAsset:e=>e===s})})}),e.hooks.done.tapPromise(n_.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let nv=f("node:os"),nw=f("process"),nS=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.1.3/node_modules/@lynx-js/type-config/index.js");var nE,nx,nA,nT,nC,nI,nP,nO,nD,nk,n$,nR,nN,nL,nM,nj,nB={},nU={};function nF(e){var t=nU[e];if(void 0!==t)return t.exports;var n=nU[e]={exports:{}};return nB[e](n,n.exports,nF),n.exports}nF.m=nB,nF.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return nF.d(t,{a:t}),t},nF.d=(e,t,n)=>{var r=(t,n)=>{for(var r in t)nF.o(t,r)&&!nF.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,[n]:t[r]})};r(t,"get"),r(n,"value")},nF.add=function(e){Object.assign(nF.m,e)},nF.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),nF.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(e){e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(e,t,n){var r=n("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");e.exports=function(e,t){if(!r(e)&&"function"!=typeof e)return{};var n={};if("string"==typeof t)return t in e&&(n[t]=e[t]),n;for(var o=t.length,i=-1;++i<o;){var a=t[i];a in e&&(n[a]=e[a])}return n}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=nw||{},n=t.argv||[],r=t.env||{},o=!(r.NO_COLOR||n.includes("--no-color"))&&(!!r.FORCE_COLOR||n.includes("--color")||"win32"===t.platform||(t.stdout||{}).isTTY&&"dumb"!==r.TERM||!!r.CI),i=(e,t,n=e)=>r=>{let o=""+r,i=o.indexOf(t,e.length);return~i?e+a(o,t,n,i)+t:e+o+t},a=(e,t,n,r)=>{let o="",i=0;do o+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return o+e.substring(i)},s=(e=o)=>{let t=e?i:()=>String;return{isColorSupported:e,reset:t("\x1b[0m","\x1b[0m"),bold:t("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:t("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:t("\x1b[3m","\x1b[23m"),underline:t("\x1b[4m","\x1b[24m"),inverse:t("\x1b[7m","\x1b[27m"),hidden:t("\x1b[8m","\x1b[28m"),strikethrough:t("\x1b[9m","\x1b[29m"),black:t("\x1b[30m","\x1b[39m"),red:t("\x1b[31m","\x1b[39m"),green:t("\x1b[32m","\x1b[39m"),yellow:t("\x1b[33m","\x1b[39m"),blue:t("\x1b[34m","\x1b[39m"),magenta:t("\x1b[35m","\x1b[39m"),cyan:t("\x1b[36m","\x1b[39m"),white:t("\x1b[37m","\x1b[39m"),gray:t("\x1b[90m","\x1b[39m"),bgBlack:t("\x1b[40m","\x1b[49m"),bgRed:t("\x1b[41m","\x1b[49m"),bgGreen:t("\x1b[42m","\x1b[49m"),bgYellow:t("\x1b[43m","\x1b[49m"),bgBlue:t("\x1b[44m","\x1b[49m"),bgMagenta:t("\x1b[45m","\x1b[49m"),bgCyan:t("\x1b[46m","\x1b[49m"),bgWhite:t("\x1b[47m","\x1b[49m"),blackBright:t("\x1b[90m","\x1b[39m"),redBright:t("\x1b[91m","\x1b[39m"),greenBright:t("\x1b[92m","\x1b[39m"),yellowBright:t("\x1b[93m","\x1b[39m"),blueBright:t("\x1b[94m","\x1b[39m"),magentaBright:t("\x1b[95m","\x1b[39m"),cyanBright:t("\x1b[96m","\x1b[39m"),whiteBright:t("\x1b[97m","\x1b[39m"),bgBlackBright:t("\x1b[100m","\x1b[49m"),bgRedBright:t("\x1b[101m","\x1b[49m"),bgGreenBright:t("\x1b[102m","\x1b[49m"),bgYellowBright:t("\x1b[103m","\x1b[49m"),bgBlueBright:t("\x1b[104m","\x1b[49m"),bgMagentaBright:t("\x1b[105m","\x1b[49m"),bgCyanBright:t("\x1b[106m","\x1b[49m"),bgWhiteBright:t("\x1b[107m","\x1b[49m")}};e.exports=s(),e.exports.createColors=s}});let nH=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 nW=globalThis.navigator?.userAgentData?.platform;function nV(e,t=globalThis.Deno?globalThis.Deno.args:w.argv){let n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),o=t.indexOf("--");return -1!==r&&(-1===o||r<o)}"macOS"===nW||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===nW||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===nW||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===nW||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===nW||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,nH||w.env.TERM_PROGRAM,nH||w.platform,nH||w.cwd;let{env:nG}=w;function nq(e,n={}){var r;return 0!==(r=function(e,{streamIsTTY:n,sniffFlags:r=!0}={}){let o=function(){if(!("FORCE_COLOR"in nG))return;if("true"===nG.FORCE_COLOR)return 1;if("false"===nG.FORCE_COLOR)return 0;if(0===nG.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(nG.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==o&&(t=o);let i=r?t:o;if(0===i)return 0;if(r){if(nV("color=16m")||nV("color=full")||nV("color=truecolor"))return 3;if(nV("color=256"))return 2}if("TF_BUILD"in nG&&"AGENT_NAME"in nG)return 1;if(e&&!n&&void 0===i)return 0;let a=i||0;if("dumb"===nG.TERM)return a;if("win32"===w.platform){let e=nv.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in nG)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in nG)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in nG)||"codeship"===nG.CI_NAME?1:a;if("TEAMCITY_VERSION"in nG)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(nG.TEAMCITY_VERSION);if("truecolor"===nG.COLORTERM||"xterm-kitty"===nG.TERM||"xterm-ghostty"===nG.TERM||"wezterm"===nG.TERM)return 3;if("TERM_PROGRAM"in nG){let e=Number.parseInt((nG.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(nG.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(nG.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(nG.TERM)||"COLORTERM"in nG?1:a}(e,{streamIsTTY:e&&e.isTTY,...n}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function nJ(e,t=nw.argv){let n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),o=t.indexOf("--");return -1!==r&&(-1===o||r<o)}function nK(e=""){if(/^\d{3,4}$/.test(e)){let t=/(\d{1,2})(\d{2})/.exec(e)??[];return{major:0,minor:Number.parseInt(t[1],10),patch:Number.parseInt(t[2],10)}}let t=(e??"").split(".").map(e=>Number.parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function nz(e){let{CI:t,CURSOR_TRACE_ID:n,FORCE_HYPERLINK:r,NETLIFY:o,TEAMCITY_VERSION:i,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:s,VTE_VERSION:l,TERM:p}=w.env;if(r)return!(r.length>0&&0===Number.parseInt(r,10));if(nJ("no-hyperlink")||nJ("no-hyperlinks")||nJ("hyperlink=false")||nJ("hyperlink=never"))return!1;if(nJ("hyperlink=true")||nJ("hyperlink=always")||o)return!0;if(!nq(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in w.env)return!0;if("win32"===w.platform||t||i)return!1;if(a){let e=nK(s);switch(a){case"iTerm.app":if(3===e.major)return e.minor>=1;return e.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(s))return s.slice(11)>="2020-06-20";return e.major>=0x1343cac;case"vscode":if(n)return!0;return e.major>1||1===e.major&&e.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(l){if("0.50.0"===l)return!1;let e=nK(l);return e.major>0||e.minor>=50}switch(p){case"alacritty":case"xterm-kitty":return!0}return!1}nV("no-color")||nV("no-colors")||nV("color=false")||nV("color=never")?t=0:(nV("color")||nV("colors")||nV("color=true")||nV("color=always"))&&(t=1),nq({isTTY:y.isatty(1)}),nq({isTTY:y.isatty(2)});let nY={stdout:nz(w.stdout),stderr:nz(w.stderr)};function nX(e,t,{target:n="stdout",...r}={}){return nY[n]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===r.fallback?e:"function"==typeof r.fallback?r.fallback(e,t):`${e} ${t}`}nX.isSupported=nY.stdout,nX.stderr=(e,t,n={})=>nX(e,t,{target:"stderr",...n}),nX.stderr.isSupported=nY.stderr;let nZ=nF("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var nQ=nF.n(nZ);class n0{options;constructor(e){this.options=e}name="LynxConfigWebpackPlugin";apply(e){e.hooks.thisCompilation.tap(this.name,e=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(e).beforeEncode.tap(this.name,e=>{let{config:t}=this.options;return e.encodeData.compilerOptions={...e.encodeData.compilerOptions,...nQ()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...nQ()(t,this.options.configKeys)},e})})}}let n1=e=>n2.has(e),n2=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"]);(nE=n$||(n$={}))[nE.Start=0]="Start",nE[nE.Property=1]="Property",nE[nE.StringKey=2]="StringKey",nE[nE.NumberKey=3]="NumberKey";let n3=nF("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var n4=nF.n(n3);let n5=Object.assign(a=e=>{if(!1===("object"==typeof e&&null!==e&&!1===Array.isArray(e)&&((e,t=!0)=>(void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C)&&(void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll)&&(void 0===e.enableA11y||"boolean"==typeof e.enableA11y)&&(void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement)&&(void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance)&&(void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables)&&(void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule)&&(void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp)&&(void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor)&&(void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough)&&(void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming)&&(void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew)&&(void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent)&&(void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands)&&(void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException)&&(void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture)&&(void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch)&&(void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList)&&(void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture)&&(void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver)&&(void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin)&&(void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex)&&(void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle)&&(void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap)&&(void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow)&&(void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition)&&(void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp)&&(void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding)&&(void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight)&&(void 0===e.longPressDuration||"number"==typeof e.longPressDuration)&&(void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope)&&(void 0===e.tapSlop||"string"==typeof e.tapSlop)&&(void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior)&&(0===Object.keys(e).length||Object.keys(e).every(t=>!!["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableListNewArchitecture","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>t===e)||void 0===e[t])))(e,!0))){var t;t=o=[],i=(e,n)=>(e&&(e=>{if(0===t.length)return!0;let n=t[t.length-1].path;return e.length>n.length||n.substring(0,e.length)!==e})(n.path)&&(void 0===n.value&&(n.description??=`The value at this path is \`undefined\`.
142
+ `:""),i},{})}let tq=f("module"),tJ="doubao:plugin:taro";class tz extends tG{toString(){return this.contents.join("\n").trim()}}async function tK({config:e,pluginSystem:t}){let r=e.context.environment;await t.callWorkerHooks("modifyEnvironment",{environment:r}),e.context.setEnvironment(r);let{entry:n}=await t.callWorkerHooks("modifyEntryOption",{entry:{app:new tz(`.${tn.sep}app.js`,"")}});return{entry:n}}let tY=e=>void 0!==process.env[e],tX=()=>tY("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||tY("LEGACY_FRAMEWORK"),tZ=()=>tY("DISABLE_APP_TEMPLATE_JS")||tY("LEGACY_FRAMEWORK");function tQ({mcpEndpoint:e}={}){let t=e?.trim();return t||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}async function t0({compiler:e,compilation:t,assets:r,metadata:n,resolveAppInfo:i,resolveVersionTag:a,isNative:o,shouldInjectAsset:s}){var l;let c,p=Object.keys(r).reduce((e,r)=>{if(!s(r))return e;let n=t.getAsset(r);return n&&e.push(n),e},[]);if(0===p.length)return;let d=n.app,u=await i?.(),m=(l=a?.(),c=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:u?.appKey||d.appId,appId:u?.appKey||d.appId,name:u?.appName||d.name,icons:u?.iconUrl?tl(u.iconUrl):d.icons})};
143
+ `,l?`${c}globalThis.__VERSION_TAG__ = ${JSON.stringify(l)};
144
+ `:c),h=new Map;if(o){let{pages:e,widgets:r}=n.getData();for(let[n,i]of t.entrypoints){let t="app"===n?{type:"app",key:n}:n===eW?{type:"client_tool",key:n}:e[n]?{type:"page",key:n,id:e[n].path}:r[n]?{type:"widget",key:n,id:r[n].id}:void 0;if(!t)continue;let a=`try {
145
+ const key = Symbol.for('doubao-apps.runtime-error-state');
146
+ const state = globalThis[key] || (globalThis[key] = {});
147
+ state.entry = Object.freeze(${JSON.stringify(t)});
148
+ } catch {}
149
+ `;for(let e of i.getEntrypointChunk().files)h.set(e,a)}}p.forEach(r=>{let n=m+(h.get(r.name)??"");if(r.source.source().toString().startsWith(n))return;let i=new e.webpack.sources.ReplaceSource(r.source,r.name);i.insert(0,n),t.updateAsset(r.name,i,r.info)})}function t1(e){let t=tn.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function t2(e){let t=e.replaceAll("\\","/");return t.split("/").some(e=>e.startsWith("__doubao_web__"))&&t1(t)}class t3{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(t3.name,t=>{t.hooks.processAssets.tapPromise({name:t3.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{await t0({compiler:e,compilation:t,assets:r,...this.options})})})}}let t4="index.web.bundle",t5="base/app.web.bundle",t9="base/client-tool/index.web.bundle";function t8(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function t7(e,t,r){return t[r]?.id??tk(r,e[r]?.folderName)}function t6(e){return!!e?.internal}function re(e={},t={},r="configured"){return"all"===r?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e,r])=>t6(r)||!!t[e]?.web))}(e,t)}class rt{apply(e){e.hooks.thisCompilation.tap(rt.name,t=>{t.hooks.processAssets.tapPromise({name:rt.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let r=rr(t,"app"),n=r?t.getAsset(r):void 0;if(!r||!n)throw Error("未生成 Worker 入口产物");await rn(t,e,r,t5);let i=rr(t,eW);i&&await rn(t,e,i,t9)})})}}function rr(e,t){let r=e.entrypoints.get(t)?.getEntrypointChunk();return[...r?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function rn(e,t,r,n){let i=e.getAsset(r);if(!i)throw Error(`未生成 Worker 入口产物:${r}`);e.emitAsset(n,new t.webpack.sources.RawSource(await ri(i.source.source().toString())));let a=e.getAsset(`${r}.map`);a&&e.emitAsset(`${n}.map`,a.source,a.info),e.deleteAsset(r)}async function ri(e){let{encode:t}=await import("./@lynx-js/web-core.js");return Buffer.from(t({styleInfo:{},manifest:{"/app-service.js":e},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 ra{options;isNative;constructor(e,t){this.options=e,this.isNative=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[ek]:"",[eN]:eL,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(ra.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(ra.name,t=>{t.hooks.optimizeTree.tapPromise(ra.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:ra.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{var n,i,a;let o,s=rr(t,"app");if(!s||!t.getAsset(s))throw Error("未生成 Worker 入口产物");this.isNative&&(n=t,i=this.options.context,a=s,i.setAppAssetPath(a),o=`${a}.map`,n.getAsset(o)&&i.setAppMapAssetPath(o));let l=rr(t,eW);await t0({compiler:e,compilation:t,assets:r,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),resolveVersionTag:()=>this.options.context.versionTag,isNative:this.isNative,shouldInjectAsset:e=>e===s||e===l})})}),e.hooks.done.tapPromise(ra.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let ro=f("node:os"),rs=f("process"),rl=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.2.0/node_modules/@lynx-js/type-config/index.js");var rc,rp,rd,ru,rm,rh,rf,rg,ry,rb,r_,rv,rE,rw,rS,rx,rA,rT,rI={},rO={};function rP(e){var t=rO[e];if(void 0!==t)return t.exports;var r=rO[e]={exports:{}};return rI[e](r,r.exports,rP),r.exports}rP.m=rI,rP.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return rP.d(t,{a:t}),t},rP.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)rP.o(t,n)&&!rP.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},rP.add=function(e){Object.assign(rP.m,e)},rP.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),rP.add({"../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(e){e.exports=function(e){return null!=e&&"object"==typeof e&&!1===Array.isArray(e)}},"../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js"(e,t,r){var n=r("../../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js");e.exports=function(e,t){if(!n(e)&&"function"!=typeof e)return{};var r={};if("string"==typeof t)return t in e&&(r[t]=e[t]),r;for(var i=t.length,a=-1;++a<i;){var o=t[a];o in e&&(r[o]=e[o])}return r}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=rs||{},r=t.argv||[],n=t.env||{},i=!(n.NO_COLOR||r.includes("--no-color"))&&(!!n.FORCE_COLOR||r.includes("--color")||"win32"===t.platform||(t.stdout||{}).isTTY&&"dumb"!==n.TERM||!!n.CI),a=(e,t,r=e)=>n=>{let i=""+n,a=i.indexOf(t,e.length);return~a?e+o(i,t,r,a)+t:e+i+t},o=(e,t,r,n)=>{let i="",a=0;do i+=e.substring(a,n)+r,a=n+t.length,n=e.indexOf(t,a);while(~n);return i+e.substring(a)},s=(e=i)=>{let t=e?a:()=>String;return{isColorSupported:e,reset:t("\x1b[0m","\x1b[0m"),bold:t("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:t("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:t("\x1b[3m","\x1b[23m"),underline:t("\x1b[4m","\x1b[24m"),inverse:t("\x1b[7m","\x1b[27m"),hidden:t("\x1b[8m","\x1b[28m"),strikethrough:t("\x1b[9m","\x1b[29m"),black:t("\x1b[30m","\x1b[39m"),red:t("\x1b[31m","\x1b[39m"),green:t("\x1b[32m","\x1b[39m"),yellow:t("\x1b[33m","\x1b[39m"),blue:t("\x1b[34m","\x1b[39m"),magenta:t("\x1b[35m","\x1b[39m"),cyan:t("\x1b[36m","\x1b[39m"),white:t("\x1b[37m","\x1b[39m"),gray:t("\x1b[90m","\x1b[39m"),bgBlack:t("\x1b[40m","\x1b[49m"),bgRed:t("\x1b[41m","\x1b[49m"),bgGreen:t("\x1b[42m","\x1b[49m"),bgYellow:t("\x1b[43m","\x1b[49m"),bgBlue:t("\x1b[44m","\x1b[49m"),bgMagenta:t("\x1b[45m","\x1b[49m"),bgCyan:t("\x1b[46m","\x1b[49m"),bgWhite:t("\x1b[47m","\x1b[49m"),blackBright:t("\x1b[90m","\x1b[39m"),redBright:t("\x1b[91m","\x1b[39m"),greenBright:t("\x1b[92m","\x1b[39m"),yellowBright:t("\x1b[93m","\x1b[39m"),blueBright:t("\x1b[94m","\x1b[39m"),magentaBright:t("\x1b[95m","\x1b[39m"),cyanBright:t("\x1b[96m","\x1b[39m"),whiteBright:t("\x1b[97m","\x1b[39m"),bgBlackBright:t("\x1b[100m","\x1b[49m"),bgRedBright:t("\x1b[101m","\x1b[49m"),bgGreenBright:t("\x1b[102m","\x1b[49m"),bgYellowBright:t("\x1b[103m","\x1b[49m"),bgBlueBright:t("\x1b[104m","\x1b[49m"),bgMagentaBright:t("\x1b[105m","\x1b[49m"),bgCyanBright:t("\x1b[106m","\x1b[49m"),bgWhiteBright:t("\x1b[107m","\x1b[49m")}};e.exports=s(),e.exports.createColors=s}});let rC=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 rR=globalThis.navigator?.userAgentData?.platform;function r$(e,t=globalThis.Deno?globalThis.Deno.args:w.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}"macOS"===rR||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===rR||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===rR||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===rR||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===rR||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,rC||w.env.TERM_PROGRAM,rC||w.platform,rC||w.cwd;let{env:rk}=w;function rN(e,r={}){var n;return 0!==(n=function(e,{streamIsTTY:r,sniffFlags:n=!0}={}){let i=function(){if(!("FORCE_COLOR"in rk))return;if("true"===rk.FORCE_COLOR)return 1;if("false"===rk.FORCE_COLOR)return 0;if(0===rk.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(rk.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==i&&(t=i);let a=n?t:i;if(0===a)return 0;if(n){if(r$("color=16m")||r$("color=full")||r$("color=truecolor"))return 3;if(r$("color=256"))return 2}if("TF_BUILD"in rk&&"AGENT_NAME"in rk)return 1;if(e&&!r&&void 0===a)return 0;let o=a||0;if("dumb"===rk.TERM)return o;if("win32"===w.platform){let e=ro.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in rk)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in rk)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in rk)||"codeship"===rk.CI_NAME?1:o;if("TEAMCITY_VERSION"in rk)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rk.TEAMCITY_VERSION);if("truecolor"===rk.COLORTERM||"xterm-kitty"===rk.TERM||"xterm-ghostty"===rk.TERM||"wezterm"===rk.TERM)return 3;if("TERM_PROGRAM"in rk){let e=Number.parseInt((rk.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rk.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rk.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rk.TERM)||"COLORTERM"in rk?1:o}(e,{streamIsTTY:e&&e.isTTY,...r}))&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function rL(e,t=rs.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}function rD(e=""){if(/^\d{3,4}$/.test(e)){let t=/(\d{1,2})(\d{2})/.exec(e)??[];return{major:0,minor:Number.parseInt(t[1],10),patch:Number.parseInt(t[2],10)}}let t=(e??"").split(".").map(e=>Number.parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function rj(e){let{CI:t,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:i,TEAMCITY_VERSION:a,TERM_PROGRAM:o,TERM_PROGRAM_VERSION:s,VTE_VERSION:l,TERM:c}=w.env;if(n)return!(n.length>0&&0===Number.parseInt(n,10));if(rL("no-hyperlink")||rL("no-hyperlinks")||rL("hyperlink=false")||rL("hyperlink=never"))return!1;if(rL("hyperlink=true")||rL("hyperlink=always")||i)return!0;if(!rN(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in w.env)return!0;if("win32"===w.platform||t||a)return!1;if(o){let e=rD(s);switch(o){case"iTerm.app":if(3===e.major)return e.minor>=1;return e.major>3;case"WezTerm":if(/^0-unstable-\d{4}-\d{2}-\d{2}$/.test(s))return s.slice(11)>="2020-06-20";return e.major>=0x1343cac;case"vscode":if(r)return!0;return e.major>1||1===e.major&&e.minor>=72;case"ghostty":case"zed":case"Orca":return!0}}if(l){if("0.50.0"===l)return!1;let e=rD(l);return e.major>0||e.minor>=50}switch(c){case"alacritty":case"xterm-kitty":return!0}return!1}r$("no-color")||r$("no-colors")||r$("color=false")||r$("color=never")?t=0:(r$("color")||r$("colors")||r$("color=true")||r$("color=always"))&&(t=1),rN({isTTY:b.isatty(1)}),rN({isTTY:b.isatty(2)});let rM={stdout:rj(w.stdout),stderr:rj(w.stderr)};function rU(e,t,{target:r="stdout",...n}={}){return rM[r]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}rU.isSupported=rM.stdout,rU.stderr=(e,t,r={})=>rU(e,t,{target:"stderr",...r}),rU.stderr.isSupported=rM.stderr;let rB=rP("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var rF=rP.n(rB);class rH{options;constructor(e){this.options=e}name="LynxConfigWebpackPlugin";apply(e){e.hooks.thisCompilation.tap(this.name,e=>{this.options.LynxTemplatePlugin.getLynxTemplatePluginHooks(e).beforeEncode.tap(this.name,e=>{let{config:t}=this.options;return e.encodeData.compilerOptions={...e.encodeData.compilerOptions,...rF()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...rF()(t,this.options.configKeys)},e})})}}let rW=e=>rG.has(e),rG=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"]);(rc=rE||(rE={}))[rc.Start=0]="Start",rc[rc.Property=1]="Property",rc[rc.StringKey=2]="StringKey",rc[rc.NumberKey=3]="NumberKey";let rV=rP("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var rq=rP.n(rV);let rJ=Object.assign(o=e=>{if(!1===("object"==typeof e&&null!==e&&!1===Array.isArray(e)&&((e,t=!0)=>(void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C)&&(void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll)&&(void 0===e.enableA11y||"boolean"==typeof e.enableA11y)&&(void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement)&&(void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance)&&(void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables)&&(void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule)&&(void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp)&&(void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor)&&(void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough)&&(void 0===e.enableEventThroughInheritFromPage||"boolean"==typeof e.enableEventThroughInheritFromPage)&&(void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming)&&(void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew)&&(void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent)&&(void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands)&&(void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException)&&(void 0===e.enableLayoutOnlyEventThrough||"boolean"==typeof e.enableLayoutOnlyEventThrough)&&(void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture)&&(void 0===e.enableMouseDragScroll||"boolean"==typeof e.enableMouseDragScroll)&&(void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch)&&(void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList)&&(void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture)&&(void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver)&&(void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin)&&(void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex)&&(void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle)&&(void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap)&&(void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow)&&(void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition)&&(void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp)&&(void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding)&&(void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight)&&(void 0===e.longPressDuration||"number"==typeof e.longPressDuration)&&(void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope)&&(void 0===e.tapSlop||"string"==typeof e.tapSlop)&&(void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior)&&(0===Object.keys(e).length||Object.keys(e).every(t=>!!["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(e=>t===e)||void 0===e[t])))(e,!0))){var t;t=i=[],a=(e,r)=>(e&&(e=>{if(0===t.length)return!0;let r=t[t.length-1].path;return e.length>r.length||r.substring(0,e.length)!==e})(r.path)&&(void 0===r.value&&(r.description??=`The value at this path is \`undefined\`.
19
150
 
20
- Please fill the \`${n.expected}\` typed value next time.`),t.push(n)),!1),((e,t,n=!0)=>("object"==typeof e&&null!==e&&!1===Array.isArray(e)||i(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,n=!0)=>[void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C||i(n,{path:t+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:e.alignMouseEventWithW3C}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||i(n,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||i(n,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||i(n,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||i(n,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||i(n,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule||i(n,{path:t+".enableCSSRule",expected:"(boolean | undefined)",value:e.enableCSSRule}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||i(n,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||i(n,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||i(n,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming||i(n,{path:t+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:e.enableFetchAPIStandardStreaming}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||i(n,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent||i(n,{path:t+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:e.enableFlexBasisZeroPercent}),void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands||i(n,{path:t+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:e.enableGridPlacementShorthands}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||i(n,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||i(n,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||i(n,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||i(n,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||i(n,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||i(n,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||i(n,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex||i(n,{path:t+".enableParseIntFlex",expected:"(boolean | undefined)",value:e.enableParseIntFlex}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||i(n,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||i(n,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||i(n,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition||i(n,{path:t+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:e.enableTransformedTouchPosition}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||i(n,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||i(n,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||i(n,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||i(n,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||i(n,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.tapSlop||"string"==typeof e.tapSlop||i(n,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||i(n,{path:t+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:e.unifyVWVHBehavior}),0===Object.keys(e).length||!1===n||Object.keys(e).map(r=>{let o;if(["alignMouseEventWithW3C","disableLongpressAfterScroll","enableA11y","enableAccessibilityElement","enableCSSInheritance","enableCSSInlineVariables","enableCSSRule","enableEndGestureAtLastFingerUp","enableEventHandleRefactor","enableEventThrough","enableFetchAPIStandardStreaming","enableFixedNew","enableFlexBasisZeroPercent","enableGridPlacementShorthands","enableJsBindingApiThrowException","enableListNewArchitecture","enableMultiTouch","enableNativeList","enableNewGesture","enableNewIntersectionObserver","enableNewTransformOrigin","enableParseIntFlex","enableReloadLifecycle","enableSimultaneousTap","enableTextOverflow","enableTransformedTouchPosition","fontScaleEffectiveOnlyOnSp","includeFontPadding","keyboardCallbackPassRelativeHeight","longPressDuration","removeDescendantSelectorScope","tapSlop","unifyVWVHBehavior"].some(e=>r===e))return!0;let a=e[r];if(void 0===a)return!0;return i(n,{path:t+(!1===n1(o=r)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(o)?`.${r}`:`[${JSON.stringify(r)}]`),expected:"undefined",value:a,description:`The property \`${r}\` is not defined in the object type.
151
+ Please fill the \`${r.expected}\` typed value next time.`),t.push(r)),!1),((e,t,r=!0)=>("object"==typeof e&&null!==e&&!1===Array.isArray(e)||a(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,r=!0)=>[void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C||a(r,{path:t+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:e.alignMouseEventWithW3C}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||a(r,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||a(r,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||a(r,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||a(r,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||a(r,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule||a(r,{path:t+".enableCSSRule",expected:"(boolean | undefined)",value:e.enableCSSRule}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||a(r,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||a(r,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||a(r,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableEventThroughInheritFromPage||"boolean"==typeof e.enableEventThroughInheritFromPage||a(r,{path:t+".enableEventThroughInheritFromPage",expected:"(boolean | undefined)",value:e.enableEventThroughInheritFromPage}),void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming||a(r,{path:t+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:e.enableFetchAPIStandardStreaming}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||a(r,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent||a(r,{path:t+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:e.enableFlexBasisZeroPercent}),void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands||a(r,{path:t+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:e.enableGridPlacementShorthands}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||a(r,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableLayoutOnlyEventThrough||"boolean"==typeof e.enableLayoutOnlyEventThrough||a(r,{path:t+".enableLayoutOnlyEventThrough",expected:"(boolean | undefined)",value:e.enableLayoutOnlyEventThrough}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||a(r,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableMouseDragScroll||"boolean"==typeof e.enableMouseDragScroll||a(r,{path:t+".enableMouseDragScroll",expected:"(boolean | undefined)",value:e.enableMouseDragScroll}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||a(r,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||a(r,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||a(r,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||a(r,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||a(r,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex||a(r,{path:t+".enableParseIntFlex",expected:"(boolean | undefined)",value:e.enableParseIntFlex}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||a(r,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||a(r,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||a(r,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition||a(r,{path:t+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:e.enableTransformedTouchPosition}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||a(r,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||a(r,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||a(r,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||a(r,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||a(r,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.tapSlop||"string"==typeof e.tapSlop||a(r,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||a(r,{path:t+".unifyVWVHBehavior",expected:"(boolean | undefined)",value:e.unifyVWVHBehavior}),0===Object.keys(e).length||!1===r||Object.keys(e).map(n=>{let i;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(e=>n===e))return!0;let o=e[n];if(void 0===o)return!0;return a(r,{path:t+(!1===rW(i=n)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(i)?`.${n}`:`[${JSON.stringify(n)}]`),expected:"undefined",value:o,description:`The property \`${n}\` is not defined in the object type.
21
152
 
22
- Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||i(!0,{path:t+"",expected:"Config",value:e}))(e,"$input",!0);let n=0===o.length;return n?{success:n,data:e}:{success:n,errors:o,data:e}}return{success:!0,data:e}},{"~standard":{version:1,vendor:"typia",validate:e=>{let t=a(e);return t.success?{value:t.data}:{issues:t.errors.map(e=>({message:`expected ${e.expected}, got ${e.value}`,path:(e=>{if(!e.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(e)}`);let t=[],n="",r=n$.Start,o=5;for(;o<e.length-1;){let i=e[++o];if(r===n$.Property?"."===i||"["===i?(t.push({key:n}),r=n$.Start):o===e.length-1?(n+=i,t.push({key:n}),o++,r=n$.Start):n+=i:r===n$.StringKey?'"'===i?(t.push({key:JSON.parse(n+i)}),o+=2,r=n$.Start):"\\"===i?(n+=e[o],n+=e[++o]):n+=i:r===n$.NumberKey&&("]"===i?(t.push({key:Number.parseInt(n)}),o++,r=n$.Start):n+=i),r===n$.Start&&o<e.length-1){let t=e[o];if(n="","["===t)'"'===e[o+1]?(r=n$.StringKey,o++,n='"'):r=n$.NumberKey;else if("."===t)r=n$.Property;else throw Error("Unreachable: pointer points invalid character")}}if(r!==n$.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function n9(e){let t=n5(e);if(t.success)return t.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(t.errors.flatMap(({expected:e,path:t,value:n})=>{var r;return"undefined"===e?[` Unsupported configuration: \`${n4().red(t)}\``,""]:[`Invalid config on \`${n4().red(t)}\`.`,` - Expect to be ${n4().green(e)}`,` - Got: ${n4().red((r=n,Object.prototype.toString.call(r).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let n8={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function n7(e){return e?.type==="Identifier"}function n6(e){return e?.type==="StringLiteral"}function re(e){return e?.type==="NumericLiteral"}function rt(e){return e?.type==="BooleanLiteral"}function rn(e){return e?.type==="ObjectExpression"}function rr(e){return e?.type==="ArrayExpression"}function ro(e){return e?.type==="KeyValueProperty"}let ri=e=>{if(rn(e)){let t={};for(let n of e.properties){if(n?.type==="SpreadElement"||!ro(n))return null;let{key:e,value:r}=n;if(!n7(e)&&!n6(e))return null;let o=e.value;rn(r)||rr(r)?t[o]=ri(r):n6(r)||re(r)||rt(r)?t[o]=r.value:n7(r)&&(t[o]=r)}return t}if(rr(e)){let t=[];for(let n of e.elements){if(!n||n.spread)return null;let e=n.expression;rn(e)||rr(e)?t.push(ri(e)):n6(e)||re(e)||rt(e)?t.push(e.value):n7(e)&&t.push(e)}return t}},ra=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function rs(e,t,n){let{widgets:r,pages:o,collector:i,define:a,onDeprecatedAIMeta:s}=n,l=o[t],p=r[t],d=e;return(l||p)&&(a&&Object.keys(a).length>0&&(d=Object.keys(a).reduce((e,t)=>{let n=a[t];if("string"==typeof n)return e.replaceAll(t,n);throw Error(`Define value ${t} is not a string`)},e)),er((0,ra.parseSync)(d,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(n7(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let n=e.arguments[0]?.expression;if(rn(n)){for(let e of n.properties)if(ro(e)&&n7(e.key)&&"aiMeta"===e.key.value){let n=ri(e.value);if(!n)continue;l?(s?.({kind:"page",entryName:l,filename:t}),i.addPageMeta(l,n)):p&&(s?.({kind:"widget",entryName:p,filename:t}),i.addWidgetMeta(p,n))}}}n7(e.callee)&&e.callee.value in Z&&(p&&i.addWidgetMeta(p,Z[e.callee.value]),l&&i.addPageMeta(l,Z[e.callee.value]))}})),e}let rl=/[/\\]/;function rp(e,t){t.forEach(([t,{id:n}])=>{if(n&&rl.test(n))throw Error(`Invalid ${e} id "${n}" for "${t}": a ${e} id cannot contain a path separator. Set an "id" without one in src/app.config.ts, or drop it to derive the id from the entry.`)})}async function rd({pages:e,widgets:t,entries:n,collector:r,normalizedAppConfig:o,define:i}){let a=new tB,s=new Set,l={collector:a,widgets:Object.fromEntries(Object.entries(t).map(([e,t])=>[t.filename,e])),pages:Object.fromEntries(Object.entries(e).map(([e,t])=>[t.filename,e])),define:i,onDeprecatedAIMeta({kind:e,entryName:t,filename:n}){let r=`${e}:${t}:${n}`;s.has(r)||(s.add(r),eh.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) is deprecated for ${t}. Configure this ${e} metadata in src/app.config.ts instead. Source: ${n}`))}},p=o.pages.entries,d=o.widgets.entries;await Promise.all(Object.values({...t,...e}).filter(({filename:e})=>/\.(ts|tsx|jsx|js)$/i.test(e)).map(({filename:e,isVirtualFile:t})=>{if(t){let t=l.widgets[e]??l.pages[e],r=n[t];return r?rs(r.toString(),e,l):void eh.warn("Cannot find virtual file",{file:t})}return rs(tz.readFileSync(e,"utf-8"),e,l)})).catch(e=>{eh.error("Failed to collect view metadata",{error:e})});let c=a.getData(),u=Z.defineLoginPage,m=t4("",u.path),h=Object.entries(e).map(([e,t])=>{let n=c.pages[e],{web:r,...o}=p[e]??{},i=n?.path,a=t.isLoginPage||void 0!==i&&t4(e,i)===m;return[e,{id:t3(e,t.folderName),...n,...o,...a?u:{},path:t4(e,a?u.path:t.isSpecial?i:void 0)}]}),f=[...new Set([...h.filter(([,e])=>e.path===m).map(([e])=>e),...h.filter(([,e])=>e.id===u.id).map(([e])=>e)])];if(f.length>1)throw Error(`Only one login page is allowed: ${f.join(", ")}`);rp("page",h),h.forEach(([e,t])=>{r.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:n,...r}=d[e]??{};return[e,{id:t3(e,t.folderName),...c.widgets[e],...r}]});rp("widget",g),function(e){let t=new Map;e.forEach(([e,{id:n}])=>{if(!n)return;let r=t.get(n)??[];r.push(e),t.set(n,r)});let n=[...t].filter(([,e])=>e.length>1);if(0===n.length)return;let r=n.map(([e,t])=>`Duplicate widget id "${e}" is used by:
23
- ${t.map(e=>`- ${e}`).join("\n")}`).join("\n\n");throw Error(`${r}
153
+ Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||a(!0,{path:t+"",expected:"Config",value:e}))(e,"$input",!0);let r=0===i.length;return r?{success:r,data:e}:{success:r,errors:i,data:e}}return{success:!0,data:e}},{"~standard":{version:1,vendor:"typia",validate:e=>{let t=o(e);return t.success?{value:t.data}:{issues:t.errors.map(e=>({message:`expected ${e.expected}, got ${e.value}`,path:(e=>{if(!e.startsWith("$input"))throw Error(`Invalid path: ${JSON.stringify(e)}`);let t=[],r="",n=rE.Start,i=5;for(;i<e.length-1;){let a=e[++i];if(n===rE.Property?"."===a||"["===a?(t.push({key:r}),n=rE.Start):i===e.length-1?(r+=a,t.push({key:r}),i++,n=rE.Start):r+=a:n===rE.StringKey?'"'===a?(t.push({key:JSON.parse(r+a)}),i+=2,n=rE.Start):"\\"===a?(r+=e[i],r+=e[++i]):r+=a:n===rE.NumberKey&&("]"===a?(t.push({key:Number.parseInt(r)}),i++,n=rE.Start):r+=a),n===rE.Start&&i<e.length-1){let t=e[i];if(r="","["===t)'"'===e[i+1]?(n=rE.StringKey,i++,r='"'):n=rE.NumberKey;else if("."===t)n=rE.Property;else throw Error("Unreachable: pointer points invalid character")}}if(n!==rE.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function rz(e){let t=rJ(e);if(t.success)return t.data;throw Error(["[pluginLynxConfig] Invalid configuration.",""].concat(t.errors.flatMap(({expected:e,path:t,value:r})=>{var n;return"undefined"===e?[` Unsupported configuration: \`${rq().red(t)}\``,""]:[`Invalid config on \`${rq().red(t)}\`.`,` - Expect to be ${rq().green(e)}`,` - Got: ${rq().red((n=r,Object.prototype.toString.call(n).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let rK={"lynx:react":"@lynx-js/react-rsbuild-plugin"},rY=(0,A.createRequire)(import.meta.url),rX={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 rZ(e){return e?new Map(e instanceof Map?e:Object.entries(e)):new Map}let rQ=r2();function r0(e){if(e)return!0===e?{}:e}function r1(e){return e.replace(/^\/+/,"")}function r2(){return{reactlynx:{resolveExternals:(e,t)=>{var r,n;let i;return r=r0(e),n=r3(t),i=r?.url?{url:r.url}:{bundlePath:r5(r,n)},Object.fromEntries(Object.entries(rX).map(([e,t])=>[e,{...t,...r?.async===void 0?{}:{async:r.async},...i}]))},resolveManagedAssets(e,t){let r=r0(e);if(!r||r.url)return new Map;let n=r3(t);return new Map([[r5(r,n),function(e,t,r){let n="production"===process.env.NODE_ENV?"prod":"dev",i=`${t}/${n}${r?"-web":""}`;try{return rY.resolve(i,{paths:[e]})}catch{throw Error(`external-bundle-rsbuild-plugin requires \`${i}\` when \`externalsPresets.reactlynx\` is enabled. Install a compatible \`${t}\` into your devDependencies.`)}}(t.rootPath,r.reactUmdPackageName??"@lynx-js/react-umd",n)]])}}}}function r3(e){let t=e.environmentName;return void 0!==t&&"lynx"!==t&&!t.startsWith("lynx-")}class r4{assets;constructor(e){this.assets=e}apply(e){e.hooks.thisCompilation.tap(r4.name,t=>{t.hooks.processAssets.tap({name:r4.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},()=>{let{RawSource:r}=e.webpack.sources;for(let[e,n]of this.assets)if(!t.getAsset(e)){if(!(0,tP.existsSync)(n))throw Error(`external-bundle-rsbuild-plugin could not find local bundle \`${n}\` for emitted asset \`${e}\`.`);t.emitAsset(e,new r((0,tP.readFileSync)(n),!1))}})})}}function r5(e,t){return e?.bundlePath?r1(e.bundlePath):t?"react.web.bundle":"react.lynx.bundle"}function r9(e,t){return"string"!=typeof t?t:{bundlePath:t,libraryName:e,background:{sectionPath:e},mainThread:{sectionPath:`${e}__main-thread`},async:!0}}function r8(e){return{name:"lynx:external-bundle",setup(t){let r,n=function(e){let t={...r2()};for(let[r,n]of Object.entries(e??{})){let e=rQ[r];t[r]=e?function(e,t){return{extends:[...e.extends?Array.isArray(e.extends)?e.extends:[e.extends]:[],...t.extends?Array.isArray(t.extends)?t.extends:[t.extends]:[]],resolveExternals:(r,n)=>({...e.resolveExternals?.(r,n)??{},...t.resolveExternals?.(r,n)??{}}),resolveManagedAssets(r,n){let i=rZ(e.resolveManagedAssets?.(r,n));for(let[e,a]of rZ(t.resolveManagedAssets?.(r,n)))i.set(e,a);return i}}}(e,n):n}return t}(e.externalsPresetDefinitions),i=new Map;t.modifyRsbuildConfig((t,{mergeRsbuildConfig:n})=>(r=t.server?.base,void 0===e.externals&&void 0===e.externalsPresets)?t:n(t,{server:{setup:({server:e,action:t})=>{"dev"===t&&e.middlewares.use((e,t,r)=>{let n=e.url?i.get(e.url):void 0;if(n&&(0,tP.existsSync)(n)){t.setHeader("Content-Type","application/octet-stream"),t.setHeader("Access-Control-Allow-Origin","*");let e=(0,tP.createReadStream)(n);e.on("error",()=>{t.headersSent||(t.statusCode=404),t.end()}),e.pipe(t);return}r()})}}})),t.modifyRspackConfig((a,{environment:o})=>{let s=t.useExposed(Symbol.for("LAYERS"));if(!s)throw Error("external-bundle-rsbuild-plugin requires exposed `LAYERS`. Please install a DSL plugin, for example `pluginReactLynx` for ReactLynx.");let l=function(e,t,r){let n={},i=new Map;for(let[a,o]of Object.entries(e??{})){if(!o)continue;let e=function e(t,r,n,i,a){let o=n[t];if(!o)throw Error(`Unknown externals preset "${t}". Define it in \`externalsPresetDefinitions\` before enabling it in \`externalsPresets\`.`);if(i.includes(t))throw Error(`Circular externals preset dependency detected: ${[...i,t].join(" -> ")}`);let s={},l=new Map,c=[...i,t];for(let t of o.extends?Array.isArray(o.extends)?o.extends:[o.extends]:[]){let r=e(t,!0,n,c,a);for(let[e,t]of(Object.assign(s,r.externals),r.managedAssets))l.set(e,t)}for(let[e,t]of(Object.assign(s,o.resolveExternals?.(r,a)??{}),rZ(o.resolveManagedAssets?.(r,a))))l.set(e,t);return{externals:s,managedAssets:l}}(a,o,t,[],r);for(let[t,r]of(Object.assign(n,e.externals),e.managedAssets))i.set(t,r)}return{externals:n,managedAssets:i}}(e.externalsPresets,n,{rootPath:t.context.rootPath,environmentName:o.name}),c=function(e){if(!e)return{};for(let[t,r]of Object.entries(e)){let e=r9(t,r);if(!e.url&&!e.bundlePath)throw Error(`external-bundle-rsbuild-plugin requires \`url\` or \`bundlePath\` for external "${t}".`)}return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,r9(e,t)]))}(e.externals),p={...l.externals,...c},d=function(e,t,r){let n=new Map(t),i=tn.resolve(r.context.rootPath,e.externalBundleRoot??"dist-external-bundle");for(let[t,r]of Object.entries(e.externals??{})){let e=r9(t,r);!e.url&&e.bundlePath&&n.set(r1(e.bundlePath),tn.resolve(i,r1(e.bundlePath)))}return n}(e,l.managedAssets,t);for(let[e,t]of d)i.set(function(e,t){let r=e??"/",n=r1(t);if("/"===r)return`/${n}`;if(/^[a-z][a-z\d+\-.]*:/i.test(r))try{return new URL(n,r).toString()}catch{}return`${r.replace(/\/$/,"")}/${n}`}(r,e),t);return a.plugins=a.plugins||[],d.size>0&&a.plugins.push(new r4(d)),a.plugins.push(new M({backgroundLayer:s.BACKGROUND,mainThreadLayer:s.MAIN_THREAD,externals:p,globalObject:e.globalObject,timeout:e.timeout,retries:e.retries})),a})}}}var r7={},r6={};function ne(e){var t=r6[e];if(void 0!==t)return t.exports;var r=r6[e]={exports:{}};return r7[e](r,r.exports,ne),r.exports}ne.m=r7,ne.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return ne.d(t,{a:t}),t},ne.d=(e,t,r)=>{var n=(t,r)=>{for(var n in t)ne.o(t,n)&&!ne.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,[r]:t[n]})};n(t,"get"),n(r,"value")},ne.add=function(e){Object.assign(ne.m,e)},ne.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ne.add({"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),{MAX_LENGTH:i,MAX_SAFE_INTEGER:a}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),{safeRe:o,t:s}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"),l=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"),{compareIdentifiers:c}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js");e.exports=class e{constructor(t,r){if(r=l(r),t instanceof e)if(!!r.loose===t.loose&&!!r.includePrerelease===t.includePrerelease)return t;else t=t.version;else if("string"!=typeof t)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>i)throw TypeError(`version is longer than ${i} characters`);n("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let c=t.trim().match(r.loose?o[s.LOOSE]:o[s.FULL]);if(!c)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+c[1],this.minor=+c[2],this.patch=+c[3],this.major>a||this.major<0)throw TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw TypeError("Invalid patch version");c[4]?this.prerelease=c[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<a)return t}return e}):this.prerelease=[],this.build=c[5]?c[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(t){if(n("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if("string"==typeof t&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return(t instanceof e||(t=new e(t,this.options)),this.major<t.major)?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return -1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n("prerelease compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return -1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n("build compare",r,e,i),void 0===e&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===e)return -1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&!1===r)throw Error("invalid increment argument: identifier is empty");if(t){let e=`-${t}`.match(this.options.loose?o[s.PRERELEASELOOSE]:o[s.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,r),this.inc("pre",t,r);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 e=+!!Number(r);if(0===this.prerelease.length)this.prerelease=[e];else{let n=this.prerelease.length;for(;--n>=0;)"number"==typeof this.prerelease[n]&&(this.prerelease[n]++,n=-2);if(-1===n){if(t===this.prerelease.join(".")&&!1===r)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let n=[t,e];!1===r&&(n=[t]),((e,t)=>{let r=t.split(".");if(r.length>e.length)return!1;for(let t=0;t<r.length;t++)if(0!==c(e[t],r[t]))return!1;return!0})(this.prerelease,t)?isNaN(this.prerelease[t.split(".").length])&&(this.prerelease=n):this.prerelease=n}break}default:throw Error(`invalid increment argument: ${e}`)}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"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js");e.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(e,t,r){let n=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js");e.exports=(e,t,r)=>n(e,t,r)>=0},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(e){e.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"(e){e.exports="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(e){let t=/^[0-9]+$/,r=(e,r)=>{if("number"==typeof e&&"number"==typeof r)return e===r?0:e<r?-1:1;let n=t.test(e),i=t.test(r);return n&&i&&(e*=1,r*=1),e===r?0:n&&!i?-1:i&&!n?1:e<r?-1:1};e.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(e){let t=Object.freeze({loose:!0}),r=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:r},"../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(e,t,r){let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:a}=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"),o=r("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"),s=(t=e.exports={}).re=[],l=t.safeRe=[],c=t.src=[],p=t.safeSrc=[],d=t.t={},u=0,m="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",a],[m,i]],f=(e,t,r)=>{let n=(e=>{for(let[t,r]of h)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e})(t),i=u++;o(e,i,t),d[e]=i,c[i]=t,p[i]=n,s[i]=new RegExp(t,r?"g":void 0),l[i]=new RegExp(n,r?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*"),f("NUMERICIDENTIFIERLOOSE","\\d+"),f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${m}*`),f("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),f("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),f("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),f("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),f("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),f("BUILDIDENTIFIER",`${m}+`),f("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),f("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),f("FULL",`^${c[d.FULLPLAIN]}$`),f("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),f("LOOSE",`^${c[d.LOOSEPLAIN]}$`),f("GTLT","((?:<|>)?=?)"),f("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),f("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),f("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),f("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),f("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),f("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),f("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),f("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?`+`(?:${c[d.BUILD]})?`+"(?:$|[^\\d])"),f("COERCERTL",c[d.COERCE],!0),f("COERCERTLFULL",c[d.COERCEFULL],!0),f("LONETILDE","(?:~>?)"),f("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",f("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),f("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),f("LONECARET","(?:\\^)"),f("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",f("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),f("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),f("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),f("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),f("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",f("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),f("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),f("STAR","(<|>)?=?\\s*\\*"),f("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),f("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}});let nt=ne("../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js");var nr=ne.n(nt);let nn=Symbol.for("@lynx-js/plugin-react-alias");function ni(e,t,r){let n,i,{ResolverFactory:a}=e.experiments.resolver;return async e=>{if(n||(n={}),void 0===n[e]){if(!i){let e=new a({conditionNames:r,enablePnp:!!process.versions.pnp});i=(t,r)=>e.sync(t,r)}let o=i(t,e);if(o.error)throw Error(o.error);if(!o.path)throw Error(`Failed to resolve ${e}`);n[e]=o.path}return n[e]}}function na(e){return e?.type==="Identifier"}function no(e){return e?.type==="StringLiteral"}function ns(e){return e?.type==="NumericLiteral"}function nl(e){return e?.type==="BooleanLiteral"}function nc(e){return e?.type==="ObjectExpression"}function np(e){return e?.type==="ArrayExpression"}function nd(e){return e?.type==="KeyValueProperty"}let nu=e=>{if(nc(e)){let t={};for(let r of e.properties){if(r?.type==="SpreadElement"||!nd(r))return null;let{key:e,value:n}=r;if(!na(e)&&!no(e))return null;let i=e.value;nc(n)||np(n)?t[i]=nu(n):no(n)||ns(n)||nl(n)?t[i]=n.value:na(n)&&(t[i]=n)}return t}if(np(e)){let t=[];for(let r of e.elements){if(!r||r.spread)return null;let e=r.expression;nc(e)||np(e)?t.push(nu(e)):no(e)||ns(e)||nl(e)?t.push(e.value):na(e)&&t.push(e)}return t}},nm=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function nh(e,t,r){let{widgets:n,pages:i,collector:a,define:o,onDeprecatedAIMeta:s}=r,l=i[t],c=n[t],p=e;return(l||c)&&(o&&Object.keys(o).length>0&&(p=Object.keys(o).reduce((e,t)=>{let r=o[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`define 配置项 ${t} 的值必须是字符串`)},e)),el((0,nm.parseSync)(p,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(na(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let r=e.arguments[0]?.expression;if(nc(r)){for(let e of r.properties)if(nd(e)&&na(e.key)&&"aiMeta"===e.key.value){let r=nu(e.value);if(!r)continue;l?(s?.({kind:"page",entryName:l,filename:t}),a.addPageMeta(l,r)):c&&(s?.({kind:"widget",entryName:c,filename:t}),a.addWidgetMeta(c,r))}}}na(e.callee)&&e.callee.value in R&&(c&&a.addWidgetMeta(c,R[e.callee.value]),l&&a.addPageMeta(l,R[e.callee.value]))}})),e}let nf=/[/\\]/;function ng(e,t){t.forEach(([t,{id:r}])=>{if(r&&nf.test(r))throw Error(`入口 "${t}" 的 ${e} id "${r}" 无效:id 不能包含路径分隔符。请在 src/app.config.ts 中设置不含路径分隔符的 "id",或删除该配置以根据入口自动生成 id。`)})}async function ny({pages:e,widgets:t,entries:r,collector:n,normalizedAppConfig:i,define:a}){let o=new tf,s=new Set,l={collector:o,widgets:Object.fromEntries(Object.entries(t).map(([e,t])=>[t.filename,e])),pages:Object.fromEntries(Object.entries(e).map(([e,t])=>[t.filename,e])),define:a,onDeprecatedAIMeta({kind:e,entryName:t,filename:r}){let n=`${e}:${t}:${r}`;s.has(n)||(s.add(n),e4.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) 已弃用,入口:${t}。请改为在 src/app.config.ts 中配置该 ${e} 的元数据。源文件:${r}`))}},c=i.pages.entries,p=i.widgets.entries;await Promise.all(Object.values({...t,...e}).filter(({filename:e})=>/\.(ts|tsx|jsx|js)$/i.test(e)).map(({filename:e,isVirtualFile:t})=>{if(t){let t=l.widgets[e]??l.pages[e],n=r[t];return n?nh(n.toString(),e,l):void e4.warn("未找到虚拟文件",{file:t})}return nh(tP.readFileSync(e,"utf-8"),e,l)})).catch(e=>{e4.error("收集视图元数据失败",{error:e})});let d=o.getData(),u=R.defineLoginPage,m=tN("",u.path),h=Object.entries(e).map(([e,t])=>{let r=d.pages[e],{web:n,...i}=c[e]??{},a=r?.path,o=t.isLoginPage||void 0!==a&&tN(e,a)===m;return[e,{id:tk(e,t.folderName),...r,...i,...o?u:{},path:tN(e,o?u.path:t.isSpecial?a:void 0)}]}),f=[...new Set([...h.filter(([,e])=>e.path===m).map(([e])=>e),...h.filter(([,e])=>e.id===u.id).map(([e])=>e)])];if(f.length>1)throw Error(`只允许配置一个登录页面:${f.join(", ")}`);ng("page",h),h.forEach(([e,t])=>{n.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:r,...n}=p[e]??{};return[e,{id:tk(e,t.folderName),...d.widgets[e],...n}]});ng("widget",g),function(e){let t=new Map;e.forEach(([e,{id:r}])=>{if(!r)return;let n=t.get(r)??[];n.push(e),t.set(r,n)});let r=[...t].filter(([,e])=>e.length>1);if(0===r.length)return;let n=r.map(([e,t])=>`重复的 widget id "${e}" 被以下入口使用:
154
+ ${t.map(e=>`- ${e}`).join("\n")}`).join("\n\n");throw Error(`${n}
24
155
 
25
- Widget IDs must be globally unique. Configure distinct "id" values in src/app.config.ts.`)}(g),g.forEach(([e,t])=>{r.addWidgetMeta(e,t)})}let rc=f("os"),ru=`base/${e2}`;async function rm({encryption:e}){let t=tz.mkdtempSync(tY.join(rc.tmpdir(),"doubao-keystore-")),n=tY.join(t,e2);try{let{generateKeystore:t}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),r=await t(n,{encryption:e});if(0!==r.status)throw Error(r.error_msg);return tz.readFileSync(n)}finally{tz.rmSync(t,{recursive:!0,force:!0})}}let rh=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class rf{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(rf.name,t=>{t.hooks.processAssets.tapPromise({name:rf.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let n=Date.now();try{let{RawSource:n}=e.webpack.sources,r=this.options.getAppAssetPath(),o=ng(t,e$);for(let e of[r,o].filter(e=>!!e)){let o=t.getAsset(e);if(!o)throw Error(`Worker entry asset was not emitted: ${e}`);let{buffer:i,encodeOptions:a,keystoreContent:s}=await this.encode([o]);if(t.updateAsset(e,new n(i,!1)),s){let e=new n(s,!1);t.getAsset(ru)?t.updateAsset(ru,e):t.emitAsset(ru,e)}eu()&&e===r&&t.emitAsset(`${tY.dirname(e)}/tasm.json`,new n(JSON.stringify(a,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-n)}})})}async encode(e){let t={},{resolveSigningEncryptionOptions:n}=this.options;for(let n of e)n.name.endsWith(".js")&&(t[n.name.replace(/\.template\.js$/,"")]={content:n.source.source().toString()});let r={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:t},o=await n?.();if(o?.signing.enabled||o?.encryption.enabled){let{encode:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),t=this.options.metadata.appId,n=t9(o,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:i,lepus_debug:a,status:s,error_msg:l}=await e(JSON.stringify(r),n);if(0!==s)throw Error(l);return!this.isGenerateKeystore&&n.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:i,encodeOptions:r,debugInfo:a,keystoreContent:await rm({encryption:{...n.encryption}})}):{buffer:i,encodeOptions:r,debugInfo:a}}let i=(0,rh.getEncodeMode)(),{buffer:a}=await i(r);return{buffer:a,encodeOptions:r}}}function rg(e,t,r,o,i){let a=!1;return{name:rg.name,apply(s){let l=new s.webpack.experiments.VirtualModulesPlugin;l.apply(s),s.hooks.thisCompilation.tap(rg.name,()=>{Object.keys(r).forEach(e=>{l.writeModule(r[e].filename,r[e].toString())})}),s.hooks.thisCompilation.tap(rg.name,r=>{let l,p=()=>{void 0!==l&&i?.(Math.max(0,Date.now()-l))},d=e.getLynxTemplatePluginHooks(r);d.beforeEncode.tapPromise(rg.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=L({},e.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0}),e)),d.encode.tapPromise({name:rg.name,stage:255},async e=>{let{encodeOptions:i}=e,l=await o?.();if(l?.signing.enabled||l?.encryption.enabled){let{encode:n}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),o=t.getData(),d=function(e,t){let n=(t??"").replaceAll("\\","/"),r=n.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(r){let[,t,n]=r,o=`${t}/${n}`;return"widgets"===t?e.widgets[o]?.id:e.pages[o]?.path}let o=tC.posix.basename(n);return e.widgets[`widgets/${o}`]?.id??e.pages[`pages/${o}`]?.path}(o,e.intermediate),c=o.app.appId,u=t9(l,{signing:{extra_config:{app_id:c,bundle_id:d}},encryption:{salt:c}}),{buffer:m,lepus_debug:h,status:g,error_msg:y}=await n(JSON.stringify(i),u);if(0!==g)throw Error(y);if(!a&&u.encryption.enabled){a=!0;let e=await rm({encryption:{...u.encryption}}),t=new s.webpack.sources.RawSource(e,!1);r.getAsset(ru)?r.updateAsset(ru,t):r.emitAsset(ru,t)}return p(),{buffer:m,debugInfo:h}}let{buffer:d,lepus_debug:c}=await (n??=new h({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js+t_74cfcecd4de87dca5f35abdf10f99dcc/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,nv.availableParallelism)()})).run({encodeOptions:i});return p(),{buffer:Buffer.from(d),debugInfo:c}})}),s.hooks.failed.tap(rg.name,e=>{ef.error("Failed to bundle template",{error:e})})}}}class ry{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return ry._instance??=new ry}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=e=>{let t=e.toString("utf-8");this.listeners.some(e=>e.run(t))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(e,t,n=0){let r=e=>()=>{let t=this.listeners.findIndex(t=>t.run===e);t>-1&&(this.listeners.splice(t,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(t){let e=this.listeners.find(e=>e.tag===t);if(e)return r(e.run)}return this.listeners.push({run:e,tag:t,priority:n,index:this.nextIndex++}),this.listeners.sort((e,t)=>e.priority-t.priority||e.index-t.index),this.start(),r(e)}}function rb(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function r_(e){ry.instance.stop(),e().catch(rb).finally(()=>ry.instance.start())}let rv=eV.child("simulator"),rw=f("node:http"),rS={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},rE=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),rx=new Set([...rE,"cookie","host","origin","referer"]),rA=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,rT="X-DBX-Sandbox-Session-ID",rC="x-tt-logid";function rI(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function rP(e){if(!e)throw Error("url 必须为非空字符串");let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error(`不支持的请求协议:${t.protocol}`);return t}function rO(e,t,n={}){let r={};for(let[t,n]of Object.entries(e))void 0===n||rx.has(t.toLowerCase())||(r[t]=n);return{...r,...n,host:t.host}}function rD(e,t=[]){let n={};for(let[t,r]of Object.entries(e))void 0===r||rE.has(t.toLowerCase())||(n[t]=r);if(t.length>0){let e=new Set(String(n["access-control-expose-headers"]??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean));for(let n of t)e.add(n.toLowerCase());n["access-control-expose-headers"]=[...e].join(", ")}return n}function rk(e,t=[]){let n=rD(Object.fromEntries(e),t);return delete n["content-encoding"],delete n["content-length"],n}function r$(e,t={}){Object.entries({...rS,...t}).forEach(([t,n])=>{void 0!==n&&e.setHeader(t,n)})}function rR(e,t,n,r){r$(e,r),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function rN(e,t,n,r){let o=JSON.stringify(n);r$(e,r),e.writeHead(t,{"Content-Length":Buffer.byteLength(o),"Content-Type":"application/json; charset=utf-8"}),e.end(o)}function rL(e,t,n){return new Promise((r,o)=>{let i=[],a=0,s=!1;e.on("data",r=>{if(s)return;let l=Uint8Array.from(Buffer.isBuffer(r)?r:Buffer.from(r));if((a+=l.byteLength)>n){s=!0,e.pause(),t.shouldKeepAlive=!1,t.setHeader("Connection","close");let n=()=>{e.destroyed||e.destroy()};t.once("finish",n),t.once("close",n),o(Error("Request body is too large"));return}i.push(l)}),e.once("end",()=>{if(s)return;s=!0;let e=new Uint8Array(a),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;r(e)}),e.once("aborted",()=>{s||(s=!0,o(Error("Request aborted")))}),e.once("error",e=>{s||(s=!0,o(e))})})}function rM(e,t,n){return rL(e,t,n).then(e=>Buffer.from(e).toString("utf8"))}function rj(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function rB(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let n=rA.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${n}`}).join("\n")}function rU(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function rF({method:e,requestBody:t,requestHeaders:n,responseBody:r,responseHeaders:o,statusCode:i,targetUrl:a}){"applet0930"===process.env.DEBUG&&rv.info(`${e} ${a.pathname}${a.search} ${(i>=500?tp.red:i>=400?tp.yellow:tp.green)(String(i))}
156
+ widget id 必须全局唯一,请在 src/app.config.ts 中配置不同的 "id"。`)}(g),g.forEach(([e,t])=>{n.addWidgetMeta(e,t)})}let nb=f("os"),n_=`base/${eF}`;async function nv({encryption:e}){let t=tT.mkdtempSync(eR.join(nb.tmpdir(),"doubao-keystore-")),r=eR.join(t,eF);try{let{generateKeystore:t}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),n=await t(r,{encryption:e});if(0!==n.status)throw Error(n.error_msg);return tT.readFileSync(r)}finally{tT.rmSync(t,{recursive:!0,force:!0})}}let nE=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class nw{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(nw.name,t=>{t.hooks.processAssets.tapPromise({name:nw.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH},async()=>{let r=Date.now();try{let{RawSource:r}=e.webpack.sources,n=this.options.getAppAssetPath(),i=rr(t,eW);for(let e of[n,i].filter(e=>!!e)){let i=t.getAsset(e);if(!i)throw Error(`未生成 Worker 入口产物:${e}`);let{buffer:a,encodeOptions:o,keystoreContent:s}=await this.encode([i]);if(t.updateAsset(e,new r(a,!1)),s){let e=new r(s,!1);t.getAsset(n_)?t.updateAsset(n_,e):t.emitAsset(n_,e)}eS()&&e===n&&t.emitAsset(`${tn.dirname(e)}/tasm.json`,new r(JSON.stringify(o,null,2)))}}finally{this.options.onProcessDuration?.(Date.now()-r)}})})}async encode(e){let t={},{resolveSigningEncryptionOptions:r}=this.options;for(let r of e)r.name.endsWith(".js")&&(t[r.name.replace(/\.template\.js$/,"")]={content:r.source.source().toString()});let n={compilerOptions:{enableFiberArch:!0,targetSdkVersion:this.options.engineVersion??"3.5"},sourceContent:{appType:"DynamicComponent"},customSections:t},i=await r?.();if(i?.signing.enabled||i?.encryption.enabled){let{encode:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),t=this.options.metadata.appId,r=tD(i,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:a,lepus_debug:o,status:s,error_msg:l}=await e(JSON.stringify(n),r);if(0!==s)throw Error(l);return!this.isGenerateKeystore&&r.encryption.enabled?(this.isGenerateKeystore=!0,{buffer:a,encodeOptions:n,debugInfo:o,keystoreContent:await nv({encryption:{...r.encryption}})}):{buffer:a,encodeOptions:n,debugInfo:o}}let a=(0,nE.getEncodeMode)(),{buffer:o}=await a(n);return{buffer:o,encodeOptions:n}}}function nS(e,t,n,i,a){let o=!1;return{name:nS.name,apply(s){let l=new s.webpack.experiments.VirtualModulesPlugin;l.apply(s),s.hooks.thisCompilation.tap(nS.name,()=>{Object.keys(n).forEach(e=>{l.writeModule(n[e].filename,n[e].toString())})}),s.hooks.thisCompilation.tap(nS.name,n=>{let l,c=()=>{void 0!==l&&a?.(Math.max(0,Date.now()-l))},p=e.getLynxTemplatePluginHooks(n);p.beforeEncode.tapPromise(nS.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=ea({},e.encodeData.sourceContent.config,{mapContainerType:1,trailNewImage:!0,disableQuickTracingGC:!0}),e)),p.encode.tapPromise({name:nS.name,stage:255},async e=>{let{encodeOptions:a}=e,l=await i?.();if(l?.signing.enabled||l?.encryption.enabled){let{encode:r}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getData(),p=function(e,t){let r=(t??"").replaceAll("\\","/"),n=r.match(/(?:^|\/)(pages|widgets)\/(.+)$/);if(n){let[,t,r]=n,i=`${t}/${r}`;return"widgets"===t?e.widgets[i]?.id:e.pages[i]?.path}let i=tn.posix.basename(r);return e.widgets[`widgets/${i}`]?.id??e.pages[`pages/${i}`]?.path}(i,e.intermediate),d=i.app.appId,u=tD(l,{signing:{extra_config:{app_id:d,bundle_id:p}},encryption:{salt:d}}),{buffer:m,lepus_debug:h,status:g,error_msg:y}=await r(JSON.stringify(a),u);if(0!==g)throw Error(y);if(!o&&u.encryption.enabled){o=!0;let e=await nv({encryption:{...u.encryption}}),t=new s.webpack.sources.RawSource(e,!1);n.getAsset(n_)?n.updateAsset(n_,t):n.emitAsset(n_,t)}return c(),{buffer:m,debugInfo:h}}let{buffer:p,lepus_debug:d}=await (r??=new h({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js+t_e17ab80716e3a051afc8527cc96a064b/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,ro.availableParallelism)()})).run({encodeOptions:a});return c(),{buffer:Buffer.from(p),debugInfo:d}})}),s.hooks.failed.tap(nS.name,e=>{e9.error("模板打包失败",{error:e})})}}}class nx{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return nx._instance??=new nx}start(){this.stdinListener||0===this.listeners.length||(this.stdinListener=e=>{let t=e.toString("utf-8");this.listeners.some(e=>e.run(t))},process.stdin.on("data",this.stdinListener),process.stdin.resume())}stop(){this.stdinListener&&(process.stdin.off("data",this.stdinListener),this.stdinListener=void 0)}addListener(e,t,r=0){let n=e=>()=>{let t=this.listeners.findIndex(t=>t.run===e);t>-1&&(this.listeners.splice(t,1),0===this.listeners.length&&(this.stop(),0===process.stdin.listenerCount("data")&&process.stdin.pause()))};if(t){let e=this.listeners.find(e=>e.tag===t);if(e)return n(e.run)}return this.listeners.push({run:e,tag:t,priority:r,index:this.nextIndex++}),this.listeners.sort((e,t)=>e.priority-t.priority||e.index-t.index),this.start(),n(e)}}function nA(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function nT(e){nx.instance.stop(),e().catch(nA).finally(()=>nx.instance.start())}let nI=eP.child("simulator"),nO=f("node:http"),nP={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},nC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),nR=new Set([...nC,"cookie","host","origin","referer"]),n$=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,nk="X-DBX-Sandbox-Session-ID",nN="x-tt-logid";function nL(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function nD(e){if(!e)throw Error("url 必须为非空字符串");let t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error(`不支持的请求协议:${t.protocol}`);return t}function nj(e,t,r={}){let n={};for(let[t,r]of Object.entries(e))void 0===r||nR.has(t.toLowerCase())||(n[t]=r);return{...n,...r,host:t.host}}function nM(e,t=[]){let r={};for(let[t,n]of Object.entries(e))void 0===n||nC.has(t.toLowerCase())||(r[t]=n);if(t.length>0){let e=new Set(String(r["access-control-expose-headers"]??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean));for(let r of t)e.add(r.toLowerCase());r["access-control-expose-headers"]=[...e].join(", ")}return r}function nU(e,t=[]){let r=nM(Object.fromEntries(e),t);return delete r["content-encoding"],delete r["content-length"],r}function nB(e,t={}){Object.entries({...nP,...t}).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})}function nF(e,t,r,n){nB(e,n),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(r)}function nH(e,t,r,n){let i=JSON.stringify(r);nB(e,n),e.writeHead(t,{"Content-Length":Buffer.byteLength(i),"Content-Type":"application/json; charset=utf-8"}),e.end(i)}function nW(e,t,r){return new Promise((n,i)=>{let a=[],o=0,s=!1;e.on("data",n=>{if(s)return;let l=Uint8Array.from(Buffer.isBuffer(n)?n:Buffer.from(n));if((o+=l.byteLength)>r){s=!0,e.pause(),t.shouldKeepAlive=!1,t.setHeader("Connection","close");let r=()=>{e.destroyed||e.destroy()};t.once("finish",r),t.once("close",r),i(Error("Request body is too large"));return}a.push(l)}),e.once("end",()=>{if(s)return;s=!0;let e=new Uint8Array(o),t=0;for(let r of a)e.set(r,t),t+=r.byteLength;n(e)}),e.once("aborted",()=>{s||(s=!0,i(Error("Request aborted")))}),e.once("error",e=>{s||(s=!0,i(e))})})}function nG(e,t,r){return nW(e,t,r).then(e=>Buffer.from(e).toString("utf8"))}function nV(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function nq(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r=n$.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${r}`}).join("\n")}function nJ(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function nz({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:a,targetUrl:o}){eS()&&nI.info(`${e} ${o.pathname}${o.search} ${(a>=500?ec.red:a>=400?ec.yellow:ec.green)(String(a))}
26
157
  Request headers:
27
- ${rB(n)}
28
- Request body: ${rU(t)}
158
+ ${nq(r)}
159
+ Request body: ${nJ(t)}
29
160
 
30
161
  Response headers:
31
- ${rB(Object.fromEntries(o))}
32
- Response body: ${rU(r)}`)}function rH(e,t){let n=new AbortController,r=()=>n.abort();return e.once("aborted",r),t.once("close",()=>{e.off("aborted",r),t.writableEnded||r()}),(e.aborted||t.destroyed)&&r(),n.signal}function rW(e,t,n){let r,o=("https:"===n.targetUrl.protocol?b:rw).request(n.targetUrl,{headers:n.requestHeaders,method:e.method},e=>{(r=e,t.destroyed||t.writableEnded)?e.destroy():(r$(t,n.commonHeaders),t.writeHead(e.statusCode??500,n.createResponseHeaders?.(e.headers)??rD(e.headers)),e.pipe(t))}),i=()=>{o.destroy(),r?.destroy()};o.once("error",e=>{if(!t.destroyed&&!t.writableEnded){if(t.headersSent)return void t.destroy(e);rR(t,502,`${n.errorMessage}: ${e.message}`,n.commonHeaders)}}),e.once("aborted",()=>{i()}),t.once("close",()=>{t.writableEnded||i()}),e.pipe(o)}async function rV(e,t,n){let r=t.find(({match:t})=>"string"==typeof t?e.url.pathname===t:t(e.url));await (r?.handle??n)(e)}function rG(e,t){return(n,r)=>{let o=rI(n);o?rV({request:n,response:r,url:o},e,t).catch(e=>(function(e,t){if(rv.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);rR(e,500,"Internal server error")}})(r,e)):rR(r,400,"Bad request")}}let rq="/__mcp_proxy",rJ=f("../../../node_modules/.pnpm/ws@8.21.2/node_modules/ws/lib/websocket-server.js");function rK(e,t,n){e.readyState!==tc.OPEN||e.bufferedAmount>0xa00000?e.terminate():e.send(JSON.stringify({type:t,data:n}))}let rz=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 rY extends Error{code;constructor(e,t){super(t),this.name="DebuggerControlError",this.code=e}}function rX(e){return"render_page"===e||"render_widget"===e}function rZ(e){return"number"==typeof e&&Number.isFinite(e)}function rQ(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function r0(e){if("submit_chat_query"===e.type)return 12e4;if("execute_sandbox_tool_call"===e.type){let t=e.toolCall?.tool_call?.deadline_ms;if("number"==typeof t&&Number.isFinite(t))return Math.max(1,t-Date.now()+1e3)}return 15e3}class r1{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(e){this.snapshotStore=e}registerClient(e,t){let n=this.getSnapshotStore(e),r=this.clients.get(e);r&&this.disconnectClient(r,"Debugger control connection was replaced");let o={clientId:e,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(e)??0,parallelJobs:new Map,queue:[],socket:t};this.clients.set(e,o),this.snapshotsByClientId.set(e,n),t.once("close",()=>{this.disconnectClient(o,"Debugger control connection was closed",!1)})}getSnapshotStore(e){return this.snapshotsByClientId.get(e)??{}}noteSnapshot(e){if(!e)return;let t=this.getSnapshotStore(e);Object.assign(t,this.snapshotStore),this.snapshotsByClientId.set(e,t);let n=Date.now();this.lastSnapshotAtByClientId.set(e,n);let r=this.clients.get(e);r&&(r.lastSnapshotAtMs=n)}execute(e,t,n){let r=void 0!==n?this.clients.get(n):"execute_sandbox_tool_call"===e?this.getToolCallClient():this.getActiveClient();if(!r||r.socket.readyState!==tc.OPEN)return Promise.reject(new rY("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===e?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let o=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((n,i)=>{let a={command:{...t,commandId:o,type:e},reject:i,resolve:n};"execute_sandbox_tool_call"===e?this.startParallelJob(r,a):(r.queue.push(a),this.flushClient(r))})}handleResult(e){var t,n;let r,o=e.clientId?.trim(),i=e.commandId?.trim(),a=o?this.clients.get(o):void 0,s=i?a?.parallelJobs.get(i):void 0,l=s??a?.activeJob;if(!a||!l||l.command.commandId!==i)return!1;if(!0===e.ok&&rX(l.command.type)&&(t=e.snapshot,t.snapshot.command_id===i&&t.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=e.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(o),r={target:e.target}):!0===e.ok&&!rX(l.command.type)&&(r=function(e,t){if("set_viewport"===e)return rQ(t.width)&&rQ(t.height)?t:void 0;if("submit_chat_query"===e)return!0===t.completed&&t.query?.trim()&&t.requestId?.trim()?t:void 0;if("take_snapshot"===e){let e=t.runtimeSnapshot;return e?.target?{runtimeSnapshot:e}:void 0}if("execute_sandbox_tool_call"===e)return!0===t.reported&&t.request_id?.trim()&&t.tool_call_id?.trim()?t:void 0;if("take_screenshot"===e||t.uid?.trim()){if("get_computed_style"===e){if(!Array.isArray(t.computedStyle)||!t.computedStyle.every(e=>!!e.name?.trim()&&"string"==typeof e.value))return;return t}if("get_element_rect"===e)return[t.x,t.y,t.width,t.height].every(rZ)?t:void 0;if("scroll_to"===e)return[t.x,t.y,t.maxX,t.maxY,t.viewportWidth,t.viewportHeight].every(e=>rZ(e)&&e>=0)&&t.x<=t.maxX&&t.y<=t.maxY?t:void 0;if("take_screenshot"===e){let e="png"===t.format?"image/png":"jpeg"===t.format?"image/jpeg":"webp"===t.format?"image/webp":void 0;return"string"==typeof t.data&&t.data.length>0&&t.mimeType===e&&rZ(t.width)&&rZ(t.height)&&(void 0===t.uid||t.uid?.trim())?t:void 0}}}(l.command.type,e.result),"take_snapshot"===l.command.type&&r&&"runtimeSnapshot"in r&&this.storeRuntimeSnapshot(a.clientId,r.runtimeSnapshot)),r)l.resolve(r);else{let t=e.error??{},r=t.code?.trim(),o=r&&rz.has(r)?r:void 0;l.reject(new rY(o??(rX(n=l.command.type)?"RENDER_FAILED":"set_viewport"===n?"VIEWPORT_FAILED":"scroll_to"===n?"SCROLL_FAILED":"submit_chat_query"===n?"CHAT_SUBMIT_FAILED":"take_snapshot"===n?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===n?"TOOL_CALL_FAILED":"take_screenshot"===n?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),t.message?.trim()||"Debugger control command failed"))}return l.timeout&&clearTimeout(l.timeout),s?a.parallelJobs.delete(i):a.activeJob=void 0,this.flushClient(a),!0}getActiveClient(){return[...this.clients.values()].filter(e=>e.socket.readyState===tc.OPEN&&e.lastSnapshotAtMs>0).sort((e,t)=>t.lastSnapshotAtMs-e.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(e,t){let n=this.getSnapshotStore(e).snapshot,r=n?.snapshot;if(!n||!r||r.client_id!==e)return;let o=n.debug_snapshot,{root:i,...a}=t,s=Date.now();this.snapshotStore.snapshot={...n,stored_at:new Date(s).toISOString(),stored_at_ms:s,snapshot:{...r,runtime_snapshot:t},...o?{debug_snapshot:{...o,runtime_snapshot:a}}:{}},this.snapshotStore.updatedAtMs=s,this.noteSnapshot(e)}getConnectedClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===tc.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===tc.OPEN&&e.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(e,t){let n=t.command.commandId;e.parallelJobs.set(n,t),t.timeout=setTimeout(()=>{e.parallelJobs.delete(n)&&t.reject(new rY("TOOL_CALL_FAILED","Debugger control command timed out"))},r0(t.command));try{rK(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}flushClient(e){if(e.activeJob||e.socket.readyState!==tc.OPEN)return;let t=e.queue.shift();if(t){e.activeJob=t,t.timeout=setTimeout(()=>{if(e.activeJob===t){if("submit_chat_query"===t.command.type){t.timeout=void 0,t.reject(new rY("CHAT_TIMEOUT","Debugger control command timed out"));try{rK(e.socket,"control",{commandId:t.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(e,"Debugger control connection was closed");return}t.timeout=setTimeout(()=>{e.activeJob===t&&this.disconnectClient(e,"Debugger chat cancellation was not acknowledged")},5e3);return}e.activeJob=void 0,t.reject(new rY(rX(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e)}},r0(t.command));try{rK(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}}disconnectClient(e,t,n=!0){if(this.clients.get(e.clientId)!==e)return;this.clients.delete(e.clientId),this.snapshotsByClientId.delete(e.clientId);let r=new rY("DEBUGGER_DISCONNECTED",t);for(let t of(e.activeJob?.timeout&&clearTimeout(e.activeJob.timeout),e.activeJob?.reject(r),e.activeJob=void 0,e.parallelJobs.values()))t.timeout&&clearTimeout(t.timeout),t.reject(r);for(let t of(e.parallelJobs.clear(),e.queue.splice(0)))t.reject(r);n&&e.socket.readyState===tc.OPEN&&e.socket.close()}}let r2=["page","widget","app"],r3=["log","info","warn","error","debug","eval"],r4=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function r5(e,t){let n=t.pageIdx??0,r=t.pageSize??50,o=n*r,i=e.slice(o,o+r);return{pageIdx:n,pageSize:r,total:e.length,hasMore:o+i.length<e.length,items:i}}function r9(e){if(!e.snapshot)return{stored:!1,updatedAtMs:e.updatedAtMs};let{debug_snapshot:t,...n}=e.snapshot;return{stored:!0,storedAt:n.stored_at,updatedAtMs:n.stored_at_ms??e.updatedAtMs,snapshot:n.snapshot}}function r8(e){return e.value??e.unserializableValue??e.description??e.type??""}function r7(e,t){var n,r;let o;return(n=e,"all"===(r=t)?r2:"page"===r||"widget"===r||"app"===r?[r]:(o=n.context,o?.page_id||o?.page_path?["page","app"]:o?.widget_id?["widget"]:r2)).flatMap(t=>{let n,r=(n=e.runtime_console?.[t],{entries:n?.entries??[],updatedAtMs:n?.updated_at_ms??n?.updatedAtMs});return r.entries.map((e,n)=>{var o;let i,a,s,l;return o=r.updatedAtMs,i=e.url??e.location?.url,a=e.lineNumber??e.location?.lineNumber,s=e.columnNumber??e.location?.columnNumber,l=e.id??String(n),{msgid:`${t}:${l}`,target:t,level:e.level??"log",source:e.source??"",timestamp:e.timestamp??0,text:e.message??(e.args??[]).map(r8).filter(Boolean).join(" "),...i?{url:i}:{},...void 0===a?{}:{lineNumber:a},...void 0===s?{}:{columnNumber:s},...void 0===o?{}:{updatedAtMs:o},entry:e}})})}function r6(e,t){return{id:e.toolCallId??e.id??`tool-call:${t}`,requestId:e.requestId??e.request_id??"",toolCallId:e.toolCallId??e.id??"",toolName:e.toolName??e.name??"",serverId:e.serverId??e.server_id??"",appKey:e.appKey??e.app_key??"",status:e.status??"",createdAtMs:e.createdAtMs??e.created_at_ms??0,updatedAtMs:e.updatedAtMs??e.updated_at_ms??0,requiresUserApproval:!0===e.requiresUserApproval,isMiniApp:!0===e.isMiniApp,message:e.message??"",resultSummary:e.resultSummary??e.structuredResultSummary}}function oe(e,t){if("page"===t){let{pageId:t,path:n}=e;if(!t||!n)return;return{pageId:t,path:n,name:e.name??t,isHome:!0===e.isHome}}let{widgetId:n}=e;if(n)return{widgetId:n,name:e.name??n}}let ot={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},on={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},or={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function oo(e,t={}){return{structuredContent:e,content:t.image?[{type:"image",...t.image}]:[{type:"text",text:t.text??JSON.stringify(e,null,2)}],...t.isError?{isError:!0}:{}}}async function oi(e,t={}){try{return await e()}catch(e){return function(e,t={}){let n=e instanceof rY?e:new rY("INSPECTION_FAILED",String(e));return oo({...t,error:{code:n.code,message:n.message}},{isError:!0})}(e,t)}}function oa(e,t,n,r){let o=O(n.inputSchema);e.registerTool(t,{...n,inputSchema:o},r)}let os="/__wsd_mcp";async function ol({request:e,response:t,url:n},r,o){if("OPTIONS"===e.method){r$(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void rR(t,405,"Method not allowed");let i=n.searchParams.get("clientId")??void 0,a=void 0===i?r:o.getSnapshotStore(i),s=D(()=>{let e,t;return e=new T({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let n=r9(a);if(!n.stored)return oo(n);let r=r5((t=n.snapshot,[{source:"simulator",events:t.simulator?.trace_events??[]},{source:"widget_runtime",events:t.widget_runtime_trace_events??[]},{source:"page_runtime",events:t.page_runtime_trace_events??[]}].flatMap(({source:e,events:t})=>t.map((t,n)=>{let r;return r=t.payload??{},{source:e,id:t.id??`${e}:${n}`,timestamp:t.timestamp??0,category:r.category??t.display?.category??"",event:r.event??t.event??"",requestId:r.request_id??r.requestId??r.trace_id??r.trace?.trace_id??"",payload:t.payload??t}}))).filter(t=>{let n,r,o;return n=e.category??[],r=e.event?.trim(),o=e.requestId?.trim(),(0===n.length||n.includes(t.category))&&(!r||t.event===r)&&(!o||t.requestId===o)}),e);return oo({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,events:r.items})},oa(e,"list_chat_messages",{annotations:ot,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let e=r9(a);if(!e.stored)return oo(e);let t=a.snapshot?.debug_snapshot?.simulator??e.snapshot.simulator;return oo({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,streamStatus:t?.stream_status,messages:t?.messages??[]})}),oa(e,"list_console_messages",{annotations:ot,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:M(A(r3)).optional(),pageIdx:x().int().min(0).optional(),pageSize:x().int().min(1).max(200).optional(),query:P().optional(),target:A(["current","page","widget","app","all"]).optional()}},async e=>{let t=r9(a);if(!t.stored)return oo(t);let n=r5(r7(t.snapshot,e.target).filter(t=>{let n,r;return n=e.levels??[],r=e.query?.trim().toLowerCase(),(!(n.length>0)||!!n.includes(t.level))&&(!r||[t.text,t.url,t.source,t.target].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(r)))}),e);return oo({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,messages:n.items.map(({entry:e,...t})=>t)})}),oa(e,"get_console_message",{annotations:ot,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:P()}},async e=>{let t=r9(a);if(!t.stored)return oo(t);let n=r7(t.snapshot,"all").find(t=>t.msgid===e.msgid);return oo({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!n,...n?{message:n}:{msgid:e.msgid}})}),oa(e,"get_log_snapshot",{annotations:ot,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=r9(a);return e.stored?oo({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):oo(e)}),oa(e,"list_render_targets",{annotations:ot,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:A(["all","page","widget"]).optional()}},async e=>{var t,n;let r,o=r9(a);return o.stored?oo({stored:!0,storedAt:o.storedAt,updatedAtMs:o.updatedAtMs,...(t=o.snapshot,n=e.type??"all",r=t.render_targets??{},{pages:"widget"===n?[]:(r.pages??[]).map(e=>oe(e,"page")).filter(Boolean),widgets:"page"===n?[]:(r.widgets??[]).map(e=>oe(e,"widget")).filter(Boolean),...r.currentTarget?{currentTarget:r.currentTarget}:{}})}):oo(o)}),oa(e,"take_snapshot",{annotations:ot,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:A(["current","page","widget"]).optional(),verbose:$().optional()}},e=>oi(async()=>{let t=function(e,t){var n,r;let o,i,a,s=e.runtime_snapshot;if(!s?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let l=s.target,p=l.type,d=t.target??"current";if(("page"===d||"widget"===d)&&p!==d)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:d,currentTarget:l};if(!s.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:l};let c=s.selectedUid,u=(n=s.root,r=!0===t.verbose,o=[],i=0,(a=(e,t)=>{var n,s;let{name:l,uid:p}=e;if(!p||!l)return;i+=1;let d=" ".repeat(t);if("text"===e.type)return void o.push(`${d}uid=${p} text ${JSON.stringify(e.text??"")}`);let u=[`uid=${p}`,l],{keyboardFocusable:m=!1,name:h,role:f}=e.accessibility??{};for(let t of(f&&(r||"generic"!==f)&&u.push(`role=${JSON.stringify(f)}`),h&&u.push(`name=${JSON.stringify(h)}`),(r||m)&&u.push(`focusable=${String(m)}`),(e.attributes??[]).map(e=>({name:e.name,value:e.value})).filter(e=>e.name&&(r||r4.has(e.name)||e.name.startsWith("aria-")))))u.push((n=t.name,(s=t.value)?`${n}=${JSON.stringify(s)}`:n));for(let n of(p===c&&u.push("[selected]"),o.push(`${d}${u.join(" ")}`),e.children??[]))a(n,t+1)})(n,0),{actualNodeCount:i,text:o.join("\n")});return{available:!0,target:l,nodeCount:s.nodeCount??u.actualNodeCount,...c?{selectedUid:c}:{},truncated:!0===s.truncated,snapshot:u.text,snapshotUpdatedAtMs:s.updatedAtMs}}({runtime_snapshot:(await o.execute("take_snapshot",{target:e.target??"current"},i)).runtimeSnapshot},e),n=r9(a),r={stored:n.stored,...n.stored?{storedAt:n.storedAt,updatedAtMs:n.updatedAtMs}:{},...t};return oo(r,{text:t.available?t.snapshot:JSON.stringify(r,null,2)})},{available:!1,stored:!1})),oa(e,"get_computed_style",{annotations:ot,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:M(P().min(1)).max(100).optional(),uid:P().min(1)}},({properties:e,uid:t})=>oi(async()=>oo(await o.execute("get_computed_style",{uid:t,...e?{properties:e}:{}},i)))),oa(e,"get_element_rect",{annotations:ot,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:P().min(1)}},({uid:e})=>oi(async()=>oo(await o.execute("get_element_rect",{uid:e},i)))),oa(e,"take_screenshot",{annotations:ot,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:A(["png","jpeg","webp"]).optional(),quality:x().min(0).max(100).optional(),uid:P().min(1).optional()}},({format:e="png",quality:t,uid:n})=>oi(async()=>{let r=await o.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...n?{uid:n}:{}},i),{data:a,...s}=r;return oo({captured:!0,...s},{image:{data:a,mimeType:r.mimeType}})},{captured:!1})),oa(e,"scroll_to",{annotations:or,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:P().min(1).optional(),x:x().min(0).optional(),y:x().min(0).optional()}},({uid:e,x:t,y:n})=>oi(async()=>oo({scrolled:!0,...await o.execute("scroll_to",{uid:e,x:t,y:n},i)}),{scrolled:!1})),oa(e,"set_viewport",{annotations:or,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:x().int().min(1).max(9999),width:x().int().min(1).max(9999)}},({height:e,width:t})=>oi(async()=>oo({updated:!0,viewport:await o.execute("set_viewport",{height:e,width:t},i)}),{updated:!1})),oa(e,"render_page",{annotations:on,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:P().min(1)}},({url:e})=>oi(async()=>oo({rendered:!0,target:(await o.execute("render_page",{url:e},i)).target}),{rendered:!1})),oa(e,"render_widget",{annotations:on,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:j(P(),C()).optional(),widgetId:P().min(1)}},({structuredContent:e,widgetId:t})=>oi(async()=>oo({rendered:!0,target:(await o.execute("render_widget",{structuredContent:e??{},widgetId:t},i)).target}),{rendered:!1})),oa(e,"submit_chat_query",{annotations:on,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:P().trim().min(1)}},({query:e})=>oi(async()=>oo({submitted:!0,...await o.execute("submit_chat_query",{query:e},i)}),{submitted:!1})),oa(e,"list_agent_trace_events",{annotations:ot,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:M(P()).optional(),event:P().optional(),pageIdx:x().int().min(0).optional(),pageSize:x().int().min(1).max(200).optional(),requestId:P().optional()}},t),oa(e,"list_agent_tool_calls",{annotations:ot,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:x().int().min(0).optional(),pageSize:x().int().min(1).max(200).optional(),query:P().optional(),requestId:P().optional(),status:M(P()).optional(),toolName:P().optional()}},async e=>{var t;let n=r9(a);if(!n.stored)return oo(n);let r=r5((t=n.snapshot,(t.simulator?.tool_calls??[]).map(r6)).filter(t=>{let n,r,o,i;return n=e.requestId?.trim(),r=e.toolName?.trim(),o=e.status??[],i=e.query?.trim().toLowerCase(),(!n||t.requestId===n)&&(!r||t.toolName===r)&&(!(o.length>0)||!!o.includes(t.status))&&(!i||[t.toolName,t.serverId,t.appKey,t.status,t.message,"string"==typeof t.resultSummary?t.resultSummary:void 0].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(i)))}),e);return oo({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,toolCalls:r.items})}),e}),l=R(s);try{await l(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):rR(t,500,e instanceof Error?e.message:String(e))}finally{await s.close().catch(()=>void 0)}}let op="/__web_sdk_debug_scenes",od="/__web_sdk_widget_view_data_templates",oc={"Cache-Control":"no-cache"};async function ou(e,t){try{let n=await t?.()??{templatesByEntry:{},templatesByWidget:{}};rN(e,200,n,oc)}catch(t){rv.error("加载 Widget viewData 模板失败",{error:t}),rN(e,500,{templatesByEntry:{},templatesByWidget:{}},oc)}}let om=f("node:crypto"),oh="/__dbx_real_device_debug",of=`${oh}/state`,og=`${oh}/start`,oy=`${oh}/cancel`,ob=`${oh}/qr`;class o_{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:of,startEndpoint:og,cancelEndpoint:oy,qrEndpoint:ob,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?om.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(oh),handle:({request:e,response:t,url:n})=>this.serveRequest(e,t,n)}]}async serveRequest(e,t,n){if(!this.validateRequest(e,t))return;let r=this.provider;if(!r)return this.writeError(t,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let o=await this.readJsonBody(e,t);if(o)try{if(n.pathname===of||n.pathname===og){if(Object.keys(o).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=n.pathname===of?await r.getState():await r.start();rN(t,200,e);return}if(n.pathname===oy){let e=o.operationId;if("string"!=typeof e||!e||1!==Object.keys(o).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");rN(t,200,await r.cancel(e));return}if(n.pathname===ob){let{operationId:e,kind:n}=o;if("string"!=typeof e||!e||"modern"!==n&&"legacy"!==n||2!==Object.keys(o).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid QR request");let i=await r.getQrImage(e,n);if(!i)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");r$(t),t.writeHead(200,{"Content-Length":i.body.byteLength,"Content-Type":i.contentType}),t.end(i.body);return}return this.writeError(t,404,"NOT_FOUND","Not found")}catch{return this.writeError(t,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(e,t){var n,r;let o,i,a;if(!function(e){if(!e)return!1;try{let t=new URL(`http://${e}`).hostname.toLowerCase();return"127.0.0.1"===t||"[::1]"===t||"localhost"===t}catch{return!1}}(e.headers.host))return this.writeError(t,403,"FORBIDDEN_HOST","Forbidden host"),!1;let s=e.headers["x-dbx-real-device-token"];if("string"!=typeof s||!this.accessToken||(n=s,r=this.accessToken,i=(o=new TextEncoder).encode(n),a=o.encode(r),!(i.length===a.length&&om.timingSafeEqual(i,a))))return this.writeError(t,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==e.method)return this.writeError(t,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(e.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(t,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let l=e.headers.origin;return!l||l===`http://${e.headers.host}`||(this.writeError(t,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(e,t){let n,r;try{n=await rM(e,t,4096)}catch{return this.writeError(t,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!n.trim())return{};try{r=JSON.parse(n)}catch{return this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body")}return!r||"object"!=typeof r||Array.isArray(r)?this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body"):r}writeError(e,t,n,r){e.writableEnded||e.destroyed||rN(e,t,{error:{code:n,message:r}})}}let ov={"Cache-Control":"no-cache"};async function ow({request:e,response:t,url:n},r,o){let i;if("OPTIONS"===e.method){r$(t,ov),t.writeHead(204),t.end();return}if("GET"===e.method){let e;return void rN(t,200,function(e,t){if(!e?.debug_snapshot)return e;let{debug_snapshot:n,...r}=e;return t?{...r,snapshot:n}:r}(r.snapshot,null!=(e=n.searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase())??{stored:!1},ov)}if("POST"!==e.method)return void rN(t,405,{error:"Method not allowed"},ov);try{i=JSON.parse(await rM(e,t,0xa00000))}catch(e){rN(t,400,{error:e.message},ov);return}oS(r,o,i),rN(t,200,{ok:!0,updated_at_ms:r.updatedAtMs},ov)}function oS(e,t,n){var r;let o,i="string"==typeof(o=(r=n).snapshot.client_id??r.debug_snapshot?.client_id)&&o.trim()?o.trim():void 0;n=function(e,t){let n=e?.snapshot,r=t.snapshot,o=n?.runtime_snapshot,i=r.runtime_snapshot;if(!n||!o||n.client_id!==r.client_id)return t;if(!i){var a;let e;if(a=o.target,e=function(e){let t=e.render_targets?.currentTarget;if(t)return t;let n=e.context;if(n){if(Object.hasOwn(n,"widget_id"))return{type:"widget"};if(Object.hasOwn(n,"page_id")||Object.hasOwn(n,"page_path"))return{type:"page"}}}(r),a&&e&&(1===Object.keys(e).length?e.type!==a.type:JSON.stringify(e)!==JSON.stringify(a)))return t;let{root:n,...i}=o;return{...t,snapshot:{...r,runtime_snapshot:o},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:i}}:{}}}return Object.hasOwn(i,"root")||!Object.hasOwn(o,"root")||o.updatedAtMs!==i.updatedAtMs||JSON.stringify(o.target)!==JSON.stringify(i.target)?t:{...t,snapshot:{...r,runtime_snapshot:{...i,root:o.root}}}}(i?t.getSnapshotStore(i).snapshot:e.snapshot,n),e.snapshot=n,e.updatedAtMs=Date.now(),t.noteSnapshot(i)}let oE="/app_developer/api/sandbox/",ox=`${oE}session/business_info/update`,oA=new Set([`${oE}resources/notices/pull`,`${oE}resources/tasks/pull`]),oT={"Access-Control-Expose-Headers":rC},oC=new Set;function oI(e,t,n,r,o,i){if("applet0930"!==process.env.DEBUG)return!1;let a=`${o[rT]??""} ${e} ${t.pathname}`,s=oA.has(t.pathname);if(s&&n>=500){if(oC.has(a))return!1;oC.add(a)}else s&&n<500&&oC.delete(a);let l=Number(process.hrtime.bigint()-r)/1e6;return rv.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:l,headers:o,logId:i}),!0}function oP({method:e,requestBody:t,requestHeaders:n,responseBody:r,responseHeaders:o,statusCode:i,targetUrl:a}){rF({method:e,requestBody:t,requestHeaders:n,responseBody:r,responseHeaders:o,statusCode:i,targetUrl:a})}function oO(e,t,n){return n&&!(oA.has(e.pathname)&&t>=500)}function oD(e,t){if(e.pathname!==ox||!t)return t;try{let e=JSON.parse(t);return JSON.stringify({...e,..."csr_pem"in e?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"invalid business info request"})}}async function ok({method:e,request:t,requestBody:n,requestHeaders:r,response:o,targetUrl:i,usePlatformFetch:a}){let s=process.hrtime.bigint(),l=rH(t,o);try{let t,p=a?await eH({internal:!0,path:`${i.pathname}${i.search}`,method:e,body:n,headers:r,signal:l}):await fetch(i,{body:"GET"===e||"HEAD"===e?void 0:n,headers:r,method:e,signal:l}),d=oI(e,i,p.status,s,r,p.headers.get(rC)??void 0);if(o.destroyed||o.writableEnded)return void p.body?.cancel().catch(()=>void 0);let c=await rj(p);return oO(i,p.status,d)&&oP({method:e,requestBody:oD(i,n),requestHeaders:r,responseBody:c,responseHeaders:p.headers,statusCode:p.status,targetUrl:i}),o.destroyed||o.writableEnded||(t=rk(p.headers,[rC]),r$(o,oT),o.writeHead(p.status,t),o.end(c)),{body:c,ok:p.ok}}catch(p){if(o.destroyed||o.writableEnded||l.aborted)return;let t=`Failed to proxy sandbox request: ${p instanceof Error?p.message:String(p)}`,a=oI(e,i,502,s,r);oO(i,502,a)&&oP({method:e,requestBody:oD(i,n),requestHeaders:r,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:i}),rR(o,502,t,oT)}}async function o$(e,t,n={}){let r;if("POST"!==e.method)return void rR(t,405,"Method not allowed",oT);try{r=JSON.parse(await rM(e,t,0xa00000))}catch(e){rR(t,400,`Invalid sandbox proxy payload: ${e.message}`,oT);return}let o=function(e,t){if(!e.url)return;let n=new URL(e.url,t);if(!n.pathname.startsWith(oE))return;let r=new URL(`${n.pathname}${n.search}`,t);var o=e.params;if(o)for(let[e,t]of Object.entries(o))null!=t&&r.searchParams.set(e,String(t));return r}(r,n.targetOrigin??en);if(!o)return void rR(t,404,"Sandbox endpoint not found",oT);if(!n.sandboxSessionId)return void rN(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},oT);let i=function(e,t,n,r){if(t.pathname.startsWith(`${oE}session/`)&&t.pathname!==`${oE}session/create`)return JSON.stringify({..."object"==typeof e.data&&null!==e.data?e.data:{},sandbox_session_id:r});if(void 0===e.data)return;if("object"!=typeof e.data||null===e.data||!n)return JSON.stringify(e.data);let o={...e.data};return t.pathname.startsWith(`${oE}jsb/`)&&"app_key"in o&&(o.app_key=n),t.pathname===`${oE}passport/open/auth`&&"client_key"in o&&(o.client_key=n),JSON.stringify(o)}(r,o,n.sandboxAppId,n.sandboxSessionId),a=r.method||"POST",s=function(e,t,n,r,o){let i=Object.fromEntries(Object.entries(rO({...e.headers,...n,...void 0===r?{}:{"content-length":String(Buffer.byteLength(r))},"content-type":"application/json"},t,{...ea(),...o?{[rT]:o}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]));for(let e of Object.keys(i))"accept-encoding"===e.toLowerCase()&&delete i[e];return i["accept-encoding"]="identity",i}(e,o,r.headers,i,n.sandboxSessionId),l=await ok({method:a,request:e,requestBody:i,requestHeaders:s,response:t,targetUrl:o,usePlatformFetch:!n.targetOrigin});if(o.pathname===ox&&l?.ok)try{let e=JSON.parse(l.body.toString("utf8"));(void 0===e.code||0===e.code)&&n.onBusinessInfoUpdated?.(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t="string"==typeof e.csr_pem?e.csr_pem.trim():"",n="string"==typeof e.phone_num?e.phone_num.trim():"";return n?{...t?{csrPem:t}:{},phoneNum:n}:void 0}(r.data))}catch{}}let oR=f("node:util"),oN="/app_developer/api/sandbox/bridge/events",oL="/app_developer/api/sandbox/bridge/response",oM=new Set(["connection","content-length","host"]),oj=new Set(["heartbeat"]),oB=[500,1e3,2e3,5e3],oU=0;function oF(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function oH(e,t=new Headers,n=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:n}}async function oW(e){let t,n,r=e.request_id||"";if(!r)return oH({error_message:"bridge request_id is required",http_status:0,request_id:r,success:!1});if(!e.path?.startsWith("/"))return oH({error_message:`invalid bridge request path: ${e.path??""}`,http_status:0,request_id:r,success:!1});let o=function(e){if(e.origin)try{var t;return new URL(e.path??"/",(t=e.origin).endsWith("/")?t:`${t}/`)}catch{return}}(e);if(!o)return oH({error_message:`invalid bridge request origin: ${e.origin??""}`,http_status:0,request_id:r,success:!1});let i=(e.method||"GET").toUpperCase(),a=function(e){let t={};for(let[n,r]of Object.entries(e??{}))!n||oM.has(n.toLowerCase())||(t[n]=r);return t}(e.headers),s="GET"===i||"HEAD"===i?void 0:e.body??"",l=new AbortController,p=setTimeout(()=>l.abort(),(t="number"==typeof e.timeout_ms?e.timeout_ms:3e3,n="number"==typeof e.deadline_ms?e.deadline_ms-Date.now():t,Math.max(1,Math.min(t,n))));try{var d;let e=await fetch(o,{body:s,headers:a,method:i,redirect:"manual",signal:l.signal}),t=await e.text();return d={method:i,requestBody:s,requestHeaders:a,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:o},rF(d),oH({body:t,http_status:e.status,request_id:r,success:!0},e.headers,e.statusText)}catch(e){return rF({method:i,requestBody:s,requestHeaders:a,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:o}),oH({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:r,success:!1})}finally{clearTimeout(p)}}function oV(e,t=new Set){if(Array.isArray(e)){for(let n of e)oV(n,t);return[...t]}if(!e||"object"!=typeof e)return[...t];for(let[n,r]of Object.entries(e)){if(n.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof r&&r)t.add(r);else if(Array.isArray(r))for(let e of r)"string"==typeof e&&e&&t.add(e);continue}oV(r,t)}return[...t]}function oG(e,t){e.onLog?.(t)}function oq(e){try{return JSON.parse(e)}catch{return}}function oJ({detail:e,requestHeaders:t,status:n,targetUrl:r}){if("applet0930"===process.env.DEBUG){if("number"==typeof n)return void rv.request({method:"CONNECT",url:r.pathname,statusCode:n,headers:t,context:{detail:e}});rv.info("Bridge connection pending",{url:r.pathname,detail:e,ppe:ti(t)})}}function oK(e,t={}){"applet0930"===process.env.DEBUG&&rv.info(e,t)}async function oz(e,t){let n=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),r={"content-type":"application/json",[rT]:e.sandboxSessionId,...ea()};if(e.targetOrigin){let t=new URL(oL,e.targetOrigin),o=await fetch(t,{body:n,headers:r,method:"POST"}),i=await o.text();if(rF({method:"POST",requestBody:n,requestHeaders:r,responseBody:i,responseHeaders:o.headers,statusCode:o.status,targetUrl:t}),!o.ok)throw Error(`upload bridge response failed: ${o.status} ${i}`);return{responseBody:i,responseHeaders:Object.fromEntries(o.headers),responsePayload:oq(i)}}let o=new URL(oL,en),i=await eH({body:n,headers:r,internal:!0,method:"POST",path:oL}),a=await i.text();if(rF({method:"POST",requestBody:n,requestHeaders:r,responseBody:a,responseHeaders:i.headers,statusCode:i.status,targetUrl:o}),!i.ok)throw Error(`upload bridge response failed: ${i.status} ${a}`);return{responseBody:a,responseHeaders:Object.fromEntries(i.headers),responsePayload:oq(a)}}async function oY(e,t){let n;try{n=JSON.parse(t)}catch(e){rv.warn("Sandbox Bridge request parse failed",{reason:e.message});return}let r=Date.now(),o=`bridge-${r}-${++oU}`,i=n.request_id||"",a={id:o,request:n,requestId:i,sandboxSessionId:e.sandboxSessionId,timestamp:r};oG(e,{...a,logIds:oV(n),status:"pending",updatedAtMs:r});let s=await oW(n),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await oz(e,s.response);oG(e,{...a,logIds:oV([n,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw oG(e,{...a,errorMessage:t instanceof Error?t.message:String(t),logIds:oV([n,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function oX(e,t,n){let r={sandbox_session_id:e.sandboxSessionId},o=new URL(`${oN}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,en),i=(d=e.sandboxSessionId,{accept:"text/event-stream",host:o.host,[rT]:d,...ea()});oJ({detail:`host=${i.host} session=${oF(e.sandboxSessionId)}`,requestHeaders:i,status:"pending",targetUrl:o}),oK("bridge/events request",{headers:{accept:i.accept,host:i.host,[rT]:oF(e.sandboxSessionId),"x-tt-env":i["x-tt-env"],"x-use-ppe":i["x-use-ppe"]},path:oN,query:r});let a=await eH({headers:i,internal:!0,method:"GET",path:oN,query:r,signal:t});if(oJ({detail:`content-type=${a.headers.get("content-type")??""}`,requestHeaders:i,status:a.status,targetUrl:o}),!a.ok||!a.body){let e=await a.text().catch(()=>"");rF({method:"GET",requestBody:void 0,requestHeaders:i,responseBody:e,responseHeaders:a.headers,statusCode:a.status,targetUrl:o}),rv.warn("Sandbox Bridge events request failed",{status:a.status,body:e.slice(0,500)});let t=Error(`Sandbox Bridge SSE failed: ${a.status} ${e}`);throw t.status=a.status,t}rF({method:"GET",requestBody:void 0,requestHeaders:i,responseBody:"",responseHeaders:a.headers,statusCode:a.status,targetUrl:o}),n?.();let s=a.body.getReader(),l=new oR.TextDecoder,p="";for(;!t.aborted;){let{done:t,value:n}=await s.read();if(t){oK("bridge/events stream ended",{session:oF(e.sandboxSessionId)});break}let r=(p+=l.decode(n,{stream:!0})).search(/\r?\n\r?\n/);for(;r>=0;){let t=p.slice(0,r),n=p.slice(r).match(/^\r?\n\r?\n/);p=p.slice(r+(n?.[0].length??2));let s=function(e){let t="message",n=[];for(let r of e.split(/\r?\n/)){if(r.startsWith("event:")){t=r.slice(6).trim();continue}r.startsWith("data:")&&n.push(r.slice(5).trimStart())}return{data:n.join("\n"),name:t}}(t);if(!function(e,t){if("applet0930"!==process.env.DEBUG||oj.has(e.name))return;let n=function(e){try{let t=JSON.parse(e);return"string"==typeof t.request_id?t.request_id:void 0}catch{return}}(e.data);rv.info("Bridge event received",{event:e.name,requestId:n,ppe:ti(t)}),rv.info(`Event detail
33
- ${e.data}`)}(s,i),"bridge_request"===s.name){var d,c=a.headers,u=a.status;rF({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:i,responseBody:"",responseHeaders:c,statusCode:u,targetUrl:o}),oY(e,s.data).catch(e=>{rv.warn("Sandbox Bridge request failed",{reason:e.message})})}else if("TOOL_CALL"===s.name){let t=z(oq(s.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{rv.warn("Sandbox tool call forwarding failed",{reason:e instanceof Error?e.message:String(e),requestId:t.request_id,toolCallId:t.tool_call.tool_call_id})}):rv.warn("Sandbox tool call event parse failed")}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=oq(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let n=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,r=n?.resource,o=n?.action,i=n?.resource_id,a=n?.revision;if(("notice"===r||"task"===r)&&("upsert"===o||"remove"===o)&&"string"==typeof i&&i&&("number"==typeof a||"string"==typeof a))return{action:o,eventId:"string"==typeof t.event_id?t.event_id:"",occurredAtMs:"number"==typeof t.occurred_at_ms?t.occurred_at_ms:void 0,resource:r,resourceId:i,revision:a}}(s.data);t?e.onResourceChanged?.(t):rv.warn("Sandbox resource event parse failed")}else if("card_delta"===s.name){let t=function(e){let t=oq(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let n=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,r=n?.card_delta;if(!("card_delta"!==t.type||!r||"object"!=typeof r||Array.isArray(r)))return r}(s.data);t?e.onSimulatorEvent?.({payload:t,type:"card_delta"}):rv.warn("Sandbox simulator event parse failed",{event:s.name})}else if("get_simulator_card_snapshots"===s.name){let t=oq(s.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:s.name}):rv.warn("Sandbox simulator event parse failed",{event:s.name})}r=p.search(/\r?\n\r?\n/)}}}async function oZ(e,t){let n=0,r=!1;for(;!t.aborted;){try{await oX(e,t,()=>{r=!1,e.onConnectionStatusChange?.("connected")}),n=0}catch(n){if(t.aborted)return;let e=n.status;if(r||(rv.warn("无法接收来自平台服务的请求",{reason:n.message}),r=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,_.setTimeout)(oB[Math.min(n,oB.length-1)],void 0,{signal:t}).catch(()=>void 0),n+=1}}let oQ=f("node:net"),o0="/__web_sdk_sandbox_bridge_logs",o1="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",o2="/app_developer/api/sandbox/session/business_info/update";function o3(e){if(!e)return!1;try{return tQ.statSync(e).isFile()}catch{return!1}}async function o4({body:e,headers:t,method:n,sandboxPath:r,targetOrigin:o,targetUrl:i}){let a=new AbortController,s=setTimeout(()=>a.abort(),3e4);try{return o?await fetch(i,{body:e,headers:t,method:n,signal:a.signal}):await eH({internal:!0,path:r,body:e,headers:t,method:n,signal:a.signal})}catch(e){if(a.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${i}`);throw e}finally{clearTimeout(s)}}function o5(e,t){return(e?.[t]??process.env[t])?.trim()??""}function o9(e,t,n,r,o,i){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-r)/1e6;rv.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:a,headers:o,logId:i})}function o8({method:e,requestBody:t,requestHeaders:n,responseBody:r,responseHeaders:o,statusCode:i,targetUrl:a}){rF({method:e,requestBody:t,requestHeaders:n,responseBody:r,responseHeaders:o,statusCode:i,targetUrl:a})}async function o7(e,t,n,r,o,i){let a,s,l="/app_developer/api/sandbox/session/create",p="POST",d=function(){let e=new Set;for(let t of(process.env[o1]??"").split(",")){let n=t.trim();if(n)try{let t=new URL(n),r=t.hostname.replace(/^\[|\]$/g,"").toLowerCase(),o="localhost"===r||"::1"===r||4===(0,oQ.isIP)(r)&&r.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!o)throw Error("only loopback HTTP(S) origins are allowed");e.add(t.origin)}catch(e){throw Error(`${o1} contains an invalid origin: ${n} (${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),c=JSON.stringify({sandbox_project_id:e,manifest:n?.()??(o3(t)?tQ.readFileSync(t,"utf8"):""),business_templates:o3(r)?tQ.readFileSync(r,"utf8"):"",...i?{app_id:i}:{},...d.length>0?{bridge_origins:d}:{}}),u={"content-type":"application/json",...ea()},m=new URL(l,o??en),h=process.hrtime.bigint();try{a=await o4({body:c,headers:u,method:p,sandboxPath:l,targetOrigin:o,targetUrl:m})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw o9(p,m,502,h,u),o8({method:p,requestBody:c,requestHeaders:u,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:m}),t}let f=a.headers.get(rC)||"",g=await a.text();o9(p,m,a.status,h,u,f),o8({method:p,requestBody:c,requestHeaders:u,responseBody:g,responseHeaders:a.headers,statusCode:a.status,targetUrl:m});try{s=JSON.parse(g||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${a.status} ${a.statusText||g||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!a.ok||0!==s.code)throw Error(`创建 Sandbox session 失败:${s.message||a.statusText||a.status}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);let y=s.data?.sandbox_session_id,b=s.data?.sandbox_appid;if(!y||!b)throw Error(`创建 Sandbox session 失败:响应缺少 ${y?"sandbox_appid":"sandbox_session_id"}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);return{appId:b,sessionId:y}}async function o6(e,t,n,r,o,i){try{return await o7(e,t,n,r,o,i)}catch(e){return rv.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function ie(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function it(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function ir(e,t){let n,r,o="/app_developer/api/sandbox/session/business_info/get",i="POST",a=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...ea()},l=new URL(o,t??en),p=process.hrtime.bigint();try{n=await o4({body:a,headers:s,method:i,sandboxPath:o,targetOrigin:t,targetUrl:l})}catch(e){throw o9(i,l,502,p,s),e}let d=n.headers.get(rC)||"",c=await n.text();o9(i,l,n.status,p,s,d);try{r=JSON.parse(c||"{}")}catch{throw o8({method:i,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({omitted:"invalid business info response"}),responseHeaders:n.headers,statusCode:n.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}let u={csrUploaded:!!r.data?.csr_pem?.trim(),phoneNumberUploaded:!!r.data?.phone_num?.trim()};if(o8({method:i,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({code:r.code,data:u,log_id:r.log_id}),responseHeaders:n.headers,statusCode:n.status,targetUrl:l}),!n.ok||void 0!==r.code&&0!==r.code)throw Error(`获取 Sandbox session 信息失败:${r.message||n.statusText||n.status}${r.log_id||d?`,log_id=${r.log_id||d}`:""}`);return u}async function io(e,t){if(!e)return ie();try{return await ir(e,t)}catch(e){return rv.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),ie()}}async function ii(e,t,n){let r,o,i="POST",a=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...ea(),[rT]:t},l=new URL(o2,n??en),p=process.hrtime.bigint();try{r=await o4({body:a,headers:s,method:i,sandboxPath:o2,targetOrigin:n,targetUrl:l})}catch(e){throw o9(i,l,502,p,s),e}let d=r.headers.get(rC)||"",c=await r.text();o9(i,l,r.status,p,s,d),o8({method:i,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:c,responseHeaders:r.headers,statusCode:r.status,targetUrl:l});try{o=JSON.parse(c||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}if(!r.ok||void 0!==o.code&&0!==o.code)throw Error(`更新 Sandbox session 信息失败:${o.message||r.statusText||r.status}${o.log_id||d?`,log_id=${o.log_id||d}`:""}`)}async function ia(e,t,n,r){if(e&&t.phoneNum&&(!n||t.csrPem))try{return await ii({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,r),rv.info("Sandbox business info 已自动上传",{sessionId:e}),it(t.csrPem)}catch(e){rv.warn(`Sandbox business info 自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function is(e,t){let n,r="/app_developer/api/sandbox/session/revoke",o="POST",i=JSON.stringify({sandbox_session_id:e}),a={"content-type":"application/json",...ea()},s=new URL(r,t??en),l=process.hrtime.bigint();try{n=await o4({body:i,headers:a,method:o,sandboxPath:r,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw o9(o,s,502,l,a),o8({method:o,requestBody:i,requestHeaders:a,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let p=n.headers.get(rC)||"",d=await n.text();o9(o,s,n.status,l,a,p),o8({method:o,requestBody:i,requestHeaders:a,responseBody:d,responseHeaders:n.headers,statusCode:n.status,targetUrl:s});let c=JSON.parse(d||"{}");if(!n.ok||0!==c.code)throw Error(`撤回 Sandbox session 失败:${c.message||n.statusText||n.status}${c.log_id||p?`,log_id=${c.log_id||p}`:""}`)}async function il(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let n=e.sandboxSessionId;n&&await is(n,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let r=await o7(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),o=r.sessionId,i=!e.sandboxSessionAppId,a=await ia(o,e.businessInfoInput,i,e.sandboxTargetOrigin)??await io(o,e.sandboxTargetOrigin);return e.sandboxAppId=r.appId,e.sandboxSessionId=o,e.businessInfo=a,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,ic(t),e.bridge=iu(e,o),rv.info("Sandbox session 已重建",{sessionId:o}),{...r,businessInfoUploaded:a.phoneNumberUploaded&&(!i||a.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function ip(e){return{bridgeLogs:e.bridgeLogs,bridgeLogsUpdatedAtMs:e.bridgeLogsUpdatedAtMs,connectionStatus:e.resourceConnectionStatus,events:e.resourceEvents,generation:e.resourceGeneration,instanceId:e.resourceInstanceId,simulatorEvents:e.simulatorEvents,updatedAtMs:e.resourceEventsUpdatedAtMs}}function id(e){clearTimeout(e.logBroadcastTimer),e.logBroadcastTimer=void 0;let t=ip(e);for(let n of e.eventListeners)n(t)}function ic(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1),id(e)}function iu(e,t){var n={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,ic(e))},onLog:t=>{let n=e.bridgeLogs.findIndex(e=>e.id===t.id);n>=0?e.bridgeLogs[n]=t:(e.bridgeLogs.push(t),e.bridgeLogs.length>200&&e.bridgeLogs.splice(0,e.bridgeLogs.length-200)),e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),e.logBroadcastTimer??=setTimeout(()=>id(e),50)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),ic(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),ic(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!n.sandboxSessionId)return void rv.warn("Sandbox Bridge skipped: missing sandbox session id");let r=new AbortController;return oK("start sandbox bridge",{session:oF(n.sandboxSessionId)}),n.onConnectionStatusChange?.("connecting"),oZ(n,r.signal),{close:()=>r.abort()}}function im(e){e.bridgeLogs.length=0,e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),id(e)}async function ih(e,t,n){if("POST"!==e.method)return void rR(t,405,"Method not allowed");if(!n)return void rR(t,503,"Sandbox session is not initialized");try{let r=await rM(e,t,1048576);if(r){let e=JSON.parse(r);if(void 0!==e.csrPem&&"string"!=typeof e.csrPem||"string"!=typeof e.phoneNum)return void rR(t,400,"Invalid Sandbox business info");n.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let o=await il(n);rN(t,200,{code:0,data:{sandbox_appid:o.appId,business_info_uploaded:o.businessInfoUploaded,sandbox_session_id:o.sessionId},message:"ok"})}catch(e){rR(t,500,e.message)}}function ig(e){let t=e.appId?.trim(),n=t&&!t.startsWith("doubao-sandbox-app-")?t:void 0,r=function(e){let t=tC.resolve(e??process.cwd()),n=t;try{n=tQ.realpathSync.native(t)}catch{}return(0,om.createHash)("sha256").update(n).digest("hex")}(e.appDirectory),o=function(e,t){let n=o5(e,"DOUBAO_SANDBOX_PHONE_NUM"),r=o5(e,"DOUBAO_SANDBOX_CSR_FILE"),o=function(e,t){if(!e)return;let n=tC.isAbsolute(e)?e:tC.resolve(t??process.cwd(),e);return o3(n)?n:void 0}(r,t),i="";if(r&&!o)rv.warn(`Sandbox CSR 文件不存在:${r}`);else if(o)try{i=tQ.readFileSync(o,"utf8").trim()}catch(e){rv.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...n?{phoneNum:n}:{},...i?{csrPem:i}:{}}}(e.env,e.appDirectory),i=`${o.phoneNum??""}\0${o.csrPem??""}`;return{businessInfoInput:o,businessInfoInputKey:i,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([i,r,n,e.targetOrigin,e.businessTemplatesPath,e.manifestPath]),manifestReader:e.manifestReader,manifestPath:e.manifestPath,onSimulatorToolCall:e.onSimulatorToolCall,projectId:r,sessionAppId:n,targetOrigin:e.targetOrigin}}class iy{configKey;manifestReader;state;constructor(e,t,n){this.state=e,this.configKey=t,this.manifestReader=n}static async start(e){let t=ig(e),n=await o6(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),r=!t.sessionAppId,o={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await ia(n.sessionId,t.businessInfoInput,r,t.targetOrigin)??await io(n.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,om.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:n.appId,sandboxProjectId:t.projectId,sandboxSessionAppId:t.sessionAppId,sandboxSessionId:n.sessionId,sandboxTargetOrigin:t.targetOrigin,simulatorBusinessTemplatesPath:t.businessTemplatesPath,simulatorManifestReader:t.manifestReader,simulatorManifestPath:t.manifestPath},i=new iy(o,t.key,t.manifestReader);return o.bridge=n.sessionId?iu(o,n.sessionId):void 0,i}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(e){return this.state.eventListeners.add(e),e(ip(this.state)),()=>{this.state.eventListeners.delete(e)}}clearBridgeLogs(){im(this.state)}matches(e){let t=ig(e);return this.configKey===t.key&&this.manifestReader===t.manifestReader}getDebugContext(){var e;let t;return{fileSystemNamespace:(t=(e=this.state).sandboxSessionAppId?`real-app\0${e.sandboxSessionAppId}`:`virtual-app\0${e.sandboxAppId}\0${e.sandboxProjectId}`,`sandbox-v1:${(0,om.createHash)("sha256").update(t).digest("hex")}`),sandboxSessionAvailable:!!this.state.sandboxSessionId,sandboxCsrRequired:!this.state.sandboxSessionAppId,sandboxCsrUploaded:this.state.businessInfo.csrUploaded,sandboxPhoneNumberUploaded:this.state.businessInfo.phoneNumberUploaded,sandboxBridgeLogsEndpoint:o0,sandboxEventsAvailable:!0,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(){return[{match:o0,handle:({request:e,response:t})=>{var n;return n=this.state,void("GET"!==e.method&&"DELETE"!==e.method?rR(t,405,"Method not allowed"):("DELETE"===e.method&&n&&im(n),rN(t,200,{logs:n?.bridgeLogs??[],updatedAtMs:n?.bridgeLogsUpdatedAtMs??0},{"Cache-Control":"no-cache"})))}},{match:"/__web_sdk_sandbox_resource_events",handle:({request:e,response:t})=>{var n;return n=this.state,void("GET"!==e.method?rR(t,405,"Method not allowed"):rN(t,200,{connectionStatus:n?.resourceConnectionStatus??"connecting",events:n?.resourceEvents??[],generation:n?.resourceGeneration??0,simulatorEvents:n?.simulatorEvents??[],updatedAtMs:n?.resourceEventsUpdatedAtMs??0},{"Cache-Control":"no-cache"}))}},{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>o$(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=it(e?.csrPem),e&&(this.state.businessInfoInput=e)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>ih(e,t,this.state)}]}}function ib(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let i_="/__tools/tools.json",iv="/__events/events.json",iw="manifest.yaml",iS="skill";function iE(e){if(!e)return!1;try{return tQ.statSync(e).isFile()}catch{return!1}}function ix(e,t){if(!e)return;let n=tC.isAbsolute(e)?e:tC.resolve(t??process.cwd(),e);return iE(n)?n:void 0}function iA(e,t){if(e&&t)return tC.relative(t,e).split(tC.sep).join("/")||"."}function iT(e){let t=tC.resolve(e);for(;;){if(iE(tC.join(t,iw)))return t;let e=tC.dirname(t);if(e===t)return;t=e}}function iC(e){try{return tQ.lstatSync(e),!0}catch{return!1}}function iI(e,t,n,r){let o;if(!t.reader&&iE(t.sourcePath)){var i;let n,o=tQ.statSync(t.sourcePath);r$(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":o.size,"Content-Type":r}),i=t.sourcePath,(n=tQ.createReadStream(i)).once("error",()=>e.destroy()),n.pipe(e);return}try{o=t.reader?.()}catch{o=void 0}void 0===o?rR(e,404,`${n} not found`):(r$(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(o),"Content-Type":r}),e.end(o))}function iP(e,t){return function(e){let t,n;if(!e)return{layout:"missing",entries:[]};let r=tC.resolve(e);try{t=tQ.lstatSync(r)}catch(e){if("ENOENT"===e.code)return{directory:r,layout:"missing",entries:[]};return{directory:r,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${r}: ${e.message}`}}if(t.isSymbolicLink()||!t.isDirectory())return{directory:r,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${r}`};try{var o;let e;o=r,e=[],function t(n){for(let r of tQ.readdirSync(n,{withFileTypes:!0})){if(r.isSymbolicLink())continue;let i=tC.join(n,r.name);r.isDirectory()?t(i):r.isFile()&&"SKILL.md"===r.name&&e.push(function(e,t){let n=tC.relative(e,t).split(tC.sep).join("/");return{content:tQ.readFileSync(t,"utf8"),relativePath:n}}(o,i))}}(o),n=e}catch(e){return{directory:r,layout:"invalid",entries:[],error:`skill directory is not readable: ${r}: ${e.message}`}}return n.sort(ib),n.length>0?{directory:r,layout:"resolved",entries:n}:{directory:r,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;if(tC.isAbsolute(t))return t;let n=e?iT(e):void 0,r=[e,n,process.cwd()].map(e=>tC.resolve(e??process.cwd(),t));return[...new Set(r)].find(iC)??r[0]}if(!e)return;let n=iT(e);return[...new Set([n?tC.join(n,iS):void 0,tC.join(e,iS),tC.join(process.cwd(),iS)].filter(Boolean))].find(iC)}(e,t))}class iO{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(e){var t,n,r;this.appDirectory=e.appDirectory,this.manifestPath=e.manifestPath?ix(e.manifestPath,e.appDirectory):e.manifestSourcePath??(e.manifestReader?void 0:function(e){if(!e)return;let t=iT(e);return[...new Set([t?tC.join(t,iw):void 0,tC.join(process.cwd(),iw)].filter(Boolean))].find(iE)}(e.appDirectory)),this.businessTemplatesPath=(t=this.manifestPath,n=e.businessTemplatesPath,r=e.appDirectory,n?ix(n,r):t?ix(tC.join(tC.dirname(t),"business-templates.yaml"),r):void 0),this.manifestReader=e.manifestReader,this.eventsConfigReader=e.eventsConfigReader,this.toolsConfigReader=e.toolsConfigReader,this.eventsConfigSource={reader:e.eventsConfigReader,sourcePath:e.eventsConfigSourcePath},this.skillsDirectory=e.skillsDirectory;let o=iP(e.appDirectory,this.skillsDirectory);if(e.skillsDirectory&&"resolved"!==o.layout)throw Error(o.error??`Simulator skills directory contains no runtime Skill: ${e.skillsDirectory}`);this.toolsConfigSource={reader:e.toolsConfigReader,sourcePath:e.toolsConfigSourcePath},this.manifestSource={reader:e.manifestReader,sourcePath:e.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(e){let t=new iO(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=iP(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,n=iA(this.businessTemplatesPath,this.appDirectory),r=iA(this.eventsConfigSource.sourcePath,this.appDirectory),o=iA(this.toolsConfigSource.sourcePath,this.appDirectory),i=iA(this.manifestSource.sourcePath,this.appDirectory),a=iA(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:iv,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...r?{eventsConfigRelativePath:r}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:i_,...o?{toolsConfigRelativePath:o}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...i?{simulatorManifestRelativePath:i}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...n?{simulatorBusinessTemplatesRelativePath:n}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...a?{simulatorSkillsDirectoryRelativePath:a}:{}}:{}}}getRequestRoutes(){return[{match:iv,handle:({response:e})=>iI(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:i_,handle:({response:e})=>iI(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>iI(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=iP(this.appDirectory,this.skillsDirectory)).layout?rR(e,404,"Simulator skills directory not found"):"invalid"===t.layout?rR(e,422,t.error??"Invalid simulator Skill layout"):rN(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}let iD=f("node:stream"),ik="/app_developer/api",i$=`${ik}/simulator/images/upload`,iR=new Set([`${ik}/simulator/chat`,i$,`${ik}/simulator/tool/report`]),iN={"Access-Control-Expose-Headers":rC};async function iL(e,t,n,r){if(!iR.has(n.pathname))return void rR(t,404,"未找到模拟器接口",iN);let o=r.targetOrigin??en,i=new URL(`${n.pathname}${n.search}`,o),a=rH(e,t);try{var s;let o=e.method??"GET",l=process.hrtime.bigint(),p=function(e,t,n){return Object.fromEntries(Object.entries(rO(e.headers,t,{...ea(),...n?{[rT]:n}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,i,r.getSandboxSessionId?.()),d=await iM(e,t,n,o),c=r.targetOrigin?await fetch(i,{body:d,headers:p,method:o,signal:a}):await eH({internal:!0,path:`${n.pathname}${n.search}`,method:o,body:d,headers:p,signal:a});if(function(e,t,n,r,o,i){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-r)/1e6;rv.request({method:e,url:`${t.pathname}${t.search}`,statusCode:n,durationMs:a,headers:o,logId:i})}(o,n,c.status,l,p,c.headers.get(rC)??void 0),t.destroyed||t.writableEnded)return void c.body?.cancel().catch(()=>void 0);await ij({method:o,requestBody:(s=d)instanceof Uint8Array?`(binary, ${s.byteLength} bytes)`:s,requestHeaders:p,requestUrl:n,response:t,upstreamResponse:c})}catch(e){if(t.destroyed||t.writableEnded||a.aborted)return;rR(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,iN)}}async function iM(e,t,n,r){if("GET"!==r&&"HEAD"!==r)return n.pathname===i$?await rL(e,t,0xb00000):await rM(e,t,0xb00000)}async function ij({method:e,requestBody:t,requestHeaders:n,requestUrl:r,response:o,upstreamResponse:i}){var a,s;if(r$(o,iN),o.writeHead(i.status,rk(i.headers,[rC])),a=r,s=i,a.pathname===`${ik}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await iB({method:e,requestBody:t,requestHeaders:n,requestUrl:r,response:o,upstreamResponse:i});if("applet0930"!==process.env.DEBUG)return i.body?void await (0,g.pipeline)(iD.Readable.fromWeb(i.body),o):void o.end();let l=await rj(i);rF({method:e,requestBody:t,requestHeaders:n,responseBody:l,responseHeaders:i.headers,statusCode:i.status,targetUrl:r}),o.end(l)}async function iB({method:e,requestBody:t,requestHeaders:n,requestUrl:r,response:o,upstreamResponse:i}){if(!i.body){rF({method:e,requestBody:t,requestHeaders:n,responseBody:"",responseHeaders:i.headers,statusCode:i.status,targetUrl:r}),o.end();return}let a=iD.Readable.fromWeb(i.body);if("applet0930"!==process.env.DEBUG)return void await (0,g.pipeline)(a,o);rF({method:e,requestBody:t,requestHeaders:n,responseBody:"(event stream)",responseHeaders:i.headers,statusCode:i.status,targetUrl:r});let s=new iD.Transform({transform(e,t,n){let o;try{o=String(e).split("\n\n").filter(Boolean)}catch(t){return rv.error(`failed to decode event stream chunk: ${t?.toString()}`),n(null,e)}for(let e of o)rv.info(`Event from ${r.pathname}${r.search}
34
- ${e}`);n(null,e)}});await (0,g.pipeline)(a,s,o)}async function iU(e,t){if("POST"!==e.method)return void rN(t,405,{message:"Method Not Allowed"});let n=rH(e,t);try{var r,o;let i,a,s,l=JSON.parse(await rM(e,t,0xa00000)),p=rP(l.url),d=(l.method??"GET").toUpperCase(),c=(r=l.header,a=new Headers(r??{"content-type":"application/json"}),["connection","content-length","host","origin","referer"].forEach(e=>a.delete(e)),a),u=await fetch(p,{signal:n,body:"GET"!==d&&"HEAD"!==d?function(e,t){let n=e.data;if(null==n)return;if("base64"===e.dataEncoding&&"string"==typeof n){var r;let e;return e=new ArrayBuffer((r=Buffer.from(n,"base64")).byteLength),new Uint8Array(e).set(r),e}if("string"==typeof n)return n;let o=t.get("content-type")?.toLowerCase()??"";if(o.includes("application/x-www-form-urlencoded")&&"object"==typeof n){let e=new URLSearchParams;return Object.entries(n).forEach(([t,n])=>{e.set(t,String(n))}),e.toString()}return o.includes("application/json")||"object"==typeof n?JSON.stringify(n):String(n)}(l,c):void 0,headers:c,method:d}),m="arraybuffer"===l.dataType||"arraybuffer"===l.responseType;if(m)i=Buffer.from(await u.arrayBuffer()).toString("base64");else{let e=await u.text();i="string"===l.dataType||0===e.length?e:JSON.parse(e)}rN(t,200,{data:i,dataEncoding:m?"base64":void 0,header:(o=u.headers,s={},o.forEach((e,t)=>{s[t]=e}),s),statusCode:u.status})}catch(e){if(n.aborted||t.destroyed)return;rN(t,500,{message:e instanceof Error?e.message:String(e)})}}let iF=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),iH="/__web_artifacts",iW="/wsd";function iV(e,t,n,r,o={}){r$(t,o.headers),iF(e,r,{root:n}).once("error",r=>{if(404===r.statusCode&&o.fallbackPath)return void iV(e,t,n,o.fallbackPath,{headers:o.headers});if(t.headersSent)return void t.destroy(r);let i=r.statusCode??500;rR(t,i,rw.STATUS_CODES[i]??"Internal Server Error")}).pipe(t)}let iG="/__webview",iq=`${iG}/client.js`,iJ=`${iG}/page`,iK=`${iG}/runtime`,iz=`${iG}/sw.js`,iY="x-doubao-web-view-target",iX="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",iZ=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"),f.b),iQ=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),i0=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.3.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._f1ff5025b08d10e5d2b82ef6fc84d557/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function i1(e,t,n,r=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void rR(t,405,"Method Not Allowed");let o=tQ.readFileSync(n,"utf8");r$(t,{"Cross-Origin-Resource-Policy":"cross-origin"}),t.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(o),"content-type":"text/javascript; charset=utf-8",...r?{"service-worker-allowed":"/"}:{}}),t.end("HEAD"===e.method?void 0:o)}function i2(e,t){let n=e.searchParams.get("parentOrigin")??t[0];if(!t.includes(n))throw Error("Invalid WebView parent origin");return n}async function i3(e,t,n,r){if("GET"!==e.method&&"HEAD"!==e.method)return void rR(t,405,"Method Not Allowed");let o=rH(e,t);try{let i=i2(n,r),a=rP(n.searchParams.get("url")??void 0),s=await fetch(a,{signal:o,headers:{"user-agent":iX,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),l=s.url?new URL(s.url):a;l.hash=a.hash;let p=s.headers.get("content-type")??"",d=rk(s.headers);if(d["cache-control"]="no-cache",d["cross-origin-resource-policy"]="cross-origin",d["x-doubao-web-view-parent-origin"]=i,"HEAD"===e.method||!p.includes("text/html")){let n="HEAD"===e.method?void 0:Buffer.from(await s.arrayBuffer());r$(t),t.writeHead(s.status,{...d,[iY]:l.toString(),...n?{"content-length":n.byteLength}:{}}),t.end(n);return}let c=function(e,t,n){let r=new URLSearchParams({mobileUserAgent:iX,originalPath:`${t.pathname}${t.search}${t.hash}`,parentOrigin:n}).toString().replaceAll("&","&amp;"),o=`<script src="${iq}?${r}"></script>`,i=/<head[^>]*>/i.exec(e);if(i){let t=i.index+i[0].length;return`${e.slice(0,t)}${o}${e.slice(t)}`}return`${o}${e}`}(await s.text(),l,i);r$(t),t.writeHead(s.status,{...d,[iY]:l.toString(),"content-length":Buffer.byteLength(c)}),t.end(c)}catch(e){if(o.aborted||t.destroyed)return;rR(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}async function i4(e){let t=new URL(e).toString();try{await S(t)}catch(e){rv.error("打开 Web 模拟器失败",{error:e}),rv.info("请手动打开 Web 模拟器(本地)",{url:t})}}async function i5(e,t){await new Promise((n,r)=>{let o=t=>{e.off("listening",i),r(t)},i=()=>{e.off("error",o),n()};e.once("error",o),e.once("listening",i),e.listen(t,"127.0.0.1")})}async function i9(e){var t;let n=await I(9e3),r=rw.createServer(rG((t=[`http://127.0.0.1:${n}`,`http://localhost:${n}`],[{match:`${iG}/bootstrap`,handle:({request:e,response:n,url:r})=>{if("GET"!==e.method&&"HEAD"!==e.method)return void rR(n,405,"Method Not Allowed");try{rP(r.searchParams.get("url")??void 0),i2(r,t)}catch{rR(n,400,"Invalid WebView URL");return}r$(n,{"Cross-Origin-Resource-Policy":"cross-origin"}),n.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),n.end("HEAD"===e.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${iG}/bootstrap.js`,handle:({request:e,response:t})=>i1(e,t,iZ)},{match:iz,handle:({request:e,response:t})=>i1(e,t,i0,!0)},{match:iq,handle:({request:e,response:t})=>i1(e,t,iQ)},{match:iK,handle:({request:e,response:t,url:n})=>(function(e,t,n){let r;try{r=rP(n.searchParams.get("url")??void 0)}catch(e){rR(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let o=rO(e.headers,r,{"user-agent":iX});for(let e of Object.keys(o))e.startsWith("sec-fetch-")&&delete o[e];rW(e,t,{createResponseHeaders:e=>{let t=rD(e),n=Array.isArray(e.location)?e.location[0]:e.location;if(n&&URL.canParse(n,r)){let e=new URL(n,r);t.location=`${iK}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:o,targetUrl:r})})(e,t,n)},{match:iJ,handle:({request:e,response:n,url:r})=>i3(e,n,r,t)}]),({response:e})=>{rR(e,404,"WebView resource not found")}));await i5(r,0);let o=r.address(),i=`http://127.0.0.1:${o.port}`,a=rw.createServer(function({webViewOrigin:e,artifactOrigin:t,debugScenes:n,debuggerProtocol:r,distPath:o,getWidgetViewDataTemplates:i,mcpEndpoint:a,mcpHeaders:s,physicalDeviceDebugGateway:l,sandboxRuntime:p,simulatorAssets:d,simulatorTargetOrigin:c}){var u;let m={routes:[{match:e=>e.pathname.startsWith(iH),handle:({request:e,response:n,url:r})=>{let o,i;return o=r.pathname.replace(iH,"")||"/",i=new URL(`${o}${r.search}`,t),void rW(e,n,{createResponseHeaders:e=>({...rD(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:rO(e.headers,i),targetUrl:i})}},{match:e=>e.pathname===iW||e.pathname.startsWith(`${iW}/`),handle:({request:e,response:t,url:n})=>{let r;!(r=n.pathname.slice(`${iW}/`.length))||r!==tC.basename(r)?rR(t,404,"Not found"):iV(e,t,tC.join(o,"wsd"),r,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>iU(e,t)},{match:"/__webview/page",handle:({request:t,response:n,url:r})=>{"GET"!==t.method&&"HEAD"!==t.method?rR(n,405,"Method Not Allowed"):(r$(n),n.writeHead(302,{"cache-control":"no-store",location:`${e}/__webview/bootstrap${r.search}`}),n.end())}},{match:"/__webview/sw.js",handle:({response:e})=>{r$(e),e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),e.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
162
+ ${nq(Object.fromEntries(i))}
163
+ Response body: ${nJ(n)}`)}function nK(e,t){let r=new AbortController,n=()=>r.abort();return e.once("aborted",n),t.once("close",()=>{e.off("aborted",n),t.writableEnded||n()}),(e.aborted||t.destroyed)&&n(),r.signal}function nY(e,t,r){let n,i=("https:"===r.targetUrl.protocol?_:nO).request(r.targetUrl,{headers:r.requestHeaders,method:e.method},e=>{(n=e,t.destroyed||t.writableEnded)?e.destroy():(nB(t,r.commonHeaders),t.writeHead(e.statusCode??500,r.createResponseHeaders?.(e.headers)??nM(e.headers)),e.pipe(t))}),a=()=>{i.destroy(),n?.destroy()};i.once("error",e=>{if(!t.destroyed&&!t.writableEnded){if(t.headersSent)return void t.destroy(e);nF(t,502,`${r.errorMessage}: ${e.message}`,r.commonHeaders)}}),e.once("aborted",()=>{a()}),t.once("close",()=>{t.writableEnded||a()}),e.pipe(i)}async function nX(e,t,r){let n=t.find(({match:t})=>"string"==typeof t?e.url.pathname===t:t(e.url));await (n?.handle??r)(e)}function nZ(e,t){return(r,n)=>{let i=nL(r);i?nX({request:r,response:n,url:i},e,t).catch(e=>(function(e,t){if(nI.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);nF(e,500,"Internal server error")}})(n,e)):nF(n,400,"Bad request")}}let nQ=f("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),n0={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},n1={"http:":"80","https:":"443"},n2=new Map;function n3(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function n4(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function n5(e,t={}){let r=function(e){var t,r;let n="string"==typeof e?new URL(e):e;if(function(e){let t=n7(["NO_PROXY","no_proxy"]);if(!t)return!1;let r=n6(e.hostname),n=e.port||n1[e.protocol]||"";for(let e of t.split(",")){let t=function(e){let t=e.trim().toLowerCase();if(!t)return{host:""};if((t=t.replace(/^[a-z][a-z\d+.-]*:\/\//,"").split("/")[0]).startsWith("[")){let e=t.indexOf("]");if(-1!==e)return{host:n6(t.slice(0,e+1)),port:":"===t[e+1]?t.slice(e+2):void 0}}let r=t.indexOf(":")===t.lastIndexOf(":")?t.match(/:(\d+)$/):void 0;return{host:n6(r?t.slice(0,-r[0].length):t),port:r?.[1]}}(e);if(t.host&&(!t.port||t.port===n)){if("*"===t.host)return!0;if(t.host.startsWith("*.")){let e=t.host.slice(1);if(r.endsWith(e))return!0;continue}if(t.host.startsWith(".")){if(r.endsWith(t.host))return!0;continue}if(r===t.host)return!0}}return!1}(n))return;let i="https:"===(t=n.protocol)?n7(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?n7(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!i)return;let a=(r=i,/^[a-z][a-z\d+.-]*:\/\//i.test(r)?r:`http://${r}`),o=n2.get(a);return o||(o=new nQ.kT(a),n2.set(a,o)),o}(e),n=r?{...t,dispatcher:r}:t;return await fetch(e,n)}async function n9({internal:e,domainId:t,path:r,query:n,method:i="GET",body:a,headers:o,signal:s,auth:l=!0}){let c={method:i,body:a,headers:{...n3(),...o}};s&&(c.signal=s);let p=function({internal:e,domainId:t,path:r,query:n}){let i=r.startsWith("/")?r:`/${r}`,a=new URLSearchParams;for(let[e,t]of Object.entries(n||{}))null!=t&&a.append(e,t.toString());let o=a.toString(),s=o?`${i.includes("?")?"&":"?"}${o}`:"",l=n4(i)?es:t?n0[t]:e?n0["sso-internal"]:n0["sms-external"];return`https://${l}${i}${s}`}({internal:e,domainId:t,path:r,query:n}),d=new Headers(c.headers),u=d.has("Cookie");if(!l||!n4(r)||d.has("Authorization")||d.has("X-Developer-Open-Build-Token"))return await n5(p,c);let m=new URL(p).origin,h=j(n5,{baseUrl:m,allowedOrigins:[m]});try{return await h(p,c)}catch(e){if(!(e instanceof q||e instanceof C))throw e;if(u)return await n5(p,c);throw Error(e instanceof C?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function n8(e){let t=await n9(e),r=t.headers.get("x-tt-logid")||"";if(!t.ok){let e=await t.text();throw Error(JSON.stringify({code:t.status,message:"HTTP 请求失败",data:e,log_id:r}))}let n=await t.json();if(0!==n.code)throw Error(JSON.stringify({...n,log_id:r}));return{...n,log_id:r}}function n7(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function n6(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let ie="/__mcp_proxy",it=f("../../../node_modules/.pnpm/ws@8.21.2/node_modules/ws/lib/websocket-server.js");function ir(e,t,r){e.readyState!==ey.OPEN||e.bufferedAmount>0xa00000?e.terminate():e.send(JSON.stringify({type:t,data:r}))}let ii=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 ia extends Error{code;constructor(e,t){super(t),this.name="DebuggerControlError",this.code=e}}function io(e){return"render_page"===e||"render_widget"===e}function is(e){return"number"==typeof e&&Number.isFinite(e)}function il(e){return"number"==typeof e&&Number.isInteger(e)&&e>=1&&e<=9999}function ic(e){if("submit_chat_query"===e.type)return 12e4;if("execute_sandbox_tool_call"===e.type){let t=e.toolCall?.tool_call?.deadline_ms;if("number"==typeof t&&Number.isFinite(t))return Math.max(1,t-Date.now()+1e3)}return 15e3}class ip{clients=new Map;lastSnapshotAtByClientId=new Map;snapshotStore;snapshotsByClientId=new Map;nextCommandId=0;constructor(e){this.snapshotStore=e}registerClient(e,t){let r=this.getSnapshotStore(e),n=this.clients.get(e);n&&this.disconnectClient(n,"Debugger control connection was replaced");let i={clientId:e,lastSnapshotAtMs:this.lastSnapshotAtByClientId.get(e)??0,parallelJobs:new Map,queue:[],socket:t};this.clients.set(e,i),this.snapshotsByClientId.set(e,r),t.once("close",()=>{this.disconnectClient(i,"Debugger control connection was closed",!1)})}getSnapshotStore(e){return this.snapshotsByClientId.get(e)??{}}noteSnapshot(e){if(!e)return;let t=this.getSnapshotStore(e);Object.assign(t,this.snapshotStore),this.snapshotsByClientId.set(e,t);let r=Date.now();this.lastSnapshotAtByClientId.set(e,r);let n=this.clients.get(e);n&&(n.lastSnapshotAtMs=r)}execute(e,t,r){let n=void 0!==r?this.clients.get(r):"execute_sandbox_tool_call"===e?this.getToolCallClient():this.getActiveClient();if(!n||n.socket.readyState!==ey.OPEN)return Promise.reject(new ia("DEBUGGER_NOT_CONNECTED","execute_sandbox_tool_call"===e?"No Web SDK debugger is connected":"No Web SDK debugger with a stored snapshot is connected"));let i=`control-${Date.now()}-${++this.nextCommandId}`;return new Promise((r,a)=>{let o={command:{...t,commandId:i,type:e},reject:a,resolve:r};"execute_sandbox_tool_call"===e?this.startParallelJob(n,o):(n.queue.push(o),this.flushClient(n))})}handleResult(e){var t,r;let n,i=e.clientId?.trim(),a=e.commandId?.trim(),o=i?this.clients.get(i):void 0,s=a?o?.parallelJobs.get(a):void 0,l=s??o?.activeJob;if(!o||!l||l.command.commandId!==a)return!1;if(!0===e.ok&&io(l.command.type)&&(t=e.snapshot,t.snapshot.command_id===a&&t.snapshot.runtime_snapshot)?(this.snapshotStore.snapshot=e.snapshot,this.snapshotStore.updatedAtMs=Date.now(),this.noteSnapshot(i),n={target:e.target}):!0===e.ok&&!io(l.command.type)&&(n=function(e,t){if("set_viewport"===e)return il(t.width)&&il(t.height)?t:void 0;if("submit_chat_query"===e)return!0===t.completed&&t.query?.trim()&&t.requestId?.trim()?t:void 0;if("take_snapshot"===e){let e=t.runtimeSnapshot;return e?.target?{runtimeSnapshot:e}:void 0}if("execute_sandbox_tool_call"===e)return!0===t.reported&&t.request_id?.trim()&&t.tool_call_id?.trim()?t:void 0;if("take_screenshot"===e||t.uid?.trim()){if("get_computed_style"===e){if(!Array.isArray(t.computedStyle)||!t.computedStyle.every(e=>!!e.name?.trim()&&"string"==typeof e.value))return;return t}if("get_element_rect"===e)return[t.x,t.y,t.width,t.height].every(is)?t:void 0;if("scroll_to"===e)return[t.x,t.y,t.maxX,t.maxY,t.viewportWidth,t.viewportHeight].every(e=>is(e)&&e>=0)&&t.x<=t.maxX&&t.y<=t.maxY?t:void 0;if("take_screenshot"===e){let e="png"===t.format?"image/png":"jpeg"===t.format?"image/jpeg":"webp"===t.format?"image/webp":void 0;return"string"==typeof t.data&&t.data.length>0&&t.mimeType===e&&is(t.width)&&is(t.height)&&(void 0===t.uid||t.uid?.trim())?t:void 0}}}(l.command.type,e.result),"take_snapshot"===l.command.type&&n&&"runtimeSnapshot"in n&&this.storeRuntimeSnapshot(o.clientId,n.runtimeSnapshot)),n)l.resolve(n);else{let t=e.error??{},n=t.code?.trim(),i=n&&ii.has(n)?n:void 0;l.reject(new ia(i??(io(r=l.command.type)?"RENDER_FAILED":"set_viewport"===r?"VIEWPORT_FAILED":"scroll_to"===r?"SCROLL_FAILED":"submit_chat_query"===r?"CHAT_SUBMIT_FAILED":"take_snapshot"===r?"SNAPSHOT_FAILED":"execute_sandbox_tool_call"===r?"TOOL_CALL_FAILED":"take_screenshot"===r?"SCREENSHOT_FAILED":"INSPECTION_FAILED"),t.message?.trim()||"Debugger control command failed"))}return l.timeout&&clearTimeout(l.timeout),s?o.parallelJobs.delete(a):o.activeJob=void 0,this.flushClient(o),!0}getActiveClient(){return[...this.clients.values()].filter(e=>e.socket.readyState===ey.OPEN&&e.lastSnapshotAtMs>0).sort((e,t)=>t.lastSnapshotAtMs-e.lastSnapshotAtMs)[0]}storeRuntimeSnapshot(e,t){let r=this.getSnapshotStore(e).snapshot,n=r?.snapshot;if(!r||!n||n.client_id!==e)return;let i=r.debug_snapshot,{root:a,...o}=t,s=Date.now();this.snapshotStore.snapshot={...r,stored_at:new Date(s).toISOString(),stored_at_ms:s,snapshot:{...n,runtime_snapshot:t},...i?{debug_snapshot:{...i,runtime_snapshot:o}}:{}},this.snapshotStore.updatedAtMs=s,this.noteSnapshot(e)}getConnectedClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===ey.OPEN)}getToolCallClient(){return[...this.clients.values()].reverse().find(e=>e.socket.readyState===ey.OPEN&&e.activeJob?.command.type==="submit_chat_query")??this.getActiveClient()??this.getConnectedClient()}startParallelJob(e,t){let r=t.command.commandId;e.parallelJobs.set(r,t),t.timeout=setTimeout(()=>{e.parallelJobs.delete(r)&&t.reject(new ia("TOOL_CALL_FAILED","Debugger control command timed out"))},ic(t.command));try{ir(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}flushClient(e){if(e.activeJob||e.socket.readyState!==ey.OPEN)return;let t=e.queue.shift();if(t){e.activeJob=t,t.timeout=setTimeout(()=>{if(e.activeJob===t){if("submit_chat_query"===t.command.type){t.timeout=void 0,t.reject(new ia("CHAT_TIMEOUT","Debugger control command timed out"));try{ir(e.socket,"control",{commandId:t.command.commandId,type:"cancel_chat_query"})}catch{this.disconnectClient(e,"Debugger control connection was closed");return}t.timeout=setTimeout(()=>{e.activeJob===t&&this.disconnectClient(e,"Debugger chat cancellation was not acknowledged")},5e3);return}e.activeJob=void 0,t.reject(new ia(io(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e)}},ic(t.command));try{ir(e.socket,"control",t.command)}catch{this.disconnectClient(e,"Debugger control connection was closed")}}}disconnectClient(e,t,r=!0){if(this.clients.get(e.clientId)!==e)return;this.clients.delete(e.clientId),this.snapshotsByClientId.delete(e.clientId);let n=new ia("DEBUGGER_DISCONNECTED",t);for(let t of(e.activeJob?.timeout&&clearTimeout(e.activeJob.timeout),e.activeJob?.reject(n),e.activeJob=void 0,e.parallelJobs.values()))t.timeout&&clearTimeout(t.timeout),t.reject(n);for(let t of(e.parallelJobs.clear(),e.queue.splice(0)))t.reject(n);r&&e.socket.readyState===ey.OPEN&&e.socket.close()}}let id=["page","widget","app"],iu=["log","info","warn","error","debug","eval"],im=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function ih(e,t){let r=t.pageIdx??0,n=t.pageSize??50,i=r*n,a=e.slice(i,i+n);return{pageIdx:r,pageSize:n,total:e.length,hasMore:i+a.length<e.length,items:a}}function ig(e){if(!e.snapshot)return{stored:!1,updatedAtMs:e.updatedAtMs};let{debug_snapshot:t,...r}=e.snapshot;return{stored:!0,storedAt:r.stored_at,updatedAtMs:r.stored_at_ms??e.updatedAtMs,snapshot:r.snapshot}}function iy(e){return e.value??e.unserializableValue??e.description??e.type??""}function ib(e,t){var r,n;let i;return(r=e,"all"===(n=t)?id:"page"===n||"widget"===n||"app"===n?[n]:(i=r.context,i?.page_id||i?.page_path?["page","app"]:i?.widget_id?["widget"]:id)).flatMap(t=>{let r,n=(r=e.runtime_console?.[t],{entries:r?.entries??[],updatedAtMs:r?.updated_at_ms??r?.updatedAtMs});return n.entries.map((e,r)=>{var i;let a,o,s,l;return i=n.updatedAtMs,a=e.url??e.location?.url,o=e.lineNumber??e.location?.lineNumber,s=e.columnNumber??e.location?.columnNumber,l=e.id??String(r),{msgid:`${t}:${l}`,target:t,level:e.level??"log",source:e.source??"",timestamp:e.timestamp??0,text:e.message??(e.args??[]).map(iy).filter(Boolean).join(" "),...a?{url:a}:{},...void 0===o?{}:{lineNumber:o},...void 0===s?{}:{columnNumber:s},...void 0===i?{}:{updatedAtMs:i},entry:e}})})}function i_(e,t){return{id:e.toolCallId??e.id??`tool-call:${t}`,requestId:e.requestId??e.request_id??"",toolCallId:e.toolCallId??e.id??"",toolName:e.toolName??e.name??"",serverId:e.serverId??e.server_id??"",appKey:e.appKey??e.app_key??"",status:e.status??"",createdAtMs:e.createdAtMs??e.created_at_ms??0,updatedAtMs:e.updatedAtMs??e.updated_at_ms??0,requiresUserApproval:!0===e.requiresUserApproval,isMiniApp:!0===e.isMiniApp,message:e.message??"",resultSummary:e.resultSummary??e.structuredResultSummary}}function iv(e,t){if("page"===t){let{pageId:t,path:r}=e;if(!t||!r)return;return{pageId:t,path:r,name:e.name??t,isHome:!0===e.isHome}}let{widgetId:r}=e;if(r)return{widgetId:r,name:e.name??r}}let iE={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},iw={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},iS={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function ix(e,t={}){return{structuredContent:e,content:t.image?[{type:"image",...t.image}]:[{type:"text",text:t.text??JSON.stringify(e,null,2)}],...t.isError?{isError:!0}:{}}}async function iA(e,t={}){try{return await e()}catch(e){return function(e,t={}){let r=e instanceof ia?e:new ia("INSPECTION_FAILED",String(e));return ix({...t,error:{code:r.code,message:r.message}},{isError:!0})}(e,t)}}function iT(e,t,r,n){let i=N(r.inputSchema);e.registerTool(t,{...r,inputSchema:i},n)}let iI="/__wsd_mcp";async function iO({request:e,response:t,url:r},n,i){if("OPTIONS"===e.method){nB(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void nF(t,405,"Method not allowed");let a=r.searchParams.get("clientId")??void 0,o=void 0===a?n:i.getSnapshotStore(a),s=L(()=>{let e,t;return e=new X({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let r=ig(o);if(!r.stored)return ix(r);let n=ih((t=r.snapshot,[{source:"simulator",events:t.simulator?.trace_events??[]},{source:"widget_runtime",events:t.widget_runtime_trace_events??[]},{source:"page_runtime",events:t.page_runtime_trace_events??[]}].flatMap(({source:e,events:t})=>t.map((t,r)=>{let n;return n=t.payload??{},{source:e,id:t.id??`${e}:${r}`,timestamp:t.timestamp??0,category:n.category??t.display?.category??"",event:n.event??t.event??"",requestId:n.request_id??n.requestId??n.trace_id??n.trace?.trace_id??"",payload:t.payload??t}}))).filter(t=>{let r,n,i;return r=e.category??[],n=e.event?.trim(),i=e.requestId?.trim(),(0===r.length||r.includes(t.category))&&(!n||t.event===n)&&(!i||t.requestId===i)}),e);return ix({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,events:n.items})},iT(e,"list_chat_messages",{annotations:iE,description:"List conversation messages in chronological order from the latest debugger snapshot, including message content and generation status.",inputSchema:{}},async()=>{let e=ig(o);if(!e.stored)return ix(e);let t=o.snapshot?.debug_snapshot?.simulator??e.snapshot.simulator;return ix({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,streamStatus:t?.stream_status,messages:t?.messages??[]})}),iT(e,"list_console_messages",{annotations:iE,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:ei(I(iu)).optional(),pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),query:Q().optional(),target:I(["current","page","widget","app","all"]).optional()}},async e=>{let t=ig(o);if(!t.stored)return ix(t);let r=ih(ib(t.snapshot,e.target).filter(t=>{let r,n;return r=e.levels??[],n=e.query?.trim().toLowerCase(),(!(r.length>0)||!!r.includes(t.level))&&(!n||[t.text,t.url,t.source,t.target].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(n)))}),e);return ix({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,total:r.total,pageIdx:r.pageIdx,pageSize:r.pageSize,hasMore:r.hasMore,messages:r.items.map(({entry:e,...t})=>t)})}),iT(e,"get_console_message",{annotations:iE,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:Q()}},async e=>{let t=ig(o);if(!t.stored)return ix(t);let r=ib(t.snapshot,"all").find(t=>t.msgid===e.msgid);return ix({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!r,...r?{message:r}:{msgid:e.msgid}})}),iT(e,"get_log_snapshot",{annotations:iE,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=ig(o);return e.stored?ix({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):ix(e)}),iT(e,"list_render_targets",{annotations:iE,description:"List Page and Widget targets that can be rendered by the Web SDK debugger.",inputSchema:{type:I(["all","page","widget"]).optional()}},async e=>{var t,r;let n,i=ig(o);return i.stored?ix({stored:!0,storedAt:i.storedAt,updatedAtMs:i.updatedAtMs,...(t=i.snapshot,r=e.type??"all",n=t.render_targets??{},{pages:"widget"===r?[]:(n.pages??[]).map(e=>iv(e,"page")).filter(Boolean),widgets:"page"===r?[]:(n.widgets??[]).map(e=>iv(e,"widget")).filter(Boolean),...n.currentTarget?{currentTarget:n.currentTarget}:{}})}):ix(i)}),iT(e,"take_snapshot",{annotations:iE,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:I(["current","page","widget"]).optional(),verbose:U().optional()}},e=>iA(async()=>{let t=function(e,t){var r,n;let i,a,o,s=e.runtime_snapshot;if(!s?.target)return{available:!1,reason:"NO_RUNTIME_SNAPSHOT"};let l=s.target,c=l.type,p=t.target??"current";if(("page"===p||"widget"===p)&&c!==p)return{available:!1,reason:"TARGET_MISMATCH",requestedTarget:p,currentTarget:l};if(!s.root)return{available:!1,reason:"NO_RENDERED_TARGET",currentTarget:l};let d=s.selectedUid,u=(r=s.root,n=!0===t.verbose,i=[],a=0,(o=(e,t)=>{var r,s;let{name:l,uid:c}=e;if(!c||!l)return;a+=1;let p=" ".repeat(t);if("text"===e.type)return void i.push(`${p}uid=${c} text ${JSON.stringify(e.text??"")}`);let u=[`uid=${c}`,l],{keyboardFocusable:m=!1,name:h,role:f}=e.accessibility??{};for(let t of(f&&(n||"generic"!==f)&&u.push(`role=${JSON.stringify(f)}`),h&&u.push(`name=${JSON.stringify(h)}`),(n||m)&&u.push(`focusable=${String(m)}`),(e.attributes??[]).map(e=>({name:e.name,value:e.value})).filter(e=>e.name&&(n||im.has(e.name)||e.name.startsWith("aria-")))))u.push((r=t.name,(s=t.value)?`${r}=${JSON.stringify(s)}`:r));for(let r of(c===d&&u.push("[selected]"),i.push(`${p}${u.join(" ")}`),e.children??[]))o(r,t+1)})(r,0),{actualNodeCount:a,text:i.join("\n")});return{available:!0,target:l,nodeCount:s.nodeCount??u.actualNodeCount,...d?{selectedUid:d}:{},truncated:!0===s.truncated,snapshot:u.text,snapshotUpdatedAtMs:s.updatedAtMs}}({runtime_snapshot:(await i.execute("take_snapshot",{target:e.target??"current"},a)).runtimeSnapshot},e),r=ig(o),n={stored:r.stored,...r.stored?{storedAt:r.storedAt,updatedAtMs:r.updatedAtMs}:{},...t};return ix(n,{text:t.available?t.snapshot:JSON.stringify(n,null,2)})},{available:!1,stored:!1})),iT(e,"get_computed_style",{annotations:iE,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:ei(Q().min(1)).max(100).optional(),uid:Q().min(1)}},({properties:e,uid:t})=>iA(async()=>ix(await i.execute("get_computed_style",{uid:t,...e?{properties:e}:{}},a)))),iT(e,"get_element_rect",{annotations:iE,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:Q().min(1)}},({uid:e})=>iA(async()=>ix(await i.execute("get_element_rect",{uid:e},a)))),iT(e,"take_screenshot",{annotations:iE,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:I(["png","jpeg","webp"]).optional(),quality:O().min(0).max(100).optional(),uid:Q().min(1).optional()}},({format:e="png",quality:t,uid:r})=>iA(async()=>{let n=await i.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...r?{uid:r}:{}},a),{data:o,...s}=n;return ix({captured:!0,...s},{image:{data:o,mimeType:n.mimeType}})},{captured:!1})),iT(e,"scroll_to",{annotations:iS,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:Q().min(1).optional(),x:O().min(0).optional(),y:O().min(0).optional()}},({uid:e,x:t,y:r})=>iA(async()=>ix({scrolled:!0,...await i.execute("scroll_to",{uid:e,x:t,y:r},a)}),{scrolled:!1})),iT(e,"set_viewport",{annotations:iS,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:O().int().min(1).max(9999),width:O().int().min(1).max(9999)}},({height:e,width:t})=>iA(async()=>ix({updated:!0,viewport:await i.execute("set_viewport",{height:e,width:t},a)}),{updated:!1})),iT(e,"render_page",{annotations:iw,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:Q().min(1)}},({url:e})=>iA(async()=>ix({rendered:!0,target:(await i.execute("render_page",{url:e},a)).target}),{rendered:!1})),iT(e,"render_widget",{annotations:iw,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:W(Q(),P()).optional(),widgetId:Q().min(1)}},({structuredContent:e,widgetId:t})=>iA(async()=>ix({rendered:!0,target:(await i.execute("render_widget",{structuredContent:e??{},widgetId:t},a)).target}),{rendered:!1})),iT(e,"submit_chat_query",{annotations:iw,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:Q().trim().min(1)}},({query:e})=>iA(async()=>ix({submitted:!0,...await i.execute("submit_chat_query",{query:e},a)}),{submitted:!1})),iT(e,"list_agent_trace_events",{annotations:iE,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:ei(Q()).optional(),event:Q().optional(),pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),requestId:Q().optional()}},t),iT(e,"list_agent_tool_calls",{annotations:iE,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:O().int().min(0).optional(),pageSize:O().int().min(1).max(200).optional(),query:Q().optional(),requestId:Q().optional(),status:ei(Q()).optional(),toolName:Q().optional()}},async e=>{var t;let r=ig(o);if(!r.stored)return ix(r);let n=ih((t=r.snapshot,(t.simulator?.tool_calls??[]).map(i_)).filter(t=>{let r,n,i,a;return r=e.requestId?.trim(),n=e.toolName?.trim(),i=e.status??[],a=e.query?.trim().toLowerCase(),(!r||t.requestId===r)&&(!n||t.toolName===n)&&(!(i.length>0)||!!i.includes(t.status))&&(!a||[t.toolName,t.serverId,t.appKey,t.status,t.message,"string"==typeof t.resultSummary?t.resultSummary:void 0].filter(e=>"string"==typeof e).some(e=>e.toLowerCase().includes(a)))}),e);return ix({stored:!0,storedAt:r.storedAt,updatedAtMs:r.updatedAtMs,total:n.total,pageIdx:n.pageIdx,pageSize:n.pageSize,hasMore:n.hasMore,toolCalls:n.items})}),e}),l=en(s);try{await l(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):nF(t,500,e instanceof Error?e.message:String(e))}finally{await s.close().catch(()=>void 0)}}let iP="/__web_sdk_debug_scenes",iC="/__web_sdk_widget_view_data_templates",iR={"Cache-Control":"no-cache"};async function i$(e,t){try{let r=await t?.()??{templatesByEntry:{},templatesByWidget:{}};nH(e,200,r,iR)}catch(t){nI.error("加载 Widget viewData 模板失败",{error:t}),nH(e,500,{templatesByEntry:{},templatesByWidget:{}},iR)}}let ik=f("node:crypto"),iN="/__dbx_real_device_debug",iL=`${iN}/state`,iD=`${iN}/start`,ij=`${iN}/cancel`,iM=`${iN}/qr`;class iU{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:iL,startEndpoint:iD,cancelEndpoint:ij,qrEndpoint:iM,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?ik.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(iN),handle:({request:e,response:t,url:r})=>this.serveRequest(e,t,r)}]}async serveRequest(e,t,r){if(!this.validateRequest(e,t))return;let n=this.provider;if(!n)return this.writeError(t,503,"REAL_DEVICE_DEBUG_UNAVAILABLE","Physical device debugging is unavailable");let i=await this.readJsonBody(e,t);if(i)try{if(r.pathname===iL||r.pathname===iD){if(Object.keys(i).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=r.pathname===iL?await n.getState():await n.start();nH(t,200,e);return}if(r.pathname===ij){let e=i.operationId;if("string"!=typeof e||!e||1!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");nH(t,200,await n.cancel(e));return}if(r.pathname===iM){let{operationId:e,kind:r}=i;if("string"!=typeof e||!e||"modern"!==r&&"legacy"!==r||2!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid QR request");let a=await n.getQrImage(e,r);if(!a)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");nB(t),t.writeHead(200,{"Content-Length":a.body.byteLength,"Content-Type":a.contentType}),t.end(a.body);return}return this.writeError(t,404,"NOT_FOUND","Not found")}catch{return this.writeError(t,500,"REAL_DEVICE_DEBUG_FAILED","Physical device debugging failed")}}validateRequest(e,t){var r,n;let i,a,o;if(!function(e){if(!e)return!1;try{let t=new URL(`http://${e}`).hostname.toLowerCase();return"127.0.0.1"===t||"[::1]"===t||"localhost"===t}catch{return!1}}(e.headers.host))return this.writeError(t,403,"FORBIDDEN_HOST","Forbidden host"),!1;let s=e.headers["x-dbx-real-device-token"];if("string"!=typeof s||!this.accessToken||(r=s,n=this.accessToken,a=(i=new TextEncoder).encode(r),o=i.encode(n),!(a.length===o.length&&ik.timingSafeEqual(a,o))))return this.writeError(t,401,"UNAUTHORIZED","Unauthorized"),!1;if("POST"!==e.method)return this.writeError(t,405,"METHOD_NOT_ALLOWED","Method must be POST"),!1;if(!(e.headers["content-type"]?.toLowerCase()??"").startsWith("application/json"))return this.writeError(t,415,"UNSUPPORTED_MEDIA_TYPE","Content-Type must be application/json"),!1;let l=e.headers.origin;return!l||l===`http://${e.headers.host}`||(this.writeError(t,403,"FORBIDDEN_ORIGIN","Forbidden origin"),!1)}async readJsonBody(e,t){let r,n;try{r=await nG(e,t,4096)}catch{return this.writeError(t,413,"PAYLOAD_TOO_LARGE","Request body is too large")}if(!r.trim())return{};try{n=JSON.parse(r)}catch{return this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body")}return!n||"object"!=typeof n||Array.isArray(n)?this.writeError(t,400,"INVALID_REQUEST","Invalid JSON body"):n}writeError(e,t,r,n){e.writableEnded||e.destroyed||nH(e,t,{error:{code:r,message:n}})}}let iB={"Cache-Control":"no-cache"},iF="/app_developer/api/sandbox/",iH=`${iF}session/business_info/update`,iW=new Set([`${iF}resources/notices/pull`,`${iF}resources/tasks/pull`]),iG={"Access-Control-Expose-Headers":nN},iV=new Set;function iq(e,t,r,n,i,a){if(!eS())return!1;let o=`${i[nk]??""} ${e} ${t.pathname}`,s=iW.has(t.pathname);if(s&&r>=500){if(iV.has(o))return!1;iV.add(o)}else s&&r<500&&iV.delete(o);let l=Number(process.hrtime.bigint()-n)/1e6;return nI.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:l,headers:i,logId:a}),!0}function iJ({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:a,targetUrl:o}){nz({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:a,targetUrl:o})}function iz(e,t,r){return r&&!(iW.has(e.pathname)&&t>=500)}function iK(e,t){if(e.pathname!==iH||!t)return t;try{let e=JSON.parse(t);return JSON.stringify({...e,..."csr_pem"in e?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]"})}catch{return JSON.stringify({omitted:"Sandbox 业务信息请求无效"})}}async function iY({method:e,request:t,requestBody:r,requestHeaders:n,response:i,targetUrl:a,usePlatformFetch:o}){let s=process.hrtime.bigint(),l=nK(t,i);try{let t,c=o?await n9({internal:!0,path:`${a.pathname}${a.search}`,method:e,body:r,headers:n,signal:l}):await fetch(a,{body:"GET"===e||"HEAD"===e?void 0:r,headers:n,method:e,signal:l}),p=iq(e,a,c.status,s,n,c.headers.get(nN)??void 0);if(i.destroyed||i.writableEnded)return void c.body?.cancel().catch(()=>void 0);let d=await nV(c);return iz(a,c.status,p)&&iJ({method:e,requestBody:iK(a,r),requestHeaders:n,responseBody:d,responseHeaders:c.headers,statusCode:c.status,targetUrl:a}),i.destroyed||i.writableEnded||(t=nU(c.headers,[nN]),nB(i,iG),i.writeHead(c.status,t),i.end(d)),{body:d,ok:c.ok}}catch(c){if(i.destroyed||i.writableEnded||l.aborted)return;let t=`代理 Sandbox 请求失败:${c instanceof Error?c.message:String(c)}`,o=iq(e,a,502,s,n);iz(a,502,o)&&iJ({method:e,requestBody:iK(a,r),requestHeaders:n,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:a}),nF(i,502,t,iG)}}async function iX(e,t,r={}){let n;if("POST"!==e.method)return void nF(t,405,"不支持的请求方法",iG);try{n=JSON.parse(await nG(e,t,0xa00000))}catch(e){nF(t,400,`Sandbox 代理请求内容无效:${e.message}`,iG);return}let i=function(e,t){if(!e.url)return;let r=new URL(e.url,t);if(!r.pathname.startsWith(iF))return;let n=new URL(`${r.pathname}${r.search}`,t);var i=e.params;if(i)for(let[e,t]of Object.entries(i))null!=t&&n.searchParams.set(e,String(t));return n}(n,r.targetOrigin??ee);if(!i)return void nF(t,404,"未找到 Sandbox endpoint",iG);if(!r.sandboxSessionId)return void nH(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},iG);let a=function(e,t,r,n){if(t.pathname.startsWith(`${iF}session/`)&&t.pathname!==`${iF}session/create`)return JSON.stringify({..."object"==typeof e.data&&null!==e.data?e.data:{},sandbox_session_id:n});if(void 0===e.data)return;if("object"!=typeof e.data||null===e.data||!r)return JSON.stringify(e.data);let i={...e.data};return t.pathname.startsWith(`${iF}jsb/`)&&"app_key"in i&&(i.app_key=r),t.pathname===`${iF}passport/open/auth`&&"client_key"in i&&(i.client_key=r),JSON.stringify(i)}(n,i,r.sandboxAppId,r.sandboxSessionId),o=n.method||"POST",s=function(e,t,r,n,i){let a=Object.fromEntries(Object.entries(nj({...e.headers,...r,...void 0===n?{}:{"content-length":String(Buffer.byteLength(n))},"content-type":"application/json"},t,{...n3(),...i?{[nk]:i}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]));for(let e of Object.keys(a))"accept-encoding"===e.toLowerCase()&&delete a[e];return a["accept-encoding"]="identity",a}(e,i,n.headers,a,r.sandboxSessionId),l=await iY({method:o,request:e,requestBody:a,requestHeaders:s,response:t,targetUrl:i,usePlatformFetch:!r.targetOrigin});if(i.pathname===iH&&l?.ok)try{let e=JSON.parse(l.body.toString("utf8"));(void 0===e.code||0===e.code)&&r.onBusinessInfoUpdated?.(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t="string"==typeof e.csr_pem?e.csr_pem.trim():"",r="string"==typeof e.phone_num?e.phone_num.trim():"";return r?{...t?{csrPem:t}:{},phoneNum:r}:void 0}(n.data))}catch{}}let iZ=f("node:util"),iQ="/app_developer/api/sandbox/bridge/events",i0="/app_developer/api/sandbox/bridge/response",i1=new Set(["connection","content-length","host"]),i2=new Set(["heartbeat"]),i3=[500,1e3,2e3,5e3],i4=0;function i5(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function i9(e,t=new Headers,r=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:r}}async function i8(e){let t,r,n=e.request_id||"";if(!n)return i9({error_message:"Bridge 请求缺少 request_id",http_status:0,request_id:n,success:!1});if(!e.path?.startsWith("/"))return i9({error_message:`Bridge 请求路径无效:${e.path??""}`,http_status:0,request_id:n,success:!1});let i=function(e){if(e.origin)try{var t;return new URL(e.path??"/",(t=e.origin).endsWith("/")?t:`${t}/`)}catch{return}}(e);if(!i)return i9({error_message:`Bridge 请求 origin 无效:${e.origin??""}`,http_status:0,request_id:n,success:!1});let a=(e.method||"GET").toUpperCase(),o=function(e){let t={};for(let[r,n]of Object.entries(e??{}))!r||i1.has(r.toLowerCase())||(t[r]=n);return t}(e.headers),s="GET"===a||"HEAD"===a?void 0:e.body??"",l=new AbortController,c=setTimeout(()=>l.abort(),(t="number"==typeof e.timeout_ms?e.timeout_ms:3e3,r="number"==typeof e.deadline_ms?e.deadline_ms-Date.now():t,Math.max(1,Math.min(t,r))));try{var p;let e=await fetch(i,{body:s,headers:o,method:a,redirect:"manual",signal:l.signal}),t=await e.text();return p={method:a,requestBody:s,requestHeaders:o,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:i},nz(p),i9({body:t,http_status:e.status,request_id:n,success:!0},e.headers,e.statusText)}catch(e){return nz({method:a,requestBody:s,requestHeaders:o,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:i}),i9({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:n,success:!1})}finally{clearTimeout(c)}}function i7(e,t=new Set){if(Array.isArray(e)){for(let r of e)i7(r,t);return[...t]}if(!e||"object"!=typeof e)return[...t];for(let[r,n]of Object.entries(e)){if(r.toLowerCase().replace(/[_-]/g,"").includes("logid")){if("string"==typeof n&&n)t.add(n);else if(Array.isArray(n))for(let e of n)"string"==typeof e&&e&&t.add(e);continue}i7(n,t)}return[...t]}function i6(e,t){e.onLog?.(t)}function ae(e){try{return JSON.parse(e)}catch{return}}function at({detail:e,requestHeaders:t,status:r,targetUrl:n}){if(eS()){if("number"==typeof r)return void nI.request({method:"CONNECT",url:n.pathname,statusCode:r,headers:t,context:{detail:e}});nI.info("Bridge 连接等待中",{url:n.pathname,detail:e,ppe:eI(t)})}}function ar(e,t={}){eS()&&nI.info(e,t)}async function an(e,t){let r=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),n={"content-type":"application/json",[nk]:e.sandboxSessionId,...n3()};if(e.targetOrigin){let t=new URL(i0,e.targetOrigin),i=await fetch(t,{body:r,headers:n,method:"POST"}),a=await i.text();if(nz({method:"POST",requestBody:r,requestHeaders:n,responseBody:a,responseHeaders:i.headers,statusCode:i.status,targetUrl:t}),!i.ok)throw Error(`上传 Bridge 响应失败:${i.status} ${a}`);return{responseBody:a,responseHeaders:Object.fromEntries(i.headers),responsePayload:ae(a)}}let i=new URL(i0,ee),a=await n9({body:r,headers:n,internal:!0,method:"POST",path:i0}),o=await a.text();if(nz({method:"POST",requestBody:r,requestHeaders:n,responseBody:o,responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),!a.ok)throw Error(`上传 Bridge 响应失败:${a.status} ${o}`);return{responseBody:o,responseHeaders:Object.fromEntries(a.headers),responsePayload:ae(o)}}async function ai(e,t){let r;try{r=JSON.parse(t)}catch(e){nI.warn("Sandbox Bridge 请求解析失败",{reason:e.message});return}let n=Date.now(),i=`bridge-${n}-${++i4}`,a=r.request_id||"",o={id:i,request:r,requestId:a,sandboxSessionId:e.sandboxSessionId,timestamp:n};i6(e,{...o,logIds:i7(r),status:"pending",updatedAtMs:n});let s=await i8(r),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await an(e,s.response);i6(e,{...o,logIds:i7([r,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw i6(e,{...o,errorMessage:t instanceof Error?t.message:String(t),logIds:i7([r,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function aa(e,t,r){let n={sandbox_session_id:e.sandboxSessionId},i=new URL(`${iQ}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,ee),a=(p=e.sandboxSessionId,{accept:"text/event-stream",host:i.host,[nk]:p,...n3()});at({detail:`host=${a.host} session=${i5(e.sandboxSessionId)}`,requestHeaders:a,status:"pending",targetUrl:i}),ar("bridge/events request",{headers:{accept:a.accept,host:a.host,[nk]:i5(e.sandboxSessionId),"x-tt-env":a["x-tt-env"],"x-use-ppe":a["x-use-ppe"]},path:iQ,query:n});let o=await n9({headers:a,internal:!0,method:"GET",path:iQ,query:n,signal:t});if(at({detail:`content-type=${o.headers.get("content-type")??""}`,requestHeaders:a,status:o.status,targetUrl:i}),!o.ok||!o.body){let e=await o.text().catch(()=>"");nz({method:"GET",requestBody:void 0,requestHeaders:a,responseBody:e,responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),nI.warn("Sandbox Bridge 事件请求失败",{status:o.status,body:e.slice(0,500)});let t=Error(`Sandbox Bridge SSE 请求失败:${o.status} ${e}`);throw t.status=o.status,t}nz({method:"GET",requestBody:void 0,requestHeaders:a,responseBody:"",responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),r?.();let s=o.body.getReader(),l=new iZ.TextDecoder,c="";for(;!t.aborted;){let{done:t,value:r}=await s.read();if(t){ar("Bridge events 流已结束",{session:i5(e.sandboxSessionId)});break}let n=(c+=l.decode(r,{stream:!0})).search(/\r?\n\r?\n/);for(;n>=0;){let t=c.slice(0,n),r=c.slice(n).match(/^\r?\n\r?\n/);c=c.slice(n+(r?.[0].length??2));let s=function(e){let t="message",r=[];for(let n of e.split(/\r?\n/)){if(n.startsWith("event:")){t=n.slice(6).trim();continue}n.startsWith("data:")&&r.push(n.slice(5).trimStart())}return{data:r.join("\n"),name:t}}(t);if(!function(e,t){if(!eS()||i2.has(e.name))return;let r=function(e){try{let t=JSON.parse(e);return"string"==typeof t.request_id?t.request_id:void 0}catch{return}}(e.data);nI.info("已收到 Bridge 事件",{event:e.name,requestId:r,ppe:eI(t)}),nI.info(`事件详情
164
+ ${e.data}`)}(s,a),"bridge_request"===s.name){var p,d=o.headers,u=o.status;nz({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:a,responseBody:"",responseHeaders:d,statusCode:u,targetUrl:i}),ai(e,s.data).catch(e=>{nI.warn("Sandbox Bridge 请求处理失败",{reason:e.message})})}else if("TOOL_CALL"===s.name){let t=J(ae(s.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{nI.warn("Sandbox Tool 调用转发失败",{reason:e instanceof Error?e.message:String(e),requestId:t.request_id,toolCallId:t.tool_call.tool_call_id})}):nI.warn("Sandbox Tool 调用事件解析失败")}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=ae(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.resource,i=r?.action,a=r?.resource_id,o=r?.revision;if(("notice"===n||"task"===n)&&("upsert"===i||"remove"===i)&&"string"==typeof a&&a&&("number"==typeof o||"string"==typeof o))return{action:i,eventId:"string"==typeof t.event_id?t.event_id:"",occurredAtMs:"number"==typeof t.occurred_at_ms?t.occurred_at_ms:void 0,resource:n,resourceId:a,revision:o}}(s.data);t?e.onResourceChanged?.(t):nI.warn("Sandbox 资源事件解析失败")}else if("card_delta"===s.name){let t=function(e){let t=ae(e);if(!t||"object"!=typeof t||Array.isArray(t))return;let r=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,n=r?.card_delta;if(!("card_delta"!==t.type||!n||"object"!=typeof n||Array.isArray(n)))return n}(s.data);t?e.onSimulatorEvent?.({payload:t,type:"card_delta"}):nI.warn("Sandbox 模拟器事件解析失败",{event:s.name})}else if("get_simulator_card_snapshots"===s.name){let t=ae(s.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:s.name}):nI.warn("Sandbox 模拟器事件解析失败",{event:s.name})}n=c.search(/\r?\n\r?\n/)}}}async function ao(e,t){let r=0,n=!1;for(;!t.aborted;){try{await aa(e,t,()=>{n=!1,e.onConnectionStatusChange?.("connected")}),r=0}catch(r){if(t.aborted)return;let e=r.status;if(n||(nI.warn("无法接收来自平台服务的请求",{reason:r.message}),n=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,v.setTimeout)(i3[Math.min(r,i3.length-1)],void 0,{signal:t}).catch(()=>void 0),r+=1}}let as=f("node:net"),al="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",ac="/app_developer/api/sandbox/session/business_info/update";function ap(e){if(!e)return!1;try{return tP.statSync(e).isFile()}catch{return!1}}async function ad({body:e,headers:t,method:r,sandboxPath:n,targetOrigin:i,targetUrl:a}){let o=new AbortController,s=setTimeout(()=>o.abort(),3e4);try{return i?await fetch(a,{body:e,headers:t,method:r,signal:o.signal}):await n9({internal:!0,path:n,body:e,headers:t,method:r,signal:o.signal})}catch(e){if(o.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${a}`);throw e}finally{clearTimeout(s)}}function au(e,t){return(e?.[t]??process.env[t])?.trim()??""}function am(e,t,r,n,i,a){if(!eS())return;let o=Number(process.hrtime.bigint()-n)/1e6;nI.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:o,headers:i,logId:a})}function ah({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:a,targetUrl:o}){nz({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:a,targetUrl:o})}async function af(e,t,r,n,i,a){let o,s,l="/app_developer/api/sandbox/session/create",c="POST",p=function(){let e=new Set;for(let t of(process.env[al]??"").split(",")){let r=t.trim();if(r)try{let t=new URL(r),n=t.hostname.replace(/^\[|\]$/g,"").toLowerCase(),i="localhost"===n||"::1"===n||4===(0,as.isIP)(n)&&n.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!i)throw Error("仅允许本机回环 HTTP(S) origin");e.add(t.origin)}catch(e){throw Error(`${al} 包含无效 origin:${r}(${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),d=JSON.stringify({sandbox_project_id:e,manifest:r?.()??(ap(t)?tP.readFileSync(t,"utf8"):""),business_templates:ap(n)?tP.readFileSync(n,"utf8"):"",...a?{app_id:a}:{},...p.length>0?{bridge_origins:p}:{}}),u={"content-type":"application/json",...n3()},m=new URL(l,i??ee),h=process.hrtime.bigint();try{o=await ad({body:d,headers:u,method:c,sandboxPath:l,targetOrigin:i,targetUrl:m})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw am(c,m,502,h,u),ah({method:c,requestBody:d,requestHeaders:u,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:m}),t}let f=o.headers.get(nN)||"",g=await o.text();am(c,m,o.status,h,u,f),ah({method:c,requestBody:d,requestHeaders:u,responseBody:g,responseHeaders:o.headers,statusCode:o.status,targetUrl:m});try{s=JSON.parse(g||"{}")}catch{throw Error(`创建 Sandbox session 失败:HTTP ${o.status} ${o.statusText||g||"响应不是有效 JSON"}${f?`,log_id=${f}`:""}`)}if(!o.ok||0!==s.code)throw Error(`创建 Sandbox session 失败:${s.message||o.statusText||o.status}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);let y=s.data?.sandbox_session_id,b=s.data?.sandbox_appid;if(!y||!b)throw Error(`创建 Sandbox session 失败:响应缺少 ${y?"sandbox_appid":"sandbox_session_id"}${s.log_id||f?`,log_id=${s.log_id||f}`:""}`);return{appId:b,sessionId:y}}async function ag(e,t,r,n,i,a){try{return await af(e,t,r,n,i,a)}catch(e){return nI.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function ay(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function ab(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function a_(e,t){let r,n,i="/app_developer/api/sandbox/session/business_info/get",a="POST",o=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...n3()},l=new URL(i,t??ee),c=process.hrtime.bigint();try{r=await ad({body:o,headers:s,method:a,sandboxPath:i,targetOrigin:t,targetUrl:l})}catch(e){throw am(a,l,502,c,s),e}let p=r.headers.get(nN)||"",d=await r.text();am(a,l,r.status,c,s,p);try{n=JSON.parse(d||"{}")}catch{throw ah({method:a,requestBody:o,requestHeaders:s,responseBody:JSON.stringify({omitted:"Sandbox 业务信息响应无效"}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}let u={csrUploaded:!!n.data?.csr_pem?.trim(),phoneNumberUploaded:!!n.data?.phone_num?.trim()};if(ah({method:a,requestBody:o,requestHeaders:s,responseBody:JSON.stringify({code:n.code,data:u,log_id:n.log_id}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),!r.ok||void 0!==n.code&&0!==n.code)throw Error(`获取 Sandbox session 信息失败:${n.message||r.statusText||r.status}${n.log_id||p?`,log_id=${n.log_id||p}`:""}`);return u}async function av(e,t){if(!e)return ay();try{return await a_(e,t)}catch(e){return nI.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),ay()}}async function aE(e,t,r){let n,i,a="POST",o=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...n3(),[nk]:t},l=new URL(ac,r??ee),c=process.hrtime.bigint();try{n=await ad({body:o,headers:s,method:a,sandboxPath:ac,targetOrigin:r,targetUrl:l})}catch(e){throw am(a,l,502,c,s),e}let p=n.headers.get(nN)||"",d=await n.text();am(a,l,n.status,c,s,p),ah({method:a,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:d,responseHeaders:n.headers,statusCode:n.status,targetUrl:l});try{i=JSON.parse(d||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${p?`,log_id=${p}`:""}`)}if(!n.ok||void 0!==i.code&&0!==i.code)throw Error(`更新 Sandbox session 信息失败:${i.message||n.statusText||n.status}${i.log_id||p?`,log_id=${i.log_id||p}`:""}`)}async function aw(e,t,r,n){if(e&&t.phoneNum&&(!r||t.csrPem))try{return await aE({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,n),nI.info("Sandbox 业务信息已自动上传",{sessionId:e}),ab(t.csrPem)}catch(e){nI.warn(`Sandbox 业务信息自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function aS(e,t){let r,n="/app_developer/api/sandbox/session/revoke",i="POST",a=JSON.stringify({sandbox_session_id:e}),o={"content-type":"application/json",...n3()},s=new URL(n,t??ee),l=process.hrtime.bigint();try{r=await ad({body:a,headers:o,method:i,sandboxPath:n,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw am(i,s,502,l,o),ah({method:i,requestBody:a,requestHeaders:o,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let c=r.headers.get(nN)||"",p=await r.text();am(i,s,r.status,l,o,c),ah({method:i,requestBody:a,requestHeaders:o,responseBody:p,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});let d=JSON.parse(p||"{}");if(!r.ok||0!==d.code)throw Error(`撤回 Sandbox session 失败:${d.message||r.statusText||r.status}${d.log_id||c?`,log_id=${d.log_id||c}`:""}`)}async function ax(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let r=e.sandboxSessionId;r&&await aS(r,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let n=await af(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),i=n.sessionId,a=!e.sandboxSessionAppId,o=await aw(i,e.businessInfoInput,a,e.sandboxTargetOrigin)??await av(i,e.sandboxTargetOrigin);return e.sandboxAppId=n.appId,e.sandboxSessionId=i,e.businessInfo=o,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,aI(t),e.bridge=aO(e,i),nI.info("Sandbox session 已重建",{sessionId:i}),{...n,businessInfoUploaded:o.phoneNumberUploaded&&(!a||o.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function aA(e){return{bridgeLogs:e.bridgeLogs,bridgeLogsUpdatedAtMs:e.bridgeLogsUpdatedAtMs,connectionStatus:e.resourceConnectionStatus,events:e.resourceEvents,generation:e.resourceGeneration,instanceId:e.resourceInstanceId,simulatorEvents:e.simulatorEvents,updatedAtMs:e.resourceEventsUpdatedAtMs}}function aT(e){clearTimeout(e.logBroadcastTimer),e.logBroadcastTimer=void 0;let t=aA(e);for(let r of e.eventListeners)r(t)}function aI(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1),aT(e)}function aO(e,t){var r={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,aI(e))},onLog:t=>{let r=e.bridgeLogs.findIndex(e=>e.id===t.id);r>=0?e.bridgeLogs[r]=t:(e.bridgeLogs.push(t),e.bridgeLogs.length>200&&e.bridgeLogs.splice(0,e.bridgeLogs.length-200)),e.bridgeLogsUpdatedAtMs=Math.max(Date.now(),e.bridgeLogsUpdatedAtMs+1),e.logBroadcastTimer??=setTimeout(()=>aT(e),50)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),aI(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),aI(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!r.sandboxSessionId)return void nI.warn("已跳过 Sandbox Bridge:缺少 Sandbox session id");let n=new AbortController;return ar("正在启动 Sandbox Bridge",{session:i5(r.sandboxSessionId)}),r.onConnectionStatusChange?.("connecting"),ao(r,n.signal),{close:()=>n.abort()}}async function aP(e,t,r){if("POST"!==e.method)return void nF(t,405,"不支持的请求方法");if(!r)return void nF(t,503,"Sandbox session 尚未初始化");try{let n=await nG(e,t,1048576);if(n){let e=JSON.parse(n);if(void 0!==e.csrPem&&"string"!=typeof e.csrPem||"string"!=typeof e.phoneNum)return void nF(t,400,"Sandbox 业务信息无效");r.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let i=await ax(r);nH(t,200,{code:0,data:{sandbox_appid:i.appId,business_info_uploaded:i.businessInfoUploaded,sandbox_session_id:i.sessionId},message:"ok"})}catch(e){nF(t,500,e.message)}}function aC(e){let t=e.appId?.trim(),r=t&&!t.startsWith("doubao-sandbox-app-")?t:void 0,n=function(e){let t=tn.resolve(e??process.cwd()),r=t;try{r=tP.realpathSync.native(t)}catch{}return(0,ik.createHash)("sha256").update(r).digest("hex")}(e.appDirectory),i=function(e,t){let r=au(e,"DOUBAO_SANDBOX_PHONE_NUM"),n=au(e,"DOUBAO_SANDBOX_CSR_FILE"),i=function(e,t){if(!e)return;let r=tn.isAbsolute(e)?e:tn.resolve(t??process.cwd(),e);return ap(r)?r:void 0}(n,t),a="";if(n&&!i)nI.warn(`Sandbox CSR 文件不存在:${n}`);else if(i)try{a=tP.readFileSync(i,"utf8").trim()}catch(e){nI.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...r?{phoneNum:r}:{},...a?{csrPem:a}:{}}}(e.env,e.appDirectory),a=`${i.phoneNum??""}\0${i.csrPem??""}`;return{businessInfoInput:i,businessInfoInputKey:a,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([a,n,r,e.targetOrigin,e.businessTemplatesPath,e.manifestPath]),manifestReader:e.manifestReader,manifestPath:e.manifestPath,onSimulatorToolCall:e.onSimulatorToolCall,projectId:n,sessionAppId:r,targetOrigin:e.targetOrigin}}class aR{configKey;manifestReader;state;constructor(e,t,r){this.state=e,this.configKey=t,this.manifestReader=r}static async start(e){let t=aC(e),r=await ag(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),n=!t.sessionAppId,i={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await aw(r.sessionId,t.businessInfoInput,n,t.targetOrigin)??await av(r.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,eventListeners:new Set,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,resourceInstanceId:(0,ik.randomUUID)(),simulatorEventSequence:0,simulatorEvents:[],sandboxAppId:r.appId,sandboxProjectId:t.projectId,sandboxSessionAppId:t.sessionAppId,sandboxSessionId:r.sessionId,sandboxTargetOrigin:t.targetOrigin,simulatorBusinessTemplatesPath:t.businessTemplatesPath,simulatorManifestReader:t.manifestReader,simulatorManifestPath:t.manifestPath},a=new aR(i,t.key,t.manifestReader);return i.bridge=r.sessionId?aO(i,r.sessionId):void 0,a}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close(),clearTimeout(this.state.logBroadcastTimer),this.state.eventListeners.clear()}subscribeEvents(e){return this.state.eventListeners.add(e),e(aA(this.state)),()=>{this.state.eventListeners.delete(e)}}clearBridgeLogs(){this.state.bridgeLogs.length=0,this.state.bridgeLogsUpdatedAtMs=Math.max(Date.now(),this.state.bridgeLogsUpdatedAtMs+1),aT(this.state)}matches(e){let t=aC(e);return this.configKey===t.key&&this.manifestReader===t.manifestReader}getDebugContext(){var e;let t;return{fileSystemNamespace:(t=(e=this.state).sandboxSessionAppId?`real-app\0${e.sandboxSessionAppId}`:`virtual-app\0${e.sandboxAppId}\0${e.sandboxProjectId}`,`sandbox-v1:${(0,ik.createHash)("sha256").update(t).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(){return[{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>iX(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=ab(e?.csrPem),e&&(this.state.businessInfoInput=e)},sandboxAppId:this.state.sandboxAppId,sandboxSessionId:this.state.sandboxSessionId,targetOrigin:this.state.sandboxTargetOrigin})},{match:"/__web_sdk_sandbox_session_recreate__",handle:({request:e,response:t})=>aP(e,t,this.state)}]}}function a$(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let ak="/__tools/tools.json",aN="/__events/events.json",aL="manifest.yaml",aD="skill";function aj(e){if(!e)return!1;try{return tP.statSync(e).isFile()}catch{return!1}}function aM(e,t){if(!e)return;let r=tn.isAbsolute(e)?e:tn.resolve(t??process.cwd(),e);return aj(r)?r:void 0}function aU(e,t){if(e&&t)return tn.relative(t,e).split(tn.sep).join("/")||"."}function aB(e){let t=tn.resolve(e);for(;;){if(aj(tn.join(t,aL)))return t;let e=tn.dirname(t);if(e===t)return;t=e}}function aF(e){try{return tP.lstatSync(e),!0}catch{return!1}}function aH(e,t,r,n){let i;if(!t.reader&&aj(t.sourcePath)){var a;let r,i=tP.statSync(t.sourcePath);nB(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":n}),a=t.sourcePath,(r=tP.createReadStream(a)).once("error",()=>e.destroy()),r.pipe(e);return}try{i=t.reader?.()}catch{i=void 0}void 0===i?nF(e,404,`未找到 ${r}`):(nB(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(i),"Content-Type":n}),e.end(i))}function aW(e,t){return function(e){let t,r;if(!e)return{layout:"missing",entries:[]};let n=tn.resolve(e);try{t=tP.lstatSync(n)}catch(e){if("ENOENT"===e.code)return{directory:n,layout:"missing",entries:[]};return{directory:n,layout:"invalid",entries:[],error:`skill path cannot be inspected: ${n}: ${e.message}`}}if(t.isSymbolicLink()||!t.isDirectory())return{directory:n,layout:"invalid",entries:[],error:`skill path must be a non-symlink directory: ${n}`};try{var i;let e;i=n,e=[],function t(r){for(let n of tP.readdirSync(r,{withFileTypes:!0})){if(n.isSymbolicLink())continue;let a=tn.join(r,n.name);n.isDirectory()?t(a):n.isFile()&&"SKILL.md"===n.name&&e.push(function(e,t){let r=tn.relative(e,t).split(tn.sep).join("/");return{content:tP.readFileSync(t,"utf8"),relativePath:r}}(i,a))}}(i),r=e}catch(e){return{directory:n,layout:"invalid",entries:[],error:`skill directory is not readable: ${n}: ${e.message}`}}return r.sort(a$),r.length>0?{directory:n,layout:"resolved",entries:r}:{directory:n,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;if(tn.isAbsolute(t))return t;let r=e?aB(e):void 0,n=[e,r,process.cwd()].map(e=>tn.resolve(e??process.cwd(),t));return[...new Set(n)].find(aF)??n[0]}if(!e)return;let r=aB(e);return[...new Set([r?tn.join(r,aD):void 0,tn.join(e,aD),tn.join(process.cwd(),aD)].filter(Boolean))].find(aF)}(e,t))}class aG{appDirectory;businessTemplatesPath;manifestPath;manifestReader;eventsConfigReader;eventsConfigSource;toolsConfigReader;toolsConfigSource;manifestSource;skillsDirectory;sourceKey;constructor(e){var t,r,n;this.appDirectory=e.appDirectory,this.manifestPath=e.manifestPath?aM(e.manifestPath,e.appDirectory):e.manifestSourcePath??(e.manifestReader?void 0:function(e){if(!e)return;let t=aB(e);return[...new Set([t?tn.join(t,aL):void 0,tn.join(process.cwd(),aL)].filter(Boolean))].find(aj)}(e.appDirectory)),this.businessTemplatesPath=(t=this.manifestPath,r=e.businessTemplatesPath,n=e.appDirectory,r?aM(r,n):t?aM(tn.join(tn.dirname(t),"business-templates.yaml"),n):void 0),this.manifestReader=e.manifestReader,this.eventsConfigReader=e.eventsConfigReader,this.toolsConfigReader=e.toolsConfigReader,this.eventsConfigSource={reader:e.eventsConfigReader,sourcePath:e.eventsConfigSourcePath},this.skillsDirectory=e.skillsDirectory;let i=aW(e.appDirectory,this.skillsDirectory);if(e.skillsDirectory&&"resolved"!==i.layout)throw Error(i.error??`Simulator skills directory contains no runtime Skill: ${e.skillsDirectory}`);this.toolsConfigSource={reader:e.toolsConfigReader,sourcePath:e.toolsConfigSourcePath},this.manifestSource={reader:e.manifestReader,sourcePath:e.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(e){let t=new aG(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=aW(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,r=aU(this.businessTemplatesPath,this.appDirectory),n=aU(this.eventsConfigSource.sourcePath,this.appDirectory),i=aU(this.toolsConfigSource.sourcePath,this.appDirectory),a=aU(this.manifestSource.sourcePath,this.appDirectory),o=aU(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:aN,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...n?{eventsConfigRelativePath:n}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:ak,...i?{toolsConfigRelativePath:i}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...a?{simulatorManifestRelativePath:a}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...r?{simulatorBusinessTemplatesRelativePath:r}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...o?{simulatorSkillsDirectoryRelativePath:o}:{}}:{}}}getRequestRoutes(){return[{match:aN,handle:({response:e})=>aH(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:ak,handle:({response:e})=>aH(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>aH(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=aW(this.appDirectory,this.skillsDirectory)).layout?nF(e,404,"未找到模拟器 Skill 目录"):"invalid"===t.layout?nF(e,422,t.error??"模拟器 Skill 目录结构无效"):nH(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}let aV=f("node:stream"),aq="/app_developer/api",aJ=`${aq}/simulator/images/upload`,az=new Set([`${aq}/simulator/chat`,aJ,`${aq}/simulator/tool/report`]),aK={"Access-Control-Expose-Headers":nN};async function aY(e,t,r,n){if(!az.has(r.pathname))return void nF(t,404,"未找到模拟器接口",aK);let i=n.targetOrigin??ee,a=new URL(`${r.pathname}${r.search}`,i),o=nK(e,t);try{var s;let i=e.method??"GET",l=process.hrtime.bigint(),c=function(e,t,r){return Object.fromEntries(Object.entries(nj(e.headers,t,{...n3(),...r?{[nk]:r}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,a,n.getSandboxSessionId?.()),p=await aX(e,t,r,i),d=n.targetOrigin?await fetch(a,{body:p,headers:c,method:i,signal:o}):await n9({internal:!0,path:`${r.pathname}${r.search}`,method:i,body:p,headers:c,signal:o});if(function(e,t,r,n,i,a){if(!eS())return;let o=Number(process.hrtime.bigint()-n)/1e6;nI.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:o,headers:i,logId:a})}(i,r,d.status,l,c,d.headers.get(nN)??void 0),t.destroyed||t.writableEnded)return void d.body?.cancel().catch(()=>void 0);await aZ({method:i,requestBody:(s=p)instanceof Uint8Array?`(binary, ${s.byteLength} bytes)`:s,requestHeaders:c,requestUrl:r,response:t,upstreamResponse:d})}catch(e){if(t.destroyed||t.writableEnded||o.aborted)return;nF(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,aK)}}async function aX(e,t,r,n){if("GET"!==n&&"HEAD"!==n)return r.pathname===aJ?await nW(e,t,0xb00000):await nG(e,t,0xb00000)}async function aZ({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:a}){var o,s;if(nB(i,aK),i.writeHead(a.status,nU(a.headers,[nN])),o=n,s=a,o.pathname===`${aq}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await aQ({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:a});if(!eS())return a.body?void await (0,g.pipeline)(aV.Readable.fromWeb(a.body),i):void i.end();let l=await nV(a);nz({method:e,requestBody:t,requestHeaders:r,responseBody:l,responseHeaders:a.headers,statusCode:a.status,targetUrl:n}),i.end(l)}async function aQ({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:a}){if(!a.body){nz({method:e,requestBody:t,requestHeaders:r,responseBody:"",responseHeaders:a.headers,statusCode:a.status,targetUrl:n}),i.end();return}let o=aV.Readable.fromWeb(a.body);if(!eS())return void await (0,g.pipeline)(o,i);nz({method:e,requestBody:t,requestHeaders:r,responseBody:"(event stream)",responseHeaders:a.headers,statusCode:a.status,targetUrl:n});let s=new aV.Transform({transform(e,t,r){let i;try{i=String(e).split("\n\n").filter(Boolean)}catch(t){return nI.error(`事件流分片解码失败:${t?.toString()}`),r(null,e)}for(let e of i)nI.info(`来自 ${n.pathname}${n.search} 的事件
165
+ ${e}`);r(null,e)}});await (0,g.pipeline)(o,s,i)}async function a0(e,t){if("POST"!==e.method)return void nH(t,405,{message:"不支持的请求方法"});let r=nK(e,t);try{var n,i;let a,o,s=JSON.parse(await nG(e,t,0xa00000)),l=function(e){if("GET"!==e&&"POST"!==e)throw Error(`Unsupported request method: ${String(e)}`);return e}(s.method),c=nD(s.url),p=await fetch(c,{signal:r,body:"POST"===l?function(e){if(void 0!==e.data&&null!==e.data){if("base64"===e.dataEncoding&&"string"==typeof e.data){var t;let r;return r=new ArrayBuffer((t=Buffer.from(e.data,"base64")).byteLength),new Uint8Array(r).set(t),r}if(void 0===e.dataEncoding&&"string"==typeof e.data)return e.data;throw Error("Invalid prepared request body")}}(s):void 0,headers:(n=s.header,a=new Headers(n),["connection","content-length","host","origin","referer"].forEach(e=>a.delete(e)),a),method:l}),d=Buffer.from(await p.arrayBuffer()).toString("base64");nH(t,200,{data:d,dataEncoding:"base64",header:(i=p.headers,o={},i.forEach((e,t)=>{o[t]=e}),o),statusCode:p.status})}catch(e){if(r.aborted||t.destroyed)return;nH(t,500,{message:e instanceof Error?e.message:String(e)})}}let a1=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),a2="/__web_artifacts",a3="/wsd";function a4(e,t,r,n,i={}){nB(t,i.headers),a1(e,n,{root:r}).once("error",n=>{if(404===n.statusCode&&i.fallbackPath)return void a4(e,t,r,i.fallbackPath,{headers:i.headers});if(t.headersSent)return void t.destroy(n);let a=n.statusCode??500;nF(t,a,nO.STATUS_CODES[a]??"Internal Server Error")}).pipe(t)}let a5="/__webview",a9=`${a5}/client.js`,a8=`${a5}/page`,a7=`${a5}/runtime`,a6=`${a5}/sw.js`,oe="x-doubao-web-view-target",ot="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",or=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-bootstrap.js"),f.b),on=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),oi=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.5.0-rc.3_@emnapi+core@1.11.3_@emnapi+runtime@1.11._dca99ae1c26311b05bd4c6e1dc1d7ba7/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function oa(e,t,r,n=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void nF(t,405,"不支持的请求方法");let i=tP.readFileSync(r,"utf8");nB(t,{"Cross-Origin-Resource-Policy":"cross-origin"}),t.writeHead(200,{"cache-control":"no-store","content-length":Buffer.byteLength(i),"content-type":"text/javascript; charset=utf-8",...n?{"service-worker-allowed":"/"}:{}}),t.end("HEAD"===e.method?void 0:i)}function oo(e,t){let r=e.searchParams.get("parentOrigin")??t[0];if(!t.includes(r))throw Error("WebView 父级 origin 无效");return r}async function os(e,t,r,n){if("GET"!==e.method&&"HEAD"!==e.method)return void nF(t,405,"不支持的请求方法");let i=nK(e,t);try{let a=oo(r,n),o=nD(r.searchParams.get("url")??void 0),s=await fetch(o,{signal:i,headers:{"user-agent":ot,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),l=s.url?new URL(s.url):o;l.hash=o.hash;let c=s.headers.get("content-type")??"",p=nU(s.headers);if(p["cache-control"]="no-cache",p["cross-origin-resource-policy"]="cross-origin",p["x-doubao-web-view-parent-origin"]=a,"HEAD"===e.method||!c.includes("text/html")){let r="HEAD"===e.method?void 0:Buffer.from(await s.arrayBuffer());nB(t),t.writeHead(s.status,{...p,[oe]:l.toString(),...r?{"content-length":r.byteLength}:{}}),t.end(r);return}let d=function(e,t,r){let n=new URLSearchParams({mobileUserAgent:ot,originalPath:`${t.pathname}${t.search}${t.hash}`,parentOrigin:r}).toString().replaceAll("&","&amp;"),i=`<script src="${a9}?${n}"></script>`,a=/<head[^>]*>/i.exec(e);if(a){let t=a.index+a[0].length;return`${e.slice(0,t)}${i}${e.slice(t)}`}return`${i}${e}`}(await s.text(),l,a);nB(t),t.writeHead(s.status,{...p,[oe]:l.toString(),"content-length":Buffer.byteLength(d)}),t.end(d)}catch(e){if(i.aborted||t.destroyed)return;nF(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}async function ol(e){let t=new URL(e).toString();try{await S(t)}catch(e){nI.error("打开 Web 模拟器失败",{error:e}),nI.info("请手动打开 Web 模拟器(本地)",{url:t})}}async function oc(e,t){await new Promise((r,n)=>{let i=t=>{e.off("listening",a),n(t)},a=()=>{e.off("error",i),r()};e.once("error",i),e.once("listening",a),e.listen(t,"127.0.0.1")})}async function op(e){var t;let r=await Z(9e3),n=nO.createServer(nZ((t=[`http://127.0.0.1:${r}`,`http://localhost:${r}`],[{match:`${a5}/bootstrap`,handle:({request:e,response:r,url:n})=>{if("GET"!==e.method&&"HEAD"!==e.method)return void nF(r,405,"不支持的请求方法");try{nD(n.searchParams.get("url")??void 0),oo(n,t)}catch{nF(r,400,"WebView URL 无效");return}nB(r,{"Cross-Origin-Resource-Policy":"cross-origin"}),r.writeHead(200,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),r.end("HEAD"===e.method?void 0:'<!doctype html><meta charset="utf-8"><script src="/__webview/bootstrap.js"><\/script>')}},{match:`${a5}/bootstrap.js`,handle:({request:e,response:t})=>oa(e,t,or)},{match:a6,handle:({request:e,response:t})=>oa(e,t,oi,!0)},{match:a9,handle:({request:e,response:t})=>oa(e,t,on)},{match:a7,handle:({request:e,response:t,url:r})=>(function(e,t,r){let n;try{n=nD(r.searchParams.get("url")??void 0)}catch(e){nF(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let i=nj(e.headers,n,{"user-agent":ot});for(let e of Object.keys(i))e.startsWith("sec-fetch-")&&delete i[e];nY(e,t,{createResponseHeaders:e=>{let t=nM(e),r=Array.isArray(e.location)?e.location[0]:e.location;if(r&&URL.canParse(r,n)){let e=new URL(r,n);t.location=`${a7}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:i,targetUrl:n})})(e,t,r)},{match:a8,handle:({request:e,response:r,url:n})=>os(e,r,n,t)}]),({response:e})=>{nF(e,404,"未找到 WebView 资源")}));await oc(n,0);let i=n.address(),a=`http://127.0.0.1:${i.port}`,o=nO.createServer(function({webViewOrigin:e,artifactOrigin:t,debugScenes:r,debuggerProtocol:n,distPath:i,getWidgetViewDataTemplates:a,mcpEndpoint:o,mcpHeaders:s,physicalDeviceDebugGateway:l,sandboxRuntime:c,simulatorAssets:p,simulatorTargetOrigin:d}){var u;let m={routes:[{match:e=>e.pathname.startsWith(a2),handle:({request:e,response:r,url:n})=>{let i,a;return i=n.pathname.replace(a2,"")||"/",a=new URL(`${i}${n.search}`,t),void nY(e,r,{createResponseHeaders:e=>({...nM(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nj(e.headers,a),targetUrl:a})}},{match:e=>e.pathname===a3||e.pathname.startsWith(`${a3}/`),handle:({request:e,response:t,url:r})=>{let n;!(n=r.pathname.slice(`${a3}/`.length))||n!==tn.basename(n)?nF(t,404,"未找到资源"):a4(e,t,tn.join(i,"wsd"),n,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>a0(e,t)},{match:"/__webview/page",handle:({request:t,response:r,url:n})=>{"GET"!==t.method&&"HEAD"!==t.method?nF(r,405,"不支持的请求方法"):(nB(r),r.writeHead(302,{"cache-control":"no-store",location:`${e}/__webview/bootstrap${n.search}`}),r.end())}},{match:"/__webview/sw.js",handle:({response:e})=>{nB(e),e.writeHead(200,{"cache-control":"no-store","content-type":"text/javascript","service-worker-allowed":"/"}),e.end(`self.addEventListener('install', e => e.waitUntil(self.skipWaiting()));
35
166
  self.addEventListener('activate', e => e.waitUntil((async () => {
36
167
  await self.clients.claim();
37
168
  await self.registration.unregister();
38
- })()));`)}},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:n})=>iV(e,t,o,n.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>rR(e,404,"Debugger resource not found")}],fallback:({request:e,response:t,url:n})=>iV(e,t,o,n.pathname,{fallbackPath:"/index.html"})};return rG([...(u={artifactOrigin:t,webViewOrigin:e,debugScenes:n,getWidgetViewDataTemplates:i,mcpEndpoint:a,physicalDeviceDebugGateway:l,sandboxRuntime:p,simulatorAssets:d},[{match:"/__web_sdk_debug_context",handle:({request:e,response:t})=>{let n,r;return r="string"==typeof(n=e.headers.host)&&n?`http://${n}`:void 0,void rN(t,200,{homeDir:nv.homedir(),webViewOrigin:u.webViewOrigin,launchDir:u.simulatorAssets.appDirectory,debugScenesEndpoint:op,widgetViewDataTemplatesEndpoint:od,debuggerMcpEndpoint:r?new URL(os,r).toString():os,manifestOriginalUrl:new URL("/base/manifest.json",u.artifactOrigin).toString(),...u.mcpEndpoint?{mcpOriginalEndpoint:u.mcpEndpoint,mcpProxyEndpoint:rq}:{},realDeviceDebug:u.physicalDeviceDebugGateway?.getDebugContext(),...u.simulatorAssets.getDebugContext(),...u.sandboxRuntime.getDebugContext()},oc)}},{match:op,handle:({response:e})=>rN(e,200,u.debugScenes??{errors:[],scenes:[]},oc)},{match:od,handle:({response:e})=>ou(e,u.getWidgetViewDataTemplates)}]),...l.getRequestRoutes(),...r,...function(e={}){return[{match:e=>e.pathname===ik||e.pathname.startsWith(`${ik}/`),handle:({request:t,response:n,url:r})=>iL(t,n,r,e)}]}({getSandboxSessionId:()=>p.sessionId,targetOrigin:c}),...p.getRequestRoutes(),...function(e={}){return[{match:rq,handle:({request:t,response:n,url:r})=>(function(e,t,n={},r=rI(e)){let o=K(n.targetEndpoint);if(!r)return void rR(t,400,"Bad request");if(!o)return void rR(t,404,"MCP endpoint not configured");let i=new URL(o);for(let[e,t]of new URLSearchParams(r.search))i.searchParams.append(e,t);rW(e,t,{createResponseHeaders:rD,errorMessage:"代理 MCP 请求失败",requestHeaders:rO(e.headers,i,{...ea(),...n.headers}),targetUrl:i})})(t,n,e,r)}]}({headers:s,targetEndpoint:a}),...d.getRequestRoutes(),...m.routes],m.fallback)}({...e,webViewOrigin:i})),s=e.debuggerProtocol.attachConnection(a,e.sandboxRuntime);try{await i5(a,n)}catch(e){throw s(),await i8(r),e}return{origin:`http://127.0.0.1:${n}`,server:a,webViewServer:r,closeConnections:s}}async function i8(e){e.listening&&await new Promise((t,n)=>{e.close(e=>{e?n(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function i7(){if(!r)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:n,webViewServer:o,closeConnections:i}=r;r=void 0,i(),e.dispose(),t.close(),await Promise.all([i8(n),i8(o)])}async function i6(e){let t,{targetOrigin:n,...o}=e.simulator??{},i={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...o},a=new iO(i);try{var s,l;let o,p,d=K(e.mcpEndpoint),c={appDirectory:e.appDirectory,appId:e.appId,businessTemplatesPath:a.businessTemplatesPath,env:e.env,manifestReader:e.simulatorManifestReader,manifestPath:a.manifestPath,targetOrigin:e.sandboxTargetOrigin};if(s=r,s?.server.listening){if(r?.artifactOrigin===e.artifactOrigin&&r.mcpEndpoint===d&&r.simulatorAssets.matches(i)&&r.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&r.sandboxRuntime.matches(c)&&r.simulatorTargetOrigin===n)return r;await i7()}let u={distPath:l=e.debuggerDistPath,indexPath:tC.join(l,"index.html")};if(!tQ.existsSync(u.indexPath))return void rv.error("Web 模拟器资源缺失,请联系框架开发者。");let m=(o={},p=new r1(o),Object.assign([{match:"/__agent_trace",handle:e=>ow(e,o,p)},{match:os,handle:e=>ol(e,o,p)}],{attachConnection:(e,t)=>{var n;let r,i,a,s;return n=e=>oS(o,p,e),r=new rJ({noServer:!0,maxPayload:0xa00000}),i=new Set,a=(o,a,s)=>{let l,d=e.address().port,c=o.headers.host;try{l=new URL(o.url??"/","http://127.0.0.1")}catch{a.destroy();return}let u=l.searchParams.get("clientId")?.trim();c!==`127.0.0.1:${d}`&&c!==`localhost:${d}`||void 0!==o.headers.origin&&o.headers.origin!==`http://${c}`?a.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==l.pathname||!u||u.length>128?a.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):r.handleUpgrade(o,a,s,e=>{p.registerClient(u,e),i.add(e),e.on("pong",()=>i.add(e)),e.on("error",()=>e.close());let r=t.subscribeEvents(t=>rK(e,"sandbox",t));e.once("close",()=>{i.delete(e),r()}),e.on("message",(r,o)=>{try{let e=o?void 0:JSON.parse(r.toString());if(!G(e))throw Error("Invalid debugger message");if("snapshot"===e.type&&G(e.data)&&G(e.data.snapshot))n({...e.data,...G(e.data.debug_snapshot)?{debug_snapshot:{...e.data.debug_snapshot,client_id:u}}:{},snapshot:{...e.data.snapshot,client_id:u}});else if("control_result"===e.type&&G(e.data))p.handleResult({...e.data,clientId:u});else if("clear_sandbox_logs"===e.type)t.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{e.close(1008,"Invalid debugger message")}})})},e.on("upgrade",a),(s=setInterval(()=>{for(let e of r.clients)i.delete(e)?e.ping():e.terminate()},3e4)).unref(),()=>{for(let t of(clearInterval(s),e.off("upgrade",a),r.clients))t.terminate();r.close()}},executeSandboxToolCall:e=>p.execute("execute_sandbox_tool_call",{toolCall:e})})),h=await iy.start({...c,onSimulatorToolCall:async e=>{await m.executeSandboxToolCall(e)}});t=h;let f=new o_,{origin:g,server:y,webViewServer:b,closeConnections:_}=await i9({artifactOrigin:e.artifactOrigin,debugScenes:e.debugScenes,debuggerProtocol:m,distPath:u.distPath,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:d,mcpHeaders:e.mcpHeaders,physicalDeviceDebugGateway:f,sandboxRuntime:h,simulatorAssets:a,simulatorTargetOrigin:n}),v=()=>{y.close(),b.close()};y.once("close",()=>{process.off("exit",v)}),process.once("exit",v);let w=new URL(g).toString();return r={artifactOrigin:e.artifactOrigin,close:()=>i7(),debuggerMcpEndpoint:new URL(os,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:d,open:()=>i4(w),origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:h,get sandboxSessionId(){return h.sessionId},server:y,webViewServer:b,closeConnections:_,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:a,simulatorTargetOrigin:n,url:w}}catch(e){t?.close(),rv.error("启动 Web SDK 调试器失败",{error:e});return}}async function ae(e,t){let n={errors:[],scenes:[]};if(!e)return n;for(let r of(await tI(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await tP(r.path);e&&function(e,t){let n=ee(e);return"tool"!==n.type&&("widget"===n.type?t.widgetIds.has(n.id):0===n.unresolvedVariables.length)}(e,t)&&n.scenes.push({content:e,name:r.name})}return n}async function at(e,t){let n=e.metadata.getData(),r=e.widgets,o=await ae(e.appDirectory,{widgetIds:new Set(Object.keys(r).map(e=>nu(r,n.widgets,e)))});return i6({...t,debuggerDistPath:t.debuggerDistPath??B(),debugScenes:o,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function an(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function ar(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function ao(e){an(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||ez.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let ai=e=>tp.bgHex("#9873b9")(tp.italic(tp.black(` ${e} `))),aa=e=>tp.bgBlueBright(tp.italic(tp.black(` ${e} `))),as=e=>tp.bold(tp.blueBright(e)),al=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],ap={page:"页面",scene:"调试场景",widget:"组件"};function ad(e){console.log(` ${as(e.command.padEnd(21))} ${tp.gray(`- ${e.description}`)}`)}async function ac(e){let t=q(e);if(0!==t.length)return await tl.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function au({matchedScene:e,appId:t,driver:n}){let r=await tP(e.path);if(!r)return;let o=await ac(r);await tO({matchedScene:e,appId:t,driver:n,variables:o},r)}async function am(e,t,n,r,o,i,{interactive:a=!0}={}){if(await o.load({appletUrl:t,appId:e,isSigned:i}),!a)return;let s=await tI(process.cwd()),l=Object.values(n),p=Object.values(r),d=p.filter(({id:e})=>!e5(e));return l.length>0&&(console.log(`
39
-
40
- ${aa("可用 pages 列表")}
41
- `),l.forEach(e=>{console.log(` - ${as(e.path)}`)})),d.length>0&&(console.log(`
42
- ${aa("可用 widgets 列表")}
43
- `),d.forEach(e=>{let t=as(e.id);console.log(` - ${t}`)})),s.length>0&&(console.log(`
44
- ${aa("可用调试场景")}
45
- `),s.forEach(e=>console.log(` - ${as(e.name)}`))),console.log(`
46
- ${aa("可以继续执行以下命令:")}
47
- `),al.forEach(ad),console.log("\n"),ry.instance.addListener(t=>{let n=t.trim();if("d"===n){let t=[...s.map(e=>({type:"scene",id:e.name})),...d.map(e=>({type:"widget",id:e.id})),...l.map(e=>({type:"page",id:e.path}))];if(0===t.length)return console.log(`
48
- ${aa("暂无可用的页面、组件或调试场景")}`),!0;r_(async()=>{let{selectedEntry:n}=await tl.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:e=>t.filter(t=>`${ap[t.type]} ${t.type} ${t.id}`.toLowerCase().includes(e?.toLowerCase()??"")).map(e=>({name:`${tp.gray(ap[e.type])}: ${e.id}`,short:`${ap[e.type]} \xb7 ${e.id}`,value:e}))}]);if("scene"===n.type){let t=s.find(e=>e.name===n.id);t&&await au({matchedScene:t,appId:e,driver:o})}else"widget"===n.type?o.pushWidget({appId:e,widgetId:n.id}):o.openPageUrl({appId:e,url:n.id})})}else{let t=s.find(e=>e.name===n);t?r_(async()=>{await au({matchedScene:t,appId:e,driver:o})}):p.some(e=>e.id===n)?o.pushWidget({appId:e,widgetId:n}):o.openPageUrl({appId:e,url:n})}return!0},"openPage")}async function ah({appId:e,appletUrl:t,pages:n,widgets:r,driver:o,isSigned:i,isDisposed:a}){let s=await tv();if(a())return;if(!s)return void ez.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let l=await tb(s).catch(e=>(a()||ez.error("重新启动应用失败",{error:e}),!1));if(a())return;if(!l)return void setTimeout(()=>{a()||ez.info("请确认应用已经启动。\n")},1e3);if(await new Promise(e=>{setTimeout(e,5e3)}),a())return;if(!o)return void ez.error("调试驱动尚未就绪。");let p=await am(e,t,n,r,o,i);a()&&p?.()}async function af({context:e,port:t,driver:n,isSigned:r,onCleanupReady:o}){let i,a,{host:s,artifactOrigin:l}=await e.resolveDevServer(t);e.devServerAbort.signal.throwIfAborted();let p=e.metadata.getData(),d=p.app.appId,c=async()=>{let t,n=await (t=e.webDebuggerLaunchOptions,at(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:l,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??ev(),mcpHeaders:t?.mcpHeaders,simulator:t?.simulator,eventsConfigReader:e.eventsResources?.readJson,eventsConfigSourcePath:e.eventsResources?.sourcePath,toolsConfigReader:e.toolsResources?.readToolsJson,toolsConfigSourcePath:e.toolsResources?.toolsSourcePath,simulatorManifestReader:t?.simulator?.manifestPath?void 0:e.toolsResources?.readManifestYaml,simulatorManifestSourcePath:t?.simulator?.manifestPath?void 0:e.toolsResources?.manifestSourcePath}));await n?.open()};if(e.devServerInteractive){let t;t=function(e={}){let t={name:"Doubao Apps SDK",...e},n=t.name?`${t.name} 开发服务`:"",r=t.origin?`正在监听 ${tp.gray(t.origin)}。`:"已启动。";return`
49
- ${as(n)}${r}
50
- `}(),eR()||console.clear(),console.log(t),console.log(((e,t)=>{if(e&&t){let n=[{title:"\uD83C\uDF10 服务地址",content:t},{title:"\uD83D\uDCE6 应用 ID",content:e}].map(({title:e,titleHighlighter:t,content:n})=>{let r=t?t(e):tp.bold(tp.gray(e));return` - ${tp.bgWhiteBright(tp.italic(tp.black(` ${r} `)))}: ${tp.gray(n.startsWith("http")?tp.underline(n):n)}`}).join("\n");return`
51
- ${ai("豆包应用服务信息")}:
52
-
53
- ${n}
169
+ })()));`)}},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:r})=>a4(e,t,i,r.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>nF(e,404,"未找到调试器资源")}],fallback:({request:e,response:t,url:r})=>a4(e,t,i,r.pathname,{fallbackPath:"/index.html"})};return nZ([...(u={artifactOrigin:t,webViewOrigin:e,debugScenes:r,getWidgetViewDataTemplates:a,mcpEndpoint:o,physicalDeviceDebugGateway:l,sandboxRuntime:c,simulatorAssets:p},[{match:"/__web_sdk_debug_context",handle:({request:e,response:t})=>{let r,n;return n="string"==typeof(r=e.headers.host)&&r?`http://${r}`:void 0,void nH(t,200,{homeDir:ro.homedir(),webViewOrigin:u.webViewOrigin,launchDir:u.simulatorAssets.appDirectory,debugScenesEndpoint:iP,widgetViewDataTemplatesEndpoint:iC,debuggerMcpEndpoint:n?new URL(iI,n).toString():iI,manifestOriginalUrl:new URL("/base/manifest.json",u.artifactOrigin).toString(),...u.mcpEndpoint?{mcpOriginalEndpoint:u.mcpEndpoint,mcpProxyEndpoint:ie}:{},realDeviceDebug:u.physicalDeviceDebugGateway?.getDebugContext(),...u.simulatorAssets.getDebugContext(),...u.sandboxRuntime.getDebugContext()},iR)}},{match:iP,handle:({response:e})=>nH(e,200,u.debugScenes??{errors:[],scenes:[]},iR)},{match:iC,handle:({response:e})=>i$(e,u.getWidgetViewDataTemplates)}]),...l.getRequestRoutes(),...n,...function(e={}){return[{match:e=>e.pathname===aq||e.pathname.startsWith(`${aq}/`),handle:({request:t,response:r,url:n})=>aY(t,r,n,e)}]}({getSandboxSessionId:()=>c.sessionId,targetOrigin:d}),...c.getRequestRoutes(),...function(e={}){return[{match:ie,handle:({request:t,response:r,url:n})=>(function(e,t,r={},n=nL(e)){let i=er(r.targetEndpoint);if(!n)return void nF(t,400,"Bad request");if(!i)return void nF(t,404,"MCP endpoint not configured");let a=new URL(i);for(let[e,t]of new URLSearchParams(n.search))a.searchParams.append(e,t);nY(e,t,{createResponseHeaders:nM,errorMessage:"代理 MCP 请求失败",requestHeaders:nj(e.headers,a,{...n3(),...r.headers}),targetUrl:a})})(t,r,e,n)}]}({headers:s,targetEndpoint:o}),...p.getRequestRoutes(),...m.routes],m.fallback)}({...e,webViewOrigin:a})),s=e.debuggerProtocol.attachConnection(o,e.sandboxRuntime);try{await oc(o,r)}catch(e){throw s(),await od(n),e}return{origin:`http://127.0.0.1:${r}`,server:o,webViewServer:n,closeConnections:s}}async function od(e){e.listening&&await new Promise((t,r)=>{e.close(e=>{e?r(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function ou(){if(!n)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:r,webViewServer:i,closeConnections:a}=n;n=void 0,a(),e.dispose(),t.close(),await Promise.all([od(r),od(i)])}async function om(e){let t,{targetOrigin:r,...i}=e.simulator??{},a={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...i},o=new aG(a);try{var s,l;let i,c,p=er(e.mcpEndpoint),d={appDirectory:e.appDirectory,appId:e.appId,businessTemplatesPath:o.businessTemplatesPath,env:e.env,manifestReader:e.simulatorManifestReader,manifestPath:o.manifestPath,targetOrigin:e.sandboxTargetOrigin};if(s=n,s?.server.listening){if(n?.artifactOrigin===e.artifactOrigin&&n.mcpEndpoint===p&&n.simulatorAssets.matches(a)&&n.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&n.sandboxRuntime.matches(d)&&n.simulatorTargetOrigin===r)return n;await ou()}let u={distPath:l=e.debuggerDistPath,indexPath:tn.join(l,"index.html")};if(!tP.existsSync(u.indexPath))return void nI.error("Web 模拟器资源缺失,请联系框架开发者。");let m=(i={},c=new ip(i),Object.assign([{match:"/__agent_trace",handle:e=>(function({request:e,response:t,url:r},n){let i;if("OPTIONS"===e.method){nB(t,iB),t.writeHead(204),t.end();return}"GET"!==e.method?nH(t,405,{error:"Method not allowed"},iB):nH(t,200,function(e,t){if(!e?.debug_snapshot)return e;let{debug_snapshot:r,...n}=e;return t?{...n,snapshot:r}:n}(n.snapshot,(i=r.searchParams.get("DEBUG"),null!=i&&"0"!==i&&"false"!==i.toLowerCase()))??{stored:!1},iB)})(e,i)},{match:iI,handle:e=>iO(e,i,c)}],{attachConnection:(e,t)=>{var r;let n,a,o,s;return r=e=>{var t,r;let n,a;return a=(r=t=e).snapshot.client_id??r.debug_snapshot?.client_id,n="string"==typeof a&&a.trim()?a.trim():void 0,void(t=function(e,t){let r=e?.snapshot,n=t.snapshot,i=r?.runtime_snapshot,a=n.runtime_snapshot;if(!r||!i||r.client_id!==n.client_id)return t;if(!a){var o;let e;if(o=i.target,e=function(e){let t=e.render_targets?.currentTarget;if(t)return t;let r=e.context;if(r){if(Object.hasOwn(r,"widget_id"))return{type:"widget"};if(Object.hasOwn(r,"page_id")||Object.hasOwn(r,"page_path"))return{type:"page"}}}(n),o&&e&&(1===Object.keys(e).length?e.type!==o.type:JSON.stringify(e)!==JSON.stringify(o)))return t;let{root:r,...a}=i;return{...t,snapshot:{...n,runtime_snapshot:i},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:a}}:{}}}return Object.hasOwn(a,"root")||!Object.hasOwn(i,"root")||i.updatedAtMs!==a.updatedAtMs||JSON.stringify(i.target)!==JSON.stringify(a.target)?t:{...t,snapshot:{...n,runtime_snapshot:{...a,root:i.root}}}}(n?c.getSnapshotStore(n).snapshot:i.snapshot,t),i.snapshot=t,i.updatedAtMs=Date.now(),c.noteSnapshot(n))},n=new it({noServer:!0,maxPayload:0xa00000}),a=new Set,o=(i,o,s)=>{let l,p=e.address().port,d=i.headers.host;try{l=new URL(i.url??"/","http://127.0.0.1")}catch{o.destroy();return}let u=l.searchParams.get("clientId")?.trim();d!==`127.0.0.1:${p}`&&d!==`localhost:${p}`||void 0!==i.headers.origin&&i.headers.origin!==`http://${d}`?o.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"):"/__wsd_connection"!==l.pathname||!u||u.length>128?o.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"):n.handleUpgrade(i,o,s,e=>{c.registerClient(u,e),a.add(e),e.on("pong",()=>a.add(e)),e.on("error",()=>e.close());let n=t.subscribeEvents(t=>ir(e,"sandbox",t));e.once("close",()=>{a.delete(e),n()}),e.on("message",(n,i)=>{try{let e=i?void 0:JSON.parse(n.toString());if(!K(e))throw Error("Invalid debugger message");if("snapshot"===e.type&&K(e.data)&&K(e.data.snapshot))r({...e.data,...K(e.data.debug_snapshot)?{debug_snapshot:{...e.data.debug_snapshot,client_id:u}}:{},snapshot:{...e.data.snapshot,client_id:u}});else if("control_result"===e.type&&K(e.data))c.handleResult({...e.data,clientId:u});else if("clear_sandbox_logs"===e.type)t.clearBridgeLogs();else throw Error("Unknown debugger message")}catch{e.close(1008,"Invalid debugger message")}})})},e.on("upgrade",o),(s=setInterval(()=>{for(let e of n.clients)a.delete(e)?e.ping():e.terminate()},3e4)).unref(),()=>{for(let t of(clearInterval(s),e.off("upgrade",o),n.clients))t.terminate();n.close()}},executeSandboxToolCall:e=>c.execute("execute_sandbox_tool_call",{toolCall:e})})),h=await aR.start({...d,onSimulatorToolCall:async e=>{await m.executeSandboxToolCall(e)}});t=h;let f=new iU,{origin:g,server:y,webViewServer:b,closeConnections:_}=await op({artifactOrigin:e.artifactOrigin,debugScenes:e.debugScenes,debuggerProtocol:m,distPath:u.distPath,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,mcpHeaders:e.mcpHeaders,physicalDeviceDebugGateway:f,sandboxRuntime:h,simulatorAssets:o,simulatorTargetOrigin:r}),v=()=>{y.close(),b.close()};y.once("close",()=>{process.off("exit",v)}),process.once("exit",v);let E=new URL(g).toString();return n={artifactOrigin:e.artifactOrigin,close:()=>ou(),debuggerMcpEndpoint:new URL(iI,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:p,open:()=>ol(E),origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:h,get sandboxSessionId(){return h.sessionId},server:y,webViewServer:b,closeConnections:_,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:o,simulatorTargetOrigin:r,url:E}}catch(e){t?.close(),nI.error("启动 Web SDK 调试器失败",{error:e});return}}async function oh(e,t){let r={errors:[],scenes:[]};if(!e)return r;for(let n of(await ti(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await ta(n.path);e&&function(e,t){let r=k(e);return"tool"!==r.type&&("widget"===r.type?t.widgetIds.has(r.id):0===r.unresolvedVariables.length)}(e,t)&&r.scenes.push({content:e,name:n.name})}return r}async function of(e,t){let r=e.metadata.getData(),n=e.widgets,i=await oh(e.appDirectory,{widgetIds:new Set(Object.keys(n).map(e=>t7(n,r.widgets,e)))});return om({...t,debuggerDistPath:t.debuggerDistPath??G(),debugScenes:i,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function og(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function oy(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function ob(e){og(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||e7.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let o_=e=>ec.bgHex("#9873b9")(ec.italic(ec.black(` ${e} `))),ov=e=>ec.bgBlueBright(ec.italic(ec.black(` ${e} `))),oE=e=>ec.bold(ec.blueBright(e)),ow=[{command:"d",description:"选择调试场景 / pages / widgets"},{command:"web",description:"打开 Web 模拟器"}],oS={page:"页面",scene:"调试场景",widget:"组件"};function ox(e){console.log(` ${oE(e.command.padEnd(21))} ${ec.gray(`- ${e.description}`)}`)}async function oA(e){let t=Y(e);if(0!==t.length)return await ed.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function oT({matchedScene:e,appId:t,driver:r}){let n=await ta(e.path);if(!n)return;let i=await oA(n);await to({matchedScene:e,appId:t,driver:r,variables:i},n)}async function oI(e,t,r,n,i,a,{interactive:o=!0}={}){if(await i.load({appletUrl:t,appId:e,isSigned:a}),!o)return;let s=await ti(process.cwd()),l=Object.values(r),c=Object.values(n),p=c.filter(({id:e})=>!eG(e));return l.length>0&&(console.log(`
170
+
171
+ ${ov("可用 pages 列表")}
172
+ `),l.forEach(e=>{console.log(` - ${oE(e.path)}`)})),p.length>0&&(console.log(`
173
+ ${ov("可用 widgets 列表")}
174
+ `),p.forEach(e=>{let t=oE(e.id);console.log(` - ${t}`)})),s.length>0&&(console.log(`
175
+ ${ov("可用调试场景")}
176
+ `),s.forEach(e=>console.log(` - ${oE(e.name)}`))),console.log(`
177
+ ${ov("可以继续执行以下命令:")}
178
+ `),ow.forEach(ox),console.log("\n"),nx.instance.addListener(t=>{let r=t.trim();if("d"===r){let t=[...s.map(e=>({type:"scene",id:e.name})),...p.map(e=>({type:"widget",id:e.id})),...l.map(e=>({type:"page",id:e.path}))];if(0===t.length)return console.log(`
179
+ ${ov("暂无可用的页面、组件或调试场景")}`),!0;nT(async()=>{let{selectedEntry:r}=await ed.prompt([{type:"search",name:"selectedEntry",message:"请选择调试目标:",source:e=>t.filter(t=>`${oS[t.type]} ${t.type} ${t.id}`.toLowerCase().includes(e?.toLowerCase()??"")).map(e=>({name:`${ec.gray(oS[e.type])}: ${e.id}`,short:`${oS[e.type]} \xb7 ${e.id}`,value:e}))}]);if("scene"===r.type){let t=s.find(e=>e.name===r.id);t&&await oT({matchedScene:t,appId:e,driver:i})}else"widget"===r.type?i.pushWidget({appId:e,widgetId:r.id}):i.openPageUrl({appId:e,url:r.id})})}else{let t=s.find(e=>e.name===r);t?nT(async()=>{await oT({matchedScene:t,appId:e,driver:i})}):c.some(e=>e.id===r)?i.pushWidget({appId:e,widgetId:r}):i.openPageUrl({appId:e,url:r})}return!0},"openPage")}async function oO({appId:e,appletUrl:t,pages:r,widgets:n,driver:i,isSigned:a,isDisposed:o}){let s=await e1();if(o())return;if(!s)return void e7.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");let l=await eQ(s).catch(e=>(o()||e7.error("重新启动应用失败",{error:e}),!1));if(o())return;if(!l)return void setTimeout(()=>{o()||e7.info("请确认应用已经启动。\n")},1e3);if(await new Promise(e=>{setTimeout(e,5e3)}),o())return;if(!i)return void e7.error("调试驱动尚未就绪。");let c=await oI(e,t,r,n,i,a);o()&&c?.()}async function oP({context:e,port:t,driver:r,isSigned:n,onCleanupReady:i}){let a,o,{host:s,artifactOrigin:l}=await e.resolveDevServer(t);e.devServerAbort.signal.throwIfAborted();let c=e.metadata.getData(),p=c.app.appId,d=async()=>{let t,r=await (t=e.webDebuggerLaunchOptions,of(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:l,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??tQ(),mcpHeaders:t?.mcpHeaders,simulator:t?.simulator,eventsConfigReader:e.eventsResources?.readJson,eventsConfigSourcePath:e.eventsResources?.sourcePath,toolsConfigReader:e.toolsResources?.readToolsJson,toolsConfigSourcePath:e.toolsResources?.toolsSourcePath,simulatorManifestReader:t?.simulator?.manifestPath?void 0:e.toolsResources?.readManifestYaml,simulatorManifestSourcePath:t?.simulator?.manifestPath?void 0:e.toolsResources?.manifestSourcePath}));await r?.open()};if(e.devServerInteractive){let t;t=function(e={}){let t={name:"Doubao Apps SDK",...e},r=t.name?`${t.name} 开发服务`:"",n=t.origin?`正在监听 ${ec.gray(t.origin)}。`:"已启动。";return`
180
+ ${oE(r)}${n}
181
+ `}(),eS()||console.clear(),console.log(t),console.log(((e,t)=>{if(e&&t){let r=[{title:"\uD83C\uDF10 服务地址",content:t},{title:"\uD83D\uDCE6 应用 ID",content:e}].map(({title:e,titleHighlighter:t,content:r})=>{let n=t?t(e):ec.bold(ec.gray(e));return` - ${ec.bgWhiteBright(ec.italic(ec.black(` ${n} `)))}: ${ec.gray(r.startsWith("http")?ec.underline(r):r)}`}).join("\n");return`
182
+ ${o_("豆包应用服务信息")}:
183
+
184
+ ${r}
54
185
 
55
186
  `}return`
56
- ${ai("豆包应用服务信息")}:
187
+ ${o_("豆包应用服务信息")}:
57
188
 
58
- 调试服务未运行。`})(d,s)),await ao(e)}let u=(i=!1,a=[],{add(e){e&&(i?e():a.push(e))},cleanup:()=>{i=!0,a.splice(0).forEach(e=>e())},isDisposed:()=>i});if(e.devServerInteractive){let t={context:e,appId:d,appletUrl:s,pages:p.pages,widgets:p.widgets,driver:n,isSigned:r,openWebDebugger:c,isDisposed:u.isDisposed};u.add(ry.instance.addListener(e=>{let n=e.trim().toLowerCase();return("r"===n||"web"===n)&&(process.stdout.write(U(2)),"r"===n?ah(t).catch(rb):t.openWebDebugger(),!0)},"devCommands",-1))}o(u.cleanup);try{if(!n){e.devServerInteractive&&ez.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}u.add(await am(d,s,p.pages,p.widgets,n,r,{interactive:e.devServerInteractive}))}catch(e){throw u.cleanup(),e}}let ag=(e,t,n)=>{if(!eu())return void n();let r=process.hrtime.bigint(),o=e.method,i=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-r)/1e6,n=i?new URL(i,"http://localhost").pathname:"",a=t.statusCode;ez.request({method:o||"UNKNOWN",url:n,statusCode:a,durationMs:e})}),n()},ay=new Set(["EACCES","EPERM"]),ab=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),a_=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),av=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),aw=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),aS={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 aE(e,t){if(!e||"object"!=typeof e||!(t in e))return;let n=e[t];return"string"==typeof n?n:void 0}function ax(e){if(!e||"object"!=typeof e)return[];if(Array.isArray(e.errors)&&e.errors.length>0)return e.errors;if(Array.isArray(e.stats))return e.stats.flatMap(ax);let t=e.stats&&"object"==typeof e.stats?e.stats:e;try{let e=t.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(e)?e:[]}catch{return[]}}function aA(e){return{scene:void 0,commandStartTime:e,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 aT(e,t){Object.assign(e,aA(t))}function aC(e,{scene:t,commandStartTime:n,compileStartTime:r}){let o=e.commandStartTime===n,i=e.prepareDurations,a=e.builderInitStartTime,s=e.appInfoDurationMs,l=e.appInfoMeasured;o&&void 0!==a&&(i.builderInitMs=Math.max(0,r-a)),aT(e,n),e.scene=t,e.compileStartTime=r,o&&(e.prepareDurations=i,e.appInfoDurationMs=s,e.appInfoMeasured=l)}function aI(e,t,n){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,n)}function aP(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let aO=new class{uploader;constructor(e){this.uploader=e}async report(e){try{var t,n;let r,o,i,a,s,l,p,d=e.context?.compileLifecycle;if(d){if(d.reported)return;d.reported=!0}let c="dev_initial"===e.scene||"hot_update"===e.scene?"dev":e.scene,u={appDirectory:e.appDirectory,targetAppId:function(e){try{let t=e?.appId;return an(t)?t:void 0}catch{return}}(e.context),scene:e.scene,command:c},m="failed"===e.status?{...u,status:e.status,errorStage:e.errorStage,error:ax(e.error)[0]??e.error}:{...u,status:e.status,pageCount:Object.keys(e.context.pages).length,widgetCount:Object.keys(e.context.widgets).length,securityMode:(r=e.context.signingEncryptionOptions,o=!!r?.signing.enabled,i=!!r?.encryption.enabled,o&&i?"signing_and_encryption":o?"signing":i?"encryption":"none"),durations:(t=e.context.compileLifecycle,n=e.compileEndTime,a=t.commandStartTime??n,s=t.compileStartTime??n,l=Math.min(n,Math.max(s,t.compilePhaseEndTimes.moduleProcess??n)),p=Math.min(n,Math.max(l,t.compilePhaseEndTimes.assetProcess??n)),{totalMs:n-a,prepareMs:s-a,compileMs:n-s,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-s,assetProcessMs:p-l,outputWriteMs:n-p})};await this.upload(m)}catch{}}async flush(e=3e3){try{await this.uploader?.flush?.(e)}catch{}}async upload(e){let{appDirectory:t,...n}=e;await (this.uploader??=new td).upload(function(e,t){let n={kit_compile_id:function(){let e="unknown";try{e=(0,nv.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,om.randomUUID)()}`}(),kit_compile_scene:e.scene,kit_command:e.command,kit_status:e.status,kit_version:t.kitVersion,kit_node_version:process.version,kit_os_name:process.platform,kit_run_env:t.runEnv.toLowerCase()};if(e.targetAppId&&(n.kit_appId=e.targetAppId),"success"===e.status)n.kit_page_count=e.pageCount,n.kit_widget_count=e.widgetCount,n.kit_security_mode=e.securityMode,n.kit_duration_ms_total=aP(e.durations.totalMs),n.kit_prepare_ms=aP(e.durations.prepareMs),n.kit_compile_ms=aP(e.durations.compileMs),n.kit_config_load_ms=aP(e.durations.configLoadMs),n.kit_project_scan_ms=aP(e.durations.projectScanMs),n.kit_context_bootstrap_ms=aP(e.durations.contextBootstrapMs),n.kit_app_info_ms=aP(e.durations.appInfoMs),n.kit_app_template_process_ms=aP(e.durations.appTemplateProcessMs),n.kit_view_template_process_ms=aP(e.durations.viewTemplateProcessMs),n.kit_plugin_bootstrap_ms=aP(e.durations.pluginBootstrapMs),n.kit_builder_init_ms=aP(e.durations.builderInitMs),n.kit_module_process_ms=aP(e.durations.moduleProcessMs),n.kit_asset_process_ms=aP(e.durations.assetProcessMs),n.kit_output_write_ms=aP(e.durations.outputWriteMs);else{n.kit_error_type=function(e){let t=aE(e,"code")?.toUpperCase();if(t){if(ay.has(t))return"permission_error";if(ab.has(t))return"dependency_error";if(a_.has(t))return"timeout_error";if(av.has(t))return"network_error";if(aw.has(t))return"filesystem_error"}let n="string"==typeof e?e:aE(e,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found/i.test(n))return"dependency_error";if(/permission denied|operation not permitted/i.test(n))return"permission_error";if(/timed out|timeout/i.test(n))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(n))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist/i.test(n))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error/i.test(n))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(n))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)/i.test(n))return"config_error";if(/loader/i.test(n))return"loader_error";if(/plugin/i.test(n))return"plugin_error";let r=aE(e,"name");return r&&aS[r]||"unknown_error"}(e.error),e.errorStage&&(n.kit_error_stage=e.errorStage);let o=function(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e||!("message"in e))return;let t=e.message;return"string"==typeof t?t:void 0}(e.error);if(o){var r;let e=(r=t.appDirectory,(0,oR.stripVTControlCharacters)(o).replaceAll(tC.resolve(r),"<project>").replaceAll((0,nv.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(n.kit_error_message=e)}}return{name:"kit_compile",params:n}}(n,{appDirectory:t,kitVersion:"0.3.0-rc.3",runEnv:process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL"}))}};function aD(e,t,n){n?.hasErrors()?aO.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:ax(n)[0]}):aO.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let ak=f("crypto");class a${constructor(e,t,n){this._content=t,this._hashCode=n,this.source=e}get content(){return this._content}get hashCode(){var e;return this._hashCode||(e=this.content,ak.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class aR extends a${constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=L(this._manifest,JSON.parse(t))}catch(e){}this.destination=e}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(e){this._manifest.manifestVersion=e}setRuntimeVersion(e){this._manifest.runtimeVersion=e}setPackageName(e){this._manifest.packageName=e}setVersionName(e){this._manifest.versionName=e}assignBasicManifest(e){Object.assign(this._manifest,e)}mergeBasicManifest(e){L(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){L(this._manifest.applet,e)}setRenderType(e=X.REACT_LYNX){this._manifest.renderType=e}appendWidget(e){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(e)}appendPage(e){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(e)}toString(){return JSON.stringify(this._manifest,null,2)}}class aN{constructor(){this.assets={}}addAsset(e,t){this.assets[e]=t}deleteAsset(e){delete this.assets[e]}getAsset(e){return this.assets[e]}getAssets(){return this.assets}getManifestAsset(e){return this.getAsset(e)||(this.assets[e]=new aR(e,JSON.stringify({}))),this.getAsset(e)}}class aL{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:n}=this.options;e.hooks.thisCompilation.tap({name:aL.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},r=>{r.hooks.processAssets.tapPromise({name:aL.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new aN,r.getAssets().forEach(e=>{let n=new a$(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,n)});let{entrypoints:o}=r,i={};o.forEach((e,n)=>{i[n]=e.getFiles().map(e=>{let n=t.getAsset(e);if(!n)throw Error(`Asset ${e} not found`);return new a$(n.source,n.content,n.hashCode)})});let a=this.options.context.appId;a&&tQ.mkdirSync(tC.join(this.options.context.rootPath,a),{recursive:!0}),await n.callAssetsHooks("beforeEmit",{assets:t,chunks:i}),Object.keys(t.getAssets()).forEach(n=>{let o=t.getAsset(n);if(!o)return;let{source:i,destination:a}=o;if(!i||!a)return;r.getAsset(i)?r.renameAsset(i,a):r.emitAsset(a,new e.rspack.sources.RawSource(o.content));let s=r.getAsset(`${i}.map`);s&&r.renameAsset(s.name,`${a}.map`)}),await n.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let aM=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class aj{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(aj.name,e=>{e.hooks.finishModules.tap(aj.name,()=>{let t=new Map,n=r=>{if(!r)return!1;let o=t.get(r);if(void 0!==o)return o;if(function(e){var t;let n=e.resourceResolveData?.descriptionFileData?.name;if("string"==typeof n&&aM.has(n))return!0;let r=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...aM].some(e=>r?.includes(`/node_modules/${e}/`))}(r))return t.set(r,!0),!0;for(let o of(t.set(r,!1),e.moduleGraph.getOutgoingConnections(r)))if(n(o.module))return t.set(r,!0),!0;return!1};e.entries.forEach((t,r)=>{t.dependencies.some(t=>n(e.moduleGraph.getModule(t)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(r)??r)})})})}}class aB{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(aB.name,async()=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(aB.name,e=>{e.hooks.optimizeTree.tapPromise(aB.name,async t=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.done.tapPromise(aB.name,async e=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:e})})}}function aU(e){return e.replaceAll("\\","/")}function aF(e,t,n,r=`${t}.map`){return t!==n&&!!e.getAsset(t)&&(e.renameAsset(t,n),e.getAsset(r)&&e.renameAsset(r,`${n}.map`),!0)}class aH{context;constructor(e){this.context=e}apply(e){e.hooks.thisCompilation.tap(aH.name,t=>{t.hooks.processAssets.tapPromise({name:aH.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var e,n;let r=this.context.metadata.getData(),o=this.context.command===eD.DEV?"all":"configured",i=nh(this.context.pages,this.context.normalizedAppConfig.pages.entries,o),a=nh(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,o),s=r.app.appId||this.context.appId;if(!s&&Object.keys(i).length>0)throw Error("appId is required to resolve Web page entry paths");s&&(e=r.pages,Object.keys(i).forEach(n=>{let r=aU(n),o=nc(r);aF(t,`${o}/template.js`,t5(s,e[n]?.path??t4(r),nl),`${o}/background.js.map`)})),n=r.widgets,Object.keys(a).forEach(e=>{var r;let o=nc(aU(e));aF(t,`${o}/template.js`,(r=nu(a,n,e),`${r}/${nl}`),`${o}/background.js.map`)})})})}}class aW{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(aW.name,()=>{t.writeModule(eo,""),t.writeModule(el,ex),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function aV(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let aG={templatesByEntry:{},templatesByWidget:{}},aq="/doubao-apps-framework.template.js",aJ="/doubao-apps-api.template.js",aK=(e,t)=>{let n=(e,n,r)=>({libraryName:r,url:t?`/wsd${e}`:e,background:{sectionPath:n},mainThread:{sectionPath:`${n}__main-thread`},async:!!t});return{"@byted-doubao-apps/bridge-base":n(aJ,"api"),"@byted-doubao-apps/open-api":n(aJ,"api"),...Object.fromEntries(Object.entries(eP).map(([t,r])=>[t,n(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",r])])),[ts(eZ)]:n(aJ,"api"),[ts(e3)]:n(aJ,"api"),[eZ]:n(aq,"framework"),[e3]:n(aq,"framework"),"@byted-doubao-apps/components":n(aq,"components"),[tr(eZ)]:n(aq,"components"),[tr(e3)]:n(aq,"components")}},az=f("node:url"),aY=(0,W.createRequire)(import.meta.url);function aX(e,t){for(let n of e)try{return aY.resolve(n,{paths:t})}catch{}throw Error(`Cannot resolve package from candidates: ${e.join(", ")}`)}class aZ{pluginSystem;constructor(e){this.pluginSystem=e}async createEntry(){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return e}async createConfig({config:e}){var t,n,r,o,i;let{appDirectory:a,command:p,metadata:h,rootPath:f}=e.context,g=e.context.environment,y=e8();await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:g}),e.context.setEnvironment(g);let b=p===eD.DEV,_=await this.createEntry(),v=eO(a),w=[a,tC.dirname((0,az.fileURLToPath)(import.meta.url))],S=aY.resolve("@lynx-js/react/transform"),E=b?"all":"configured",x=nh(e.context.pages,e.context.normalizedAppConfig.pages.entries,E),A=new Set([...Object.keys(nh(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,E)),...Object.keys(x)]),T=A.size>0;T&&await rd({widgets:e.context.widgets,pages:e.context.pages,entries:_,collector:h,normalizedAppConfig:e.context.normalizedAppConfig,define:e.context.userConfig?.source?.define});let C={include:e.options.source?.include,exclude:e.options.source?.exclude,decorators:e.options.source?.decorators,define:{...e.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(e.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},I=e=>[eo,el,e.filename],P={...C,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,I(t)]))},O=Object.fromEntries(Object.entries(_).filter(([e])=>A.has(e))),D=new Map(Object.keys(O).map(e=>[nc(e),e])),$={...P,entry:Object.fromEntries(Object.entries(O).map(([e,t])=>[nc(e),I(t)])),define:{...P.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},R=[...ed()?[]:[H({externals:aK(b),globalObject:"lynx"})]],N=[function({metadata:e,resolveAppInfo:t}){return{name:"ai-manifest-plugin",setup(n){n.modifyBundlerChain((n,r)=>{let o=r?.environment?.name==="web"?na:ni;n.plugin(ns.name).use(ns,[{metadata:e,resolveAppInfo:t,shouldInjectAsset:o}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo()})],L={source:P,plugins:R},M=[function e({metadata:t,entry:n,resolveSigningEncryptionOptions:r,onProcessDuration:o}){return{name:e.name,setup(e){e.modifyBundlerChain((i,a)=>{if(a?.environment?.name==="web")return;let s=e.useExposed(Symbol.for("LynxTemplatePlugin"));i.plugin(rg.name).use(rg,[s.LynxTemplatePlugin,t,n,r,o])})}}}({metadata:h,entry:_,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(e.context.compileLifecycle.viewTemplateProcessDurationMs,t)}}),function({context:e,normalizeEntryName:t}){return{name:"template-widget-entry-plugin",setup(n){n.modifyBundlerChain((n,r)=>{let o=r?.environment?.name;n.plugin("template-widget-entry-plugin").use(aj,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,o)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?D.get(e):e}),(t=this.pluginSystem,n=e.context,{name:"output-plugin",setup(e){let r={pluginSystem:t,context:n};e.modifyBundlerChain((e,t)=>{t?.environment?.name!=="web"&&e.plugin("output-plugin").use(aL,[r])})}}),...p===eD.DEV&&T?[function({context:e}){let t;return e.getWidgetViewDataTemplates=async()=>{if(t)return t;try{t=function(e,t,n){let r=function(e){let t,n=(0,W.createRequire)(tC.join(e,"package.json"));try{t=n.resolve("typescript")}catch(e){return}return n(t)}(e);if(!r)return{templatesByEntry:{},templatesByWidget:{}};let o=[...new Set(Object.values(t).map(({filename:e})=>e))],i=r.createProgram({options:function(e,t){let n={allowJs:!0,checkJs:!1,jsx:e.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:e.ScriptTarget.ESNext},r=e.findConfigFile(t,tQ.existsSync);if(!r)return n;let o=e.readConfigFile(r,e.sys.readFile);return o.error?n:{...e.parseJsonConfigFileContent(o.config,e.sys,tC.dirname(r)).options,...n}}(r,e),rootNames:o}),a=i.getTypeChecker(),s=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let n,o=i.getSourceFile(t);return[Q(e),o?(n={},!function e(t){if(r.isCallExpression(t)&&("getViewData"===aV(r,t.expression)||"useViewData"===aV(r,t.expression))&&t.typeArguments?.[0]){let e=a.getTypeFromTypeNode(t.typeArguments[0]);for(let o of a.getPropertiesOfType(e)){let i=o.valueDeclaration??o.declarations?.[0]??t;n[o.getName()]=function e(t,n,r,o,i){let a=(n.isUnion()?n.types:[n]).filter(e=>!(e.flags&(t.TypeFlags.Undefined|t.TypeFlags.Never)));if(a.some(e=>e.flags&t.TypeFlags.Null))return null;if(a.some(e=>e.flags&t.TypeFlags.StringLike))return"";if(a.some(e=>e.flags&(t.TypeFlags.NumberLike|t.TypeFlags.BigIntLike)))return 0;if(a.some(e=>e.flags&t.TypeFlags.BooleanLike))return!1;if(a.some(e=>r.isArrayType(e)||r.isTupleType(e)))return[];let s=a.find(e=>e.flags&t.TypeFlags.Object);if(!s||i.has(s))return{};i.add(s);let l=Object.fromEntries(r.getPropertiesOfType(s).map(n=>{let a=n.valueDeclaration??n.declarations?.[0]??o;return[n.getName(),e(t,r.getTypeOfSymbolAtLocation(n,a),r,a,i)]}));return i.delete(s),l}(r,a.getTypeOfSymbolAtLocation(o,i),a,i,new Set([e]))}}r.forEachChild(t,e)}(o),n):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let r=Q(e);return[nu(t,n,e),s[r]??{}]}));return{templatesByEntry:s,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=aG}return t},{name:"WidgetViewDataPlugin",setup(e){e.onAfterDevCompile(({stats:e})=>{e.hasErrors()||(t=void 0)})}}}({context:e.context})]:[],(({context:e})=>({name:"DevServerLogPlugin",setup(t){let n,r=!1,o=!1;t.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{setup({server:e}){e.middlewares.use(ag)}}})),t.onAfterCreateCompiler(({compiler:t})=>{for(let n of"compilers"in t?t.compilers:[t])n.hooks.failed.tap("DevServerLogPlugin",t=>e.finishInitialDevCompile(t))}),t.onAfterDevCompile(async({stats:i})=>{if(i.hasErrors())return void e.finishInitialDevCompile(Error(i.toString({all:!1,errors:!0,colors:!1})));if(r)return;let{devServer:a}=t.context;if(!a)return;r=!0;let s=await tA({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(rb);o||(e.finishInitialDevCompile(),af({context:e,port:a.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){o?e():n=e}}).catch(e=>{o||ez.error("Failed to initialize dev server actions",{error:e})}))}),t.onCloseDevServer(()=>{o=!0,e.devServerAbort.abort(),n?.(),n=void 0})}}))({context:e.context}),function({context:e}){let t="KitMonitorPlugin";return{name:t,setup(n){if(n.onAfterCreateCompiler(({compiler:n})=>{for(let r of"compilers"in n?n.compilers:[n])r.hooks.finishMake.tap(t,()=>{aI(e.compileLifecycle,"moduleProcess",Date.now())}),r.hooks.emit.tap(t,()=>{aI(e.compileLifecycle,"assetProcess",Date.now())}),r.hooks.failed.tap(t,t=>{aO.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===eD.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==eD.DEV){let t=e.command;n.onBeforeBuild(()=>{let n=Date.now();aC(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??n,compileStartTime:n})}),n.onAfterBuild(({stats:n})=>{aD(e,t,n)})}else n.onBeforeDevCompile(({isFirstCompile:t})=>{let n=Date.now();aC(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??n:n,compileStartTime:n})}),n.onAfterDevCompile(({stats:t})=>{aD(e,e.compileLifecycle.scene??"dev_initial",t)})}}}({context:e.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(e){e.onBeforeCreateCompiler(({bundlerConfigs:e})=>{let{BytedRsdoctorPlugin:t}=aY(aX(["@byted/rsdoctor"],w));for(let n of e){let e=tC.join(n.output?.path??"",`.rsdoctor-${n.name}`);n.plugins??=[],n.plugins.push(new t({disableClientServer:!0,supports:{banner:!0},output:{reportDir:e}}))}})}}]:[],(r=this.pluginSystem,o=e.context,{name:"view-hooks-plugin",setup(e){e.modifyBundlerChain((e,t)=>{t?.environment?.name==="web"||e.plugin("view-hooks-plugin").use(aB,[{pluginSystem:r,context:o}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:n,metadata:r,resolveSigningEncryptionOptions:o,onProcessDuration:i})=>({name:"lynx:encode-worker",async setup(a){eg()||a.modifyBundlerChain((a,s)=>{s?.environment?.name!=="web"&&a.plugin(rf.name).use(rf,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:n,metadata:r,resolveSigningEncryptionOptions:o,onProcessDuration:i}]).end()})}}))({getAppAssetPath:()=>e.context.appAssetPath,getAppMapAssetPath:()=>e.context.appMapAssetPath,metadata:e.context.metadata,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.appTemplateProcessDurationMs+=t}}),...e.rsbuildPlugins||[]],j=[{name:"web-virtual-entry-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(aW.name).use(aW,[O])})}},(i=e.context,{name:"web-output-plugin",setup(e){e.modifyBundlerChain({order:"post",handler(e,{environment:t}){if("web"===t.name){let t=".rspeedy/";for(let n of Object.keys(e.plugins.entries()??{}))n.startsWith("lynx:template-")&&e.plugin(n).tap(e=>{let n=e[0];return n?.intermediate?.startsWith(t)&&(n.intermediate=n.intermediate.slice(t.length)),e});e.plugins.has("lynx:sourcemap")&&e.plugin("lynx:sourcemap").tap(e=>{var t;let n,r=e[0];return r.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],t=i.appDirectory,n=tC.resolve(t),r.moduleFilenameTemplate=({absoluteResourcePath:e,query:t=""})=>{let r=tC.relative(n,e),o=".."!==r&&!r.startsWith(`..${tC.sep}`)&&!tC.isAbsolute(r),i=o?aU(r):aU(e).replace(/^\/+/,"");return`${o?"file":"webpack"}:///${i}${t}`},e}),e.plugin(aH.name).use(aH,[i])}}})}})],B=d({mode:p===eD.DEV?"development":"production",environments:T?{lynx:L,web:{source:$,output:{distPath:{css:"",js:"base/web-common"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!b&&"cheap-module-source-map",css:!1}},plugins:[H({externals:aK(p===eD.DEV,!0),globalObject:"lynx"})]}}:{lynx:L},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,n=tC.join(tC.dirname((0,az.fileURLToPath)(import.meta.url)),"components-loader.js"),r=aX){let o=t===e3?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"];try{return r(o,e)}catch(e){if((0,tQ.existsSync)(n))return n;throw e}}(w,v),options:{frameworkPackage:v}}]},plugins:[new c.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:c.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...C,entry:{}},server:{cors:!0,host:e.context.devServerHost},dev:{writeToDisk:eu(),hmr:p===eD.DEV},output:{distPath:{js:"base/common",root:f||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...e.options.resolve?.alias||{}}},performance:{printFileSize:eu(),...ed()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){k({LAYERS:s,lazy:!1,rootPath:tC.dirname((0,az.fileURLToPath)(import.meta.url))}).setup(e)}},{name:"set-server.printUrls-false",setup(e){e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{printUrls:!1}}))}},l({compat:{componentsPkg:[],newRuntimePkg:v,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...e7]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(e){e.modifyBundlerChain((e,{CHAIN_ID:t})=>{let n=e.module.rule(t.RULE.JS).oneOf(t.ONE_OF.JS_MAIN);for(let e of[s.BACKGROUND,s.MAIN_THREAD]){let t=n.oneOfs.get(e)?.uses.get(e);if(!t)throw Error(`React transform loader not found for layer: ${e}`);t.tap(e=>({...e,transformPath:S}))}})}},function(e){let{compilerOptionsKeys:t=nS.compilerOptionsKeys,configKeys:n=nS.configKeys,validate:r=n9,dslPluginName2PkgName:o=n8,upgradeRspeedyLink:i="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return r(e),{name:"lynx:config",async setup(r){r.expose(Symbol.for("lynx.config"),{config:e}),r.modifyBundlerChain(a=>{let s=r.useExposed(Symbol.for("LynxTemplatePlugin"));if(!s){let e="Rspeedy and plugins";throw Object.entries(o).forEach(([t,n])=>{r.isPluginExists(t)&&(e=n)}),Error(`\
59
- [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${nX("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
189
+ 调试服务未运行。`})(p,s)),await ob(e)}let u=(a=!1,o=[],{add(e){e&&(a?e():o.push(e))},cleanup:()=>{a=!0,o.splice(0).forEach(e=>e())},isDisposed:()=>a});if(e.devServerInteractive){let t={context:e,appId:p,appletUrl:s,pages:c.pages,widgets:c.widgets,driver:r,isSigned:n,openWebDebugger:d,isDisposed:u.isDisposed};u.add(nx.instance.addListener(e=>{let r=e.trim().toLowerCase();return("r"===r||"web"===r)&&(process.stdout.write(V(2)),"r"===r?oO(t).catch(nA):t.openWebDebugger(),!0)},"devCommands",-1))}i(u.cleanup);try{if(!r){e.devServerInteractive&&e7.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}u.add(await oI(p,s,c.pages,c.widgets,r,n,{interactive:e.devServerInteractive}))}catch(e){throw u.cleanup(),e}}let oC=(e,t,r)=>{if(!eS())return void r();let n=process.hrtime.bigint(),i=e.method,a=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-n)/1e6,r=a?new URL(a,"http://localhost").pathname:"",o=t.statusCode;e7.request({method:i||"UNKNOWN",url:r,statusCode:o,durationMs:e})}),r()},oR=new Set(["EACCES","EPERM"]),o$=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),ok=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),oN=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),oL=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),oD={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 oj(e,t){if(!e||"object"!=typeof e||!(t in e))return;let r=e[t];return"string"==typeof r?r:void 0}function oM(e){if(!e||"object"!=typeof e)return[];if(Array.isArray(e.errors)&&e.errors.length>0)return e.errors;if(Array.isArray(e.stats))return e.stats.flatMap(oM);let t=e.stats&&"object"==typeof e.stats?e.stats:e;try{let e=t.toJson?.({all:!1,errors:!0}).errors;return Array.isArray(e)?e:[]}catch{return[]}}function oU(e){return{scene:void 0,commandStartTime:e,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 oB(e,t){Object.assign(e,oU(t))}function oF(e,{scene:t,commandStartTime:r,compileStartTime:n}){let i=e.commandStartTime===r,a=e.prepareDurations,o=e.builderInitStartTime,s=e.appInfoDurationMs,l=e.appInfoMeasured;i&&void 0!==o&&(a.builderInitMs=Math.max(0,n-o)),oB(e,r),e.scene=t,e.compileStartTime=n,i&&(e.prepareDurations=a,e.appInfoDurationMs=s,e.appInfoMeasured=l)}function oH(e,t,r){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,r)}function oW(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let oG=new class{uploader;constructor(e){this.uploader=e}async reportEvent(e){try{await (this.uploader??=new ep).upload({name:e.name,params:{...e.params,kit_version:"0.5.0-rc.3",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(e){try{var t,r;let n,i,a,o,s,l,c,p=e.context?.compileLifecycle;if(p){if(p.reported)return;p.reported=!0}let d="dev_initial"===e.scene||"hot_update"===e.scene?"dev":e.scene,u={appDirectory:e.appDirectory,targetAppId:function(e){try{let t=e?.appId;return og(t)?t:void 0}catch{return}}(e.context),scene:e.scene,command:d},m="failed"===e.status?{...u,status:e.status,errorStage:e.errorStage,error:oM(e.error)[0]??e.error}:{...u,status:e.status,pageCount:Object.keys(e.context.pages).length,widgetCount:Object.keys(e.context.widgets).length,securityMode:(n=e.context.signingEncryptionOptions,i=!!n?.signing.enabled,a=!!n?.encryption.enabled,i&&a?"signing_and_encryption":i?"signing":a?"encryption":"none"),durations:(t=e.context.compileLifecycle,r=e.compileEndTime,o=t.commandStartTime??r,s=t.compileStartTime??r,l=Math.min(r,Math.max(s,t.compilePhaseEndTimes.moduleProcess??r)),c=Math.min(r,Math.max(l,t.compilePhaseEndTimes.assetProcess??r)),{totalMs:r-o,prepareMs:s-o,compileMs:r-s,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-s,assetProcessMs:c-l,outputWriteMs:r-c})};await this.upload(m)}catch{}}async flush(e=3e3){try{await this.uploader?.flush?.(e)}catch{}}async upload(e){let{appDirectory:t,...r}=e;await this.reportEvent(function(e,t){let r={kit_compile_id:function(){let e="unknown";try{e=(0,ro.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,ik.randomUUID)()}`}(),kit_compile_scene:e.scene,kit_command:e.command,kit_status:e.status};if(e.targetAppId&&(r.kit_appId=e.targetAppId),"success"===e.status)r.kit_page_count=e.pageCount,r.kit_widget_count=e.widgetCount,r.kit_security_mode=e.securityMode,r.kit_duration_ms_total=oW(e.durations.totalMs),r.kit_prepare_ms=oW(e.durations.prepareMs),r.kit_compile_ms=oW(e.durations.compileMs),r.kit_config_load_ms=oW(e.durations.configLoadMs),r.kit_project_scan_ms=oW(e.durations.projectScanMs),r.kit_context_bootstrap_ms=oW(e.durations.contextBootstrapMs),r.kit_app_info_ms=oW(e.durations.appInfoMs),r.kit_app_template_process_ms=oW(e.durations.appTemplateProcessMs),r.kit_view_template_process_ms=oW(e.durations.viewTemplateProcessMs),r.kit_plugin_bootstrap_ms=oW(e.durations.pluginBootstrapMs),r.kit_builder_init_ms=oW(e.durations.builderInitMs),r.kit_module_process_ms=oW(e.durations.moduleProcessMs),r.kit_asset_process_ms=oW(e.durations.assetProcessMs),r.kit_output_write_ms=oW(e.durations.outputWriteMs);else{r.kit_error_type=function(e){let t=oj(e,"code")?.toUpperCase();if(t){if(oR.has(t))return"permission_error";if(o$.has(t))return"dependency_error";if(ok.has(t))return"timeout_error";if(oN.has(t))return"network_error";if(oL.has(t))return"filesystem_error"}let r="string"==typeof e?e:oj(e,"message")??"";if(/cannot find module|can't resolve|cannot resolve|module not found|package .+ not found|无法解析以下候选包/i.test(r))return"dependency_error";if(/permission denied|operation not permitted/i.test(r))return"permission_error";if(/timed out|timeout/i.test(r))return"timeout_error";if(/connection (?:refused|reset)|getaddrinfo|network error|socket hang up|unable to connect/i.test(r))return"network_error";if(/no such file|file does not exist|not a directory|directory does not exist|配置的入口文件不存在/i.test(r))return"filesystem_error";if(/syntax\s*error|syntaxerror|unexpected token|failed to parse|pars(?:e|ing) error|解析 (?:tools\.json|manifest\.yaml) 失败/i.test(r))return"syntax_error";if(/\bTS\d{4}:|\btype\s*error\b|\btypeerror\b/i.test(r))return"type_error";if(/appId is required|entry config|invalid config|configuration (?:is )?(?:invalid|missing)|入口配置|(?:需要|提供) appId/i.test(r))return"config_error";if(/loader|加载器/i.test(r))return"loader_error";if(/plugin/i.test(r))return"plugin_error";let n=oj(e,"name");return n&&oD[n]||"unknown_error"}(e.error),e.errorStage&&(r.kit_error_stage=e.errorStage);let i=function(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e||!("message"in e))return;let t=e.message;return"string"==typeof t?t:void 0}(e.error);if(i){var n;let e=(n=t.appDirectory,(0,iZ.stripVTControlCharacters)(i).replaceAll(tn.resolve(n),"<project>").replaceAll((0,ro.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(r.kit_error_message=e)}}return{name:"kit_compile",params:r}}(r,{appDirectory:t}))}};function oV(e,t,r){r?.hasErrors()?oG.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:oM(r)[0]}):oG.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let oq=f("crypto");class oJ{constructor(e,t,r){this._content=t,this._hashCode=r,this.source=e}get content(){return this._content}get hashCode(){var e;return this._hashCode||(e=this.content,oq.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class oz extends oJ{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=ea(this._manifest,JSON.parse(t))}catch(e){}this.destination=e}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(e){this._manifest.manifestVersion=e}setRuntimeVersion(e){this._manifest.runtimeVersion=e}setPackageName(e){this._manifest.packageName=e}setVersionName(e){this._manifest.versionName=e}assignBasicManifest(e){Object.assign(this._manifest,e)}mergeBasicManifest(e){ea(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){ea(this._manifest.applet,e)}setRenderType(e=H.REACT_LYNX){this._manifest.renderType=e}appendWidget(e){this._manifest.widgets||(this._manifest.widgets=[]),this._manifest.widgets.push(e)}appendPage(e){this._manifest.applet.pages||(this._manifest.applet.pages=[]),this._manifest.applet.pages.push(e)}toString(){return JSON.stringify(this._manifest,null,2)}}class oK{constructor(){this.assets={}}addAsset(e,t){this.assets[e]=t}deleteAsset(e){delete this.assets[e]}getAsset(e){return this.assets[e]}getAssets(){return this.assets}getManifestAsset(e){return this.getAsset(e)||(this.assets[e]=new oz(e,JSON.stringify({}))),this.getAsset(e)}}class oY{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:r}=this.options;e.hooks.thisCompilation.tap({name:oY.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},n=>{n.hooks.processAssets.tapPromise({name:oY.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new oK,n.getAssets().forEach(e=>{let r=new oJ(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,r)});let{entrypoints:i}=n,a={};i.forEach((e,r)=>{a[r]=e.getFiles().map(e=>{let r=t.getAsset(e);if(!r)throw Error(`未找到构建产物 ${e}`);return new oJ(r.source,r.content,r.hashCode)})});let o=this.options.context.appId;o&&tP.mkdirSync(tn.join(this.options.context.rootPath,o),{recursive:!0}),await r.callAssetsHooks("beforeEmit",{assets:t,chunks:a}),Object.keys(t.getAssets()).forEach(r=>{let i=t.getAsset(r);if(!i)return;let{source:a,destination:o}=i;if(!a||!o)return;n.getAsset(a)?n.renameAsset(a,o):n.emitAsset(o,new e.rspack.sources.RawSource(i.content));let s=n.getAsset(`${a}.map`);s&&n.renameAsset(s.name,`${o}.map`)}),await r.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let oX=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class oZ{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(oZ.name,e=>{e.hooks.finishModules.tap(oZ.name,()=>{let t=new Map,r=n=>{if(!n)return!1;let i=t.get(n);if(void 0!==i)return i;if(function(e){var t;let r=e.resourceResolveData?.descriptionFileData?.name;if("string"==typeof r&&oX.has(r))return!0;let n=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...oX].some(e=>n?.includes(`/node_modules/${e}/`))}(n))return t.set(n,!0),!0;for(let i of(t.set(n,!1),e.moduleGraph.getOutgoingConnections(n)))if(r(i.module))return t.set(n,!0),!0;return!1};e.entries.forEach((t,n)=>{t.dependencies.some(t=>r(e.moduleGraph.getModule(t)))&&this.options.markTemplateWidgetEntry(this.options.normalizeEntryName?.(n)??n)})})})}}class oQ{options;constructor(e){this.options=e}apply(e){e.hooks.make.tapPromise(oQ.name,async()=>{await this.options.pluginSystem.callViewHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(oQ.name,e=>{e.hooks.optimizeTree.tapPromise(oQ.name,async t=>{await this.options.pluginSystem.callViewHooks("build",{metadata:this.options.context.metadata,fileDependencies:e.fileDependencies})})}),e.hooks.done.tapPromise(oQ.name,async e=>{await this.options.pluginSystem.callViewHooks("afterBuild",{stats:e})})}}function o0(e){return e.replaceAll("\\","/")}function o1(e,t,r,n=`${t}.map`){return t!==r&&!!e.getAsset(t)&&(e.renameAsset(t,r),e.getAsset(n)&&e.renameAsset(n,`${r}.map`),!0)}class o2{context;constructor(e){this.context=e}apply(e){e.hooks.thisCompilation.tap(o2.name,t=>{t.hooks.processAssets.tapPromise({name:o2.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{var e,r;let n=this.context.metadata.getData(),i=this.context.command===rb.DEV?"all":"configured",a=re(this.context.pages,this.context.normalizedAppConfig.pages.entries,i),o=re(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,i),s=n.app.appId||this.context.appId;if(!s&&Object.keys(a).length>0)throw Error("解析 Web 页面入口路径需要 appId");s&&(e=n.pages,Object.keys(a).forEach(r=>{let n=o0(r),i=t8(n);o1(t,`${i}/template.js`,tL(s,e[r]?.path??tN(n),t4),`${i}/background.js.map`)})),r=n.widgets,Object.keys(o).forEach(e=>{var n;let i=t8(o0(e));o1(t,`${i}/template.js`,(n=t7(o,r,e),`${n}/${t4}`),`${i}/background.js.map`)})})})}}class o3{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(o3.name,()=>{t.writeModule(ek,""),t.writeModule(eN,eL),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function o4(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let o5={templatesByEntry:{},templatesByWidget:{}},o9="/doubao-apps-framework.template.js",o8="/doubao-apps-api.template.js",o7=(e,t)=>{let r=(e,r,n)=>({libraryName:n,url:t?`/wsd${e}`:e,background:{sectionPath:r},mainThread:{sectionPath:`${r}__main-thread`},async:!!t});return{"@byted-doubao-apps/bridge-base":r(o8,"api"),"@byted-doubao-apps/open-api":r(o8,"api"),...Object.fromEntries(Object.entries(eH).map(([t,n])=>[t,r(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",n])])),[`${tM}/api`]:r(o8,"api"),[`${tU}/api`]:r(o8,"api"),[tM]:r(o9,"framework"),[tU]:r(o9,"framework"),"@byted-doubao-apps/components":r(o9,"components"),[tF(tM)]:r(o9,"components"),[tF(tU)]:r(o9,"components")}},o6=f("node:url"),se=(0,A.createRequire)(import.meta.url);function st(e,t){for(let r of e)try{return se.resolve(r,{paths:t})}catch{}throw Error(`无法解析以下候选包:${e.join(", ")}`)}class sr{pluginSystem;constructor(e){this.pluginSystem=e}async createEntry(){let{entry:e}=await this.pluginSystem.callViewHooks("modifyEntryOption",{entry:{}});return e}async createConfig({config:e}){var t,r,n,i,a;let{appDirectory:o,command:c,metadata:h,rootPath:f}=e.context,g=e.context.environment,y="1"===process.env.ENABLE_SELF_CONTAINED;await this.pluginSystem.callViewHooks("modifyEnvironment",{environment:g}),e.context.setEnvironment(g);let b=c===rb.DEV,_=await this.createEntry(),v=tW(o),E=[o,tn.dirname((0,o6.fileURLToPath)(import.meta.url))],w=se.resolve("@lynx-js/react/transform"),S=b?"all":"configured",x=re(e.context.pages,e.context.normalizedAppConfig.pages.entries,S),T=new Set([...Object.keys(re(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,S)),...Object.keys(x)]),I=T.size>0;I&&await ny({widgets:e.context.widgets,pages:e.context.pages,entries:_,collector:h,normalizedAppConfig:e.context.normalizedAppConfig,define:e.context.userConfig?.source?.define});let O={include:e.options.source?.include,exclude:e.options.source?.exclude,decorators:e.options.source?.decorators,define:{...e.options.source?.define,__DOUBAO__:JSON.stringify(!0),__MAIN_PROCESS__:JSON.stringify(!1),__DOUBAO_APPS_WEB__:JSON.stringify(!1),__VERSION_TAG__:JSON.stringify(e.context.versionTag)??"undefined",__LEPUS__:JSON.stringify(!1),"process.env":"({})"}},P=e=>[ek,eN,e.filename],C={...O,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,P(t)]))},R=Object.fromEntries(Object.entries(_).filter(([e])=>T.has(e))),k=new Map(Object.keys(R).map(e=>[t8(e),e])),N={...C,entry:Object.fromEntries(Object.entries(R).map(([e,t])=>[t8(e),P(t)])),define:{...C.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},L=[...tX()?[]:[r8({externals:o7(b),globalObject:"lynx"})]],D=[function({metadata:e,resolveAppInfo:t,resolveVersionTag:r}){return{name:"ai-manifest-plugin",setup(n){n.modifyBundlerChain((n,i)=>{let a=i?.environment?.name==="web"?t2:t1;n.plugin(t3.name).use(t3,[{metadata:e,resolveAppInfo:t,resolveVersionTag:r,isNative:i?.environment?.name!=="web",shouldInjectAsset:a}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo(),resolveVersionTag:()=>e.context.versionTag})],j={source:{...C,define:{...C.define,...tX()?{__DOUBAO_APPS_SDK_VERSION__:JSON.stringify(se(se.resolve(`${v}/package.json`,{paths:[o]})).version)}:{}}},plugins:L},M=[function e({metadata:t,entry:r,resolveSigningEncryptionOptions:n,onProcessDuration:i}){return{name:e.name,setup(e){e.modifyBundlerChain((a,o)=>{if(o?.environment?.name==="web")return;let s=e.useExposed(Symbol.for("LynxTemplatePlugin"));a.plugin(nS.name).use(nS,[s.LynxTemplatePlugin,t,r,n,i])})}}}({metadata:h,entry:_,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.viewTemplateProcessDurationMs=Math.max(e.context.compileLifecycle.viewTemplateProcessDurationMs,t)}}),function({context:e,normalizeEntryName:t}){return{name:"template-widget-entry-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name;r.plugin("template-widget-entry-plugin").use(oZ,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,i)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?k.get(e):e}),(t=this.pluginSystem,r=e.context,{name:"output-plugin",setup(e){let n={pluginSystem:t,context:r};e.modifyBundlerChain((e,t)=>{t?.environment?.name!=="web"&&e.plugin("output-plugin").use(oY,[n])})}}),...c===rb.DEV&&I?[function({context:e}){let t;return e.getWidgetViewDataTemplates=async()=>{if(t)return t;try{t=function(e,t,r){let n=function(e){let t,r=(0,A.createRequire)(tn.join(e,"package.json"));try{t=r.resolve("typescript")}catch(e){return}return r(t)}(e);if(!n)return{templatesByEntry:{},templatesByWidget:{}};let i=[...new Set(Object.values(t).map(({filename:e})=>e))],a=n.createProgram({options:function(e,t){let r={allowJs:!0,checkJs:!1,jsx:e.JsxEmit.Preserve,noEmit:!0,skipLibCheck:!0,target:e.ScriptTarget.ESNext},n=e.findConfigFile(t,tP.existsSync);if(!n)return r;let i=e.readConfigFile(n,e.sys.readFile);return i.error?r:{...e.parseJsonConfigFileContent(i.config,e.sys,tn.dirname(n)).options,...r}}(n,e),rootNames:i}),o=a.getTypeChecker(),s=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let r,i=a.getSourceFile(t);return[$(e),i?(r={},!function e(t){if(n.isCallExpression(t)&&("getViewData"===o4(n,t.expression)||"useViewData"===o4(n,t.expression))&&t.typeArguments?.[0]){let e=o.getTypeFromTypeNode(t.typeArguments[0]);for(let i of o.getPropertiesOfType(e)){let a=i.valueDeclaration??i.declarations?.[0]??t;r[i.getName()]=function e(t,r,n,i,a){let o=(r.isUnion()?r.types:[r]).filter(e=>!(e.flags&(t.TypeFlags.Undefined|t.TypeFlags.Never)));if(o.some(e=>e.flags&t.TypeFlags.Null))return null;if(o.some(e=>e.flags&t.TypeFlags.StringLike))return"";if(o.some(e=>e.flags&(t.TypeFlags.NumberLike|t.TypeFlags.BigIntLike)))return 0;if(o.some(e=>e.flags&t.TypeFlags.BooleanLike))return!1;if(o.some(e=>n.isArrayType(e)||n.isTupleType(e)))return[];let s=o.find(e=>e.flags&t.TypeFlags.Object);if(!s||a.has(s))return{};a.add(s);let l=Object.fromEntries(n.getPropertiesOfType(s).map(r=>{let o=r.valueDeclaration??r.declarations?.[0]??i;return[r.getName(),e(t,n.getTypeOfSymbolAtLocation(r,o),n,o,a)]}));return a.delete(s),l}(n,o.getTypeOfSymbolAtLocation(i,a),o,a,new Set([e]))}}n.forEachChild(t,e)}(i),r):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let n=$(e);return[t7(t,r,e),s[n]??{}]}));return{templatesByEntry:s,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=o5}return t},{name:"WidgetViewDataPlugin",setup(e){e.onAfterDevCompile(({stats:e})=>{e.hasErrors()||(t=void 0)})}}}({context:e.context})]:[],(({context:e})=>({name:"DevServerLogPlugin",setup(t){let r,n=!1,i=!1;t.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{setup({server:e}){e.middlewares.use(oC)}}})),t.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DevServerLogPlugin",t=>e.finishInitialDevCompile(t))}),t.onAfterDevCompile(async({stats:a})=>{if(a.hasErrors())return void e.finishInitialDevCompile(Error(a.toString({all:!1,errors:!0,colors:!1})));if(n)return;let{devServer:o}=t.context;if(!o)return;n=!0;let s=await tt({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(nA);i||(e.finishInitialDevCompile(),oP({context:e,port:o.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){i?e():r=e}}).catch(e=>{i||e7.error("初始化开发服务操作失败",{error:e})}))}),t.onCloseDevServer(()=>{i=!0,e.devServerAbort.abort(),r?.(),r=void 0})}}))({context:e.context}),function({context:e}){let t="KitMonitorPlugin";return{name:t,setup(r){if(r.onAfterCreateCompiler(({compiler:r})=>{for(let n of"compilers"in r?r.compilers:[r])n.hooks.finishMake.tap(t,()=>{oH(e.compileLifecycle,"moduleProcess",Date.now())}),n.hooks.emit.tap(t,()=>{oH(e.compileLifecycle,"assetProcess",Date.now())}),n.hooks.failed.tap(t,t=>{oG.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===rb.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==rb.DEV){let t=e.command;r.onBeforeBuild(()=>{let r=Date.now();oF(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??r,compileStartTime:r})}),r.onAfterBuild(({stats:r})=>{oV(e,t,r)})}else r.onBeforeDevCompile(({isFirstCompile:t})=>{let r=Date.now();oF(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??r:r,compileStartTime:r})}),r.onAfterDevCompile(({stats:t})=>{oV(e,e.compileLifecycle.scene??"dev_initial",t)})}}}({context:e.context}),..."true"===process.env.BYTED_RSDOCTOR?[{name:"doubao-apps:byted-rsdoctor",setup(e){e.onBeforeCreateCompiler(({bundlerConfigs:e})=>{let{BytedRsdoctorPlugin:t}=se(st(["@byted/rsdoctor"],E));for(let r of e){let e=tn.join(r.output?.path??"",`.rsdoctor-${r.name}`);r.plugins??=[],r.plugins.push(new t({disableClientServer:!0,supports:{banner:!0},output:{reportDir:e}}))}})}}]:[],(n=this.pluginSystem,i=e.context,{name:"view-hooks-plugin",setup(e){e.modifyBundlerChain((e,t)=>{t?.environment?.name==="web"||e.plugin("view-hooks-plugin").use(oQ,[{pluginSystem:n,context:i}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:a})=>({name:"lynx:encode-worker",async setup(o){tZ()||o.modifyBundlerChain((o,s)=>{s?.environment?.name!=="web"&&o.plugin(nw.name).use(nw,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:a}]).end()})}}))({getAppAssetPath:()=>e.context.appAssetPath,getAppMapAssetPath:()=>e.context.appMapAssetPath,metadata:e.context.metadata,resolveSigningEncryptionOptions:()=>e.context.resolveSigningEncryptionOptions(),onProcessDuration:t=>{e.context.compileLifecycle.appTemplateProcessDurationMs+=t}}),...e.rsbuildPlugins||[]],U=[{name:"web-virtual-entry-plugin",setup(e){e.modifyBundlerChain((e,{environment:t})=>{"web"===t.name&&e.plugin(o3.name).use(o3,[R])})}},(a=e.context,{name:"web-output-plugin",setup(e){e.modifyBundlerChain({order:"post",handler(e,{environment:t}){if("web"===t.name){let t=".rspeedy/";for(let r of Object.keys(e.plugins.entries()??{}))r.startsWith("lynx:template-")&&e.plugin(r).tap(e=>{let r=e[0];return r?.intermediate?.startsWith(t)&&(r.intermediate=r.intermediate.slice(t.length)),e});e.plugins.has("lynx:sourcemap")&&e.plugin("lynx:sourcemap").tap(e=>{var t;let r,n=e[0];return n.ignoreList=[/^(?!file:\/\/\/)/,/\/(?:externals-loading-runtime|webpack\/runtime)(?:\/|$)/,/\/node_modules\//,/\.(?:css|less|sass|scss)(?:[?#]|$)/],t=a.appDirectory,r=tn.resolve(t),n.moduleFilenameTemplate=({absoluteResourcePath:e,query:t=""})=>{let n=tn.relative(r,e),i=".."!==n&&!n.startsWith(`..${tn.sep}`)&&!tn.isAbsolute(n),a=i?o0(n):o0(e).replace(/^\/+/,"");return`${i?"file":"webpack"}:///${a}${t}`},e}),e.plugin(o2.name).use(o2,[a])}}})}})],B=p({mode:c===rb.DEV?"development":"production",environments:I?{lynx:j,web:{source:N,output:{distPath:{css:"",js:"base/web-common"},cleanDistPath:!1,filename:{assets:"[name]/web.bundle"},sourceMap:{js:!!b&&"cheap-module-source-map",css:!1}},plugins:[r8({externals:o7(c===rb.DEV,!0),globalObject:"lynx"})]}}:{lynx:j},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,r=tn.join(tn.dirname((0,o6.fileURLToPath)(import.meta.url)),"components-loader.js"),n=st){try{return n(t===tU?["@doubao-dev/kit/components-loader","@byted-doubao-apps/kit/components-loader"]:["@byted-doubao-apps/kit/components-loader","@doubao-dev/kit/components-loader"],e)}catch(e){if((0,tP.existsSync)(r))return r;throw e}}(E,v),options:{frameworkPackage:v}}]},plugins:[new d.BannerPlugin({banner:'"use registerWorkletInternal";',raw:!0,entryOnly:!0,stage:d.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE+1,test:/\.js$/})]}},source:{...O,entry:{}},server:{cors:!0,host:e.context.devServerHost},dev:{writeToDisk:eS(),hmr:c===rb.DEV},output:{distPath:{js:"base/common",root:f||"dist"},cleanDistPath:!1,filename:{bundle:"[name]/template.js"},dataUriLimit:5120},resolve:{alias:{...e.options.resolve?.alias||{}}},performance:{printFileSize:eS(),...tX()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){(function(e){let{LAYERS:t,lazy:r,rootPath:n,elementTemplate:i}=e??{};return{name:"lynx:react-alias",setup(e){let a=(0,A.createRequire)(import.meta.url),o=a.resolve("@lynx-js/react/package.json",{paths:[n??e.context.rootPath]}),{version:s}=a(o),l=tn.dirname(o);e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{source:{include:[l]}})),e.modifyBundlerChain(async(a,{isProd:o,rspack:c})=>{if(Object.hasOwn(a,nn))return;let p=ni(c,n??e.context.rootPath,r?["lazy","import"]:["import"]),d=ni(c,l,["import"]);e.expose(Symbol.for("@lynx-js/react/internal:resolve"),{resolve:p}),Object.defineProperty(a,nn,{value:!0});let[u,m,h,f,g,y,b,_,v,E,w,S,x,A]=await Promise.all([p("@lynx-js/react/jsx-runtime"),p("@lynx-js/react/lepus/jsx-runtime"),p("@lynx-js/react/jsx-dev-runtime"),p("@lynx-js/react/lepus/jsx-dev-runtime"),i?p("@lynx-js/react/element-template/jsx-runtime"):Promise.resolve(null),i?p("@lynx-js/react/element-template/jsx-dev-runtime"):Promise.resolve(null),d("preact/hooks"),p("@lynx-js/react/hooks"),p("@lynx-js/react/lepus/hooks"),p("@lynx-js/react"),p("@lynx-js/react/lepus"),nr()(s,"0.111.9999")?p("@lynx-js/react/compat"):Promise.resolve(null),i?p("@lynx-js/react/element-template"):Promise.resolve(null),i?p("@lynx-js/react/element-template/internal"):Promise.resolve(null)]),T={background:u,mainThread:g??m},I={background:h,mainThread:y??f};a.module.rule("react:jsx-runtime:main-thread").issuerLayer(t.MAIN_THREAD).resolve.alias.set("react/jsx-runtime",T.mainThread).set("react/jsx-dev-runtime",I.mainThread).set("@lynx-js/react/jsx-runtime",T.mainThread).set("@lynx-js/react/jsx-dev-runtime",I.mainThread).set("@lynx-js/react/lepus$",w).set("@lynx-js/react/lepus/jsx-runtime",T.mainThread).set("@lynx-js/react/lepus/jsx-dev-runtime",I.mainThread).set("preact/hooks",v).set("@lynx-js/react/hooks",v).set("@lynx-js/react/lepus/hooks",v).set("@lynx-js/react-signals$","@lynx-js/react-signals/lepus").end().end().end().rule("react:jsx-runtime:background").issuerLayer(t.BACKGROUND).resolve.alias.set("react/jsx-runtime",T.background).set("react/jsx-dev-runtime",I.background).set("@lynx-js/react/jsx-runtime",T.background).set("@lynx-js/react/jsx-dev-runtime",I.background).set("@lynx-js/react/lepus$",x??E).set("preact/hooks",b).set("@lynx-js/react/hooks",_).end().end().end().end();let O=new Map;for(let[e,t]of(i&&O.set("experimental/lazy/import",tn.join(l,"runtime/lazy/element-template-import.js")),await Promise.all(["experimental/lazy/import","internal","legacy-react-runtime","runtime-components","worklet-runtime/bindings"].map(async e=>{let t=`@lynx-js/react/${e}`,r=O.get(e)??await p(t);return[`${t}$`,r]}))))a.resolve.alias.set(e,t);o&&(a.resolve.alias.set("@lynx-js/react/debug$",!1),process.env.REACT_DEVTOOL||a.resolve.alias.set("@lynx-js/preact-devtools$",!1)),a.resolve.alias.has("react$")||a.resolve.alias.set("react$",E),a.resolve.alias.set("@lynx-js/react$",x??E).set("@lynx-js/react/internal$",A??a.resolve.alias.get("@lynx-js/react/internal$")).set("@lynx-js/react/jsx-runtime",T.background).set("@lynx-js/react/jsx-dev-runtime",I.background),i&&a.resolve.alias.set("@lynx-js/react/element-template$",x).set("@lynx-js/react/element-template/internal$",A).set("@lynx-js/react/element-template/jsx-runtime",g).set("@lynx-js/react/element-template/jsx-dev-runtime",y),S&&a.resolve.alias.set("@lynx-js/react/compat$",S),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(e=>d(e).then(t=>{a.resolve.alias.set(`${e}$`,t)})))})}}})({LAYERS:s,lazy:!1,rootPath:tn.dirname((0,o6.fileURLToPath)(import.meta.url))}).setup(e)}},{name:"set-server.printUrls-false",setup(e){e.modifyRsbuildConfig((e,{mergeRsbuildConfig:t})=>t(e,{server:{printUrls:!1}}))}},l({compat:{componentsPkg:[],newRuntimePkg:v,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...tB]}}),{name:"pin-react-transform-path",pre:["lynx:react"],setup(e){e.modifyBundlerChain((e,{CHAIN_ID:t})=>{let r=e.module.rule(t.RULE.JS).oneOf(t.ONE_OF.JS_MAIN);for(let e of[s.BACKGROUND,s.MAIN_THREAD]){let t=r.oneOfs.get(e)?.uses.get(e);if(!t)throw Error(`未找到该层的 React 转换加载器:${e}`);t.tap(e=>({...e,transformPath:w}))}})}},function(e){let{compilerOptionsKeys:t=rl.compilerOptionsKeys,configKeys:r=rl.configKeys,validate:n=rz,dslPluginName2PkgName:i=rK,upgradeRspeedyLink:a="https://www.npmjs.com/package/upgrade-rspeedy"}=(void 0)??{};return n(e),{name:"lynx:config",async setup(n){n.expose(Symbol.for("lynx.config"),{config:e}),n.modifyBundlerChain(o=>{let s=n.useExposed(Symbol.for("LynxTemplatePlugin"));if(!s){let e="Rspeedy and plugins";throw Object.entries(i).forEach(([t,r])=>{n.isPluginExists(t)&&(e=r)}),Error(`\
190
+ [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${rU("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
60
191
 
61
192
  Please upgrade ${e} to latest version.
62
193
 
63
- See ${nX(n4().yellow("Upgrade Rspeedy"),i)} for more details.
64
- `)}let{LynxTemplatePlugin:l}=s;a.plugin("lynx:config").use(n0,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:n}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableSimultaneousTap:!0,enableReloadLifecycle:!0}),m(),u(),...T?[]:R,...N,...M,...T?j:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:B}),B}}async function aQ(e,t){let n=new aZ(t),r=await n.createConfig({config:e}),o=await p({rspeedyConfig:r,cwd:e.context.appDirectory});return o.removePlugins(["lynx:react-alias"]),o}async function a0(e,t){var n;let{entry:r}=await nr({config:e,pluginSystem:t});return await aQ({...e,rsbuildPlugins:[...e.rsbuildPlugins||[],(n={context:e.context,entry:r,pluginSystem:t},{name:"worker-in-view-plugin",setup(e){e.modifyRspackConfig((e,{environment:t})=>{var r,o,i;let a;("lynx"===t.name||"web"===t.name)&&(r=e,o=n,i=t.name,r.entry??={},a=r.entry,Object.entries(o.entry).forEach(([e,t])=>{a[e]={filename:"web"===i?`${e}.js`:`base/${e}${eg()?".js":".template.js"}`,import:"web"===i&&"development"===r.mode&&"app"===e?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",t.filename]:t.filename,layer:s.BACKGROUND}}),e.plugins.push(new n_(n,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new nf))})}})]},t)}async function a1(e){let t=globalThis,n=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),r=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await e6(e)}finally{n?t.defineAppConfig=r:delete t.defineAppConfig}}async function a2({cwd:e=process.cwd()}={}){let t=eW(tY.resolve(e,"src"),te);if(t)try{let e=await a1(t);return{...void 0!==e.darkMode?{darkMode:e.darkMode}:{},...void 0!==e.chat?{chat:e.chat}:{},...Array.isArray(e.pages)?{pages:e.pages}:{},...Array.isArray(e.widgets)?{widgets:e.widgets}:{}}}catch(e){throw eh.error("Failed to load Taro app config file",{path:t}),e}}let a3=async(e,t=tC.basename(e))=>{if(!tQ.existsSync(e))return{};let n={};for(let r of(await tT.readdir(e))){let o=tC.resolve(e,r);if(!tQ.statSync(o).isDirectory())continue;let i=tC.resolve(o,em);tQ.existsSync(i)&&(n[`${t}/${r}/index`]={folderName:`${r}/index`,renderType:X.REACT_LYNX,filename:i})}return n},a4=async(e,t=tC.basename(e))=>{if(!tQ.existsSync(e))return{viewEntries:{},apiEntries:{}};let n=await a3(e,t),r={},o=tC.resolve(e,ey);tQ.existsSync(o)&&(r[`${t}/login`]={filename:o,folderName:e});let i=tC.resolve(e,ep);return tQ.existsSync(i)&&(r[`${t}/${e9}`]={filename:i,folderName:e}),{viewEntries:n,apiEntries:r}},a5=async(e,t)=>tQ.existsSync(e)?(await tT.readdir(e)).reduce((n,r)=>{let o=tC.resolve(e,r);return tQ.statSync(o).isDirectory()&&tQ.existsSync(tC.resolve(o,t))&&(n[r]=tC.resolve(o,t)),n},{}):{};function a9(e){return tC.resolve(e,"app.ts")}function a8(e,t,n,r){let o=`${n}/`;if(!t.startsWith(o))throw Error(`${n} config key must start with "${o}": ${t}`);let i=t.slice(o.length),a=tC.resolve(e,n,`${i}${r}`);if(!tQ.existsSync(a))throw Error(`Configured entry file does not exist for ${t}: ${a}`);return{relativeEntry:i,filename:a}}function a7(e,t){let n=t.entries[e]?.name;if(void 0===n)return t3(e);if("string"!=typeof n||!n.trim())throw Error(`Configured Tool name must be a non-empty string: ${e}`);return n.trim()}let a6=async(e,t={entryNames:[],entries:{}})=>{let n=tC.resolve(e,"tools"),r={...await a5(n,ew)};t.entryNames.forEach(n=>{let{filename:o}=a8(e,n,"tools",".ts"),i=a7(n,t),a=r[i];if(a&&a!==o)throw Error(`Tool name "${i}" is already used by another entry: ${a}`);r[i]=o});let o=a9(e);return{tools:r,app:tQ.existsSync(o)?o:void 0}},se=async(e,t)=>{let n=tC.resolve(e,"pages"),r=tC.resolve(e,eC),o=tC.resolve(e,"auth"),i=tC.resolve(e,"mcp-ui"),[a,s,l,p]=await Promise.all([a3(n),a3(r),a4(i),a4(o)]),d=Object.keys(p.viewEntries).length>0||Object.keys(p.apiEntries).length>0?p:l,c=t.pages,u=t.widgets,m=(t,n,r)=>{let o={...t};return n.forEach(t=>{if(o[t])return;let{relativeEntry:n,filename:i}=a8(e,t,r,".tsx");o[t]={folderName:n,renderType:X.REACT_LYNX,filename:i,isVirtualFile:!1}}),o},h=m(a,c.entryNames,"pages");return{widgets:m(s,u.entryNames,"widgets"),pages:h,auth:d}};function st(e,t,n=!1,r=!1){let o=eO(t);return Object.keys(e).reduce((i,a)=>{let{filename:s}=e[a],l=r&&e[a].isLoginPage?"defineLoginPage":r?"definePage":"defineWidget",p=`${eq}${tC.sep}${a}${tC.extname(s)}`,d=t8(tC.join(t,p,".."),s);return i[a]=new t7(p),i[a].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]},{moduleSpecifier:o,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]}),i[a].appendContent(`
65
- lynx.__DOUBAO_VIEW_TYPE__ = ${JSON.stringify(r?"page":"widget")};
194
+ See ${rU(rq().yellow("Upgrade Rspeedy"),a)} for more details.
195
+ `)}let{LynxTemplatePlugin:l}=s;o.plugin("lynx:config").use(rH,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:r}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableReloadLifecycle:!0}),m(),u(),...I?[]:L,...D,...M,...I?U:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:B}),B}}async function sn(e,t){let r=new sr(t),n=await r.createConfig({config:e}),i=await c({rspeedyConfig:n,cwd:e.context.appDirectory});return i.removePlugins(["lynx:react-alias"]),i}async function si(e,t){var r;let{entry:n}=await tK({config:e,pluginSystem:t});return await sn({...e,rsbuildPlugins:[...e.rsbuildPlugins||[],(r={context:e.context,entry:n,pluginSystem:t},{name:"worker-in-view-plugin",setup(e){e.modifyRspackConfig((e,{environment:t})=>{var n,i,a;let o;("lynx"===t.name||"web"===t.name)&&(n=e,i=r,a=t.name,n.entry??={},o=n.entry,Object.entries(i.entry).forEach(([e,t])=>{o[e]={filename:"web"===a?`${e}.js`:`base/${e}${tZ()?".js":".template.js"}`,import:"web"===a&&"development"===n.mode&&"app"===e?["@lynx-js/webpack-dev-transport/client","@rspack/core/hot/dev-server",t.filename]:t.filename,layer:s.BACKGROUND}}),e.plugins.push(new ra(r,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new rt))})}})]},t)}function sa(e){if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}let so=e=>{try{return tP.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function ss({internal:e,appKey:t}){try{return await n8({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw e5.error("获取 KEK 失败",{error:e,appKey:t,operation:"get-kek"}),e}}async function sl(e,t,r,n){if(!(n||tY("DISABLE_SIGNING_ENCRYPTION")||tY("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===rb.DEPLOY){if(!r)throw Error("获取 KEK 需要 appId");let{data:e}=await ss({internal:!1,appKey:r}),t=Number(Object.keys(e.keys)[0]);return{signing:{enabled:!1},encryption:{enabled:!0,wrap_key:e.keys[t],key_id:t,salt:""}}}}}let sc=tn.join("node_modules",".doubao-dev","config.json");function sp(e,t,r){if(r){let t=tn.isAbsolute(r)?r:tn.resolve(e,r);if(tP.existsSync(t))return t;e4.warn("未找到配置文件",{path:t})}for(let r of eq.map(r=>tn.resolve(e,`${t}${r}`)))if(so(r))return r;return!1}async function sd(e){let t=(0,E.createJiti)((0,o6.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function su({cwd:e=process.cwd(),customConfigFile:t}){let r=sp(e,"doubao.config",t);if(!r)return{};try{return await sd(r)}catch(e){throw e4.error("加载配置文件失败",{path:r}),e}}async function sm({cwd:e=process.cwd()}={}){let t=sp(tn.resolve(e,"src"),eV);if(t)try{return await sd(t)}catch(e){throw e4.error("加载应用配置文件失败",{path:t}),e}}async function sh(e){let t=globalThis,r=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),n=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await sd(e)}finally{r?t.defineAppConfig=n:delete t.defineAppConfig}}async function sf({cwd:e=process.cwd()}={}){let t=sp(tn.resolve(e,"src"),eV);if(t)try{let e=await sh(t);return{...void 0!==e.darkMode?{darkMode:e.darkMode}:{},...void 0!==e.chat?{chat:e.chat}:{},...Array.isArray(e.pages)?{pages:e.pages}:{},...Array.isArray(e.widgets)?{widgets:e.widgets}:{}}}catch(e){throw e4.error("加载 Taro 应用配置文件失败",{path:t}),e}}let sg=async(e,t=tn.basename(e))=>{if(!tP.existsSync(e))return{};let r={};for(let n of(await tr.readdir(e))){let i=tn.resolve(e,n);if(!tP.statSync(i).isDirectory())continue;let a=tn.resolve(i,"index.tsx");tP.existsSync(a)&&(r[`${t}/${n}/index`]={folderName:`${n}/index`,renderType:H.REACT_LYNX,filename:a})}return r},sy=async(e,t=tn.basename(e))=>{if(!tP.existsSync(e))return{viewEntries:{},apiEntries:{}};let r=await sg(e,t),n={},i=tn.resolve(e,"login.ts");tP.existsSync(i)&&(n[`${t}/login`]={filename:i,folderName:e});let a=tn.resolve(e,"privacy.ts");return tP.existsSync(a)&&(n[`${t}/privacy`]={filename:a,folderName:e}),{viewEntries:r,apiEntries:n}},sb=async(e,t)=>tP.existsSync(e)?(await tr.readdir(e)).reduce((r,n)=>{let i=tn.resolve(e,n);return tP.statSync(i).isDirectory()&&tP.existsSync(tn.resolve(i,t))&&(r[n]=tn.resolve(i,t)),r},{}):{};function s_(e,t){return tj(e,t).replace(/\.(?:t|j)sx?$/i,"")}function sv(e){return tn.resolve(e,"app.ts")}function sE(e,t,r,n){let i=`${r}/`;if(!t.startsWith(i))throw Error(`${r} 配置键必须以 "${i}" 开头:${t}`);let a=t.slice(i.length),o=tn.resolve(e,r,`${a}${n}`);if(!tP.existsSync(o))throw Error(`配置的入口文件不存在:${o}(入口:${t})`);return{relativeEntry:a,filename:o}}function sw(e,t){let r=t.entries[e]?.name;if(void 0===r)return tk(e);if("string"!=typeof r||!r.trim())throw Error(`配置的 Tool 名称必须是非空字符串:${e}`);return r.trim()}let sS=async(e,t={entryNames:[],entries:{}})=>{let r=tn.resolve(e,"tools"),n={...await sb(r,"index.ts")};t.entryNames.forEach(r=>{let{filename:i}=sE(e,r,"tools",".ts"),a=sw(r,t),o=n[a];if(o&&o!==i)throw Error(`Tool 名称 "${a}" 已被其他入口使用:${o}`);n[a]=i});let i=sv(e);return{tools:n,app:tP.existsSync(i)?i:void 0}},sx=async(e,t)=>{let r=tn.resolve(e,"pages"),n=tn.resolve(e,"widgets"),i=tn.resolve(e,"auth"),a=tn.resolve(e,"mcp-ui"),[o,s,l,c]=await Promise.all([sg(r),sg(n),sy(a),sy(i)]),p=Object.keys(c.viewEntries).length>0||Object.keys(c.apiEntries).length>0?c:l,d=t.pages,u=t.widgets,m=(t,r,n)=>{let i={...t};return r.forEach(t=>{if(i[t])return;let{relativeEntry:r,filename:a}=sE(e,t,n,".tsx");i[t]={folderName:r,renderType:H.REACT_LYNX,filename:a,isVirtualFile:!1}}),i},h=m(o,d.entryNames,"pages");return{widgets:m(s,u.entryNames,"widgets"),pages:h,auth:p}};function sA(e,t,r=!1,n=!1){let i=tW(t);return Object.keys(e).reduce((a,o)=>{let{filename:s}=e[o],l=n&&e[o].isLoginPage?"defineLoginPage":n?"definePage":"defineWidget",c=`${e$}${tn.sep}${o}${tn.extname(s)}`,p=tj(tn.join(t,c,".."),s);return a[o]=new tG(c),a[o].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:i,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]},{moduleSpecifier:p,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]}),a[o].appendContent(`
196
+ lynx.__DOUBAO_VIEW_TYPE__ = ${JSON.stringify(n?"page":"widget")};
66
197
 
67
198
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
68
199
 
@@ -74,14 +205,14 @@ const View =
74
205
  ? ViewEntry
75
206
  : ${l}({ render: () => <ViewEntry /> });
76
207
 
77
- const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(r)});
208
+ const FC = bootstrapReactLynx(View, viewId, ${JSON.stringify(n)});
78
209
 
79
210
  root.render(<FC />);
80
- `),n&&i[a].appendContent(`
211
+ `),r&&a[o].appendContent(`
81
212
  if (import.meta.webpackHot) {
82
213
  import.meta.webpackHot.accept()
83
214
  }
84
- `),i},{})}let sn={name:"AuthPlugin",async setup(e){eQ()||(e.view.hooks.modifyEnvironment.tapPromise(sn.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:sn.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let n,r,o,i,a,s,l,{isDev:p,auth:d,appDirectory:c}=e.context,u={},m=Object.keys(d.viewEntries).reduce((e,t)=>(e[t]={...d.viewEntries[t],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===t||"auth/mcp-login-page/index"===t||"mcp-ui/mcp-login-page/index"===t},e),{});return e.context.appendPages(m),t=Object.assign(t,(n=eO(c),r=`${eq}${tC.sep}${eG}${tC.sep}${eM}.tsx`,u[o=`${eG}/${eM}`]={filename:r,renderType:X.REACT_LYNX,folderName:eM,isVirtualFile:!0,isSpecial:!0,internal:!0},i=new t7(r),a=tC.join(c,tC.dirname(r)),s=Object.values(d.apiEntries).find(e=>"login"===tC.parse(e.filename).name),l=Object.values(d.apiEntries).find(e=>"privacy"===tC.parse(e.filename).name),s&&i.appendImports({moduleSpecifier:t8(a,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&i.appendImports({moduleSpecifier:t8(a,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),i.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:n,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${n}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),i.appendContent(`
215
+ `),a},{})}let sT={name:"AuthPlugin",async setup(e){tY("DISABLE_GENERATE_LOGIN_CARD")||tY("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(sT.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:sT.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,a,o,s,l,{isDev:c,auth:p,appDirectory:d}=e.context,u={},m=Object.keys(p.viewEntries).reduce((e,t)=>(e[t]={...p.viewEntries[t],internal:!0,isSpecial:!0,isLoginPage:"auth/login-page/index"===t||"auth/mcp-login-page/index"===t||"mcp-ui/mcp-login-page/index"===t},e),{});return e.context.appendPages(m),t=Object.assign(t,(r=tW(d),n=`${e$}${tn.sep}${eD}${tn.sep}${eU}.tsx`,u[i=`${eD}/${eU}`]={filename:n,renderType:H.REACT_LYNX,folderName:eU,isVirtualFile:!0,isSpecial:!0,internal:!0},a=new tG(n),o=tn.join(d,tn.dirname(n)),s=Object.values(p.apiEntries).find(e=>"login"===tn.parse(e.filename).name),l=Object.values(p.apiEntries).find(e=>"privacy"===tn.parse(e.filename).name),a.appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"definePrivacyLoginWidget",name:"definePrivacyLoginWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"MCPAuthCard",name:"MCPAuthCard"}]}),s&&a.appendImports({moduleSpecifier:tj(o,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&a.appendImports({moduleSpecifier:tj(o,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),a.appendContent(`
85
216
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
86
217
 
87
218
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -101,11 +232,11 @@ const View = definePrivacyLoginWidget({
101
232
 
102
233
  const FC = bootstrapReactLynx(View, viewId);
103
234
  root.render(<FC />);
104
- `,p?`
235
+ `,c?`
105
236
  if (import.meta.webpackHot) {
106
237
  import.meta.webpackHot.accept()
107
238
  }
108
- `:""),{[o]:i}),st(m,c,p,!0)),e.context.appendWidgets(u),{entry:t}}))}};(nx=nR||(nR={}))[nx.DISABLED=0]="DISABLED",nx[nx.ENABLED=1]="ENABLED";let sr="AppletDoubaoAppInfoPlugin",so={name:sr,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sr,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==eD.DEV&&e.context.command!==eD.BUILD&&e.context.command!==eD.DEPLOY||!e.context.appId)return;let n=await e.context.resolveAppInfo();if(n){var r=t.getManifestAsset(e.context.manifestAssetPath),o=e.context.permissions;r.assignBasicManifest({permissions:void 0===o?Object.fromEntries(n.permissionList.filter(e=>e.status===nR.ENABLED).map(e=>[e.scope_name,{desc:e.description||e.scope_name||"",apis:(e.api_list||[]).map(e=>e.api_name).filter(Boolean)}]).filter(([e,t])=>e&&t.apis.length>0)):Object.fromEntries(o.filter(e=>"string"==typeof e?.scope_name&&!!e.scope_name.trim()).map(e=>{let t=e.scope_name.trim();return[t,{desc:"string"==typeof e.description&&e.description?e.description:t,apis:[]}]}))}),n?.appName&&r.mergeAppletManifest({name:n.appName}),n?.iconUrl&&r.mergeAppletManifest({icons:tk(n.iconUrl)})}})}},si={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:si.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let n,r,o,i,{isDev:a,appDirectory:s}=e.context,l={};return t=Object.assign(t,(n=eO(s),r=`${eq}${tC.sep}${eG}${tC.sep}${eX}.tsx`,l[o=`${eG}/${eX}`]={filename:r,renderType:X.REACT_LYNX,folderName:eX,isVirtualFile:!0,isSpecial:!0,internal:!0},(i=new t7(r)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:n,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${n}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),i.appendContent(`
239
+ `:""),{[i]:a}),sA(m,d,c,!0)),e.context.appendWidgets(u),{entry:t}}))}};(rp=rw||(rw={}))[rp.DISABLED=0]="DISABLED",rp[rp.ENABLED=1]="ENABLED";let sI="AppletDoubaoAppInfoPlugin",sO={name:sI,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sI,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==rb.DEV&&e.context.command!==rb.BUILD&&e.context.command!==rb.DEPLOY||!e.context.appId)return;let r=await e.context.resolveAppInfo();if(r){var n=t.getManifestAsset(e.context.manifestAssetPath),i=e.context.permissions;n.assignBasicManifest({permissions:void 0===i?Object.fromEntries(r.permissionList.filter(e=>e.status===rw.ENABLED).map(e=>[e.scope_name,{desc:e.description||e.scope_name||"",apis:(e.api_list||[]).map(e=>e.api_name).filter(Boolean)}]).filter(([e,t])=>e&&t.apis.length>0)):Object.fromEntries(i.filter(e=>"string"==typeof e?.scope_name&&!!e.scope_name.trim()).map(e=>{let t=e.scope_name.trim();return[t,{desc:"string"==typeof e.description&&e.description?e.description:t,apis:[]}]}))}),r?.appName&&n.mergeAppletManifest({name:r.appName}),r?.iconUrl&&n.mergeAppletManifest({icons:tl(r.iconUrl)})}})}},sP={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:sP.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,a,{isDev:o,appDirectory:s}=e.context,l={};return t=Object.assign(t,(r=tW(s),n=`${e$}${tn.sep}${eD}${tn.sep}${eB}.tsx`,l[i=`${eD}/${eB}`]={filename:n,renderType:H.REACT_LYNX,folderName:eB,isVirtualFile:!0,isSpecial:!0,internal:!0},(a=new tG(n)).appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:r,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:"getViewContext",name:"getViewContext"},{propertyName:"defineWidget",name:"defineWidget"}]},{moduleSpecifier:`${r}/components`,importSpecifiers:[{propertyName:"UpdatedState",name:"UpdatedState"}]}),a.appendContent(`
109
240
  lynx.__DOUBAO_VIEW_TYPE__ = 'widget';
110
241
 
111
242
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
@@ -120,12 +251,12 @@ const View = defineWidget({
120
251
 
121
252
  const FC = bootstrapReactLynx(View, viewId);
122
253
  root.render(<FC />);
123
- `,a?`
254
+ `,o?`
124
255
  if (import.meta.webpackHot) {
125
256
  import.meta.webpackHot.accept()
126
257
  }
127
- `:""),{[o]:i})),e.context.appendWidgets(l),{entry:t}})}},sa="LynxPlugin",ss={name:sa,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(sa,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:sa,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:n})=>{let{appDirectory:r,isDev:o,widgets:i,pages:a}=e.context;return t=n=Object.assign(n,st(i,r,o),st(a,r,o,!0)),{entry:n}}),e.view.hooks.collectMetaData.tapPromise({name:sa,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:n})=>{let{normalizedAppConfig:r,userConfig:o,widgets:i,pages:a}=e.context;await rd({widgets:i,pages:a,entries:t,collector:n,normalizedAppConfig:r,define:o.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:sa,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:n,pages:r,app:o}=e.context.metadata.getInstance(),i=e.context.templateWidgetEntries;Object.keys(n).forEach(r=>{let o=n[r],a=`${r}/template.js`,s=t.getAsset(a);if(o&&s){let n=`${o.metadata.id}/template.js`;s.destination=n;let a=t.getManifestAsset(e.context.manifestAssetPath),l=o.toManifest(n,s.hashCode,X.LYNX);i.has(r)&&(l.titleType=Y.NONE),a.appendWidget(l)}}),Object.keys(r).forEach(n=>{let i=r[n],a=`${n}/template.js`,s=t.getAsset(a);if(i&&s){let n=t5(o.metadata.appId,i.metadata.path,"template.js");s.destination=n,t.getManifestAsset(e.context.manifestAssetPath).appendPage(i.toManifest(n,s.hashCode,X.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(sa,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(sa,async({stats:e})=>{})}};async function sl(e,t,n){let{app:r,tools:o,collector:i,define:a}=n,s=o[t],l=e;(s||r===t)&&(a&&Object.keys(a).length>0&&(l=Object.keys(a).reduce((e,t)=>{let n=a[t];if("string"==typeof n)return e.replaceAll(t,n);throw Error(`Define value ${t} is not a string`)},e)),er((0,ra.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(n7(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(rn(t)){for(let e of t.properties)if(ro(e)&&n7(e.key)&&"aiMeta"===e.key.value){let t=ri(e.value);s?i.addToolMeta(s,t):i.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function sp({tools:e,app:t,collector:n,define:r,appConfig:o}){let i={collector:n,tools:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),app:t,define:r};Object.entries(e).forEach(([e])=>{n.addToolMeta(e,{id:e})}),tz.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&tz.existsSync(e)).map(e=>sl(tz.readFileSync(e,"utf-8"),e,i))):eh.warn("App file does not exist",{path:t});let a=n.app,s=o?.appId??a.appId;if(!s)throw Error("appId is required in app config or AI metadata");n.addAppMeta({...a,name:o?.name??a.name,description:o?.description??a.description,icons:o?.icons??a.icons,keywords:o?.keywords??a.keywords,version:o?.version??a.version,darkMode:o?.darkMode??a.darkMode,chat:o?.chat??a.chat,appId:s})}let sd={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var n,r,o;let i,{app:a,tools:s}=e.context,l=Object.fromEntries((n=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=a7(e,n),r=s[t];if(!r)throw Error(`Configured Tool entry was not analyzed: ${e}`);return[t,r]}));return Object.assign(t,{app:(r=`${e.context.appDirectory}${tC.sep}${eq}${tC.sep}app.js`,i=(({dirname:e,app:t,tools:n})=>{let r=[],o=[],i=eO(tY.resolve(t,"..",".."));Object.entries(n).forEach(([t,n],i)=>{let a=JSON.stringify(t);r.push(`import Tool${i} from "${t8(e,n)}";`),o.push(`toAppRuntimeTool(Tool${i}, ${a})`)});let a=o.length>0?`function toAppRuntimeTool(tool, id) {
128
- return typeof tool === 'object' &&
258
+ `:""),{[i]:a})),e.context.appendWidgets(l),{entry:t}})}},sC="LynxPlugin",sR={name:sC,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(sC,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:sC,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:r})=>{let{appDirectory:n,isDev:i,widgets:a,pages:o}=e.context;return t=r=Object.assign(r,sA(a,n,i),sA(o,n,i,!0)),{entry:r}}),e.view.hooks.collectMetaData.tapPromise({name:sC,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:r})=>{let{normalizedAppConfig:n,userConfig:i,widgets:a,pages:o}=e.context;await ny({widgets:a,pages:o,entries:t,collector:r,normalizedAppConfig:n,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:sC,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:r,pages:n,app:i}=e.context.metadata.getInstance(),a=e.context.templateWidgetEntries;Object.keys(r).forEach(n=>{let i=r[n],o=`${n}/template.js`,s=t.getAsset(o);if(i&&s){let r=`${i.metadata.id}/template.js`;s.destination=r;let o=t.getManifestAsset(e.context.manifestAssetPath),l=i.toManifest(r,s.hashCode,H.LYNX);a.has(n)&&(l.titleType=F.NONE),o.appendWidget(l)}}),Object.keys(n).forEach(r=>{let a=n[r],o=`${r}/template.js`,s=t.getAsset(o);if(a&&s){let r=tL(i.metadata.appId,a.metadata.path,"template.js");s.destination=r,t.getManifestAsset(e.context.manifestAssetPath).appendPage(a.toManifest(r,s.hashCode,H.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(sC,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(sC,async({stats:e})=>{})}},s$=`function toAppRuntimeTool(tool, id, key) {
259
+ const normalizedTool = typeof tool === 'object' &&
129
260
  tool !== null &&
130
261
  '__FUNCTIONAL__' in tool &&
131
262
  tool.__FUNCTIONAL__ === true
@@ -142,22 +273,24 @@ if (import.meta.webpackHot) {
142
273
  return tool(typeof input === 'string' ? JSON.parse(input) : input);
143
274
  }
144
275
  });
145
- }`:"",s=o.length>0?"Applet, defineTool":"Applet";return`
146
- import { ${s} } from "${i}";
147
- import App from "${t8(e,t)}";
148
-
149
- ${r.join("\n")}
150
276
 
151
- ${a}
277
+ return Object.defineProperty(normalizedTool, '__runtimeEntry', {
278
+ value: Object.freeze({ type: 'functional_tool', key, id: normalizedTool.aiMeta.id })
279
+ });
280
+ }`;async function sk(e,t,r){let{app:n,tools:i,collector:a,define:o}=r,s=i[t],l=e;(s||n===t)&&(o&&Object.keys(o).length>0&&(l=Object.keys(o).reduce((e,t)=>{let r=o[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`define 配置项 ${t} 的值必须是字符串`)},e)),el((0,nm.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(na(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(nc(t)){for(let e of t.properties)if(nd(e)&&na(e.key)&&"aiMeta"===e.key.value){let t=nu(e.value);s?a.addToolMeta(s,t):a.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function sN({tools:e,app:t,collector:r,define:n,appConfig:i}){let a={collector:r,tools:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),app:t,define:n};Object.entries(e).forEach(([e])=>{r.addToolMeta(e,{id:e})}),tP.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&tP.existsSync(e)).map(e=>sk(tP.readFileSync(e,"utf-8"),e,a))):e4.warn("应用入口文件不存在",{path:t});let o=r.app,s=i?.appId??o.appId;if(!s)throw Error("请在应用配置或 AI 元数据中提供 appId");r.addAppMeta({...o,name:i?.name??o.name,description:i?.description??o.description,icons:i?.icons??o.icons,keywords:i?.keywords??o.keywords,version:i?.version??o.version,darkMode:i?.darkMode??o.darkMode,chat:i?.chat??o.chat,appId:s})}let sL={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var r;let{app:n,srcDirectory:i,tools:a}=e.context,o=Object.fromEntries((r=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=sw(e,r),n=a[t];if(!n)throw Error(`未解析到配置的 Tool 入口:${e}`);return[t,n]}));return Object.assign(t,{app:((e,t,r,n=tn.dirname(t))=>{let i=tn.dirname(e),a=tW(tn.resolve(t,"..","..")),o=[],s=[];Object.entries(r).forEach(([e,t],r)=>{let a=s_(n,t);o.push(`import Tool${r} from "${tj(i,t)}";`),s.push(`toAppRuntimeTool(Tool${r}, ${JSON.stringify(e)}, ${JSON.stringify(a)})`)});let l=s.length>0;return new tG(e,`
281
+ import { ${l?"Applet, defineTool":"Applet"} } from "${a}";
282
+ import App from "${tj(i,t)}";
283
+ ${o.join("\n")}
152
284
 
153
- new Applet(App, [${o.join(", ")}]).bootstrap();
154
- `})({dirname:tY.dirname(r),app:a,tools:s}),new t7(r,i))}),Object.keys(l).length>0&&(t[e$]=(o=`${e.context.appDirectory}${tC.sep}${eq}${tC.sep}${e$}.js`,new t7(o,function({appDirectory:e,clientTools:t,dirname:n}){let r=eO(e),o=[],i=[];return Object.entries(t).forEach(([e,t],r)=>{o.push(`import ClientTool${r} from "${t8(n,t)}";`),i.push(`{ name: ${JSON.stringify(e)}, handler: ClientTool${r} }`)}),`
155
- import { bootstrapClientToolRuntime } from "${r}";
285
+ ${l?s$:""}
156
286
 
287
+ new Applet(App, [${s.join(", ")}]).bootstrap();
288
+ `)})(`${e.context.appDirectory}${tn.sep}${e$}${tn.sep}app.js`,n,a,i)}),Object.keys(o).length>0&&(t[eW]=function(e,t,r,n=tn.resolve(r,"src")){let i=tn.dirname(e),a=tW(r),o=[],s=[];return Object.entries(t).forEach(([e,t],r)=>{let a={type:"client_tool",key:s_(n,t),id:e};o.push(`import ClientTool${r} from "${tj(i,t)}";`),s.push(`{ name: ${JSON.stringify(e)}, handler: ClientTool${r}, entry: Object.freeze(${JSON.stringify(a)}) }`)}),new tG(e,`
289
+ import { bootstrapClientToolRuntime } from "${a}";
157
290
  ${o.join("\n")}
158
291
 
159
- bootstrapClientToolRuntime([${i.join(", ")}]);
160
- `}({appDirectory:e.context.appDirectory,clientTools:l,dirname:tC.dirname(o)})))),{entry:t}}),e.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:e})=>{}),e.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:e.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{app:n,appConfig:r,tools:o,userConfig:i}=e.context;await sp({appConfig:r,tools:o,app:n,collector:t,define:i.source?.define}),e.context.setVersionTag(e.context.metadata.app.version)}),e.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:t,chunks:n})=>{var r,o;let{app:i,pages:a,tools:s}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),p=n[e$]?.find(({source:e})=>e.endsWith(".js")),d=t.getManifestAsset(e.context.manifestAssetPath),{manifest:c}=d,u=[];c.applet.pages.forEach(e=>{u.push(e.digest)});let m=i.metadata.appId,h=e.context.versionTag;d.assignBasicManifest({manifestVersion:"3.0",packageName:m,appId:m,versionName:h,versionTag:h,scmVersion:process.env.BUILD_VERSION,versionCode:Date.now().toString(),runtimeVersion:"1.0",sourceType:e.context.internal?1:2,settings:e.context.manifestSettings});let f=e.context.appAssetPath,g=e.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(e.context.pages)[0],y=g?a[g]?.metadata.path:void 0,b=i.toManifest({toolsMetadata:s,hashCode:l?.hashCode??(r=l?.hashCode??c?.applet?.digest,o=u.join(""),ak.createHash("sha256").update(r+o).digest("hex").substring(0,8)),appRuntimeEntry:f,appRuntimeType:e.context.environment.useLynx?"lynx":"js"});p&&(b.toolRuntimeEntry=p.source),d.mergeAppletManifest(b),y&&d.mergeAppletManifest({appletEntry:y})}),e.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e})=>{}),e.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:e})=>{}))}},sc={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,n=a9(t);if(!tQ.existsSync(n))throw Error("ENOENT: no such file or directory")}},su={name:"AppletManifestPlugin",setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:e.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:t})=>{let{signing:n}=await e.context.resolveSigningEncryptionOptions()||{};if(n?.enabled){let{signData:r}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),o=t.getManifestAsset(e.context.manifestAssetPath),{manifest:i}=o,{buffer:a,status:s,error_msg:l}=await r(Buffer.from(o.content),t9(n,{extra_config:{app_id:i.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let p=new a$(eE,a);p.destination=eE,t.addAsset(eE,p)}})}},sm="AppletWebManifestPlugin",sh={name:sm,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sm,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var n,r;let o=e.context.metadata.getData(),i=o.app.appId||e.context.appId,a=e.context.command===eD.DEV?"all":"configured",s=nh(e.context.pages,e.context.normalizedAppConfig.pages.entries,a),l=nh(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,a);if(!i&&Object.keys(s).length>0)throw Error("appId is required to resolve Web page entry paths");let p=i?(n=o.pages,Object.keys(s).map(e=>{let t=n[e]??{},r=t.path??t4(e),o={entry:t5(i,r,nl)},a=nm(s[e]);return{path:r,entryName:e,web:o,debugHidden:a,manifest:{...t,path:r,digest:"",entry:"",renderType:X.LYNX,web:o,...a?{debugHidden:!0}:{}}}})):[],d=(r=o.widgets,Object.keys(l).map(e=>{let{id:t,...n}=r[e]??{},o=t??nu(l,r,e),i={entry:`${o}/${nl}`},a=nm(l[e]);return{id:o,entryName:e,web:i,debugHidden:a,manifest:{...n,widgetId:o,digest:"",entry:"",renderType:X.LYNX,web:i,...a?{debugHidden:!0}:{}}}}));if(0===p.length&&0===d.length&&0===e.context.normalizedAppConfig.tools.entryNames.length)return;let c=t.getManifestAsset(e.context.manifestAssetPath),u=new Map(p.map(e=>[e.path,e])),m=new Set(c.manifest.applet.pages?.map(e=>e.path));for(let e of(c.manifest.applet.pages?.forEach(e=>{let t=u.get(e.path);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),p))m.has(e.path)||c.appendPage(e.manifest);let h=new Map(d.map(e=>[e.id,e])),f=new Set(c.manifest.widgets?.map(e=>e.widgetId));for(let t of(c.manifest.widgets?.forEach(e=>{let t=h.get(e.widgetId);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),d))if(!f.has(t.id)){let n=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(n.titleType=Y.NONE),c.appendWidget(n)}e.context.app&&(c.manifest.applet.web={appRuntimeEntry:np,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:nd}:{}})})}};function sf(e,t){let n;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))n=e;else if("object"==typeof e)t&&eh.warn(`${t} config object map is deprecated. Use an array of strings or { entry, ...metadata } objects instead.`),n=Object.entries(e).map(([e,t])=>{let n;return{...t,entry:(n=e.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?n:`${n}/index`}});else throw Error("Entry config must be an array or object map.");let r=[],o={},i=new Set,a=[],s=new Set;return n.forEach(e=>{let t,n;if("string"==typeof e)t=e,n={};else{let{entry:r,...o}=e;if(!r)throw Error('Entry config object must include "entry".');t=r,n=o}i.has(t)?s.has(t)||(a.push(t),s.add(t)):(r.push(t),i.add(t)),o[t]=n}),t&&a.length>0&&eh.warn(`${t} config contains duplicate entries: ${a.join(", ")}. Entries are deduplicated, and the last metadata config takes effect.`),{entryNames:r,entries:o}}class sg{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._cookie="",this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:e,metadata:t,versionTag:n,srcDirectory:r="",virtualEntryDir:o="",appDirectory:i=process.cwd(),rootPath:a="",manifestPath:s="",pages:l={},widgets:p={},auth:d,mcpUI:c,app:u="",tools:m={},environment:h={useLynx:!1,useAuth:!1},viewEntriesByType:f={},loginCookieResolver:g,cachedLoginCookieResolver:y}){this._command=e,this._metadata=t,this._versionTag=n,this._srcDirectory=r,this._virtualEntryDir=o,this._appDirectory=i,this._rootPath=a,this._manifestPath=s,this._pages={...l},this._widgets={...p};let b=d??c??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=u,this._tools={...m},this._environment={useLynx:h.useLynx,useAuth:!!(h.useAuth||h.useMcpUI)},this._cookie="",this._loginCookieResolver=g,this._loginCookiePromise=void 0,this._cachedLoginCookieResolver=y,this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}])),this._isInitialized=!0}assertInitialized(e){if(!this._isInitialized)throw Error(`BuildContext.${e} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===eD.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(tQ.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(e){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return eb}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(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}async getLoginCookie(){return(this.assertInitialized("getLoginCookie"),this._cookie)?this._cookie:this._loginCookieResolver?(this._loginCookiePromise||(this._loginCookiePromise=this._loginCookieResolver().then(e=>(this._cookie=e??"",e)).catch(e=>{throw this._loginCookiePromise=void 0,e})),await this._loginCookiePromise):void 0}async getCachedLoginCookie(){if(this.assertInitialized("getCachedLoginCookie"),this._cookie)return this._cookie;if(!this._cachedLoginCookieResolver)return;let e=await this._cachedLoginCookieResolver();return e&&(this._cookie=e),e}get appId(){return this._appId||this._metadata.appId}setAppId(e){this._appId=e}setApp(e){this._app=e}setTools(e){this._tools=e}setEnvironment(e){this._environment={...e}}mergeEnvironment(e){this._environment={...this._environment,...e}}setPages(e){this._pages=e}setWidgets(e){this._widgets=e}appendPages(e){Object.assign(this._pages,e)}appendWidgets(e){Object.assign(this._widgets,e)}getViewEntriesByType(e){let t=this._viewEntriesByType[e];return t?{pages:{...t.pages},widgets:{...t.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(e,t){this._viewEntriesByType[e]={pages:{...t.pages},widgets:{...t.widgets}}}setAppAssetPath(e){this._appAssetPath=e}setAppMapAssetPath(e){this._appMapAssetPath=e}setManifest(e){this._manifest=e}setVersionTag(e){return this.assertInitialized("versionTag"),!this._versionTag&&e&&(this._versionTag=e),this._versionTag}setAuthApi(e){this._auth={viewEntries:{...e.viewEntries},apiEntries:{...e.apiEntries}}}setMcpUIApi(e){this.setAuthApi(e)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function sy({internal:e,domainId:t,appLimit:n,appOffset:r,keyWord:o,appKey:i,cookie:a}){return await eB({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:n,app_offset:r,key_word:o,app_key:i},method:"GET",headers:a?{Cookie:a}:void 0})}async function sb({source:e,internal:t,domainId:n,appLimit:r,appOffset:o,releaseStatus:i,keyWord:a,appKey:s,cookie:l}){return await eB({internal:t,domainId:n,path:"/developer/api/apps",query:{source:e,app_limit:r,app_offset:o,release_status:i,key_word:a,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function s_({appKey:e,source:t,internal:n,domainId:r,releaseStatus:o,limit:i,offset:a,status:s,keyWord:l,versionTag:p,cookie:d}){return await eB({internal:n,domainId:r,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:o,limit:i,offset:a,status:s,key_word:l,version_tag:p},method:"GET",headers:d?{Cookie:d}:void 0})}async function sv({appKey:e,versionTag:t,internal:n,domainId:r,pageSize:o,pageNum:i,cookie:a}){return await eB({internal:n,domainId:r,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:o,page_num:i},method:"GET",headers:a?{Cookie:a}:void 0})}function sw(e){return e.is_latest||e.is_current}function sS(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function sE(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function sx(e){return e.version_tag}function sA(e,t){eR()&&eh.info(e,t)}async function sT({appKey:e,internal:t=!1,cookie:n,source:r=nj.REQUEST_SOURCE_IDE}){sA("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:n?"present":"absent"});let o=await sy({internal:t,appLimit:1,appOffset:0,appKey:e,cookie:n}).then(({data:t,log_id:n})=>{let r=t?.app_list||[],o=r.find(t=>t.app_key===e);return sA("[app-info] MGetApps 请求完成",{appKey:e,appCount:r.length,exactMatch:!!o,logId:n}),o}).catch(t=>{if(sA("[app-info] MGetApps 请求失败",{appKey:e,reason:eI(t)}),ar(t))throw t}),i=o?void 0:await sb({source:r,internal:t,appLimit:1,appOffset:0,appKey:e,cookie:n}).then(({data:t,log_id:n})=>{let r=t?.org_list?.flatMap(e=>e.app_list)||[],o=r.find(t=>t.app_key===e),i=o||r[0];return sA("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:r.length,exactMatch:!!o,logId:n}),i?.app_meta}).catch(t=>{sA("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:eI(t)})});if(!o&&!i)throw sA("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let a=o?void 0:await s_({appKey:e,source:r,internal:t,cookie:n}).then(({data:t,log_id:n})=>{let r=Array.isArray(t?.version_list)?t.version_list:[];if(sA("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:r.length,logId:n}),0===r.length)return;let o=r.find(sw);return o||r.reduce((e,t)=>{let n,r;return!e||(n=sS(t),r=sS(e),(Number.isNaN(n)&&Number.isNaN(r)?sE(t)-sE(e):(Number.isNaN(n)?-1/0:n)-(Number.isNaN(r)?-1/0:r))>0)?t:e},void 0)}).catch(t=>{sA("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:eI(t)})}),s=o?.current_version_tag||(a?sx(a):""),l=o?.icon_url||(a?a.icon_url:void 0)||i?.icon_url,p=o?.name||i?.name,d=a&&sx(a)===s?a:o?{version_tag:o.current_version_tag,icon_url:o.icon_url,updated_at:o.updated_at,online_at:o.online_at,offline_at:o.offline_at}:{version_tag:s,icon_url:l};if(o||!s||!n)return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:d};let c=await sv({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:n}).then(t=>(sA("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw sA("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:eI(t)}),t});return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:c.data?.permission_list||[],permissionTotal:c.data?.total||0,version:d}}function sC(){return function({fetch:e,getCacheKey:t,ttl:n,timeout:r,cacheFailures:o=!1,now:i=Date.now}){let a=new Map;return function(...s){var l,p;let d,c="string"==typeof(l=t(...s))?l:JSON.stringify(l),u=i(),m=a.get(c);if(m&&m.expiresAt>u)return m.promise;let h=(p=e(...s),void 0===r?p:Promise.race([p,new Promise((e,t)=>{d=setTimeout(()=>{t(Error(`Request timed out after ${r}ms`))},r)})]).finally(()=>{d&&clearTimeout(d)})).catch(e=>{throw o||a.get(c)?.promise!==h||a.delete(c),e});return a.set(c,{expiresAt:u+n,promise:h}),h}}({fetch:sT,getCacheKey:({appKey:e,internal:t,cookie:n})=>[e,t,n],ttl:6e4,timeout:1e4,cacheFailures:!0})}async function sI(e="0.0.0.0"){if(!e||e.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");let{address:t}=await (0,E.lookup)(e,{family:4});if("0.0.0.0"!==t)return t;let n=ta()[0];return n||(ez.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function sP(e,t,n){let r=await fetch(`${e}/base/manifest.json`,{signal:AbortSignal.any([n,AbortSignal.timeout(1500)]),redirect:"error"}),o=await r.json();if(!r.ok||t&&o?.appId!==t)throw Error(`开发服务器返回的 manifest 无效:${e}(HTTP ${r.status},appId:${t})`)}async function sO(e,t,n,r){let o,i=e4(e,t),a=AbortSignal.any([r,AbortSignal.timeout(5e3)]);try{for(;;)try{await sP(i,n,a);break}catch(e){o=e,await (0,_.setTimeout)(200,void 0,{signal:a})}}catch{throw r.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${i}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:o})}return{host:i,artifactOrigin:i}}(nA=nN||(nN={}))[nA.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",nA[nA.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(nT=nL||(nL={}))[nT.DRAFT=0]="DRAFT",nT[nT.UNDER_REVIEW=1]="UNDER_REVIEW",nT[nT.APPROVED=2]="APPROVED",nT[nT.REJECTED=3]="REJECTED",nT[nT.WITHDRAWN=4]="WITHDRAWN",nT[nT.PUBLISHING=5]="PUBLISHING",nT[nT.PUBLISHED=6]="PUBLISHED",nT[nT.ARCHIVED=7]="ARCHIVED",nT[nT.DELETED=8]="DELETED",(nC=nM||(nM={}))[nC.DRAFT=0]="DRAFT",nC[nC.PUBLISHED=1]="PUBLISHED",nC[nC.ARCHIVED=2]="ARCHIVED",(nI=nj||(nj={}))[nI.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",nI[nI.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",nI[nI.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",nI[nI.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class sD extends sg{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(e=>{this.finishInitialDevCompile=e,this.devServerAbort.signal.addEventListener("abort",()=>e(void 0),{once:!0})});devServerResolution;resolveDevServer(e){return this.devServerResolution??=this.initialDevCompile.then(t=>{if(t)throw t;return this.devServerAbort.signal.throwIfAborted(),sO(e,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=aA();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=sC();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){return eY(this._normalizedAppConfig)}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(e=>({...e}))}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(e){this._rawSigningEncryptionOptions=e,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(e){this._templateWidgetEntries.add(e)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let e=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==e&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-e))}}async resolveAppInfoInternal(){var e;let t=this.appId;if(!an(t))return;let n="string"==typeof(e=this._appConfig.icons)?e.length>0?e:void 0:e?.["3x"]||e?.["2x"]||e?.["1x"],r={appKey:t,versionTag:this.versionTag??"",permissionList:[],permissionTotal:0,version:{},...this._appConfig.name?{appName:this._appConfig.name}:{},...n?{iconUrl:n}:{}};if(this._skipAppInfoFetch)return r;let o=await this.getCachedLoginCookie().catch(()=>void 0);try{return Object.assign(r,await this._fetchCachedAppInfo({appKey:t,cookie:o,internal:this.internal})),r.appName||=this._appConfig.name,r.iconUrl||=n,r}catch(e){if(this.command!==eD.DEV&&this.command!==eD.BUILD)throw e;if(ar(e))return r;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,eh.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:eI(e)})),r}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:n,userConfig:r,appConfig:o={},normalizedAppConfig:i={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:a,metadata:s,signingEncryptionOptions:l,disableSigningEncryption:p,appId:d,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,internal:y,skipAppInfoFetch:b,permissions:_,devServerInteractive:v=!0,env:w={},loginCookieResolver:S,cachedLoginCookieResolver:E}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:tC.resolve(t,eq),rootPath:n,manifestPath:tC.resolve(`${n}/${eb}`),command:a,metadata:s,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:S,cachedLoginCookieResolver:E});let{icons:x,...A}=o??{};this._userConfig=r,this.devServerInteractive=v,this._env={...w},this._appConfig={...A,...void 0!==d?{appId:d}:{},...void 0!==x?{icons:tk(x)}:{}},this._normalizedAppConfig=i,this._internal=y??ec(t),this._skipAppInfoFetch=!!b,this._permissions=_?.map(e=>({...e})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=l,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!p,this._appId=d??o?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=sC()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await to(this._rawSigningEncryptionOptions,this.command,e,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=e(),eu()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function sk({appId:e,versionTag:t,versionCode:n,packagePath:r,internal:o,domainId:i,cookie:a,token:s,needAuth:l=!0}){let p=new FormData,d=new Blob([new Uint8Array(tQ.readFileSync(r))],{type:"application/zip"});p.append("applet_file",d,"doubao_app.zip"),p.append("applet_version_code",n.toString());let c=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await eB({internal:o,domainId:s?"sms-external":i,path:c,method:"POST",body:p,headers:{...a?{Cookie:a}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function s$({versionTag:e,appKey:t,manifest:n,rootPath:r,internal:o,needAuth:i=!0,cookie:a,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:p,versionCode:d}=n,c=function(e,t){let n=e||t.versionTag||t.versionName;if(!n)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return n}(e,n),{packageResource:u}=await t0({channelName:"doubao_app",manifest:n,rootPath:r});if(!u)throw Error("Failed to archive package");let m=await sk({appId:t||l||p,versionTag:c,versionCode:d,packagePath:u.resource,internal:o,needAuth:i,cookie:a,token:s});return console.log("Deploy success:",m),m}let sR=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),sN="x-db-llm-modifiable",sL="x-db-is-entity-id",sM="x-db-is-refresh-key",sj=["entity_type"];function sB(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sU(e,t,n){if(!sB(e))throw Error(`Tool "${n}" requires an object ${t}`);return e}function sF(e,t,n,r,o=!1){let i=`Tool "${t}" ${n} property "${r}"`;if(!sB(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${i} requires a string type`);let a=e.type.trim(),s=e[sN];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${i} ${sN} must be a boolean`);if(s&&"outputSchema"!==n)throw Error(`${i} ${sN} is only supported in outputSchema`);if(s&&"array"!==a)throw Error(`${i} ${sN} is only supported for array fields`);let l=e[sL];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${i} ${sL} must be a boolean`);if(l&&!o)throw Error(`${i} ${sL} is only supported on top-level card output fields`);let p=e[sM];if(void 0!==p&&"boolean"!=typeof p)throw Error(`${i} ${sM} must be a boolean`);if(p&&!o)throw Error(`${i} ${sM} is only supported on top-level card output fields`);let d={type:function(e,t){if("integer"===e)return"int";if("number"===e)return"float";if(["string","boolean","object","array"].includes(e))return e;throw Error(`${t} has unsupported type "${e}"`)}(a,i),...s?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===a){if(!sB(e.properties))throw Error(`${i} requires object properties`);if(d.properties=Object.fromEntries(Object.entries(e.properties).map(([e,o])=>[e,sF(o,t,n,`${r}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${i} required must be a string array`);d.required=e.required}}if("array"===a){if(!sB(e.items))throw Error(`${i} requires object array items`);d.items=sF(e.items,t,n,`${r}[]`)}return d}function sH(e,t,n){let r=e[t];if(void 0===r)return{};if(!sB(r))throw Error(`manifest.yaml ${t} must be an object: ${n}`);return{...r}}function sW(e,t){if(!tQ.existsSync(e)||!tQ.statSync(e).isFile())throw Error(`${t} does not exist: ${e}`);return tQ.readFileSync(e,"utf8")}class sV{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(e=process.cwd()){this.appDirectory=e}async prepare(e,t={},n){let r=this.context;try{let r=Date.now(),o=await this.getUserConfig(t),i={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tk(t.appIcon)}:{}},a={pages:sf(i?.pages,"pages"),tools:sf(i?.tools,"tools"),widgets:sf(i?.widgets,"widgets")},s=function(e){let t=tC.join(e,"events.json");if(tQ.existsSync(t)&&tQ.statSync(t).isFile())return{readJson:()=>tQ.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let n=tC.join(e,"tools.json");if(!tQ.existsSync(n))return;let r=tC.join(e,"manifest.yaml"),o=()=>sW(n,"tools.json"),i=()=>(function({tools:e,manifestPath:t,manifestText:n}){let r=function(e,t){let n;try{n=(0,sR.qg)(e)}catch(e){throw Error(`Failed to parse manifest.yaml: ${t}`,{cause:e})}if(!sB(n))throw Error(`manifest.yaml must contain an object: ${t}`);return n}(n,t),o=sH(r,"tools",t),i=sH(r,"entities",t);for(let t of e){if(t.name in o)throw Error(`Tool "${t.name}" conflicts with a tool in manifest.yaml`);if(o[t.name]={login_type:"no_login",description:t.description,..."client"===t.toolType?{is_client_tool:!0}:{},input_schema:function(e,t){if("object"!==e.type||!sB(e.properties))throw Error(`Tool "${t}" inputSchema requires type object and object properties`);let n=Object.fromEntries(Object.entries(e.properties).map(([e,n])=>[e,sF(n,t,"inputSchema",e)])),r=e.required;if(void 0!==r&&(!Array.isArray(r)||r.some(e=>"string"!=typeof e)))throw Error(`Tool "${t}" inputSchema required must be a string array`);return{type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}(t.inputSchema,t.name),output:t.widgetId?{kind:"entities",entity_types:[t.name]}:{kind:"execution_result"},...t.permissions.length>0?{permissions:t.permissions}:{}},t.widgetId){if(t.name in i)throw Error(`Tool "${t.name}" conflicts with an entity in manifest.yaml`);i[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let n=t.name;if("array"!==e.type||!sB(e.items))throw Error(`Card Tool "${n}" outputSchema must be an array`);if("object"!==e.items.type||!sB(e.items.properties))throw Error(`Card Tool "${n}" outputSchema items must be objects`);let r=e.items.properties,o=sj.find(e=>e in r);if(o)throw Error(`Tool "${n}" outputSchema must not declare reserved field "${o}"`);let i=Object.entries(r).filter(([e,t])=>{if(!sB(t)||void 0===t[sL])return!1;if("boolean"!=typeof t[sL])throw Error(`Tool "${n}" outputSchema property "${e}" ${sL} must be a boolean`);return t[sL]});if(1!==i.length)throw Error(`Card Tool "${n}" outputSchema requires exactly one ${sL} field; found ${i.length}`);let a=Object.entries(r).filter(([e,t])=>{if(!sB(t)||void 0===t[sM])return!1;if("boolean"!=typeof t[sM])throw Error(`Tool "${n}" outputSchema property "${e}" ${sM} must be a boolean`);return t[sM]});if("same_conversation"===t.expirePolicy){let e=i[0]?.[0];if(1!==a.length||a[0]?.[0]!==e)throw Error(`Card Tool "${n}" with expirePolicy "same_conversation" requires ${sM} on its ${sL} field`)}return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,sF(t,n,"outputSchema",e,!0)]))}(t.outputSchema,t)},tool_card_binding:{[t.name]:t.widgetId},..."same_conversation"===t.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,sR.As)({...r,tools:o,entities:i})})({tools:(()=>{let e=function(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Failed to parse tools.json: ${t}`,{cause:e})}if(!sB(n)||!Array.isArray(n.tools)||0===n.tools.length)throw Error(`tools.json requires a non-empty tools array: ${t}`);let r=new Set;return{tools:n.tools.map((e,n)=>{let o=function(e,t,n){if(!sB(e))throw Error(`Tool at index ${t} must be an object: ${n}`);let r="string"==typeof e.name?e.name.trim():"",o="string"==typeof e.description?e.description.trim():"";if(!r||!o)throw Error(`Tool at index ${t} requires name and description: ${n}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${r}" tool_type must be "client" or "server"`);let i=function(e,t){if(void 0===e)return{};if(!sB(e))throw Error(`Tool "${t}" _meta must be an object`);if(void 0===e.ui)return{};if(!sB(e.ui))throw Error(`Tool "${t}" _meta.ui must be an object`);if("widgetPath"in e.ui)throw Error(`Tool "${t}" must use _meta.ui.widgetId instead of widgetPath`);let n=e.ui.widgetId;if(void 0!==n&&("string"!=typeof n||!n.trim()))throw Error(`Tool "${t}" _meta.ui.widgetId must be a non-empty string`);let r=e.ui.expirePolicy;if(void 0!==r&&"same_conversation"!==r)throw Error(`Tool "${t}" _meta.ui.expirePolicy must be "same_conversation" when provided`);if("same_conversation"===r&&"string"!=typeof n)throw Error(`Tool "${t}" _meta.ui.expirePolicy requires _meta.ui.widgetId`);return{..."string"==typeof n?{widgetId:n.trim()}:{},..."same_conversation"===r?{expirePolicy:r}:{}}}(e._meta,r);return{name:r,description:o,...i,inputSchema:sU(e.inputSchema,"inputSchema",r),outputSchema:sU(e.outputSchema,"outputSchema",r),permissions:function(e,t){if(void 0===e)return[];if(!Array.isArray(e)||e.some(e=>"string"!=typeof e||!e.trim()))throw Error(`Tool "${t}" permissions must be an array of non-empty strings`);return e.map(e=>e.trim())}(e.permissions,r),toolType:"client"===e.tool_type?"client":"server"}}(e,n,t);if(r.has(o.name))throw Error(`Duplicate Tool name: ${o.name}`);return r.add(o.name),o})}}(o(),n);var r=e.tools;let i=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??t3(e)));for(let e of r)if(e.widgetId&&!i.has(e.widgetId))throw Error(`Tool "${e.name}" references widgetId "${e.widgetId}" not declared in app.config.ts`);return e})().tools,manifestPath:r,manifestText:sW(r,"manifest.yaml")});return i(),{manifestSourcePath:r,readManifestYaml:i,readToolsJson:o,toolsSourcePath:n}}({appDirectory:this.appDirectory,normalizedAppConfig:a}),p=function(e){if(e)return!0===e?{mcpEndpoint:ev()}:{...e,mcpEndpoint:ev({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),d=Date.now()-r;this.rootPath=tC.resolve(this.appDirectory,"dist"),tQ.existsSync(tC.resolve(this.rootPath))&&tQ.rmSync(tC.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new sD,aT(this.context.compileLifecycle,r),this.context.compileLifecycle.prepareDurations.configLoadMs=d;let c=tC.resolve(this.appDirectory,"src"),u=Date.now(),{pages:m,widgets:h,auth:f,app:g,tools:y}=await this.analyzeConvention(c,a);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let b=new tB,_=ec(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:c,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:o,env:this._env,appConfig:i,normalizedAppConfig:a,command:e,metadata:b,signingEncryptionOptions:t.signingEncryptionOptions,skipAppInfoFetch:!!t.token,permissions:t.permissions,appId:t.appId,versionTag:t.versionTag,pages:m,widgets:h,auth:f,app:g,tools:y,internal:_,devServerInteractive:t.interactive,loginCookieResolver:()=>eF(t,{internal:_}),cachedLoginCookieResolver:()=>e_(t,_)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,(e===eD.DEV||void 0!==t.host)&&(this.context.devServerHost=await sI(t.host)),this.context.webDebuggerLaunchOptions=p,this.context.eventsResources=s,this.context.toolsResources=l,this.pluginSystem=new tK(this.context,[sd,ss,sc,sn,sh,so,su,si,...o.experiments?.taro?[function({name:e,appId:t,icons:n,widgets:r}){return{name:nt,setup:o=>{let i=(0,ne.createRequire)(import.meta.url);o.view.hooks.modifyEntryOption.tapPromise({name:nt,stage:o.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:n,pages:r,widgets:i}=o.context,a=t6(r,t,!1,n);return{entry:e=Object.assign(e,a,t6(i,t,!0,n))}}),o.view.hooks.beforeBuild.tapPromise({name:nt,stage:o.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=o.context;t9(e,{resolve:{alias:{"@tarojs/components":i.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,tY.dirname)(i.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),o.worker.hooks.modifyEntryOption.tapPromise({name:nt,stage:o.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:n})=>{let{appDirectory:r,isDev:i}=o.context,{app:a}=o.context;return a&&(n.app=function(e,t,n,r,o=!1){var i;let a=`${eq}${tC.sep}app.js`,s=(i=t8(tC.dirname(a),e)).startsWith(".")?i:`./${i}`,l=eO(t);return new t7(a,`
292
+ bootstrapClientToolRuntime([${s.join(", ")}]);
293
+ `)}(`${e.context.appDirectory}${tn.sep}${e$}${tn.sep}${eW}.js`,o,e.context.appDirectory,i)),{entry:t}}),e.worker.hooks.modifyEnvironment.tapPromise("AppletMainPlugin",async({environment:e})=>{}),e.worker.hooks.collectMetaData.tapPromise({name:"AppletMainPlugin",stage:e.worker.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:t})=>{let{app:r,appConfig:n,tools:i,userConfig:a}=e.context;await sN({appConfig:n,tools:i,app:r,collector:t,define:a.source?.define}),e.context.setVersionTag(e.context.metadata.app.version)}),e.assets.hooks.beforeEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:t,chunks:r})=>{var n,i;let{app:a,pages:o,tools:s}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),c=r[eW]?.find(({source:e})=>e.endsWith(".js")),p=t.getManifestAsset(e.context.manifestAssetPath),{manifest:d}=p,u=[];d.applet.pages.forEach(e=>{u.push(e.digest)});let m=a.metadata.appId,h=e.context.versionTag;p.assignBasicManifest({manifestVersion:"3.0",packageName:m,appId:m,versionName:h,versionTag:h,scmVersion:process.env.BUILD_VERSION,versionCode:Date.now().toString(),runtimeVersion:"1.0",sourceType:e.context.internal?1:2,settings:e.context.manifestSettings});let f=e.context.appAssetPath,g=e.context.normalizedAppConfig.pages.entryNames[0]??Object.keys(e.context.pages)[0],y=g?o[g]?.metadata.path:void 0,b=a.toManifest({toolsMetadata:s,hashCode:l?.hashCode??(n=l?.hashCode??d?.applet?.digest,i=u.join(""),oq.createHash("sha256").update(n+i).digest("hex").substring(0,8)),appRuntimeEntry:f,appRuntimeType:e.context.environment.useLynx?"lynx":"js"});c&&(b.toolRuntimeEntry=c.source),p.mergeAppletManifest(b),y&&p.mergeAppletManifest({appletEntry:y})}),e.assets.hooks.afterEmit.tapPromise({name:"AppletMainPlugin",stage:e.assets.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS},async({assets:e})=>{}),e.worker.hooks.afterBuild.tapPromise("AppletMainPlugin",async({stats:e})=>{}))}},sD={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,r=sv(t);if(!tP.existsSync(r))throw Error("ENOENT: no such file or directory")}},sj={name:"AppletManifestPlugin",setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:"AppletManifestPlugin",stage:e.assets.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS},async({assets:t})=>{let{signing:r}=await e.context.resolveSigningEncryptionOptions()||{};if(r?.enabled){let{signData:n}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)}),i=t.getManifestAsset(e.context.manifestAssetPath),{manifest:a}=i,{buffer:o,status:s,error_msg:l}=await n(Buffer.from(i.content),tD(r,{extra_config:{app_id:a.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let c=new oJ(eM,o);c.destination=eM,t.addAsset(eM,c)}})}},sM="AppletWebManifestPlugin",sU={name:sM,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sM,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var r,n;let i=e.context.metadata.getData(),a=i.app.appId||e.context.appId,o=e.context.command===rb.DEV?"all":"configured",s=re(e.context.pages,e.context.normalizedAppConfig.pages.entries,o),l=re(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,o);if(!a&&Object.keys(s).length>0)throw Error("解析 Web 页面入口路径需要 appId");let c=a?(r=i.pages,Object.keys(s).map(e=>{let t=r[e]??{},n=t.path??tN(e),i={entry:tL(a,n,t4)},o=t6(s[e]);return{path:n,entryName:e,web:i,debugHidden:o,manifest:{...t,path:n,digest:"",entry:"",renderType:H.LYNX,web:i,...o?{debugHidden:!0}:{}}}})):[],p=(n=i.widgets,Object.keys(l).map(e=>{let{id:t,...r}=n[e]??{},i=t??t7(l,n,e),a={entry:`${i}/${t4}`},o=t6(l[e]);return{id:i,entryName:e,web:a,debugHidden:o,manifest:{...r,widgetId:i,digest:"",entry:"",renderType:H.LYNX,web:a,...o?{debugHidden:!0}:{}}}}));if(0===c.length&&0===p.length&&0===e.context.normalizedAppConfig.tools.entryNames.length)return;let d=t.getManifestAsset(e.context.manifestAssetPath),u=new Map(c.map(e=>[e.path,e])),m=new Set(d.manifest.applet.pages?.map(e=>e.path));for(let e of(d.manifest.applet.pages?.forEach(e=>{let t=u.get(e.path);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),c))m.has(e.path)||d.appendPage(e.manifest);let h=new Map(p.map(e=>[e.id,e])),f=new Set(d.manifest.widgets?.map(e=>e.widgetId));for(let t of(d.manifest.widgets?.forEach(e=>{let t=h.get(e.widgetId);t&&(e.web=t.web,t.debugHidden&&(e.debugHidden=!0))}),p))if(!f.has(t.id)){let r=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(r.titleType=F.NONE),d.appendWidget(r)}e.context.app&&(d.manifest.applet.web={appRuntimeEntry:t5,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:t9}:{}})})}};function sB(e=((e=process.cwd())=>tH(e)===tM)()){return e?"sso":"sms"}async function sF(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sB(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function sH(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sB(t)})}function sW(e,t){let r;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))r=e;else if("object"==typeof e)t&&e4.warn(`${t} 的对象映射配置已弃用,请改用由字符串或 { entry, ...metadata } 对象组成的数组。`),r=Object.entries(e).map(([e,t])=>{let r;return{...t,entry:(r=e.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"")).endsWith("/index")?r:`${r}/index`}});else throw Error("入口配置必须是数组或对象映射。");let n=[],i={},a=new Set,o=[],s=new Set;return r.forEach(e=>{let t,r;if("string"==typeof e)t=e,r={};else{let{entry:n,...i}=e;if(!n)throw Error('入口配置对象必须包含 "entry"。');t=n,r=i}a.has(t)?s.has(t)||(o.push(t),s.add(t)):(n.push(t),a.add(t)),i[t]=r}),t&&o.length>0&&e4.warn(`${t} 配置中存在重复入口:${o.join(", ")}。已合并重复入口,以最后一次的元数据配置为准。`),{entryNames:n,entries:i}}class sG{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._cookie="",this._pages={},this._auth={viewEntries:{},apiEntries:{}},this._viewEntriesByType={}}async bootstrap({command:e,metadata:t,versionTag:r,srcDirectory:n="",virtualEntryDir:i="",appDirectory:a=process.cwd(),rootPath:o="",manifestPath:s="",pages:l={},widgets:c={},auth:p,mcpUI:d,app:u="",tools:m={},environment:h={useLynx:!1,useAuth:!1},viewEntriesByType:f={},loginCookieResolver:g,cachedLoginCookieResolver:y}){this._command=e,this._metadata=t,this._versionTag=r,this._srcDirectory=n,this._virtualEntryDir=i,this._appDirectory=a,this._rootPath=o,this._manifestPath=s,this._pages={...l},this._widgets={...c};let b=p??d??{viewEntries:{},apiEntries:{}};this._auth={viewEntries:{...b.viewEntries},apiEntries:{...b.apiEntries}},this._app=u,this._tools={...m},this._environment={useLynx:h.useLynx,useAuth:!!(h.useAuth||h.useMcpUI)},this._cookie="",this._loginCookieResolver=g,this._loginCookiePromise=void 0,this._cachedLoginCookieResolver=y,this._viewEntriesByType=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}])),this._isInitialized=!0}assertInitialized(e){if(!this._isInitialized)throw Error(`BuildContext.${e} is unavailable before bootstrap`)}get isDev(){return this.assertInitialized("isDev"),this._command===rb.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(tP.readFileSync(this._manifestPath,"utf-8")),{...this._manifest}}catch(e){return{}}}get useLynx(){return this._environment.useLynx}get useAuth(){return this._environment.useAuth}get useMcpUI(){return this.useAuth}get manifestAssetPath(){return ej}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(([e,t])=>[e,{pages:{...t.pages},widgets:{...t.widgets}}]))}get app(){return this._app}get tools(){return{...this._tools}}async getLoginCookie(){return(this.assertInitialized("getLoginCookie"),this._cookie)?this._cookie:this._loginCookieResolver?(this._loginCookiePromise||(this._loginCookiePromise=this._loginCookieResolver().then(e=>(this._cookie=e??"",e)).catch(e=>{throw this._loginCookiePromise=void 0,e})),await this._loginCookiePromise):void 0}async getCachedLoginCookie(){if(this.assertInitialized("getCachedLoginCookie"),this._cookie)return this._cookie;if(!this._cachedLoginCookieResolver)return;let e=await this._cachedLoginCookieResolver();return e&&(this._cookie=e),e}get appId(){return this._appId||this._metadata.appId}setAppId(e){this._appId=e}setApp(e){this._app=e}setTools(e){this._tools=e}setEnvironment(e){this._environment={...e}}mergeEnvironment(e){this._environment={...this._environment,...e}}setPages(e){this._pages=e}setWidgets(e){this._widgets=e}appendPages(e){Object.assign(this._pages,e)}appendWidgets(e){Object.assign(this._widgets,e)}getViewEntriesByType(e){let t=this._viewEntriesByType[e];return t?{pages:{...t.pages},widgets:{...t.widgets}}:{pages:{},widgets:{}}}setViewEntriesByType(e,t){this._viewEntriesByType[e]={pages:{...t.pages},widgets:{...t.widgets}}}setAppAssetPath(e){this._appAssetPath=e}setAppMapAssetPath(e){this._appMapAssetPath=e}setManifest(e){this._manifest=e}setVersionTag(e){return this.assertInitialized("versionTag"),!this._versionTag&&e&&(this._versionTag=e),this._versionTag}setAuthApi(e){this._auth={viewEntries:{...e.viewEntries},apiEntries:{...e.apiEntries}}}setMcpUIApi(e){this.setAuthApi(e)}get versionTag(){return this.assertInitialized("versionTag"),this._versionTag}}async function sV({internal:e,domainId:t,appLimit:r,appOffset:n,keyWord:i,appKey:a,cookie:o}){return await n8({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:r,app_offset:n,key_word:i,app_key:a},method:"GET",headers:o?{Cookie:o}:void 0})}async function sq({source:e,internal:t,domainId:r,appLimit:n,appOffset:i,releaseStatus:a,keyWord:o,appKey:s,cookie:l}){return await n8({internal:t,domainId:r,path:"/developer/api/apps",query:{source:e,app_limit:n,app_offset:i,release_status:a,key_word:o,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function sJ({appKey:e,source:t,internal:r,domainId:n,releaseStatus:i,limit:a,offset:o,status:s,keyWord:l,versionTag:c,cookie:p}){return await n8({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:i,limit:a,offset:o,status:s,key_word:l,version_tag:c},method:"GET",headers:p?{Cookie:p}:void 0})}async function sz({appKey:e,versionTag:t,internal:r,domainId:n,pageSize:i,pageNum:a,cookie:o}){return await n8({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:i,page_num:a},method:"GET",headers:o?{Cookie:o}:void 0})}function sK(e){return e.is_latest||e.is_current}function sY(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function sX(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function sZ(e){return e.version_tag}function sQ(e,t){eS()&&e4.info(e,t)}async function s0({appKey:e,internal:t=!1,cookie:r,source:n=rT.REQUEST_SOURCE_IDE}){sQ("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:r?"present":"absent"});let i=await sV({internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.app_list||[],i=n.find(t=>t.app_key===e);return sQ("[app-info] MGetApps 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),i}).catch(t=>{if(sQ("[app-info] MGetApps 请求失败",{appKey:e,reason:sa(t)}),oy(t))throw t}),a=i?void 0:await sq({source:n,internal:t,appLimit:1,appOffset:0,appKey:e,cookie:r}).then(({data:t,log_id:r})=>{let n=t?.org_list?.flatMap(e=>e.app_list)||[],i=n.find(t=>t.app_key===e),a=i||n[0];return sQ("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),a?.app_meta}).catch(t=>{sQ("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:sa(t)})});if(!i&&!a)throw sQ("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let o=i?void 0:await sJ({appKey:e,source:n,internal:t,cookie:r}).then(({data:t,log_id:r})=>{let n=Array.isArray(t?.version_list)?t.version_list:[];if(sQ("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:n.length,logId:r}),0===n.length)return;let i=n.find(sK);return i||n.reduce((e,t)=>{let r,n;return!e||(r=sY(t),n=sY(e),(Number.isNaN(r)&&Number.isNaN(n)?sX(t)-sX(e):(Number.isNaN(r)?-1/0:r)-(Number.isNaN(n)?-1/0:n))>0)?t:e},void 0)}).catch(t=>{sQ("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:sa(t)})}),s=i?.current_version_tag||(o?sZ(o):""),l=i?.icon_url||(o?o.icon_url:void 0)||a?.icon_url,c=i?.name||a?.name,p=o&&sZ(o)===s?o:i?{version_tag:i.current_version_tag,icon_url:i.icon_url,updated_at:i.updated_at,online_at:i.online_at,offline_at:i.offline_at}:{version_tag:s,icon_url:l};if(i||!s||!r)return{appKey:e,appName:c,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:p};let d=await sz({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:r}).then(t=>(sQ("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw sQ("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:sa(t)}),t});return{appKey:e,appName:c,versionTag:s,iconUrl:l,permissionList:d.data?.permission_list||[],permissionTotal:d.data?.total||0,version:p}}function s1(){return function({fetch:e,getCacheKey:t,ttl:r,timeout:n,cacheFailures:i=!1,now:a=Date.now}){let o=new Map;return function(...s){var l,c;let p,d="string"==typeof(l=t(...s))?l:JSON.stringify(l),u=a(),m=o.get(d);if(m&&m.expiresAt>u)return m.promise;let h=(c=e(...s),void 0===n?c:Promise.race([c,new Promise((e,t)=>{p=setTimeout(()=>{t(Error(`Request timed out after ${n}ms`))},n)})]).finally(()=>{p&&clearTimeout(p)})).catch(e=>{throw i||o.get(d)?.promise!==h||o.delete(d),e});return o.set(d,{expiresAt:u+r,promise:h}),h}}({fetch:s0,getCacheKey:({appKey:e,internal:t,cookie:r})=>[e,t,r],ttl:6e4,timeout:1e4,cacheFailures:!0})}async function s2(e="0.0.0.0"){if(!e||e.includes(":"))throw Error("--host 必须是 IPv4 地址或主机名,不能包含协议或端口;暂不支持 IPv6。");let{address:t}=await (0,x.lookup)(e,{family:4});if("0.0.0.0"!==t)return t;let r=eg()[0];return r||(e7.warn("未找到外部 IPv4 地址,将使用 127.0.0.1,仅支持本机访问。"),"127.0.0.1")}async function s3(e,t,r){let n=await fetch(`${e}/base/manifest.json`,{signal:AbortSignal.any([r,AbortSignal.timeout(1500)]),redirect:"error"}),i=await n.json();if(!n.ok||t&&i?.appId!==t)throw Error(`开发服务器返回的 manifest 无效:${e}(HTTP ${n.status},appId:${t})`)}async function s4(e,t,r,n){let i,a=eh(e,t),o=AbortSignal.any([n,AbortSignal.timeout(5e3)]);try{for(;;)try{await s3(a,r,o);break}catch(e){i=e,await (0,v.setTimeout)(200,void 0,{signal:o})}}catch{throw n.throwIfAborted(),Error(`开发服务器的 manifest 在 5 秒内未就绪:${a}/base/manifest.json。请检查网络,或使用 --host <IP> 指定设备可访问的本机 IP`,{cause:i})}return{host:a,artifactOrigin:a}}(rd=rS||(rS={}))[rd.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",rd[rd.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(ru=rx||(rx={}))[ru.DRAFT=0]="DRAFT",ru[ru.UNDER_REVIEW=1]="UNDER_REVIEW",ru[ru.APPROVED=2]="APPROVED",ru[ru.REJECTED=3]="REJECTED",ru[ru.WITHDRAWN=4]="WITHDRAWN",ru[ru.PUBLISHING=5]="PUBLISHING",ru[ru.PUBLISHED=6]="PUBLISHED",ru[ru.ARCHIVED=7]="ARCHIVED",ru[ru.DELETED=8]="DELETED",(rm=rA||(rA={}))[rm.DRAFT=0]="DRAFT",rm[rm.PUBLISHED=1]="PUBLISHED",rm[rm.ARCHIVED=2]="ARCHIVED",(rh=rT||(rT={}))[rh.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",rh[rh.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",rh[rh.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",rh[rh.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class s5 extends sG{devServerInteractive=!0;devServerHost="0.0.0.0";devServerAbort=new AbortController;finishInitialDevCompile;initialDevCompile=new Promise(e=>{this.finishInitialDevCompile=e,this.devServerAbort.signal.addEventListener("abort",()=>e(void 0),{once:!0})});devServerResolution;resolveDevServer(e){return this.devServerResolution??=this.initialDevCompile.then(t=>{if(t)throw t;return this.devServerAbort.signal.throwIfAborted(),s4(e,this.devServerHost,this.appId,this.devServerAbort.signal)})}getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=oU();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=s1();_skipAppInfoFetch=!1;_hasWarnedAppInfoFetchFailure=!1;_templateWidgetEntries=new Set;_permissions;get userConfig(){return this._userConfig}get env(){return{...this._env}}get appConfig(){return this._appConfig}get normalizedAppConfig(){var e;return{pages:{entryNames:[...(e=this._normalizedAppConfig).pages.entryNames],entries:Object.fromEntries(Object.entries(e.pages.entries).map(([e,t])=>[e,{...t}]))},tools:{entryNames:[...e.tools.entryNames],entries:Object.fromEntries(Object.entries(e.tools.entries).map(([e,t])=>[e,{...t}]))},widgets:{entryNames:[...e.widgets.entryNames],entries:Object.fromEntries(Object.entries(e.widgets.entries).map(([e,t])=>[e,{...t}]))}}}get templateWidgetEntries(){return new Set(this._templateWidgetEntries)}get permissions(){return this._permissions?.map(e=>({...e}))}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(e){this._rawSigningEncryptionOptions=e,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(e){this._templateWidgetEntries.add(e)}async resolveSigningEncryptionOptions(){return this._signingEncryptionOptionsPromise||(this._signingEncryptionOptionsPromise=this.resolveSigningEncryptionOptionsOnce()),this._signingEncryptionOptionsPromise}async resolveAppInfo(){this.assertInitialized("resolveAppInfo");let e=this.compileLifecycle.appInfoMeasured?void 0:Date.now();this.compileLifecycle.appInfoMeasured=!0;try{return await this.resolveAppInfoInternal()}finally{void 0!==e&&(this.compileLifecycle.appInfoDurationMs=Math.max(0,Date.now()-e))}}async resolveAppInfoInternal(){var e;let t=this.appId;if(!og(t))return;let r="string"==typeof(e=this._appConfig.icons)?e.length>0?e:void 0:e?.["3x"]||e?.["2x"]||e?.["1x"],n={appKey:t,versionTag:this.versionTag??"",permissionList:[],permissionTotal:0,version:{},...this._appConfig.name?{appName:this._appConfig.name}:{},...r?{iconUrl:r}:{}};if(this._skipAppInfoFetch)return n;let i=await this.getCachedLoginCookie().catch(()=>void 0);try{return Object.assign(n,await this._fetchCachedAppInfo({appKey:t,cookie:i,internal:this.internal})),n.appName||=this._appConfig.name,n.iconUrl||=r,n}catch(e){if(this.command!==rb.DEV&&this.command!==rb.BUILD)throw e;if(oy(e))return n;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,e4.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:sa(e)})),n}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:r,userConfig:n,appConfig:i={},normalizedAppConfig:a={pages:{entryNames:[],entries:{}},tools:{entryNames:[],entries:{}},widgets:{entryNames:[],entries:{}}},command:o,metadata:s,signingEncryptionOptions:l,disableSigningEncryption:c,appId:p,versionTag:d,pages:u,widgets:m,auth:h,app:f,tools:g,internal:y,skipAppInfoFetch:b,permissions:_,devServerInteractive:v=!0,env:E={},loginCookieResolver:w,cachedLoginCookieResolver:S}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:tn.resolve(t,e$),rootPath:r,manifestPath:tn.resolve(`${r}/${ej}`),command:o,metadata:s,versionTag:d,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:w,cachedLoginCookieResolver:S});let{icons:x,...A}=i??{};this._userConfig=n,this.devServerInteractive=v,this._env={...E},this._appConfig={...A,...void 0!==p?{appId:p}:{},...void 0!==x?{icons:tl(x)}:{}},this._normalizedAppConfig=a,this._internal=y??((e=process.cwd())=>tH(e)===tM)(t),this._skipAppInfoFetch=!!b,this._permissions=_?.map(e=>({...e})),this._hasWarnedAppInfoFetchFailure=!1,this._templateWidgetEntries=new Set,this._rawSigningEncryptionOptions=l,this._signingEncryptionOptions=void 0,this._signingEncryptionOptionsPromise=void 0,this._disableSigningEncryption=!!c,this._appId=p??i?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=s1()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await sl(this._rawSigningEncryptionOptions,this.command,e,this._disableSigningEncryption),this._signingEncryptionOptions?.encryption.enabled){let{generateDEK:e}=await import("node:module").then(function(e){return f.t(e.createRequire(import.meta.url)("@doubao-dev/security-tasm"),18)});this._dek=e(),eS()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function s9({appId:e,versionTag:t,versionCode:r,packagePath:n,internal:i,domainId:a,cookie:o,token:s,needAuth:l=!0}){let c=new FormData,p=new Blob([new Uint8Array(tP.readFileSync(n))],{type:"application/zip"});c.append("applet_file",p,"doubao_app.zip"),c.append("applet_version_code",r.toString());let d=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await n8({internal:i,domainId:s?"sms-external":a,path:d,method:"POST",body:c,headers:{...o?{Cookie:o}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function s8({versionTag:e,appKey:t,manifest:r,rootPath:n,internal:i,needAuth:a=!0,cookie:o,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:c,versionCode:p}=r,d=function(e,t){let r=e||t.versionTag||t.versionName;if(!r)throw Error("Doubao Apps Platform deploy requires versionTag in params or app metadata.");return r}(e,r),{packageResource:u}=await tC({channelName:"doubao_app",manifest:r,rootPath:n});if(!u)throw Error("Failed to archive package");let m=await s9({appId:t||l||c,versionTag:d,versionCode:p,packagePath:u.resource,internal:i,needAuth:a,cookie:o,token:s});return console.log("Deploy success:",m),m}let s7=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),s6="x-db-llm-modifiable",le="x-db-is-entity-id",lt="x-db-is-refresh-key",lr=["entity_type"];function ln(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function li(e,t,r){if(!ln(e))throw Error(`Tool "${r}" 的 ${t} 必须是对象`);return e}function la(e,t,r,n,i=!1){let a=`Tool "${t}" 的 ${r} 属性 "${n}"`;if(!ln(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${a} 必须提供字符串类型的 type`);let o=e.type.trim(),s=e[s6];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${a} 的 ${s6} 必须是布尔值`);if(s&&"outputSchema"!==r)throw Error(`${a} 的 ${s6} 仅支持在 outputSchema 中使用`);if(s&&"array"!==o)throw Error(`${a} 的 ${s6} 仅支持用于数组字段`);let l=e[le];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${a} 的 ${le} 必须是布尔值`);if(l&&!i)throw Error(`${a} 的 ${le} 仅支持用于卡片输出的顶层字段`);let c=e[lt];if(void 0!==c&&"boolean"!=typeof c)throw Error(`${a} 的 ${lt} 必须是布尔值`);if(c&&!i)throw Error(`${a} 的 ${lt} 仅支持用于卡片输出的顶层字段`);let p={type:function(e,t){if("integer"===e)return"int";if("number"===e)return"float";if(["string","boolean","object","array"].includes(e))return e;throw Error(`${t} 使用了不支持的类型 "${e}"`)}(o,a),...s?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===o){if(!ln(e.properties))throw Error(`${a} 必须提供对象类型的 properties`);if(p.properties=Object.fromEntries(Object.entries(e.properties).map(([e,i])=>[e,la(i,t,r,`${n}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${a} 的 required 必须是字符串数组`);p.required=e.required}}if("array"===o){if(!ln(e.items))throw Error(`${a} 必须提供对象类型的数组项定义 items`);p.items=la(e.items,t,r,`${n}[]`)}return p}function lo(e,t,r){let n=e[t];if(void 0===n)return{};if(!ln(n))throw Error(`manifest.yaml 的 ${t} 必须是对象:${r}`);return{...n}}function ls(e,t){if(!tP.existsSync(e)||!tP.statSync(e).isFile())throw Error(`${t} 文件不存在:${e}`);return tP.readFileSync(e,"utf8")}class ll{pluginSystem;rootPath="dist";context;appDirectory;_userConfig;_appConfig;_appConfigLoaded=!1;_env={};constructor(e=process.cwd()){this.appDirectory=e}async prepare(e,t={},r){let n=this.context;try{let n=Date.now(),i=await this.getUserConfig(t),a={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tl(t.appIcon)}:{}},o={pages:sW(a?.pages,"pages"),tools:sW(a?.tools,"tools"),widgets:sW(a?.widgets,"widgets")},s=function(e){let t=tn.join(e,"events.json");if(tP.existsSync(t)&&tP.statSync(t).isFile())return{readJson:()=>tP.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let r=tn.join(e,"tools.json");if(!tP.existsSync(r))return;let n=tn.join(e,"manifest.yaml"),i=()=>ls(r,"tools.json"),a=()=>(function({tools:e,manifestPath:t,manifestText:r}){let n=function(e,t){let r;try{r=(0,s7.qg)(e)}catch(e){throw Error(`解析 manifest.yaml 失败:${t}`,{cause:e})}if(!ln(r))throw Error(`manifest.yaml 必须包含一个对象:${t}`);return r}(r,t),i=lo(n,"tools",t),a=lo(n,"entities",t);for(let t of e){if(t.name in i)throw Error(`Tool "${t.name}" 与 manifest.yaml 中的 Tool 重名`);if(i[t.name]={login_type:"no_login",description:t.description,..."client"===t.toolType?{is_client_tool:!0}:{},input_schema:function(e,t){if("object"!==e.type||!ln(e.properties))throw Error(`Tool "${t}" 的 inputSchema.type 必须为 object,且 properties 必须是对象`);let r=Object.fromEntries(Object.entries(e.properties).map(([e,r])=>[e,la(r,t,"inputSchema",e)])),n=e.required;if(void 0!==n&&(!Array.isArray(n)||n.some(e=>"string"!=typeof e)))throw Error(`Tool "${t}" 的 inputSchema.required 必须是字符串数组`);return{type:"object",properties:r,...n&&n.length>0?{required:n}:{}}}(t.inputSchema,t.name),output:t.widgetId?{kind:"entities",entity_types:[t.name]}:{kind:"execution_result"},...t.permissions.length>0?{permissions:t.permissions}:{}},t.widgetId){if(t.name in a)throw Error(`Tool "${t.name}" 与 manifest.yaml 中的实体重名`);a[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let r=t.name;if("array"!==e.type||!ln(e.items))throw Error(`Card Tool "${r}" 的 outputSchema.type 必须为 array,且 items 必须是对象`);if("object"!==e.items.type||!ln(e.items.properties))throw Error(`Card Tool "${r}" 的 outputSchema.items 必须是对象类型的定义`);let n=e.items.properties,i=lr.find(e=>e in n);if(i)throw Error(`Tool "${r}" 的 outputSchema 不能声明保留字段 "${i}"`);let a=Object.entries(n).filter(([e,t])=>{if(!ln(t)||void 0===t[le])return!1;if("boolean"!=typeof t[le])throw Error(`Tool "${r}" 的 outputSchema 属性 "${e}" 的 ${le} 必须是布尔值`);return t[le]});if(1!==a.length)throw Error(`Card Tool "${r}" 的 outputSchema 必须有且仅有一个 ${le} 字段,当前有 ${a.length} 个`);let o=Object.entries(n).filter(([e,t])=>{if(!ln(t)||void 0===t[lt])return!1;if("boolean"!=typeof t[lt])throw Error(`Tool "${r}" 的 outputSchema 属性 "${e}" 的 ${lt} 必须是布尔值`);return t[lt]});if("same_conversation"===t.expirePolicy){let e=a[0]?.[0];if(1!==o.length||o[0]?.[0]!==e)throw Error(`Card Tool "${r}" 使用 expirePolicy "same_conversation" 时,必须在 ${le} 字段上设置 ${lt}`)}return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,la(t,r,"outputSchema",e,!0)]))}(t.outputSchema,t)},tool_card_binding:{[t.name]:t.widgetId},..."same_conversation"===t.expirePolicy?{history_card_refresh:{enabled:!0,scope:"same_conversation",refresh_to:"fixed_style"}}:{}}}}return(0,s7.As)({...n,tools:i,entities:a})})({tools:(()=>{let e=function(e,t){let r;try{r=JSON.parse(e)}catch(e){throw Error(`解析 tools.json 失败:${t}`,{cause:e})}if(!ln(r)||!Array.isArray(r.tools)||0===r.tools.length)throw Error(`tools.json 必须包含非空的 tools 数组:${t}`);let n=new Set;return{tools:r.tools.map((e,r)=>{let i=function(e,t,r){if(!ln(e))throw Error(`索引为 ${t} 的 Tool 配置必须是对象:${r}`);let n="string"==typeof e.name?e.name.trim():"",i="string"==typeof e.description?e.description.trim():"";if(!n||!i)throw Error(`索引为 ${t} 的 Tool 配置必须提供 name 和 description:${r}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${n}" 的 tool_type 必须为 "client" 或 "server"`);let a=function(e,t){if(void 0===e)return{};if(!ln(e))throw Error(`Tool "${t}" 的 _meta 必须是对象`);if(void 0===e.ui)return{};if(!ln(e.ui))throw Error(`Tool "${t}" 的 _meta.ui 必须是对象`);if("widgetPath"in e.ui)throw Error(`Tool "${t}" 必须使用 _meta.ui.widgetId,不能使用 widgetPath`);let r=e.ui.widgetId;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error(`Tool "${t}" 的 _meta.ui.widgetId 必须是非空字符串`);let n=e.ui.expirePolicy;if(void 0!==n&&"same_conversation"!==n)throw Error(`Tool "${t}" 的 _meta.ui.expirePolicy 如有设置,必须为 "same_conversation"`);if("same_conversation"===n&&"string"!=typeof r)throw Error(`Tool "${t}" 设置 _meta.ui.expirePolicy 时必须提供 _meta.ui.widgetId`);return{..."string"==typeof r?{widgetId:r.trim()}:{},..."same_conversation"===n?{expirePolicy:n}:{}}}(e._meta,n);return{name:n,description:i,...a,inputSchema:li(e.inputSchema,"inputSchema",n),outputSchema:li(e.outputSchema,"outputSchema",n),permissions:function(e,t){if(void 0===e)return[];if(!Array.isArray(e)||e.some(e=>"string"!=typeof e||!e.trim()))throw Error(`Tool "${t}" 的 permissions 必须是由非空字符串组成的数组`);return e.map(e=>e.trim())}(e.permissions,n),toolType:"client"===e.tool_type?"client":"server"}}(e,r,t);if(n.has(i.name))throw Error(`Tool 名称重复:${i.name}`);return n.add(i.name),i})}}(i(),r);var n=e.tools;let a=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??tk(e)));for(let e of n)if(e.widgetId&&!a.has(e.widgetId))throw Error(`Tool "${e.name}" 引用的 widgetId "${e.widgetId}" 未在 app.config.ts 中声明`);return e})().tools,manifestPath:n,manifestText:ls(n,"manifest.yaml")});return a(),{manifestSourcePath:n,readManifestYaml:a,readToolsJson:i,toolsSourcePath:r}}({appDirectory:this.appDirectory,normalizedAppConfig:o}),c=function(e){if(e)return!0===e?{mcpEndpoint:tQ()}:{...e,mcpEndpoint:tQ({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),p=Date.now()-n;this.rootPath=tn.resolve(this.appDirectory,"dist"),tP.existsSync(tn.resolve(this.rootPath))&&tP.rmSync(tn.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new s5,oB(this.context.compileLifecycle,n),this.context.compileLifecycle.prepareDurations.configLoadMs=p;let d=tn.resolve(this.appDirectory,"src"),u=Date.now(),{pages:m,widgets:h,auth:f,app:g,tools:y}=await this.analyzeConvention(d,o);this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let b=new tf,_=((e=process.cwd())=>tH(e)===tM)(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:d,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:i,env:this._env,appConfig:a,normalizedAppConfig:o,command:e,metadata:b,signingEncryptionOptions:t.signingEncryptionOptions,skipAppInfoFetch:!!t.token,permissions:t.permissions,appId:t.appId,versionTag:t.versionTag,pages:m,widgets:h,auth:f,app:g,tools:y,internal:_,devServerInteractive:t.interactive,loginCookieResolver:()=>sF(t,{internal:_}),cachedLoginCookieResolver:()=>sH(t,_)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,(e===rb.DEV||void 0!==t.host)&&(this.context.devServerHost=await s2(t.host)),this.context.webDebuggerLaunchOptions=c,this.context.eventsResources=s,this.context.toolsResources=l,this.pluginSystem=new tA(this.context,[sL,sR,sD,sT,sU,sO,sj,sP,...i.experiments?.taro?[function({name:e,appId:t,icons:r,widgets:n}){return{name:tJ,setup:i=>{let a=(0,tq.createRequire)(import.meta.url);i.view.hooks.modifyEntryOption.tapPromise({name:tJ,stage:i.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:r,pages:n,widgets:a}=i.context,o=tV(n,t,!1,r);return{entry:e=Object.assign(e,o,tV(a,t,!0,r))}}),i.view.hooks.beforeBuild.tapPromise({name:tJ,stage:i.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=i.context;tD(e,{resolve:{alias:{"@tarojs/components":a.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eR.dirname)(a.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),i.worker.hooks.modifyEntryOption.tapPromise({name:tJ,stage:i.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:r})=>{let{appDirectory:n,isDev:a}=i.context,{app:o}=i.context;return o&&(r.app=function(e,t,r,n,i=!1){var a;let o=`${e$}${tn.sep}app.js`,s=(a=tj(tn.dirname(o),e)).startsWith(".")?a:`./${a}`,l=tW(t);return new tG(o,`
161
294
  import { Applet } from "${l}";
162
295
  import { defineApp } from '${l}';
163
296
  import { APP_ID, getLifecycle, setCurrentId } from '@doubao-dev/taro-runtime/internal';
@@ -175,7 +308,7 @@ if (typeof App === 'function') {
175
308
  }
176
309
 
177
310
  const app = defineApp({
178
- aiMeta: { name: '${n}', appId: '${r}', description: '${n}' },
311
+ aiMeta: { name: '${r}', appId: '${n}', description: '${r}' },
179
312
  onLaunch() {
180
313
  lifecycle.onLaunch.forEach((handler) => handler());
181
314
  },
@@ -197,9 +330,9 @@ const app = defineApp({
197
330
  });
198
331
 
199
332
  new Applet(app, []).bootstrap();
200
- ${o?`
333
+ ${i?`
201
334
  if (import.meta.webpackHot) {
202
335
  import.meta.webpackHot.accept()
203
336
  }
204
337
  `:""}
205
- `)}(a,r,e,t,i)),{entry:n}}),o.worker.hooks.collectMetaData.tapPromise(nt,async({collector:r})=>{r.addAppMeta({name:e,appId:t,icons:n})}),o.view.hooks.collectMetaData.tapPromise({name:nt,stage:o.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:e})=>{let{pages:t,widgets:n}=o.context;Object.entries(t).forEach(([t,n])=>{let{folderName:r}=n;e.addPageMeta(t,{id:t3(t,r),path:t4(t)})}),Object.entries(n).forEach(([t,n])=>{let o,{folderName:i}=n;e.addWidgetMeta(t,(o=t3(t,i),{...r?.[i]??r?.[t]??r?.[o]??{},id:o}))})})}}}(o.experiments.taro)]:[],...o.plugins||[]]);let w=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-w,this.context.setVersionTag(i.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let S=await a0({options:o,commandType:e,context:this.context,rsbuildPlugins:n},this.pluginSystem);return{userConfig:o,builder:S}}catch(t){throw aO.report({appDirectory:this.appDirectory,context:this.context===r?void 0:this.context,scene:e===eD.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,n,{builder:r}=await this.prepare(eD.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=tt({cwd:this.appDirectory});let o=await r.startDevServer(),i=this.context.webDebuggerLaunchOptions;try{let e=await this.context.resolveDevServer(o.port);t=e.host,n=i?await at(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:e.artifactOrigin,env:{...this.context.env,...i.env??{}},mcpEndpoint:i.mcpEndpoint,mcpHeaders:i.mcpHeaders,simulator:i.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:i.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:i.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await o.server.close(),e}let a=async()=>{ez.info("Shutting down...");try{await n?.close(),await o.server.close()}finally{await aO.flush()}ez.info("dev server closed")};return{host:t,devServerReady:!0,...n?{webDebugger:n}:{},closeServer:a}}async build(e){let{builder:t}=await this.prepare(eD.BUILD,e,e.rsbuildPlugins);try{await t.build(),this.copyWebAssetsToRoot()}finally{if(e.skipCleanupRootPath||eu()){if(e.archive&&e.channel){let{channel:t}=e;await t0({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else tQ.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(eD.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(eD.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(eD.DEPLOY,e),n=e.deployType||t2.NORMAL;if(this.context.deploy={...this.context.deploy,...e.appId?{appId:e.appId}:{},...e.versionCode?{versionCode:e.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.doubaoAppsPlatform&&!this.context.deploy.selfBuilt){if(n!==t2.NORMAL)return void es.error("Please use deploy plugin in doubao.config.ts");let r=e.token?void 0:await this.context.getLoginCookie();if(!e.token&&!r)throw Error("Doubao Apps Platform 部署需要登录,请运行 `doubao login` 后重试。");return await t.build(),this.copyWebAssetsToRoot(),await s$({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...e.appId?{appKey:e.appId}:{},manifest:this.context.manifest,rootPath:this.rootPath,internal:this.context.internal,needAuth:!0,...r?{cookie:r}:{},...e.token?{token:e.token}:{}})}(e.build||n===t2.NORMAL)&&(await t.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:n})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case e0.DEV:return await this.dev(t);case e0.BUILD:return await this.build(t);case e0.ANALYZE:return await this.analyze(t);case e0.PERF:return await this.perf(t);case e0.DEPLOY:return await this.deploy(t)}}async getUserConfig(e){if(!this._userConfig){let t=(0,v.loadEnv)({cwd:this.appDirectory,mode:e.envMode}),n=await e1({cwd:this.appDirectory,customConfigFile:e.config});this._env=t.parsed,n.source||={},n.source.define={...t.publicVars,...n.source.define},e.debugDriver&&(n.debugDriver=e.debugDriver),void 0!==e.skipAdbForegroundAppWatch&&(n.skipAdbForegroundAppWatch=e.skipAdbForegroundAppWatch),this._userConfig=n}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let e=[this.context.manifest?.applet.web?.appRuntimeEntry,...this.context.manifest?.applet.pages?.map(e=>e.web?.entry)??[],...this.context.manifest?.widgets?.map(e=>e.web?.entry)??[]].filter(e=>!!e);if(0===e.length)return;let t=tC.resolve(this.appDirectory,"dist");for(let n of e){let e=tC.resolve(t,n);if(e!==t&&!e.startsWith(`${t}${tC.sep}`))throw Error(`Web artifact path escapes the Web output root: ${n}`);if(!tQ.existsSync(e))throw Error(`Web artifact is missing after build: ${e}`);let r=tC.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`,n);tQ.mkdirSync(tC.dirname(r),{recursive:!0}),tQ.copyFileSync(e,r)}let n=tC.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`),r=tC.resolve(n,"base","manifest.json");tQ.mkdirSync(tC.dirname(r),{recursive:!0}),tQ.writeFileSync(r,JSON.stringify(this.context.manifest),"utf-8")}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await a2({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await eT({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:n,widgets:r,auth:o}=await se(e,t),{app:i,tools:a}=await a6(e,t.tools);return{pages:n,widgets:r,auth:o,app:i,tools:a}}}async function sG(e){let t=await tA(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function sq({compileHooks:e,output:t}){let n=new Map,r={percentage:0},o=()=>{if(0===n.size)return;let e=[...n.values()].reduce((e,t)=>t.percentage<e.percentage?t:e);(e.percentage!==r.percentage||e.stage!==r.stage)&&(r=e,t?.onProgress?.(e))},i=e=>{for(let t of(n.clear(),e))n.set(t,{percentage:0});r={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(r){t?.printLogs===!1&&(r.logger.level="silent"),t?.progressBar!==void 0&&r.modifyRsbuildConfig(e=>((e.dev??={}).progressBar=t.progressBar,e)),t?.onProgress&&(r.modifyRspackConfig((e,{appendPlugins:t,environment:r,environments:a})=>{0===n.size&&i(Object.keys(a)),t(new v.rspack.ProgressPlugin((e,t)=>{n.set(r.name,{percentage:Math.max(0,Math.min(1,e)),...t?{stage:t}:{}}),o()}))}),r.onBeforeDevCompile(({environments:e})=>{i(Object.keys(e))})),r.onAfterCreateCompiler(({compiler:t})=>{for(let n of"compilers"in t?t.compilers:[t])n.hooks.failed.tap("DoubaoAppsDevPlugin",t=>e?.onDevCompileFailed?.(t))}),r.onAfterDevCompile(({stats:t})=>{if(n.size>0){for(let e of n.keys())n.set(e,{percentage:1,stage:"done"});o()}e?.onAfterDevCompile?.(ax(t))})}}]}class sJ{appDirectory;launcher;constructor(e,t=sV){this.appDirectory=e,this.launcher=new t(e)}createCloudBuildLauncher(e={}){return new ej(e,this.appDirectory||process.cwd())}async create(e){await tu(e)}async dev(e={}){let{compileHooks:t,output:n,simulator:r,...o}=e,i=r;if("object"==typeof r){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:n,targetOrigin:o,...a}=r;i={...a,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:n,targetOrigin:o}}}let a=()=>this.launcher.dev({...o,...void 0!==i?{openWebDebugger:i}:{},rsbuildPlugins:sq({compileHooks:t,output:n}),signingEncryptionOptions:e.signingEncryptionOptions});return n?await eU(n,a):await a()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...n}=e;await this.launcher.build({...n,rsbuildPlugins:sq({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!e5(e))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(e){let{widgetId:t,deviceId:n,botId:r,widgetData:o,debugDriver:i,skipAdbForegroundAppWatch:a}=e,s=await sG({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:a}),l=this.launcher.context.metadata.appId;s.pushWidget({appId:l,widgetId:t,widgetData:o,botId:r})}async openPage(e){let{pageId:t,pageData:n,pageSettings:r,mode:o,debugDriver:i,deviceId:a,skipAdbForegroundAppWatch:s}=e,l=await sG({debugDriver:i,deviceId:a,skipAdbForegroundAppWatch:s}),p=this.launcher.context.metadata.appId;l.openPage({appId:p,pageId:t,pageData:n,pageSettings:r,mode:o})}async callTool(e){let{toolId:t,toolData:n,debugDriver:r,deviceId:o,skipAdbForegroundAppWatch:i}=e,a=await sG({debugDriver:r,deviceId:o,skipAdbForegroundAppWatch:i}),s=this.launcher.context.metadata.appId;a.callTool({appId:s,toolId:t,toolData:n})}async executeDebugScene(e){let{matchedScene:t,variables:n,deviceId:r,debugDriver:o,skipAdbForegroundAppWatch:i}=e,a=this.launcher.context.metadata.appId,s=await sG({debugDriver:o,deviceId:r,skipAdbForegroundAppWatch:i});await tO({matchedScene:t,appId:a,driver:s,variables:n})}async getDebugScenes(){let e=await tI(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await tP(e.path)})))}async cloud(e={}){let{versionTag:t,logs:n,runner:r,createJobConfig:o,variables:i,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).start({versionTag:t,logs:n,runner:r,config:o,variables:i,properties:a})}async cloudUpload(e={}){let{packOnly:t,outputDir:n,...r}=e;return await this.createCloudBuildLauncher(r).upload({packOnly:t,outputDir:n})}async cloudPackage(e={}){let{outputDir:t,...n}=e;return await this.createCloudBuildLauncher(n).package({outputDir:t})}async cloudBuild(e){let{sourceRef:t,versionTag:n,runner:r,createJobConfig:o,variables:i,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).build({sourceRef:t,versionTag:n,runner:r,config:o,variables:i,properties:a})}async cloudCancel(e){let{jobId:t,reason:n,...r}=e;return await this.createCloudBuildLauncher(r).cancel({jobId:t,reason:n})}async cloudGetStatus(e){let{jobId:t,...n}=e;return await this.createCloudBuildLauncher(n).getStatus({jobId:t})}async cloudLog(e){let{jobId:t,start:n,end:r,...o}=e;return await this.createCloudBuildLauncher(o).log({jobId:t,start:n,end:r})}async deploy(e){let{versionTag:t,cookie:n,token:r,appKey:o,signingEncryptionOptions:i}=e;if(!n&&!r)throw Error("Doubao Apps SDK 部署需要 Cookie 或 Developer Open Build Token。");process.env.NODE_ENV="production",await this.launcher.build({skipCleanupRootPath:!0,cookie:n,signingEncryptionOptions:i,token:r,versionTag:t});let{manifest:a}=this.launcher.context;try{return await s$({versionTag:this.launcher.context.versionTag,...o?{appKey:o}:{},manifest:a,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:n,token:r})}finally{eu()||tQ.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{sJ as DoubaoAppsSDK};
338
+ `)}(o,n,e,t,a)),{entry:r}}),i.worker.hooks.collectMetaData.tapPromise(tJ,async({collector:n})=>{n.addAppMeta({name:e,appId:t,icons:r})}),i.view.hooks.collectMetaData.tapPromise({name:tJ,stage:i.view.COLLECT_METADATA_STAGE_OPTIMIZE},async({collector:e})=>{let{pages:t,widgets:r}=i.context;Object.entries(t).forEach(([t,r])=>{let{folderName:n}=r;e.addPageMeta(t,{id:tk(t,n),path:tN(t)})}),Object.entries(r).forEach(([t,r])=>{let i,{folderName:a}=r;e.addWidgetMeta(t,(i=tk(t,a),{...n?.[a]??n?.[t]??n?.[i]??{},id:i}))})})}}}(i.experiments.taro)]:[],...i.plugins||[]]);let E=Date.now();await this.pluginSystem.bootstrap(),this.context.compileLifecycle.prepareDurations.pluginBootstrapMs=Date.now()-E,this.context.setVersionTag(a.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let w=await si({options:i,commandType:e,context:this.context,rsbuildPlugins:r},this.pluginSystem);return{userConfig:i,builder:w}}catch(t){throw oG.report({appDirectory:this.appDirectory,context:this.context===n?void 0:this.context,scene:e===rb.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,r,{builder:n}=await this.prepare(rb.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=function({cwd:e=process.cwd()}={}){let t=tn.resolve(e,sc);if(tP.existsSync(t))try{let e=JSON.parse(tP.readFileSync(t,"utf-8"));if(!K(e))throw TypeError("开发配置必须是 JSON 对象");return e}catch(e){e4.warn("加载开发配置文件失败,已忽略该文件",{path:t,reason:sa(e)});return}}({cwd:this.appDirectory});let i=await n.startDevServer(),a=this.context.webDebuggerLaunchOptions;try{let e=await this.context.resolveDevServer(i.port);t=e.host,r=a?await of(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:e.artifactOrigin,env:{...this.context.env,...a.env??{}},mcpEndpoint:a.mcpEndpoint,mcpHeaders:a.mcpHeaders,simulator:a.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:a.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:a.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await i.server.close(),e}let o=async()=>{e7.info("正在关闭开发服务…");try{await r?.close(),await i.server.close()}finally{await oG.flush()}e7.info("开发服务已关闭")};return{host:t,devServerReady:!0,...r?{webDebugger:r}:{},closeServer:o}}async build(e){let{builder:t}=await this.prepare(rb.BUILD,e,e.rsbuildPlugins);try{await t.build(),this.copyWebAssetsToRoot()}finally{if(e.skipCleanupRootPath||eS()){if(e.archive&&e.channel){let{channel:t}=e;await tC({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else tP.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(rb.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(rb.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(rb.DEPLOY,e),r=e.deployType||t$.NORMAL;if(this.context.deploy={...this.context.deploy,...e.appId?{appId:e.appId}:{},...e.versionCode?{versionCode:e.versionCode}:{}},await this.pluginSystem.callDeployHooks("beforeDeploy",{config:this.context.deploy}),!this.context.deploy.doubaoAppsPlatform&&!this.context.deploy.selfBuilt){if(r!==t$.NORMAL)return void e8.error("请在 doubao.config.ts 中配置部署插件");let n=e.token?void 0:await this.context.getLoginCookie();if(!e.token&&!n)throw Error("Doubao Apps Platform 部署需要登录,请运行 `doubao login` 后重试。");return await t.build(),this.copyWebAssetsToRoot(),await s8({...this.context.versionTag?{versionTag:this.context.versionTag}:{},...e.appId?{appKey:e.appId}:{},manifest:this.context.manifest,rootPath:this.rootPath,internal:this.context.internal,needAuth:!0,...n?{cookie:n}:{},...e.token?{token:e.token}:{}})}(e.build||r===t$.NORMAL)&&(await t.build(),this.copyWebAssetsToRoot());try{await this.pluginSystem.callDeployHooks("deploy",{deployType:r})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case tg.DEV:return await this.dev(t);case tg.BUILD:return await this.build(t);case tg.ANALYZE:return await this.analyze(t);case tg.PERF:return await this.perf(t);case tg.DEPLOY:return await this.deploy(t)}}async getUserConfig(e){if(!this._userConfig){let t=(0,y.loadEnv)({cwd:this.appDirectory,mode:e.envMode}),r=await su({cwd:this.appDirectory,customConfigFile:e.config});this._env=t.parsed,r.source||={},r.source.define={...t.publicVars,...r.source.define},e.debugDriver&&(r.debugDriver=e.debugDriver),void 0!==e.skipAdbForegroundAppWatch&&(r.skipAdbForegroundAppWatch=e.skipAdbForegroundAppWatch),this._userConfig=r}return this._userConfig}copyWebAssetsToRoot(){if(!this.context)return;let e=[this.context.manifest?.applet.web?.appRuntimeEntry,...this.context.manifest?.applet.pages?.map(e=>e.web?.entry)??[],...this.context.manifest?.widgets?.map(e=>e.web?.entry)??[]].filter(e=>!!e);if(0===e.length)return;let t=tn.resolve(this.appDirectory,"dist");for(let r of e){let e=tn.resolve(t,r);if(e!==t&&!e.startsWith(`${t}${tn.sep}`))throw Error(`Web 构建产物路径超出输出根目录:${r}`);if(!tP.existsSync(e))throw Error(`构建完成后未找到 Web 构建产物:${e}`);let n=tn.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`,r);tP.mkdirSync(tn.dirname(n),{recursive:!0}),tP.copyFileSync(e,n)}let r=tn.resolve(this.rootPath,`web_${this.context.manifest.versionCode}`),n=tn.resolve(r,"base","manifest.json");tP.mkdirSync(tn.dirname(n),{recursive:!0}),tP.writeFileSync(n,JSON.stringify(this.context.manifest),"utf-8")}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await sf({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await sm({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:r,widgets:n,auth:i}=await sx(e,t),{app:a,tools:o}=await sS(e,t.tools);return{pages:r,widgets:n,auth:i,app:a,tools:o}}}async function lc(e){let t=await tt(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function lp({compileHooks:e,output:t}){let r=new Map,n={percentage:0},i=()=>{if(0===r.size)return;let e=[...r.values()].reduce((e,t)=>t.percentage<e.percentage?t:e);(e.percentage!==n.percentage||e.stage!==n.stage)&&(n=e,t?.onProgress?.(e))},a=e=>{for(let t of(r.clear(),e))r.set(t,{percentage:0});n={percentage:0}};return[{name:"DoubaoAppsDevPlugin",setup(n){t?.printLogs===!1&&(n.logger.level="silent"),t?.progressBar!==void 0&&n.modifyRsbuildConfig(e=>((e.dev??={}).progressBar=t.progressBar,e)),t?.onProgress&&(n.modifyRspackConfig((e,{appendPlugins:t,environment:n,environments:o})=>{0===r.size&&a(Object.keys(o)),t(new y.rspack.ProgressPlugin((e,t)=>{r.set(n.name,{percentage:Math.max(0,Math.min(1,e)),...t?{stage:t}:{}}),i()}))}),n.onBeforeDevCompile(({environments:e})=>{a(Object.keys(e))})),n.onAfterCreateCompiler(({compiler:t})=>{for(let r of"compilers"in t?t.compilers:[t])r.hooks.failed.tap("DoubaoAppsDevPlugin",t=>e?.onDevCompileFailed?.(t))}),n.onAfterDevCompile(({stats:t})=>{if(r.size>0){for(let e of r.keys())r.set(e,{percentage:1,stage:"done"});i()}e?.onAfterDevCompile?.(oM(t))})}}]}class ld{appDirectory;launcher;constructor(e,t=ll){this.appDirectory=e,this.launcher=new t(e)}async create(e){await eb(e)}async dev(e={}){let{compileHooks:t,output:r,simulator:n,...i}=e,a=n;if("object"==typeof n){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i,...o}=n;a={...o,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i}}}let o=()=>this.launcher.dev({...i,...void 0!==a?{openWebDebugger:a}:{},rsbuildPlugins:lp({compileHooks:t,output:r}),signingEncryptionOptions:e.signingEncryptionOptions});return r?await ew.run(r,o):await o()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...r}=e;await this.launcher.build({...r,rsbuildPlugins:lp({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!eG(e))}async discoverPages(){return Object.values(this.launcher.context.metadata.getData().pages)}async discoverTools(){return Object.values(this.launcher.context.metadata.getData().tools)}async pushWidget(e){let{widgetId:t,deviceId:r,botId:n,widgetData:i,debugDriver:a,skipAdbForegroundAppWatch:o}=e,s=await lc({debugDriver:a,deviceId:r,skipAdbForegroundAppWatch:o}),l=this.launcher.context.metadata.appId;s.pushWidget({appId:l,widgetId:t,widgetData:i,botId:n})}async openPage(e){let{pageId:t,pageData:r,pageSettings:n,mode:i,debugDriver:a,deviceId:o,skipAdbForegroundAppWatch:s}=e,l=await lc({debugDriver:a,deviceId:o,skipAdbForegroundAppWatch:s}),c=this.launcher.context.metadata.appId;l.openPage({appId:c,pageId:t,pageData:r,pageSettings:n,mode:i})}async callTool(e){let{toolId:t,toolData:r,debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:a}=e,o=await lc({debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:a}),s=this.launcher.context.metadata.appId;o.callTool({appId:s,toolId:t,toolData:r})}async executeDebugScene(e){let{matchedScene:t,variables:r,deviceId:n,debugDriver:i,skipAdbForegroundAppWatch:a}=e,o=this.launcher.context.metadata.appId,s=await lc({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:a});await to({matchedScene:t,appId:o,driver:s,variables:r})}async getDebugScenes(){let e=await ti(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await ta(e.path)})))}async cloudPackage(e={}){let t=this.appDirectory||process.cwd(),r=tn.resolve(t,e.appDir||".");(0,y.loadEnv)({cwd:r,mode:e.envMode});let n=await D({appDir:r,outputDir:e.outputDir?tn.resolve(t,e.outputDir):void 0});for(let e of n.warnings)e9.warn(e);if(n.blockers.length>0)throw Error(n.blockers.join("\n"));return n.archivePath}async deploy(e){let{versionTag:t,cookie:r,token:n,appKey:i,signingEncryptionOptions:a}=e;if(!r&&!n)throw Error("Doubao Apps SDK 部署需要 Cookie 或 Developer Open Build Token。");process.env.NODE_ENV="production",await this.launcher.build({skipCleanupRootPath:!0,cookie:r,signingEncryptionOptions:a,token:n,versionTag:t});let{manifest:o}=this.launcher.context;try{return await s8({versionTag:this.launcher.context.versionTag,...i?{appKey:i}:{},manifest:o,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:r,token:n})}finally{eS()||tP.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{ld as DoubaoAppsSDK,sa as error_getErrorMessage,eS as isDebugMode};