@doubao-dev/cli 0.0.26 → 0.0.28

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 (68) hide show
  1. package/dist/2168.js +14 -14
  2. package/dist/{2861.js → 2611.js} +2 -2
  3. package/dist/4931.js +1 -1
  4. package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
  5. package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
  6. package/dist/app.js +1 -1
  7. package/dist/assets/web-sdk-debugger/index.html +1 -1
  8. package/dist/assets/web-sdk-debugger/static/js/index.1448a806d8.js +26 -0
  9. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
  10. package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
  11. package/dist/check.js +1 -0
  12. package/dist/dbx.js +2 -2
  13. package/dist/demo-server.js +3 -3
  14. package/dist/demo.js +2 -0
  15. package/dist/dev-shell.js +1 -1
  16. package/dist/dev.js +5 -5
  17. package/dist/init.js +4 -4
  18. package/dist/ink.js +1 -1
  19. package/dist/login.js +1 -1
  20. package/dist/prompt.js +1 -1
  21. package/dist/run.js +2 -2
  22. package/dist/sdk.js +15 -15
  23. package/dist/sdk~1.js +5 -5
  24. package/dist/skill.js +1 -1
  25. package/dist/skills.js +1 -1
  26. package/dist/skills~2.js +2 -2
  27. package/dist/templates/README.md +1 -1
  28. package/dist/upload.js +6 -6
  29. package/dist/workspace.js +1 -1
  30. package/dist/yaml.js +1 -1
  31. package/package.json +2 -2
  32. package/skills/dbx-eval/SKILL.md +2 -2
  33. package/skills/doubao-agentic-service-development/SKILL.md +8 -8
  34. package/skills/doubao-agentic-service-development/references/auth.md +2 -2
  35. package/skills/doubao-agentic-service-development/references/business-template-debug.md +3 -3
  36. package/skills/doubao-agentic-service-development/references/dev-debug.md +2 -2
  37. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/01-/345/237/272/347/241/200.md +175 -15
  38. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/02-/347/263/273/347/273/237.md +3 -3
  39. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/03-/350/207/252/345/256/232/344/271/211/351/200/232/344/277/241.md +1 -1
  40. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/04-/345/256/232/344/275/215.md +1 -1
  41. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/08-/344/272/244/344/272/222.md +221 -7
  42. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/10-/347/275/221/347/273/234.md +20 -20
  43. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/11-/345/252/222/344/275/223.md +2 -2
  44. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/12-/344/270/232/345/212/241/350/203/275/345/212/233.md +3 -4
  45. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/16-/350/223/235/347/211/231.md +3 -3
  46. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/25-/346/227/240/351/232/234/347/242/215.md +1 -1
  47. 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 +3 -3
  48. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/28-/345/211/252/350/264/264/346/235/277.md +2 -2
  49. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/32-/346/211/253/347/240/201.md +1 -1
  50. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/33-/345/261/217/345/271/225.md +1 -1
  51. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/34-/351/234/207/345/212/250.md +2 -2
  52. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/common-errors.md +1 -1
  53. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/groups.md +3 -3
  54. package/skills/doubao-agentic-service-development/references/frontend/doubao-agentic-service-api/quick-reference.md +7 -3
  55. package/skills/doubao-agentic-service-development/references/frontend-dev.md +3 -3
  56. package/skills/doubao-agentic-service-development/references/generate-skill.md +1 -1
  57. package/skills/doubao-agentic-service-development/references/local-debug/simulator-eval.md +26 -22
  58. package/skills/doubao-agentic-service-development/references/manifest-guide.md +3 -3
  59. package/skills/doubao-agentic-service-development/references/mcp-protocol.md +1 -1
  60. package/skills/doubao-agentic-service-development/references/overview.md +4 -3
  61. package/skills/doubao-agentic-service-development/references/service-notice.md +1 -3
  62. package/skills/doubao-agentic-service-development/references/task-management.md +1 -3
  63. package/dist/assets/web-sdk-debugger/static/js/index.b85cbec3be.js +0 -26
  64. package/dist/dbx-demo.js +0 -2
  65. package/dist/eval.js +0 -1
  66. package/dist/validate.js +0 -1
  67. /package/dist/{2861.js.LICENSE.txt → 2611.js.LICENSE.txt} +0 -0
  68. /package/dist/{6780.js → 4594.js} +0 -0
package/dist/sdk.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*! LICENSE: sdk.js.LICENSE.txt */
2
- let e,t,r,n,i,o,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,core_namespaceObject as y,external_node_process_namespaceObject as b,external_node_tty_namespaceObject as _,external_node_https_namespaceObject as w,promises_namespaceObject as v,external_jiti_namespaceObject as E}from"./3768.js";import{external_node_module_namespaceObject as S}from"./3551.js";import{parseDebugScene as x,schemas_enum as A,schemas_number as T,unknown as C,TokenExpiredError as O,AUTH_META as I,normalizeWidgetSourceEntry as P,resolveDebugScene as k,schemas_object as D,createMcpHandler as $,prepareCloudBuildSource as N,schemas_boolean as R,withAuth as L,RenderType as M,lodash_es_get as j,TitleType as U,schemas_record as B,getWebSdkDebuggerDistPath as F,eraseLines as W,NotLoggedInError as H,parseSandboxSimulatorToolCallEvent as V,lodash_es_mergeWith as G,pluginExternalBundle as q,isRecord as J,getDebugSceneVariableEntries as K,McpServer as z,dist_esm as Y,schemas_string as X,execaCommand as Z,inquirer_dist as Q,APP_DEVELOPER_ORIGIN as ee,normalizeHttpEndpoint as et,pluginReactAlias as er,toNodeHandler as en,schemas_array as ei,lodash_es_merge as eo,BoxType as ea,APP_DEVELOPER_DOMAIN as es}from"./2861.js";import{walk_simple as el}from"./7526.js";import"./180.js";import"./yaml.js";import"./ora.js";import{source as ep,TeaUploader as ed}from"./6780.js";import{create as ec}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.1_f61de653352e1ffdfcf3cfbd2dcb3ac0/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.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.1_f61de653352e1ffdfcf3cfbd2dcb3ac0/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.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js_089fc2c25cf06b41592540314396dd42/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 eu=f("node:async_hooks"),em=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),eh=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,ef=new eu.AsyncLocalStorage;function eg(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function ey(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 ey(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=>ey(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>{let n=eh.test(eg(e))?'"[REDACTED]"':ey(r,t);return`${JSON.stringify(e)}:${n}`}).join(",")}}`;return t.delete(e),r}function eb(e){return ep.cyan(`[${e}]`.padEnd(em))}function e_(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 ew(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[eg(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let r=eh.test(e)?"[REDACTED]":ey(t);return ep.dim(`${e}=${r}`)}).join(" ")}let ev=new class e{constructor(e={}){this.sink=e.sink??y.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??(()=>"applet0930"===process.env.DEBUG)}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){this.isDebugEnabled()&&this.emit("debug",e,t)&&this.sink.debug(this.formatMessage(e,t))}error(e,t={}){let r,{error:n,...i}=t,o=this.tag?`${eb(this.tag)} `:"",a=e instanceof Error?e.message:String(e),s=`${o}${a}`;if(void 0!==n)s+=`: ${n instanceof Error?n.message:ey(n)}`,this.isDebugEnabled()&&n instanceof Error&&n.stack&&(r=n.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(r=e.stack);let l=ew({...this.context,...i});l&&(s+=` ${l}`),r&&(s+=`
2
+ let e,t,r,n,i,o,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,core_namespaceObject as y,external_node_process_namespaceObject as b,external_node_tty_namespaceObject as _,external_node_https_namespaceObject as w,promises_namespaceObject as v,external_jiti_namespaceObject as E}from"./3768.js";import{external_node_module_namespaceObject as S}from"./3551.js";import{parseDebugScene as x,schemas_enum as A,schemas_number as T,unknown as C,TokenExpiredError as O,AUTH_META as I,normalizeWidgetSourceEntry as P,resolveDebugScene as k,schemas_object as D,createMcpHandler as $,prepareCloudBuildSource as N,schemas_boolean as R,withAuth as L,RenderType as M,lodash_es_get as j,TitleType as U,schemas_record as B,getWebSdkDebuggerDistPath as F,eraseLines as W,NotLoggedInError as H,parseSandboxSimulatorToolCallEvent as V,lodash_es_mergeWith as G,pluginExternalBundle as q,isRecord as J,getDebugSceneVariableEntries as K,McpServer as z,dist_esm as Y,schemas_string as X,execaCommand as Z,inquirer_dist as Q,APP_DEVELOPER_ORIGIN as ee,normalizeHttpEndpoint as et,pluginReactAlias as er,toNodeHandler as en,schemas_array as ei,lodash_es_merge as eo,BoxType as ea,APP_DEVELOPER_DOMAIN as es}from"./2611.js";import{walk_simple as el}from"./7526.js";import"./180.js";import"./yaml.js";import"./ora.js";import{source as ep,TeaUploader as ed}from"./4594.js";import{create as ec}from"./@byted-doubao-apps/create.js";f.add({"../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.1_df7782748b6d5198f7cf2625253ae483/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.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.1_df7782748b6d5198f7cf2625253ae483/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.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js_e448f1bf1172a453640970b92f024ac6/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 eu=f("node:async_hooks"),em=Math.max(...["cli","auth","config","security","build","deploy","dev-server","simulator"].map(e=>`[${e}]`.length)),eh=/authorization|cookie|token|secret|password|credential|private_?key|\bdek\b/i,ef=new eu.AsyncLocalStorage;function eg(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function ey(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 ey(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=>ey(e,t)).join(",")}]`:`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,r])=>{let n=eh.test(eg(e))?'"[REDACTED]"':ey(r,t);return`${JSON.stringify(e)}:${n}`}).join(",")}}`;return t.delete(e),r}function eb(e){return ep.cyan(`[${e}]`.padEnd(em))}function e_(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 ew(e){let t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[eg(e),t]).sort(([e],[t])=>e.localeCompare(t));return 0===t.length?"":t.map(([e,t])=>{let r=eh.test(e)?"[REDACTED]":ey(t);return ep.dim(`${e}=${r}`)}).join(" ")}let ev=new class e{constructor(e={}){this.sink=e.sink??y.logger,this.tag=e.tag,this.context=e.context??{},this.isDebugEnabled=e.isDebug??(()=>"applet0930"===process.env.DEBUG)}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){this.isDebugEnabled()&&this.emit("debug",e,t)&&this.sink.debug(this.formatMessage(e,t))}error(e,t={}){let r,{error:n,...i}=t,o=this.tag?`${eb(this.tag)} `:"",a=e instanceof Error?e.message:String(e),s=`${o}${a}`;if(void 0!==n)s+=`: ${n instanceof Error?n.message:ey(n)}`,this.isDebugEnabled()&&n instanceof Error&&n.stack&&(r=n.stack);else e instanceof Error&&this.isDebugEnabled()&&e.stack&&(r=e.stack);let l=ew({...this.context,...i});l&&(s+=` ${l}`),r&&(s+=`
3
3
  ${r}`),this.emit("error",a,{...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,o,a,s,l,p=e.timestamp??new Date,d=ep.gray(`[${(r=p.getFullYear(),n=String(p.getMonth()+1).padStart(2,"0"),i=String(p.getDate()).padStart(2,"0"),o=String(p.getHours()).padStart(2,"0"),a=String(p.getMinutes()).padStart(2,"0"),s=String(p.getSeconds()).padStart(2,"0"),l=String(p.getMilliseconds()).padStart(3,"0"),`${r}-${n}-${i} ${o}:${a}:${s}.${l}`)}]`),c=ep.bold(e.method),u=void 0===e.durationMs?"":` ${ep.dim(`${e.durationMs.toFixed(1)}ms`)}`,m=e_(e.headers),h=Array.isArray(e.logId)?e.logId.join(","):e.logId,f=[m?ew({ppe:m}):"",h?ew({logid:h}):"",ew({...this.context,...e.context})].filter(Boolean).join(" "),g=`${this.tag?`${eb(this.tag)} `:""}${d} ${c} ${e.url} ${((t=e.statusCode)>=500?ep.red:t>=400?ep.yellow:ep.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},p.getTime())&&("error"===y?this.sink.error(g):"warn"===y?this.sink.warn(g):this.sink.info(g))}formatMessage(e,t={}){let r=ew({...this.context,...t}),n=this.tag?`${eb(this.tag)} `:"",i=e instanceof Error?e.message:String(e);return`${n}${i}${r?` ${r}`:""}`}emit(e,t,r={},n=Date.now()){let i=ef.getStore(),o=i?.onLog;if(o)try{o({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])=>[eg(e),t]).sort(([e],[t])=>e.localeCompare(t));if(0!==t.length)return Object.fromEntries(t.map(([e,t])=>[e,eh.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,eh.test(eg(t))?"[REDACTED]":e(n,r)]));return r.delete(t),n}(t)]))}({...this.context,...r})})}catch{}return i?.printLogs!==!1}},eE=ev.child("build");var eS,ex,eA,eT,eC,eO,eI,eP,ek,eD,e$,eN,eR,eL,eM,ej,eU,eB,eF,eW,eH,eV,eG,eq=((eN={}).Adb="adb",eN.Hdt="hdt",eN.DevTools="devtools",eN);let eJ=["adb","hdt","devtools"],eK=f("path"),ez="./node_modules/.doubao",eY="./node_modules/.injected.js",eX="./node_modules/.injected.css",eZ=`.doubao-apps-style-anchor{display:none}
4
4
  :root {
5
5
  --doubao-picker-view-height: 108px;
@@ -124,7 +124,7 @@ ${r}`),this.emit("error",a,{...i,...void 0!==n?{error:n}:{}})&&this.sink.error(s
124
124
  line-height: var(--doubao-picker-view-item-line-height);
125
125
  font-weight: var(--doubao-picker-view-item-font-weight);
126
126
  color: var(--doubao-picker-view-item-selected-color);
127
- }`,eQ="widgets";eK.sep;let e0=`base${eK.sep}manifest.json`,e1=`base${eK.sep}manifest.sign`,e3="mcp-privacy-login-card",e2="__doubao_apps__expired-widget",e4="bundle.keystore",e5={"@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"},e9="client-tool",e8=e=>e===e3||e===e2,e6="app.config",e7=[".js",".ts",".mjs"],te="com.larus.nova";class tt{}let tr=f("node:fs"),tn=f("node:path"),ti="@byted-doubao-apps/framework",to="@doubao-dev/framework",ta=[ti,to];function ts(e){return`${e}/components`}function tl(e){let t=tn.resolve(e,"package.json");if(tr.existsSync(t))try{let e=JSON.parse(tr.readFileSync(t,"utf8")),r={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(r[to])return to;if(r[ti])return ti}catch{}}function tp(e){return tl(e)??ti}let td=e=>void 0!==process.env[e],tc=()=>(process.env.DEBUG??"").toLocaleLowerCase().split(",").includes("applet0930"),tu=()=>td("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||td("LEGACY_FRAMEWORK"),tm=()=>td("DISABLE_APP_TEMPLATE_JS")||td("LEGACY_FRAMEWORK");function th({mcpEndpoint:e}={}){let t=e?.trim();return t||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}function tf(e,t=3e3){return Z(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function tg(e,t){return tf(`adb -s ${e} ${t}`)}async function ty(e){let t=(await tf(`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 tb(e,t){let r=(await tg(e,`shell pidof ${t}`)).stdout.trim();return r?r.split(/\s+/)[0]:void 0}async function t_(e){let t=await ty(e);return(t===te||"com.flow.aisdk.example"===t)&&(await tf(`adb -s ${e} shell am force-stop ${t}`),await tf(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function tw(){return(await tf("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function tv(){let e=await tw();if(e.length>1){let{device:t}=await Q.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class tE extends tt{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 tb(this.deviceId,te);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 tb(this.deviceId,te)!==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}`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await tg(this.deviceId,i)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:o}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${r} --es appletPageData '${n}' --es appletPageSettings '${i}' --es mode '${o}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${a}`)),await tg(this.deviceId,a)}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}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${n}`)),await tg(this.deviceId,n)}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e,o=`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}`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${o}`)),await tg(this.deviceId,o)}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}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await tg(this.deviceId,i)}}class tS extends tt{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}ev.child("cli");let tx=ev.child("config"),tA=ev.child("security"),tT=ev.child("build"),tC=tT.withContext({mode:"cloud"}),tO=ev.child("deploy"),tI=ev.child("dev-server");class tP{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 o=n();this.debugDriver=o,o.getAllAppClients().forEach(e=>this.onConnect(e,r)),o.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){tI.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 tk extends tt{server;constructor(){super(),this.server=new tP({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:o}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:r,appletPageData:n,appletPageSettings:i,mode:o}})}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 tD(t={}){if(!e){let r=t.debugDriver??eq.Adb;if(!eJ.includes(r))throw Error(`无效的调试驱动 "${r}",可选值:${eJ.join(", ")}。`);switch(r){case eq.Hdt:e=new tk;break;case eq.DevTools:e=new tS;break;case eq.Adb:{let r=t.deviceId??await tv();r&&(e=new tE(r,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${r}",可选值:${eJ.join(", ")}。`)}}return e}let t$=f("node:fs/promises");async function tN(e){let t=(0,tn.join)(e,"debug-scene");try{return(await (0,t$.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 tR(e){try{return x(JSON.parse(await (0,t$.readFile)(e,"utf8")))}catch(t){return tc()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function tL(e,t){let{matchedScene:r,appId:n,driver:i,variables:o}=e,a=t??await tR(r.path);if(!a)return;let s=k(a,o);if("page"===s.type){var l,p;l=r.name,0!==(p=s.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${p.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 tM="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tj(e){if("string"==typeof e){let t=e.length>0?e:tM;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||tM,"2x":e?.["2x"]||tM,"3x":e?.["3x"]||tM}}(eS=eR||(eR={})).DEV="dev",eS.BUILD="build",eS.PERF="perf",eS.DEPLOY="deploy",eS.ANALYZE="analyze";let tU={DEV:eR.DEV,BUILD:eR.BUILD,PERF:eR.PERF,DEPLOY:eR.DEPLOY,ANALYZE:eR.ANALYZE};function tB(e){let t=Object.keys(e);return t.sort(),t.reduce((t,r)=>(t[r]=e[r],t),{})}class tF{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tW extends tF{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 tH extends tF{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:"full_box"===i.boxType?ea.FULL_BOX:ea.INBOX,titleType:i.titleType?tH.TITLE_TYPE_MAP[i.titleType]:void 0}}}tH.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tV extends tF{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 tG extends tF{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:tj(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:r,appRuntimeType:n}}}class tq{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 tG(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tV(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tW(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tH(t)}getData(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n.metadata??{},tools:tB(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tB(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tB(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:tB(e),pages:tB(t),widgets:tB(r)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}let tJ={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tK={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tz={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tY={...tJ,...tK,...tz},tX={...tJ,...tK,...tz};(ex=eL||(eL={}))[ex.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",ex[ex.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",ex[ex.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",ex[ex.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tZ=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tQ(){return{modifyEnvironment:new tZ.FU(["arg0"]),modifyEntryOption:new tZ.BD(["arg0"]),beforeBuild:new tZ.FU(["arg0"]),collectMetaData:new tZ.FU(["arg0"]),build:new tZ.FU(["arg0"]),afterBuild:new tZ.FU(["arg0"])}}function t0({hooks:e,stages:t}){return{hooks:e,...t}}class t1{constructor(e,t=[]){this.plugins=[],this.api={...{worker:t0({hooks:tQ(),stages:tX}),view:t0({hooks:tQ(),stages:tY}),assets:t0({hooks:{beforeEmit:new tZ.FU(["arg0"]),afterEmit:new tZ.FU(["arg0"])},stages:eL}),deploy:t0({hooks:{beforeDeploy:new tZ.FU(["arg0"]),deploy:new tZ.FU(["arg0"]),afterDeploy:new tZ.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=j(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 t3=f("fs"),t2=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function t4(e,t,r,n){return new Promise((i,o)=>{let a=t3.createWriteStream(e),s=t2("zip",{zlib:{level:9}});s.pipe(a),s.directory(t,r??!1),a.on("close",()=>{n?.deleteResource&&t3.rmSync(t,{recursive:!0}),eE.success("Compiled artifacts packaged",{file:eK.basename(e)}),i("")}),s.on("error",e=>{eE.error("An error occurred during packaging",{error:e}),o(e)}),s.finalize()})}async function t5({channelName:e,manifest:t,rootPath:r}){let n=eK.resolve(r),i=eK.resolve(r,"doubao_app_output"),o=eK.resolve(i,t.packageName),a={outputFolder:i,transformFolder:o,manifest:t};t3.existsSync(i)&&t3.rmSync(i,{recursive:!0}),t3.mkdirSync(i),t3.mkdirSync(o),function(e,t){let{transformFolder:r,manifest:n}=t,{applet:i,widgets:o}=n,a=eK.resolve(e,"base"),s=eK.resolve(r,"base");t3.mkdirSync(s),t3.cpSync(a,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=eK.resolve(e,i.appletId),p=eK.resolve(r,i.appletId);t3.mkdirSync(p),i.pages.length>0&&t3.cpSync(l,p,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),o.forEach(t=>{let n=eK.resolve(e,t.widgetId),i=eK.resolve(r,t.widgetId);t3.mkdirSync(i),t3.cpSync(n,i,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})})}(n,a);let s=await t9(e,a);return eE.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function t9(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:o,widgets:a,packageName:s,versionCode:l}=r,p=eK.resolve(n,"deploy-package"),d=eK.resolve(p,e),c=eK.resolve(d,s);t3.mkdirSync(p),t3.mkdirSync(d),t3.mkdirSync(c),t3.cpSync(i,c,{recursive:!0});let u={},m=t3.readdirSync(c).filter(e=>t3.statSync(eK.resolve(c,e)).isDirectory()),h=eK.resolve(p,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if("base"===e)return t4(eK.resolve(c,`${e}_${l}.zip`),eK.resolve(c,e),e,{deleteResource:!0});if(e===o.appletId){let t=`${e}_${o.digest}.zip`;return u[o.appletId]=t,t4(eK.resolve(c,t),eK.resolve(c,e),e,{deleteResource:!0})}let t=a.find(t=>t.widgetId===e);if(t){let r=`${e}_${t.digest}.zip`;return u[t.widgetId]=r,t4(eK.resolve(c,r),eK.resolve(c,e),e,{deleteResource:!0})}return eE.error("Invalid package directory",{directory:e}),Promise.resolve()})),await t4(h,d,e),process.env.BUILD_VERSION){let e=eK.resolve(n,"scm-deploy-package"),t=eK.resolve(e,s);t3.mkdirSync(e),t3.mkdirSync(t),t3.cpSync(c,t,{recursive:!0})}return eE.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(eA=eM||(eM={})).NORMAL="normal",eA.SELF_BUILT_CREATE="selfBuiltCreate",eA.SELF_BUILT_PUBLISH="selfBuiltPublish",eA.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",eA.SELF_BUILT_STOP="selfBuiltStop",eA.SELF_BUILT_ROLLBACK="selfBuiltRollback";let t8={NORMAL:eM.NORMAL,SELF_BUILT_CREATE:eM.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:eM.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:eM.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:eM.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:eM.SELF_BUILT_ROLLBACK};function t6(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 t7(e,t){let[r]=(t??e).split(/[?#]/,1),n=r.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function re(e,t,r){let n=t7(t).slice(1);return`${e}/${n}/${r}`}function rt(e,...t){return G(e,...t,(e,t,r)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let rr=(e,t)=>tn.relative(e,t).replaceAll(tn.sep,"/");class rn{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=eK.dirname(this._filename);(0,t3.existsSync)(t)||(0,t3.mkdirSync)(t,{recursive:!0}),(0,t3.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function ri(e,t,r=!1,n=!1){return Object.keys(e).reduce((i,o)=>{let{filename:a,isVirtualFile:s,isSpecial:l}=e[o];if(s||l)return i;let p=`${ez}${tn.sep}${o}${tn.extname(a)}`,d=rr(tn.join(t,p,".."),a),c=tp(t),u=r?"defineWidget":"definePage";return i[o]=new rn(p),i[o].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"}]}),i[o].appendContent(`
127
+ }`,eQ="widgets";eK.sep;let e0=`base${eK.sep}manifest.json`,e1=`base${eK.sep}manifest.sign`,e2="mcp-privacy-login-card",e3="__doubao_apps__expired-widget",e4="bundle.keystore",e5={"@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"},e9="client-tool",e8=e=>e===e2||e===e3,e6="app.config",e7=[".js",".ts",".mjs"],te="com.larus.nova";class tt{}let tr=f("node:fs"),tn=f("node:path"),ti="@byted-doubao-apps/framework",to="@doubao-dev/framework",ta=[ti,to];function ts(e){return`${e}/components`}function tl(e){let t=tn.resolve(e,"package.json");if(tr.existsSync(t))try{let e=JSON.parse(tr.readFileSync(t,"utf8")),r={...e.dependencies,...e.devDependencies,...e.peerDependencies};if(r[to])return to;if(r[ti])return ti}catch{}}function tp(e){return tl(e)??ti}let td=e=>void 0!==process.env[e],tc=()=>(process.env.DEBUG??"").toLocaleLowerCase().split(",").includes("applet0930"),tu=()=>td("DISABLE_EXTERNAL")||"1"===process.env.ENABLE_SELF_CONTAINED||td("LEGACY_FRAMEWORK"),tm=()=>td("DISABLE_APP_TEMPLATE_JS")||td("LEGACY_FRAMEWORK");function th({mcpEndpoint:e}={}){let t=e?.trim();return t||(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT?.trim()??"")}function tf(e,t=3e3){return Z(e,{timeout:t}).catch(()=>({stdout:"",stderr:""}))}async function tg(e,t){return tf(`adb -s ${e} ${t}`)}async function ty(e){let t=(await tf(`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 tb(e,t){let r=(await tg(e,`shell pidof ${t}`)).stdout.trim();return r?r.split(/\s+/)[0]:void 0}async function t_(e){let t=await ty(e);return(t===te||"com.flow.aisdk.example"===t)&&(await tf(`adb -s ${e} shell am force-stop ${t}`),await tf(`adb -s ${e} shell monkey -p ${t} -c android.intent.category.LAUNCHER 1`),!0)}async function tw(){return(await tf("adb devices")).stdout.split("\n").slice(1).map(e=>e.split(" ")[0].trim()).filter(Boolean)}async function tv(){let e=await tw();if(e.length>1){let{device:t}=await Q.prompt([{type:"search",name:"device",message:"检测到多个设备,请选择用于调试的设备(可按设备 ID 搜索):",source:t=>e.filter(e=>e.toLowerCase().includes(t?.toLowerCase()??""))}]);return t}return e[0]}class tE extends tt{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 tb(this.deviceId,te);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 tb(this.deviceId,te)!==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}`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await tg(this.deviceId,i)}async openPage(e){let{appId:t,pageId:r,pageData:n,pageSettings:i,mode:o}=e,a=`shell am broadcast -a com.bytedance.applet.START_APPLET --es appletName ${t} --es appletPageName ${r} --es appletPageData '${n}' --es appletPageSettings '${i}' --es mode '${o}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${a}`)),await tg(this.deviceId,a)}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}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${n}`)),await tg(this.deviceId,n)}async pushWidget(e){let{appId:t,widgetId:r,widgetData:n,botId:i}=e,o=`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}`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${o}`)),await tg(this.deviceId,o)}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}'`;tc()&&console.log(ep.dim(`adb -s ${this.deviceId} ${i}`)),await tg(this.deviceId,i)}}class tS extends tt{async load(e){}async openPage(e){}async openPageUrl(e){}async pushWidget(e){}async callTool(e){}}ev.child("cli");let tx=ev.child("config"),tA=ev.child("security"),tT=ev.child("build"),tC=tT.withContext({mode:"cloud"}),tO=ev.child("deploy"),tI=ev.child("dev-server");class tP{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 o=n();this.debugDriver=o,o.getAllAppClients().forEach(e=>this.onConnect(e,r)),o.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){tI.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 tk extends tt{server;constructor(){super(),this.server=new tP({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:o}=e;this.server.sendMessage({method:"Applet_OpenPage",params:{appletName:t,appletPageName:r,appletPageData:n,appletPageSettings:i,mode:o}})}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 tD(t={}){if(!e){let r=t.debugDriver??eq.Adb;if(!eJ.includes(r))throw Error(`无效的调试驱动 "${r}",可选值:${eJ.join(", ")}。`);switch(r){case eq.Hdt:e=new tk;break;case eq.DevTools:e=new tS;break;case eq.Adb:{let r=t.deviceId??await tv();r&&(e=new tE(r,{skipForegroundAppWatch:t.skipAdbForegroundAppWatch}));break}default:throw Error(`无效的调试驱动 "${r}",可选值:${eJ.join(", ")}。`)}}return e}let t$=f("node:fs/promises");async function tN(e){let t=(0,tn.join)(e,"debug-scene");try{return(await (0,t$.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 tR(e){try{return x(JSON.parse(await (0,t$.readFile)(e,"utf8")))}catch(t){return tc()&&console.warn(`[DoubaoApps] 加载调试场景 "${e}" 失败:${t instanceof Error?t.message:String(t)}`),null}}async function tL(e,t){let{matchedScene:r,appId:n,driver:i,variables:o}=e,a=t??await tR(r.path);if(!a)return;let s=k(a,o);if("page"===s.type){var l,p;l=r.name,0!==(p=s.unresolvedVariables).length&&console.warn(`[DoubaoApps] 调试场景 "${l}" 存在未解析的变量占位符:${p.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 tM="https://lf3-static.bytednsdoc.com/obj/eden-cn/777eh7nuptpfnuhd/default.svg";function tj(e){if("string"==typeof e){let t=e.length>0?e:tM;return{"1x":t,"2x":t,"3x":t}}return{"1x":e?.["1x"]||tM,"2x":e?.["2x"]||tM,"3x":e?.["3x"]||tM}}(eS=eR||(eR={})).DEV="dev",eS.BUILD="build",eS.PERF="perf",eS.DEPLOY="deploy",eS.ANALYZE="analyze";let tU={DEV:eR.DEV,BUILD:eR.BUILD,PERF:eR.PERF,DEPLOY:eR.DEPLOY,ANALYZE:eR.ANALYZE};function tB(e){let t=Object.keys(e);return t.sort(),t.reduce((t,r)=>(t[r]=e[r],t),{})}class tF{get metadata(){return this._metadata}toString(){return JSON.stringify(this._metadata,null,2)}}class tW extends tF{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 tH extends tF{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:"full_box"===i.boxType?ea.FULL_BOX:ea.INBOX,titleType:i.titleType?tH.TITLE_TYPE_MAP[i.titleType]:void 0}}}tH.TITLE_TYPE_MAP={none:2,normal:0,float:1};class tV extends tF{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 tG extends tF{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:tj(this._metadata.icons),digest:t,prop:"",tools:Object.values(e).map(e=>e.toManifest()),appRuntimeEntry:r,appRuntimeType:n}}}class tq{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 tG(e)}addToolMeta(e,t){this.metadata.tools[e]?this.metadata.tools[e].assign(t):this.metadata.tools[e]=new tV(t)}addPageMeta(e,t){this.metadata.pages[e]?this.metadata.pages[e].assign(t):this.metadata.pages[e]=new tW(t)}addWidgetMeta(e,t){this.metadata.widgets[e]?this.metadata.widgets[e].assign(t):this.metadata.widgets[e]=new tH(t)}getData(){let{tools:e,pages:t,widgets:r,app:n}=this.metadata;return{app:n.metadata??{},tools:tB(Object.fromEntries(Object.keys(e).map(t=>[t,e[t].metadata]))),pages:tB(Object.fromEntries(Object.keys(t).map(e=>[e,t[e].metadata]))),widgets:tB(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:tB(e),pages:tB(t),widgets:tB(r)}}clearData(){this.metadata={app:{},pages:{},tools:{},widgets:{}}}}let tJ={MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE:1e3,MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY:2e3,MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE:3e3},tK={BEFORE_BUILD_STAGE_CREATE_CONFIG:1e3,BEFORE_BUILD_STAGE_MODIFY_BUILD_CONFIG:2e3,BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG:3e3},tz={COLLECT_METADATA_STAGE_START:1e3,COLLECT_METADATA_STAGE_PROCESS_METADATA:2e3,COLLECT_METADATA_STAGE_OPTIMIZE:3e3,COLLECT_METADATA_STAGE_FINISH:4e3},tY={...tJ,...tK,...tz},tX={...tJ,...tK,...tz};(ex=eL||(eL={}))[ex.BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS=1e3]="BEFORE_EMIT_STAGE_PROCESS_WORKER_ASSETS",ex[ex.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS=2e3]="BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS",ex[ex.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=3e3]="BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS",ex[ex.BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS=3999]="BEFORE_EMIT_STAGE_SIGN_MANIFEST_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS=4e3]="AFTER_EMIT_STAGE_PROCESS_VIEW_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS=5e3]="AFTER_EMIT_STAGE_PROCESS_WORKER_ASSETS",ex[ex.AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS=6e3]="AFTER_EMIT_STAGE_PROCESS_MANIFEST_ASSETS";let tZ=f("../../../node_modules/.pnpm/tapable@2.2.1/node_modules/tapable/lib/index.js");function tQ(){return{modifyEnvironment:new tZ.FU(["arg0"]),modifyEntryOption:new tZ.BD(["arg0"]),beforeBuild:new tZ.FU(["arg0"]),collectMetaData:new tZ.FU(["arg0"]),build:new tZ.FU(["arg0"]),afterBuild:new tZ.FU(["arg0"])}}function t0({hooks:e,stages:t}){return{hooks:e,...t}}class t1{constructor(e,t=[]){this.plugins=[],this.api={...{worker:t0({hooks:tQ(),stages:tX}),view:t0({hooks:tQ(),stages:tY}),assets:t0({hooks:{beforeEmit:new tZ.FU(["arg0"]),afterEmit:new tZ.FU(["arg0"])},stages:eL}),deploy:t0({hooks:{beforeDeploy:new tZ.FU(["arg0"]),deploy:new tZ.FU(["arg0"]),afterDeploy:new tZ.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=j(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 t2=f("fs"),t3=f("../../../node_modules/.pnpm/archiver@7.0.1/node_modules/archiver/index.js");function t4(e,t,r,n){return new Promise((i,o)=>{let a=t2.createWriteStream(e),s=t3("zip",{zlib:{level:9}});s.pipe(a),s.directory(t,r??!1),a.on("close",()=>{n?.deleteResource&&t2.rmSync(t,{recursive:!0}),eE.success("Compiled artifacts packaged",{file:eK.basename(e)}),i("")}),s.on("error",e=>{eE.error("An error occurred during packaging",{error:e}),o(e)}),s.finalize()})}async function t5({channelName:e,manifest:t,rootPath:r}){let n=eK.resolve(r),i=eK.resolve(r,"doubao_app_output"),o=eK.resolve(i,t.packageName),a={outputFolder:i,transformFolder:o,manifest:t};t2.existsSync(i)&&t2.rmSync(i,{recursive:!0}),t2.mkdirSync(i),t2.mkdirSync(o),function(e,t){let{transformFolder:r,manifest:n}=t,{applet:i,widgets:o}=n,a=eK.resolve(e,"base"),s=eK.resolve(r,"base");t2.mkdirSync(s),t2.cpSync(a,s,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0});let l=eK.resolve(e,i.appletId),p=eK.resolve(r,i.appletId);t2.mkdirSync(p),i.pages.length>0&&t2.cpSync(l,p,{filter:(e,t)=>null===e.match(/(.)*\.map$/),recursive:!0}),o.forEach(t=>{let n=eK.resolve(e,t.widgetId),i=eK.resolve(r,t.widgetId);t2.mkdirSync(i),t2.cpSync(n,i,{filter:e=>null===e.match(/(.)*\.map$/),recursive:!0})})}(n,a);let s=await t9(e,a);return eE.debug("Package resource created",{packageResource:s}),{packageResource:s}}async function t9(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:o,widgets:a,packageName:s,versionCode:l}=r,p=eK.resolve(n,"deploy-package"),d=eK.resolve(p,e),c=eK.resolve(d,s);t2.mkdirSync(p),t2.mkdirSync(d),t2.mkdirSync(c),t2.cpSync(i,c,{recursive:!0});let u={},m=t2.readdirSync(c).filter(e=>t2.statSync(eK.resolve(c,e)).isDirectory()),h=eK.resolve(p,`${e}.zip`);try{if(await Promise.all(m.map(e=>{if("base"===e)return t4(eK.resolve(c,`${e}_${l}.zip`),eK.resolve(c,e),e,{deleteResource:!0});if(e===o.appletId){let t=`${e}_${o.digest}.zip`;return u[o.appletId]=t,t4(eK.resolve(c,t),eK.resolve(c,e),e,{deleteResource:!0})}let t=a.find(t=>t.widgetId===e);if(t){let r=`${e}_${t.digest}.zip`;return u[t.widgetId]=r,t4(eK.resolve(c,r),eK.resolve(c,e),e,{deleteResource:!0})}return eE.error("Invalid package directory",{directory:e}),Promise.resolve()})),await t4(h,d,e),process.env.BUILD_VERSION){let e=eK.resolve(n,"scm-deploy-package"),t=eK.resolve(e,s);t2.mkdirSync(e),t2.mkdirSync(t),t2.cpSync(c,t,{recursive:!0})}return eE.success("Deploy package archived",{destination:h}),{resource:h,fileNames:u}}catch(e){throw Error(`ERROR: Archive the deploy-package failed. ${e}`)}}(eA=eM||(eM={})).NORMAL="normal",eA.SELF_BUILT_CREATE="selfBuiltCreate",eA.SELF_BUILT_PUBLISH="selfBuiltPublish",eA.SELF_BUILT_CHECK_STATUS="selfBuiltCheckStatus",eA.SELF_BUILT_STOP="selfBuiltStop",eA.SELF_BUILT_ROLLBACK="selfBuiltRollback";let t8={NORMAL:eM.NORMAL,SELF_BUILT_CREATE:eM.SELF_BUILT_CREATE,SELF_BUILT_PUBLISH:eM.SELF_BUILT_PUBLISH,SELF_BUILT_CHECK_STATUS:eM.SELF_BUILT_CHECK_STATUS,SELF_BUILT_STOP:eM.SELF_BUILT_STOP,SELF_BUILT_ROLLBACK:eM.SELF_BUILT_ROLLBACK};function t6(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 t7(e,t){let[r]=(t??e).split(/[?#]/,1),n=r.replace(/\.(?:t|j)sx?$/i,"").replace(/^\/+|\/+$/g,"");return n?`/${n}`:"/"}function re(e,t,r){let n=t7(t).slice(1);return`${e}/${n}/${r}`}function rt(e,...t){return G(e,...t,(e,t,r)=>Array.isArray(e)?e.concat(t):Buffer.isBuffer(t)?t:void 0)}let rr=(e,t)=>tn.relative(e,t).replaceAll(tn.sep,"/");class rn{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=eK.dirname(this._filename);(0,t2.existsSync)(t)||(0,t2.mkdirSync)(t,{recursive:!0}),(0,t2.writeFileSync)(this._filename,this.toString(),e)}return this._filename}}function ri(e,t,r=!1,n=!1){return Object.keys(e).reduce((i,o)=>{let{filename:a,isVirtualFile:s,isSpecial:l}=e[o];if(s||l)return i;let p=`${ez}${tn.sep}${o}${tn.extname(a)}`,d=rr(tn.join(t,p,".."),a),c=tp(t),u=r?"defineWidget":"definePage";return i[o]=new rn(p),i[o].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"}]}),i[o].appendContent(`
128
128
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
129
129
 
130
130
  const View = ${u}({
@@ -140,14 +140,14 @@ if (import.meta.webpackHot) {
140
140
  import.meta.webpackHot.accept()
141
141
  }
142
142
  `:""),i},{})}let ro=f("module"),ra="doubao:plugin:taro";class rs extends rn{toString(){return this.contents.join("\n").trim()}}async function rl({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 rs(`.${tn.sep}app.js`,"")}});return{entry:n}}async function rp({compiler:e,compilation:t,assets:r,metadata:n,resolveAppInfo:i,shouldInjectAsset:o}){let a=Object.keys(r).reduce((e,r)=>{if(!o(r))return e;let n=t.getAsset(r);return n&&e.push(n),e},[]);if(0===a.length)return;let s=n.app,l=await i?.(),p=`globalThis.__AI_MANIFEST__ = ${JSON.stringify({package:l?.appKey||s.appId,appId:l?.appKey||s.appId,name:l?.appName||s.name,icons:l?.iconUrl?tj(l.iconUrl):s.icons})};
143
- `;a.forEach(r=>{if(r.source.source().toString().startsWith(p))return;let n=new e.webpack.sources.ReplaceSource(r.source,r.name);n.insert(0,p),t.updateAsset(r.name,n,r.info)})}function rd(e){let t=eK.posix.basename(e);return"background.js"===t||"main-thread.js"===t||/^background\.[^/]+\.js$/.test(t)||/^main-thread\.[^/]+\.js$/.test(t)}function rc(e){let t=e.replaceAll("\\","/");return t.startsWith("__doubao_web__")&&"template.js"===eK.posix.basename(t)}class ru{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(ru.name,t=>{t.hooks.processAssets.tapPromise({name:ru.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{await rp({compiler:e,compilation:t,assets:r,...this.options})})})}}let rm="index.web.bundle",rh="base/app.web.bundle",rf="base/client-tool/index.web.bundle";function rg(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function ry(e,t,r){return t[r]?.id??t6(r,e[r]?.folderName)}function rb(e){return!!(e?.isVirtualFile||e?.isSpecial)}function r_(e={},t={},r="configured"){return"all"===r?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e])=>t[e]?.web===!0))}(e,t)}class rw{apply(e){e.hooks.thisCompilation.tap(rw.name,t=>{t.hooks.processAssets.tapPromise({name:rw.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let r=rv(t,"app"),n=r?t.getAsset(r):void 0;if(!r||!n)throw Error("Worker entry asset was not emitted.");await rE(t,e,r,rh);let i=rv(t,e9);i&&await rE(t,e,i,rf)})})}}function rv(e,t){let r=e.entrypoints.get(t)?.getEntrypointChunk();return[...r?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function rE(e,t,r,n){let i=e.getAsset(r);if(!i)throw Error(`Worker entry asset was not emitted: ${r}`);e.emitAsset(n,new t.webpack.sources.RawSource(await rS(i.source.source().toString())));let o=e.getAsset(`${r}.map`);o&&e.emitAsset(`${n}.map`,o.source,o.info),e.deleteAsset(r)}async function rS(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 rx{options;recordNativeAppAssetPaths;constructor(e,t){this.options=e,this.recordNativeAppAssetPaths=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[eY]:"",[eX]:eZ,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(rx.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(rx.name,t=>{t.hooks.optimizeTree.tapPromise(rx.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:rx.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{var n,i,o;let a,s=rv(t,"app");if(!s||!t.getAsset(s))throw Error("Worker entry asset was not emitted.");this.recordNativeAppAssetPaths&&(n=t,i=this.options.context,o=s,i.setAppAssetPath(o),a=`${o}.map`,n.getAsset(a)&&i.setAppMapAssetPath(a)),await rp({compiler:e,compilation:t,assets:r,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),shouldInjectAsset:e=>e===s})})}),e.hooks.done.tapPromise(rx.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let rA=f("node:os"),rT=f("process"),rC=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.1.3/node_modules/@lynx-js/type-config/index.js");var rO={},rI={};function rP(e){var t=rI[e];if(void 0!==t)return t.exports;var r=rI[e]={exports:{}};return rO[e](r,r.exports,rP),r.exports}rP.m=rO,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,o=-1;++o<i;){var a=t[o];a in e&&(r[a]=e[a])}return r}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=rT||{},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),o=(e,t,r=e)=>n=>{let i=""+n,o=i.indexOf(t,e.length);return~o?e+a(i,t,r,o)+t:e+i+t},a=(e,t,r,n)=>{let i="",o=0;do i+=e.substring(o,n)+r,o=n+t.length,n=e.indexOf(t,o);while(~n);return i+e.substring(o)},s=(e=i)=>{let t=e?o:()=>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 rk=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 rD=globalThis.navigator?.userAgentData?.platform;function r$(e,t=globalThis.Deno?globalThis.Deno.args:b.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}"macOS"===rD||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===rD||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===rD||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===rD||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===rD||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,rk||b.env.TERM_PROGRAM,rk||b.platform,rk||b.cwd;let{env:rN}=b;function rR(e,r={}){var n;return 0!==(n=function(e,{streamIsTTY:r,sniffFlags:n=!0}={}){let i=function(){if(!("FORCE_COLOR"in rN))return;if("true"===rN.FORCE_COLOR)return 1;if("false"===rN.FORCE_COLOR)return 0;if(0===rN.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(rN.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==i&&(t=i);let o=n?t:i;if(0===o)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 rN&&"AGENT_NAME"in rN)return 1;if(e&&!r&&void 0===o)return 0;let a=o||0;if("dumb"===rN.TERM)return a;if("win32"===b.platform){let e=rA.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in rN)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in rN)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in rN)||"codeship"===rN.CI_NAME?1:a;if("TEAMCITY_VERSION"in rN)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rN.TEAMCITY_VERSION);if("truecolor"===rN.COLORTERM||"xterm-kitty"===rN.TERM||"xterm-ghostty"===rN.TERM||"wezterm"===rN.TERM)return 3;if("TERM_PROGRAM"in rN){let e=Number.parseInt((rN.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rN.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rN.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rN.TERM)||"COLORTERM"in rN?1:a}(e,{streamIsTTY:e&&e.isTTY,...r}))&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function rL(e,t=rT.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}function rM(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:o,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:s,VTE_VERSION:l,TERM:p}=b.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(!rR(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in b.env)return!0;if("win32"===b.platform||t||o)return!1;if(a){let e=rM(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(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=rM(l);return e.major>0||e.minor>=50}switch(p){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),rR({isTTY:_.isatty(1)}),rR({isTTY:_.isatty(2)});let rU={stdout:rj(b.stdout),stderr:rj(b.stderr)};function rB(e,t,{target:r="stdout",...n}={}){return rU[r]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}rB.isSupported=rU.stdout,rB.stderr=(e,t,r={})=>rB(e,t,{target:"stderr",...r}),rB.stderr.isSupported=rU.stderr;let rF=rP("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var rW=rP.n(rF);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,...rW()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...rW()(t,this.options.configKeys)},e})})}}let rV=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"]);(eT=ej||(ej={}))[eT.Start=0]="Start",eT[eT.Property=1]="Property",eT[eT.StringKey=2]="StringKey",eT[eT.NumberKey=3]="NumberKey";let rq=rP("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var rJ=rP.n(rq);let rK=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=i=[],o=(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\`.
143
+ `;a.forEach(r=>{if(r.source.source().toString().startsWith(p))return;let n=new e.webpack.sources.ReplaceSource(r.source,r.name);n.insert(0,p),t.updateAsset(r.name,n,r.info)})}function rd(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 rc(e){let t=e.replaceAll("\\","/");return t.split("/").some(e=>e.startsWith("__doubao_web__"))&&rd(t)}class ru{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(ru.name,t=>{t.hooks.processAssets.tapPromise({name:ru.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{await rp({compiler:e,compilation:t,assets:r,...this.options})})})}}let rm="index.web.bundle",rh="base/app.web.bundle",rf="base/client-tool/index.web.bundle";function rg(e){return`__doubao_web__${e.replaceAll("\\","/").replaceAll("/","__")}`}function ry(e,t,r){return t[r]?.id??t6(r,e[r]?.folderName)}function rb(e){return!!(e?.isVirtualFile||e?.isSpecial)}function r_(e={},t={},r="configured"){return"all"===r?e:function(e={},t={}){return Object.fromEntries(Object.entries(e).filter(([e])=>t[e]?.web===!0))}(e,t)}class rw{apply(e){e.hooks.thisCompilation.tap(rw.name,t=>{t.hooks.processAssets.tapPromise({name:rw.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{let r=rv(t,"app"),n=r?t.getAsset(r):void 0;if(!r||!n)throw Error("Worker entry asset was not emitted.");await rE(t,e,r,rh);let i=rv(t,e9);i&&await rE(t,e,i,rf)})})}}function rv(e,t){let r=e.entrypoints.get(t)?.getEntrypointChunk();return[...r?.files??[]].find(t=>t.endsWith(".js")&&!e.getAsset(t)?.info?.hotModuleReplacement)}async function rE(e,t,r,n){let i=e.getAsset(r);if(!i)throw Error(`Worker entry asset was not emitted: ${r}`);e.emitAsset(n,new t.webpack.sources.RawSource(await rS(i.source.source().toString())));let o=e.getAsset(`${r}.map`);o&&e.emitAsset(`${n}.map`,o.source,o.info),e.deleteAsset(r)}async function rS(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 rx{options;recordNativeAppAssetPaths;constructor(e,t){this.options=e,this.recordNativeAppAssetPaths=t}apply(e){new e.webpack.experiments.VirtualModulesPlugin({[eY]:"",[eX]:eZ,...Object.fromEntries(Object.entries(this.options.entry).map(([,e])=>[e.filename,e.toString()]))}).apply(e),e.hooks.make.tapPromise(rx.name,async()=>{await this.options.pluginSystem.callWorkerHooks("collectMetaData",{collector:this.options.context.metadata})}),e.hooks.thisCompilation.tap(rx.name,t=>{t.hooks.optimizeTree.tapPromise(rx.name,async()=>{await this.options.pluginSystem.callWorkerHooks("build",{metadata:this.options.context.metadata,fileDependencies:t.fileDependencies})}),t.hooks.processAssets.tapPromise({name:rx.name,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS},async r=>{var n,i,o;let a,s=rv(t,"app");if(!s||!t.getAsset(s))throw Error("Worker entry asset was not emitted.");this.recordNativeAppAssetPaths&&(n=t,i=this.options.context,o=s,i.setAppAssetPath(o),a=`${o}.map`,n.getAsset(a)&&i.setAppMapAssetPath(a)),await rp({compiler:e,compilation:t,assets:r,metadata:this.options.context.metadata,resolveAppInfo:()=>this.options.context.resolveAppInfo(),shouldInjectAsset:e=>e===s})})}),e.hooks.done.tapPromise(rx.name,async e=>{await this.options.pluginSystem.callWorkerHooks("afterBuild",{stats:e})})}}let rA=f("node:os"),rT=f("process"),rC=f("../../../node_modules/.pnpm/@lynx-js+type-config@4.1.3/node_modules/@lynx-js/type-config/index.js");var rO={},rI={};function rP(e){var t=rI[e];if(void 0!==t)return t.exports;var r=rI[e]={exports:{}};return rO[e](r,r.exports,rP),r.exports}rP.m=rO,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,o=-1;++o<i;){var a=t[o];a in e&&(r[a]=e[a])}return r}},"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(e){let t=rT||{},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),o=(e,t,r=e)=>n=>{let i=""+n,o=i.indexOf(t,e.length);return~o?e+a(i,t,r,o)+t:e+i+t},a=(e,t,r,n)=>{let i="",o=0;do i+=e.substring(o,n)+r,o=n+t.length,n=e.indexOf(t,o);while(~n);return i+e.substring(o)},s=(e=i)=>{let t=e?o:()=>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 rk=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 rD=globalThis.navigator?.userAgentData?.platform;function r$(e,t=globalThis.Deno?globalThis.Deno.args:b.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}"macOS"===rD||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform,"Windows"===rD||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform,"Linux"===rD||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform,"iOS"===rD||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),"Android"===rD||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform,rk||b.env.TERM_PROGRAM,rk||b.platform,rk||b.cwd;let{env:rN}=b;function rR(e,r={}){var n;return 0!==(n=function(e,{streamIsTTY:r,sniffFlags:n=!0}={}){let i=function(){if(!("FORCE_COLOR"in rN))return;if("true"===rN.FORCE_COLOR)return 1;if("false"===rN.FORCE_COLOR)return 0;if(0===rN.FORCE_COLOR.length)return 1;let e=Math.min(Number.parseInt(rN.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}();void 0!==i&&(t=i);let o=n?t:i;if(0===o)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 rN&&"AGENT_NAME"in rN)return 1;if(e&&!r&&void 0===o)return 0;let a=o||0;if("dumb"===rN.TERM)return a;if("win32"===b.platform){let e=rA.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in rN)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in rN)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in rN)||"codeship"===rN.CI_NAME?1:a;if("TEAMCITY_VERSION"in rN)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(rN.TEAMCITY_VERSION);if("truecolor"===rN.COLORTERM||"xterm-kitty"===rN.TERM||"xterm-ghostty"===rN.TERM||"wezterm"===rN.TERM)return 3;if("TERM_PROGRAM"in rN){let e=Number.parseInt((rN.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(rN.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(rN.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(rN.TERM)||"COLORTERM"in rN?1:a}(e,{streamIsTTY:e&&e.isTTY,...r}))&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function rL(e,t=rT.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return -1!==n&&(-1===i||n<i)}function rM(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:o,TERM_PROGRAM:a,TERM_PROGRAM_VERSION:s,VTE_VERSION:l,TERM:p}=b.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(!rR(e)||e&&!e.isTTY)return!1;if("WT_SESSION"in b.env)return!0;if("win32"===b.platform||t||o)return!1;if(a){let e=rM(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(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=rM(l);return e.major>0||e.minor>=50}switch(p){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),rR({isTTY:_.isatty(1)}),rR({isTTY:_.isatty(2)});let rU={stdout:rj(b.stdout),stderr:rj(b.stderr)};function rB(e,t,{target:r="stdout",...n}={}){return rU[r]?["\x1b]","8",";",";",t,"\x07",e,"\x1b]","8",";",";","\x07"].join(""):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}rB.isSupported=rU.stdout,rB.stderr=(e,t,r={})=>rB(e,t,{target:"stderr",...r}),rB.stderr.isSupported=rU.stderr;let rF=rP("../../../node_modules/.pnpm/object.pick@1.3.0/node_modules/object.pick/index.js");var rW=rP.n(rF);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,...rW()(t,this.options.compilerOptionsKeys)},e.encodeData.sourceContent.config={...e.encodeData.sourceContent.config,...rW()(t,this.options.configKeys)},e})})}}let rV=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"]);(eT=ej||(ej={}))[eT.Start=0]="Start",eT[eT.Property=1]="Property",eT[eT.StringKey=2]="StringKey",eT[eT.NumberKey=3]="NumberKey";let rq=rP("../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");var rJ=rP.n(rq);let rK=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=i=[],o=(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\`.
144
144
 
145
145
  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)||o(!0,{path:t+"",expected:"Config",value:e}))&&((e,t,r=!0)=>[void 0===e.alignMouseEventWithW3C||"boolean"==typeof e.alignMouseEventWithW3C||o(r,{path:t+".alignMouseEventWithW3C",expected:"(boolean | undefined)",value:e.alignMouseEventWithW3C}),void 0===e.disableLongpressAfterScroll||"boolean"==typeof e.disableLongpressAfterScroll||o(r,{path:t+".disableLongpressAfterScroll",expected:"(boolean | undefined)",value:e.disableLongpressAfterScroll}),void 0===e.enableA11y||"boolean"==typeof e.enableA11y||o(r,{path:t+".enableA11y",expected:"(boolean | undefined)",value:e.enableA11y}),void 0===e.enableAccessibilityElement||"boolean"==typeof e.enableAccessibilityElement||o(r,{path:t+".enableAccessibilityElement",expected:"(boolean | undefined)",value:e.enableAccessibilityElement}),void 0===e.enableCSSInheritance||"boolean"==typeof e.enableCSSInheritance||o(r,{path:t+".enableCSSInheritance",expected:"(boolean | undefined)",value:e.enableCSSInheritance}),void 0===e.enableCSSInlineVariables||"boolean"==typeof e.enableCSSInlineVariables||o(r,{path:t+".enableCSSInlineVariables",expected:"(boolean | undefined)",value:e.enableCSSInlineVariables}),void 0===e.enableCSSRule||"boolean"==typeof e.enableCSSRule||o(r,{path:t+".enableCSSRule",expected:"(boolean | undefined)",value:e.enableCSSRule}),void 0===e.enableEndGestureAtLastFingerUp||"boolean"==typeof e.enableEndGestureAtLastFingerUp||o(r,{path:t+".enableEndGestureAtLastFingerUp",expected:"(boolean | undefined)",value:e.enableEndGestureAtLastFingerUp}),void 0===e.enableEventHandleRefactor||"boolean"==typeof e.enableEventHandleRefactor||o(r,{path:t+".enableEventHandleRefactor",expected:"(boolean | undefined)",value:e.enableEventHandleRefactor}),void 0===e.enableEventThrough||"boolean"==typeof e.enableEventThrough||o(r,{path:t+".enableEventThrough",expected:"(boolean | undefined)",value:e.enableEventThrough}),void 0===e.enableFetchAPIStandardStreaming||"boolean"==typeof e.enableFetchAPIStandardStreaming||o(r,{path:t+".enableFetchAPIStandardStreaming",expected:"(boolean | undefined)",value:e.enableFetchAPIStandardStreaming}),void 0===e.enableFixedNew||"boolean"==typeof e.enableFixedNew||o(r,{path:t+".enableFixedNew",expected:"(boolean | undefined)",value:e.enableFixedNew}),void 0===e.enableFlexBasisZeroPercent||"boolean"==typeof e.enableFlexBasisZeroPercent||o(r,{path:t+".enableFlexBasisZeroPercent",expected:"(boolean | undefined)",value:e.enableFlexBasisZeroPercent}),void 0===e.enableGridPlacementShorthands||"boolean"==typeof e.enableGridPlacementShorthands||o(r,{path:t+".enableGridPlacementShorthands",expected:"(boolean | undefined)",value:e.enableGridPlacementShorthands}),void 0===e.enableJsBindingApiThrowException||"boolean"==typeof e.enableJsBindingApiThrowException||o(r,{path:t+".enableJsBindingApiThrowException",expected:"(boolean | undefined)",value:e.enableJsBindingApiThrowException}),void 0===e.enableListNewArchitecture||"boolean"==typeof e.enableListNewArchitecture||o(r,{path:t+".enableListNewArchitecture",expected:"(boolean | undefined)",value:e.enableListNewArchitecture}),void 0===e.enableMultiTouch||"boolean"==typeof e.enableMultiTouch||o(r,{path:t+".enableMultiTouch",expected:"(boolean | undefined)",value:e.enableMultiTouch}),void 0===e.enableNativeList||"boolean"==typeof e.enableNativeList||o(r,{path:t+".enableNativeList",expected:"(boolean | undefined)",value:e.enableNativeList}),void 0===e.enableNewGesture||"boolean"==typeof e.enableNewGesture||o(r,{path:t+".enableNewGesture",expected:"(boolean | undefined)",value:e.enableNewGesture}),void 0===e.enableNewIntersectionObserver||"boolean"==typeof e.enableNewIntersectionObserver||o(r,{path:t+".enableNewIntersectionObserver",expected:"(boolean | undefined)",value:e.enableNewIntersectionObserver}),void 0===e.enableNewTransformOrigin||"boolean"==typeof e.enableNewTransformOrigin||o(r,{path:t+".enableNewTransformOrigin",expected:"(boolean | undefined)",value:e.enableNewTransformOrigin}),void 0===e.enableParseIntFlex||"boolean"==typeof e.enableParseIntFlex||o(r,{path:t+".enableParseIntFlex",expected:"(boolean | undefined)",value:e.enableParseIntFlex}),void 0===e.enableReloadLifecycle||"boolean"==typeof e.enableReloadLifecycle||o(r,{path:t+".enableReloadLifecycle",expected:"(boolean | undefined)",value:e.enableReloadLifecycle}),void 0===e.enableSimultaneousTap||"boolean"==typeof e.enableSimultaneousTap||o(r,{path:t+".enableSimultaneousTap",expected:"(boolean | undefined)",value:e.enableSimultaneousTap}),void 0===e.enableTextOverflow||"boolean"==typeof e.enableTextOverflow||o(r,{path:t+".enableTextOverflow",expected:"(boolean | undefined)",value:e.enableTextOverflow}),void 0===e.enableTransformedTouchPosition||"boolean"==typeof e.enableTransformedTouchPosition||o(r,{path:t+".enableTransformedTouchPosition",expected:"(boolean | undefined)",value:e.enableTransformedTouchPosition}),void 0===e.fontScaleEffectiveOnlyOnSp||"boolean"==typeof e.fontScaleEffectiveOnlyOnSp||o(r,{path:t+".fontScaleEffectiveOnlyOnSp",expected:"(boolean | undefined)",value:e.fontScaleEffectiveOnlyOnSp}),void 0===e.includeFontPadding||"boolean"==typeof e.includeFontPadding||o(r,{path:t+".includeFontPadding",expected:"(boolean | undefined)",value:e.includeFontPadding}),void 0===e.keyboardCallbackPassRelativeHeight||"boolean"==typeof e.keyboardCallbackPassRelativeHeight||o(r,{path:t+".keyboardCallbackPassRelativeHeight",expected:"(boolean | undefined)",value:e.keyboardCallbackPassRelativeHeight}),void 0===e.longPressDuration||"number"==typeof e.longPressDuration||o(r,{path:t+".longPressDuration",expected:"(number | undefined)",value:e.longPressDuration}),void 0===e.removeDescendantSelectorScope||"boolean"==typeof e.removeDescendantSelectorScope||o(r,{path:t+".removeDescendantSelectorScope",expected:"(boolean | undefined)",value:e.removeDescendantSelectorScope}),void 0===e.tapSlop||"string"==typeof e.tapSlop||o(r,{path:t+".tapSlop",expected:"(string | undefined)",value:e.tapSlop}),void 0===e.unifyVWVHBehavior||"boolean"==typeof e.unifyVWVHBehavior||o(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","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=>n===e))return!0;let a=e[n];if(void 0===a)return!0;return o(r,{path:t+(!1===rV(i=n)&&/^[a-zA-Z_$][a-zA-Z_$0-9]*$/g.test(i)?`.${n}`:`[${JSON.stringify(n)}]`),expected:"undefined",value:a,description:`The property \`${n}\` is not defined in the object type.
146
146
 
147
- Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||o(!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=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=[],r="",n=ej.Start,i=5;for(;i<e.length-1;){let o=e[++i];if(n===ej.Property?"."===o||"["===o?(t.push({key:r}),n=ej.Start):i===e.length-1?(r+=o,t.push({key:r}),i++,n=ej.Start):r+=o:n===ej.StringKey?'"'===o?(t.push({key:JSON.parse(r+o)}),i+=2,n=ej.Start):"\\"===o?(r+=e[i],r+=e[++i]):r+=o:n===ej.NumberKey&&("]"===o?(t.push({key:Number.parseInt(r)}),i++,n=ej.Start):r+=o),n===ej.Start&&i<e.length-1){let t=e[i];if(r="","["===t)'"'===e[i+1]?(n=ej.StringKey,i++,r='"'):n=ej.NumberKey;else if("."===t)n=ej.Property;else throw Error("Unreachable: pointer points invalid character")}}if(n!==ej.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function rz(e){let t=rK(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: \`${rJ().red(t)}\``,""]:[`Invalid config on \`${rJ().red(t)}\`.`,` - Expect to be ${rJ().green(e)}`,` - Got: ${rJ().red((n=r,Object.prototype.toString.call(n).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let rY={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function rX(e){return e?.type==="Identifier"}function rZ(e){return e?.type==="StringLiteral"}function rQ(e){return e?.type==="NumericLiteral"}function r0(e){return e?.type==="BooleanLiteral"}function r1(e){return e?.type==="ObjectExpression"}function r3(e){return e?.type==="ArrayExpression"}function r2(e){return e?.type==="KeyValueProperty"}let r4=e=>{if(r1(e)){let t={};for(let r of e.properties){if(r?.type==="SpreadElement"||!r2(r))return null;let{key:e,value:n}=r;if(!rX(e)&&!rZ(e))return null;let i=e.value;r1(n)||r3(n)?t[i]=r4(n):rZ(n)||rQ(n)||r0(n)?t[i]=n.value:rX(n)&&(t[i]=n)}return t}if(r3(e)){let t=[];for(let r of e.elements){if(!r||r.spread)return null;let e=r.expression;r1(e)||r3(e)?t.push(r4(e)):rZ(e)||rQ(e)||r0(e)?t.push(e.value):rX(e)&&t.push(e)}return t}},r5=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function r9(e,t,r){let{widgets:n,pages:i,collector:o,define:a,onDeprecatedAIMeta:s}=r,l=i[t],p=n[t],d=e;return(l||p)&&(a&&Object.keys(a).length>0&&(d=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),el((0,r5.parseSync)(d,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(rX(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let r=e.arguments[0]?.expression;if(r1(r)){for(let e of r.properties)if(r2(e)&&rX(e.key)&&"aiMeta"===e.key.value){let r=r4(e.value);if(!r)continue;l?(s?.({kind:"page",entryName:l,filename:t}),o.addPageMeta(l,r)):p&&(s?.({kind:"widget",entryName:p,filename:t}),o.addWidgetMeta(p,r))}}}rX(e.callee)&&e.callee.value in I&&(p&&o.addWidgetMeta(p,I[e.callee.value]),l&&o.addPageMeta(l,I[e.callee.value]))}})),e}let r8=/[/\\]/;function r6(e,t){t.forEach(([t,{id:r}])=>{if(r&&r8.test(r))throw Error(`Invalid ${e} id "${r}" 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 r7({pages:e,widgets:t,entries:r,collector:n,normalizedAppConfig:i,define:o}){let a=new tq,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:o,onDeprecatedAIMeta({kind:e,entryName:t,filename:r}){let n=`${e}:${t}:${r}`;s.has(n)||(s.add(n),tx.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) is deprecated for ${t}. Configure this ${e} metadata in src/app.config.ts instead. Source: ${r}`))}},p=i.pages.entries,d=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?r9(n.toString(),e,l):void tx.warn("Cannot find virtual file",{file:t})}return r9(t3.readFileSync(e,"utf-8"),e,l)})).catch(e=>{tx.error("Failed to collect view metadata",{error:e})});let c=a.getData(),u=I.defineLoginPage,m=t7("",u.path),h=Object.entries(e).map(([e,t])=>{let r=c.pages[e],{web:n,...i}=p[e]??{},o=r?.path,a=t.isLoginPage||void 0!==o&&t7(e,o)===m;return[e,{id:t6(e,t.folderName),...r,...i,...a?u:{},path:t7(e,a?u.path:t.isSpecial?o: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(", ")}`);r6("page",h),h.forEach(([e,t])=>{n.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:r,...n}=d[e]??{};return[e,{id:t6(e,t.folderName),...c.widgets[e],...n}]});r6("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])=>`Duplicate widget id "${e}" is used by:
147
+ Please remove the property next time.`})}).every(e=>e)].every(e=>e))(e,t+"",!0)||o(!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=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=[],r="",n=ej.Start,i=5;for(;i<e.length-1;){let o=e[++i];if(n===ej.Property?"."===o||"["===o?(t.push({key:r}),n=ej.Start):i===e.length-1?(r+=o,t.push({key:r}),i++,n=ej.Start):r+=o:n===ej.StringKey?'"'===o?(t.push({key:JSON.parse(r+o)}),i+=2,n=ej.Start):"\\"===o?(r+=e[i],r+=e[++i]):r+=o:n===ej.NumberKey&&("]"===o?(t.push({key:Number.parseInt(r)}),i++,n=ej.Start):r+=o),n===ej.Start&&i<e.length-1){let t=e[i];if(r="","["===t)'"'===e[i+1]?(n=ej.StringKey,i++,r='"'):n=ej.NumberKey;else if("."===t)n=ej.Property;else throw Error("Unreachable: pointer points invalid character")}}if(n!==ej.Start)throw Error(`Failed to parse path: ${JSON.stringify(e)}`);return t})(e.path)}))}}}});function rz(e){let t=rK(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: \`${rJ().red(t)}\``,""]:[`Invalid config on \`${rJ().red(t)}\`.`,` - Expect to be ${rJ().green(e)}`,` - Got: ${rJ().red((n=r,Object.prototype.toString.call(n).replace(/^\[object\s+([a-z]+)\]$/i,"$1").toLowerCase()))}`,""]})).join("\n"))}let rY={"lynx:react":"@lynx-js/react-rsbuild-plugin"};function rX(e){return e?.type==="Identifier"}function rZ(e){return e?.type==="StringLiteral"}function rQ(e){return e?.type==="NumericLiteral"}function r0(e){return e?.type==="BooleanLiteral"}function r1(e){return e?.type==="ObjectExpression"}function r2(e){return e?.type==="ArrayExpression"}function r3(e){return e?.type==="KeyValueProperty"}let r4=e=>{if(r1(e)){let t={};for(let r of e.properties){if(r?.type==="SpreadElement"||!r3(r))return null;let{key:e,value:n}=r;if(!rX(e)&&!rZ(e))return null;let i=e.value;r1(n)||r2(n)?t[i]=r4(n):rZ(n)||rQ(n)||r0(n)?t[i]=n.value:rX(n)&&(t[i]=n)}return t}if(r2(e)){let t=[];for(let r of e.elements){if(!r||r.spread)return null;let e=r.expression;r1(e)||r2(e)?t.push(r4(e)):rZ(e)||rQ(e)||r0(e)?t.push(e.value):rX(e)&&t.push(e)}return t}},r5=f("../../../node_modules/.pnpm/@swc+core@1.15.11_@swc+helpers@0.5.23/node_modules/@swc/core/index.js");function r9(e,t,r){let{widgets:n,pages:i,collector:o,define:a,onDeprecatedAIMeta:s}=r,l=i[t],p=n[t],d=e;return(l||p)&&(a&&Object.keys(a).length>0&&(d=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),el((0,r5.parseSync)(d,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(rX(e.callee)&&["defineWidget","definePage"].includes(e.callee.value)){let r=e.arguments[0]?.expression;if(r1(r)){for(let e of r.properties)if(r3(e)&&rX(e.key)&&"aiMeta"===e.key.value){let r=r4(e.value);if(!r)continue;l?(s?.({kind:"page",entryName:l,filename:t}),o.addPageMeta(l,r)):p&&(s?.({kind:"widget",entryName:p,filename:t}),o.addWidgetMeta(p,r))}}}rX(e.callee)&&e.callee.value in I&&(p&&o.addWidgetMeta(p,I[e.callee.value]),l&&o.addPageMeta(l,I[e.callee.value]))}})),e}let r8=/[/\\]/;function r6(e,t){t.forEach(([t,{id:r}])=>{if(r&&r8.test(r))throw Error(`Invalid ${e} id "${r}" 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 r7({pages:e,widgets:t,entries:r,collector:n,normalizedAppConfig:i,define:o}){let a=new tq,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:o,onDeprecatedAIMeta({kind:e,entryName:t,filename:r}){let n=`${e}:${t}:${r}`;s.has(n)||(s.add(n),tx.warn(`define${"page"===e?"Page":"Widget"}({ aiMeta }) is deprecated for ${t}. Configure this ${e} metadata in src/app.config.ts instead. Source: ${r}`))}},p=i.pages.entries,d=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?r9(n.toString(),e,l):void tx.warn("Cannot find virtual file",{file:t})}return r9(t2.readFileSync(e,"utf-8"),e,l)})).catch(e=>{tx.error("Failed to collect view metadata",{error:e})});let c=a.getData(),u=I.defineLoginPage,m=t7("",u.path),h=Object.entries(e).map(([e,t])=>{let r=c.pages[e],{web:n,...i}=p[e]??{},o=r?.path,a=t.isLoginPage||void 0!==o&&t7(e,o)===m;return[e,{id:t6(e,t.folderName),...r,...i,...a?u:{},path:t7(e,a?u.path:t.isSpecial?o: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(", ")}`);r6("page",h),h.forEach(([e,t])=>{n.addPageMeta(e,t)});let g=Object.entries(t).map(([e,t])=>{let{web:r,...n}=d[e]??{};return[e,{id:t6(e,t.folderName),...c.widgets[e],...n}]});r6("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])=>`Duplicate widget id "${e}" is used by:
148
148
  ${t.map(e=>`- ${e}`).join("\n")}`).join("\n\n");throw Error(`${n}
149
149
 
150
- Widget IDs must be globally unique. Configure distinct "id" values in src/app.config.ts.`)}(g),g.forEach(([e,t])=>{n.addWidgetMeta(e,t)})}let ne=f("os");function nt(e){let[t,r]=e.split(".").map(e=>Number(e));return Number.isNaN(t)||Number.isNaN(r)?1/0:10===t?0:172===t&&r>=16&&r<=31?1:192===t&&168===r?2:3}function nr(e){return/^(?:utun|tun|tap|ppp|ipsec|wg|docker|vboxnet|vmnet)\d*$/i.test(e)||/^br-/i.test(e)||/(?:vEthernet|Hyper-V|Docker|VirtualBox|VMware)/i.test(e)}function nn(e=function(){let e=Object.entries(ne.networkInterfaces()),t=[],r=[],n=[],i=[];for(let[o,a]of e)if(a)for(let e of a){let{address:a,family:s,internal:l}=e;if(!l)if("IPv4"===s)nr(o)||a.startsWith("169.254.")?n.push(a):t.push(a);else"IPv6"!==s||/^fe[89ab]/i.test(a)||(nr(o)?i.push(a):r.push(a))}return t.length>0?t:n.length>0?n:r.length>0?r:i}()){return e.slice().sort((e,t)=>nt(e)-nt(t))[0]}function ni(e){let t=nn()??"127.0.0.1",r=t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t;return`http://${r}:${e}`}let no=`base/${e4}`;async function na({encryption:e}){let t=t3.mkdtempSync(eK.join(ne.tmpdir(),"doubao-keystore-")),r=eK.join(t,e4);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 t3.readFileSync(r)}finally{t3.rmSync(t,{recursive:!0,force:!0})}}let ns=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class nl{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(nl.name,t=>{t.hooks.processAssets.tapPromise({name:nl.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=rv(t,e9);for(let e of[n,i].filter(e=>!!e)){let i=t.getAsset(e);if(!i)throw Error(`Worker entry asset was not emitted: ${e}`);let{buffer:o,encodeOptions:a,keystoreContent:s}=await this.encode([i]);if(t.updateAsset(e,new r(o,!1)),s){let e=new r(s,!1);t.getAsset(no)?t.updateAsset(no,e):t.emitAsset(no,e)}tc()&&e===n&&t.emitAsset(`${eK.dirname(e)}/tasm.json`,new r(JSON.stringify(a,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=rt(i,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:o,lepus_debug:a,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:o,encodeOptions:n,debugInfo:a,keystoreContent:await na({encryption:{...r.encryption}})}):{buffer:o,encodeOptions:n,debugInfo:a}}let o=(0,ns.getEncodeMode)(),{buffer:a}=await o(n);return{buffer:a,encodeOptions:n}}}function np(e,t,n,i,o){let a=!1;return{name:np.name,apply(s){let l=new s.webpack.experiments.VirtualModulesPlugin;l.apply(s),s.hooks.thisCompilation.tap(np.name,()=>{Object.keys(n).forEach(e=>{l.writeModule(n[e].filename,n[e].toString())})}),s.hooks.thisCompilation.tap(np.name,n=>{let l,p=()=>{void 0!==l&&o?.(Math.max(0,Date.now()-l))},d=e.getLynxTemplatePluginHooks(n);d.beforeEncode.tapPromise(np.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=eo({},e.encodeData.sourceContent.config,{mapContainerType:1}),e)),d.encode.tapPromise({name:np.name,stage:255},async e=>{let{encodeOptions:o}=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(),d=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=eK.posix.basename(r);return e.widgets[`widgets/${i}`]?.id??e.pages[`pages/${i}`]?.path}(i,e.intermediate),c=i.app.appId,u=rt(l,{signing:{extra_config:{app_id:c,bundle_id:d}},encryption:{salt:c}}),{buffer:m,lepus_debug:h,status:g,error_msg:y}=await r(JSON.stringify(o),u);if(0!==g)throw Error(y);if(!a&&u.encryption.enabled){a=!0;let e=await na({encryption:{...u.encryption}}),t=new s.webpack.sources.RawSource(e,!1);n.getAsset(no)?n.updateAsset(no,t):n.emitAsset(no,t)}return p(),{buffer:m,debugInfo:h}}let{buffer:d,lepus_debug:c}=await (r??=new h({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js_089fc2c25cf06b41592540314396dd42/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,rA.availableParallelism)()})).run({encodeOptions:o});return p(),{buffer:Buffer.from(d),debugInfo:c}})}),s.hooks.failed.tap(np.name,e=>{tT.error("Failed to bundle template",{error:e})})}}}class nd{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return nd._instance??=new nd}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 nc(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function nu(e){nd.instance.stop(),e().catch(nc).finally(()=>nd.instance.start())}let nm=ev.child("simulator"),nh=f("node:http"),nf={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},ng=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),ny=new Set([...ng,"cookie","host","origin","referer"]),nb=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,n_="X-DBX-Sandbox-Session-ID",nw="x-tt-logid";function nv(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function nE(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 nS(e,t,r={}){let n={};for(let[t,r]of Object.entries(e))void 0===r||ny.has(t.toLowerCase())||(n[t]=r);return{...n,...r,host:t.host}}function nx(e,t=[]){let r={};for(let[t,n]of Object.entries(e))void 0===n||ng.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 nA(e,t=[]){let r=nx(Object.fromEntries(e),t);return delete r["content-encoding"],delete r["content-length"],r}function nT(e,t={}){Object.entries({...nf,...t}).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})}function nC(e,t,r,n){nT(e,n),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(r)}function nO(e,t,r,n){let i=JSON.stringify(r);nT(e,n),e.writeHead(t,{"Content-Length":Buffer.byteLength(i),"Content-Type":"application/json; charset=utf-8"}),e.end(i)}function nI(e,t,r){return new Promise((n,i)=>{let o=[],a=0,s=!1;e.on("data",n=>{if(s)return;let l=Uint8Array.from(Buffer.isBuffer(n)?n:Buffer.from(n));if((a+=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}o.push(l)}),e.once("end",()=>{if(s)return;s=!0;let e=new Uint8Array(a),t=0;for(let r of o)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 nP(e,t,r){return nI(e,t,r).then(e=>Buffer.from(e).toString("utf8"))}function nk(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function nD(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r=nb.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${r}`}).join("\n")}function n$(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){"applet0930"===process.env.DEBUG&&nm.info(`${e} ${a.pathname}${a.search} ${(o>=500?ep.red:o>=400?ep.yellow:ep.green)(String(o))}
150
+ Widget IDs must be globally unique. Configure distinct "id" values in src/app.config.ts.`)}(g),g.forEach(([e,t])=>{n.addWidgetMeta(e,t)})}let ne=f("os");function nt(e){let[t,r]=e.split(".").map(e=>Number(e));return Number.isNaN(t)||Number.isNaN(r)?1/0:10===t?0:172===t&&r>=16&&r<=31?1:192===t&&168===r?2:3}function nr(e){return/^(?:utun|tun|tap|ppp|ipsec|wg|docker|vboxnet|vmnet)\d*$/i.test(e)||/^br-/i.test(e)||/(?:vEthernet|Hyper-V|Docker|VirtualBox|VMware)/i.test(e)}function nn(e=function(){let e=Object.entries(ne.networkInterfaces()),t=[],r=[],n=[],i=[];for(let[o,a]of e)if(a)for(let e of a){let{address:a,family:s,internal:l}=e;if(!l)if("IPv4"===s)nr(o)||a.startsWith("169.254.")?n.push(a):t.push(a);else"IPv6"!==s||/^fe[89ab]/i.test(a)||(nr(o)?i.push(a):r.push(a))}return t.length>0?t:n.length>0?n:r.length>0?r:i}()){return e.slice().sort((e,t)=>nt(e)-nt(t))[0]}function ni(e){let t=nn()??"127.0.0.1",r=t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t;return`http://${r}:${e}`}let no=`base/${e4}`;async function na({encryption:e}){let t=t2.mkdtempSync(eK.join(ne.tmpdir(),"doubao-keystore-")),r=eK.join(t,e4);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 t2.readFileSync(r)}finally{t2.rmSync(t,{recursive:!0,force:!0})}}let ns=f("../../../node_modules/.pnpm/@byted-lynx+tasm@4.4.40_debug@4.4.3/node_modules/@byted-lynx/tasm/index.js");class nl{options;isGenerateKeystore=!1;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(nl.name,t=>{t.hooks.processAssets.tapPromise({name:nl.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=rv(t,e9);for(let e of[n,i].filter(e=>!!e)){let i=t.getAsset(e);if(!i)throw Error(`Worker entry asset was not emitted: ${e}`);let{buffer:o,encodeOptions:a,keystoreContent:s}=await this.encode([i]);if(t.updateAsset(e,new r(o,!1)),s){let e=new r(s,!1);t.getAsset(no)?t.updateAsset(no,e):t.emitAsset(no,e)}tc()&&e===n&&t.emitAsset(`${eK.dirname(e)}/tasm.json`,new r(JSON.stringify(a,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=rt(i,{signing:{extra_config:{app_id:t,bundle_id:t}},encryption:{salt:t}}),{buffer:o,lepus_debug:a,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:o,encodeOptions:n,debugInfo:a,keystoreContent:await na({encryption:{...r.encryption}})}):{buffer:o,encodeOptions:n,debugInfo:a}}let o=(0,ns.getEncodeMode)(),{buffer:a}=await o(n);return{buffer:a,encodeOptions:n}}}function np(e,t,n,i,o){let a=!1;return{name:np.name,apply(s){let l=new s.webpack.experiments.VirtualModulesPlugin;l.apply(s),s.hooks.thisCompilation.tap(np.name,()=>{Object.keys(n).forEach(e=>{l.writeModule(n[e].filename,n[e].toString())})}),s.hooks.thisCompilation.tap(np.name,n=>{let l,p=()=>{void 0!==l&&o?.(Math.max(0,Date.now()-l))},d=e.getLynxTemplatePluginHooks(n);d.beforeEncode.tapPromise(np.name,async e=>(l??=Date.now(),e.encodeData.sourceContent.config=eo({},e.encodeData.sourceContent.config,{mapContainerType:1}),e)),d.encode.tapPromise({name:np.name,stage:255},async e=>{let{encodeOptions:o}=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(),d=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=eK.posix.basename(r);return e.widgets[`widgets/${i}`]?.id??e.pages[`pages/${i}`]?.path}(i,e.intermediate),c=i.app.appId,u=rt(l,{signing:{extra_config:{app_id:c,bundle_id:d}},encryption:{salt:c}}),{buffer:m,lepus_debug:h,status:g,error_msg:y}=await r(JSON.stringify(o),u);if(0!==g)throw Error(y);if(!a&&u.encryption.enabled){a=!0;let e=await na({encryption:{...u.encryption}}),t=new s.webpack.sources.RawSource(e,!1);n.getAsset(no)?n.updateAsset(no,t):n.emitAsset(no,t)}return p(),{buffer:m,debugInfo:h}}let{buffer:d,lepus_debug:c}=await (r??=new h({filename:new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+kit@0.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.11.3_@lynx-js_e448f1bf1172a453640970b92f024ac6/node_modules/@byted-doubao-apps/kit/dist/builder/plugins/bundle-template-rspeedy-plugin/encode-worker.js"),f.b).href,maxThreads:(0,rA.availableParallelism)()})).run({encodeOptions:o});return p(),{buffer:Buffer.from(d),debugInfo:c}})}),s.hooks.failed.tap(np.name,e=>{tT.error("Failed to bundle template",{error:e})})}}}class nd{static _instance;listeners=[];stdinListener;nextIndex=0;static get instance(){return nd._instance??=new nd}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 nc(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e}function nu(e){nd.instance.stop(),e().catch(nc).finally(()=>nd.instance.start())}let nm=ev.child("simulator"),nh=f("node:http"),nf={"Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless"},ng=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),ny=new Set([...ng,"cookie","host","origin","referer"]),nb=/authorization|cookie|token|secret|password|credential|private[-_]?key|(?:^|[-_])api[-_]?key(?:$|[-_])|(?:^|[-_])dek(?:$|[-_])/i,n_="X-DBX-Sandbox-Session-ID",nw="x-tt-logid";function nv(e){try{return new URL(e.url??"/","http://localhost")}catch{return}}function nE(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 nS(e,t,r={}){let n={};for(let[t,r]of Object.entries(e))void 0===r||ny.has(t.toLowerCase())||(n[t]=r);return{...n,...r,host:t.host}}function nx(e,t=[]){let r={};for(let[t,n]of Object.entries(e))void 0===n||ng.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 nA(e,t=[]){let r=nx(Object.fromEntries(e),t);return delete r["content-encoding"],delete r["content-length"],r}function nT(e,t={}){Object.entries({...nf,...t}).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})}function nC(e,t,r,n){nT(e,n),e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(r)}function nO(e,t,r,n){let i=JSON.stringify(r);nT(e,n),e.writeHead(t,{"Content-Length":Buffer.byteLength(i),"Content-Type":"application/json; charset=utf-8"}),e.end(i)}function nI(e,t,r){return new Promise((n,i)=>{let o=[],a=0,s=!1;e.on("data",n=>{if(s)return;let l=Uint8Array.from(Buffer.isBuffer(n)?n:Buffer.from(n));if((a+=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}o.push(l)}),e.once("end",()=>{if(s)return;s=!0;let e=new Uint8Array(a),t=0;for(let r of o)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 nP(e,t,r){return nI(e,t,r).then(e=>Buffer.from(e).toString("utf8"))}function nk(e){return e.arrayBuffer().then(e=>Buffer.from(e))}function nD(e){return Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r=nb.test(e)?"[REDACTED]":Array.isArray(t)?t.join(", "):t;return` ${e}: ${r}`}).join("\n")}function n$(e){return("string"==typeof e||void 0===e?e:e.toString("utf8"))||"(no content)"}function nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){"applet0930"===process.env.DEBUG&&nm.info(`${e} ${a.pathname}${a.search} ${(o>=500?ep.red:o>=400?ep.yellow:ep.green)(String(o))}
151
151
  Request headers:
152
152
  ${nD(r)}
153
153
  Request body: ${n$(t)}
@@ -160,9 +160,9 @@ Response body: ${n$(n)}`)}function nR(e,t,r){let n,i=("https:"===r.targetUrl.pro
160
160
 
161
161
  `)}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 nj(nU(t.command.type)?"RENDER_TIMEOUT":"COMMAND_TIMEOUT","Debugger control command timed out")),this.flushClient(e)}},nW(t.command));try{e.response.write(`data: ${JSON.stringify(t.command)}
162
162
 
163
- `)}catch{t.timeout&&clearTimeout(t.timeout),e.activeJob=void 0,t.reject(new nj("DEBUGGER_DISCONNECTED","Debugger control connection was closed")),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);let n=new nj("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.response.writableEnded&&e.response.end()}}async function nV({request:e,response:t},r){let n;if("POST"!==e.method)return void nO(t,405,{error:"Method not allowed"});try{n=JSON.parse(await nP(e,t,0xa00000))}catch(e){nO(t,400,{error:e.message});return}r.handleResult(n)?nO(t,200,{ok:!0}):nO(t,404,{error:"Pending debugger command not found"})}let nG=["page","widget","app"],nq=["log","info","warn","error","debug","eval"],nJ=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function nK(e,t){let r=t.pageIdx??0,n=t.pageSize??50,i=r*n,o=e.slice(i,i+n);return{pageIdx:r,pageSize:n,total:e.length,hasMore:i+o.length<e.length,items:o}}function nz(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 nY(e){return e.value??e.unserializableValue??e.description??e.type??""}function nX(e,t){var r,n;let i;return(r=e,"all"===(n=t)?nG:"page"===n||"widget"===n||"app"===n?[n]:(i=r.context,i?.page_id||i?.page_path?["page","app"]:i?.widget_id?["widget"]:nG)).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 o,a,s,l;return i=n.updatedAtMs,o=e.url??e.location?.url,a=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(nY).filter(Boolean).join(" "),...o?{url:o}:{},...void 0===a?{}:{lineNumber:a},...void 0===s?{}:{columnNumber:s},...void 0===i?{}:{updatedAtMs:i},entry:e}})})}function nZ(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 nQ(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 n0={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},n1={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},n3={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function n2(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 n4(e,t={}){try{return await e()}catch(e){return function(e,t={}){let r=e instanceof nj?e:new nj("INSPECTION_FAILED",String(e));return n2({...t,error:{code:r.code,message:r.message}},{isError:!0})}(e,t)}}function n5(e,t,r,n){let i=D(r.inputSchema);e.registerTool(t,{...r,inputSchema:i},n)}let n9="/__wsd_mcp";async function n8({request:e,response:t},r,n){if("OPTIONS"===e.method){nT(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void nC(t,405,"Method not allowed");let i=$(()=>{let e,t;return e=new z({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let n=nz(r);if(!n.stored)return n2(n);let i=nK((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,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 n2({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:i.total,pageIdx:i.pageIdx,pageSize:i.pageSize,hasMore:i.hasMore,events:i.items})},n5(e,"list_console_messages",{annotations:n0,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:ei(A(nq)).optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:X().optional(),target:A(["current","page","widget","app","all"]).optional()}},async e=>{let t=nz(r);if(!t.stored)return n2(t);let n=nK(nX(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 n2({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)})}),n5(e,"get_console_message",{annotations:n0,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:X()}},async e=>{let t=nz(r);if(!t.stored)return n2(t);let n=nX(t.snapshot,"all").find(t=>t.msgid===e.msgid);return n2({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!n,...n?{message:n}:{msgid:e.msgid}})}),n5(e,"get_log_snapshot",{annotations:n0,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=nz(r);return e.stored?n2({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):n2(e)}),n5(e,"list_render_targets",{annotations:n0,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 i,o=nz(r);return o.stored?n2({stored:!0,storedAt:o.storedAt,updatedAtMs:o.updatedAtMs,...(t=o.snapshot,n=e.type??"all",i=t.render_targets??{},{pages:"widget"===n?[]:(i.pages??[]).map(e=>nQ(e,"page")).filter(Boolean),widgets:"page"===n?[]:(i.widgets??[]).map(e=>nQ(e,"widget")).filter(Boolean),...i.currentTarget?{currentTarget:i.currentTarget}:{}})}):n2(o)}),n5(e,"take_snapshot",{annotations:n0,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:A(["current","page","widget"]).optional(),verbose:R().optional()}},e=>n4(async()=>{let t=function(e,t){var r,n;let i,o,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=(r=s.root,n=!0===t.verbose,i=[],o=0,(a=(e,t)=>{var r,s;let{name:l,uid:p}=e;if(!p||!l)return;o+=1;let d=" ".repeat(t);if("text"===e.type)return void i.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&&(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||nJ.has(e.name)||e.name.startsWith("aria-")))))u.push((r=t.name,(s=t.value)?`${r}=${JSON.stringify(s)}`:r));for(let r of(p===c&&u.push("[selected]"),i.push(`${d}${u.join(" ")}`),e.children??[]))a(r,t+1)})(r,0),{actualNodeCount:o,text:i.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 n.execute("take_snapshot",{target:e.target??"current"})).runtimeSnapshot},e),i=nz(r),o={stored:i.stored,...i.stored?{storedAt:i.storedAt,updatedAtMs:i.updatedAtMs}:{},...t};return n2(o,{text:t.available?t.snapshot:JSON.stringify(o,null,2)})},{available:!1,stored:!1})),n5(e,"get_computed_style",{annotations:n0,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:ei(X().min(1)).max(100).optional(),uid:X().min(1)}},({properties:e,uid:t})=>n4(async()=>n2(await n.execute("get_computed_style",{uid:t,...e?{properties:e}:{}})))),n5(e,"get_element_rect",{annotations:n0,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:X().min(1)}},({uid:e})=>n4(async()=>n2(await n.execute("get_element_rect",{uid:e})))),n5(e,"take_screenshot",{annotations:n0,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:A(["png","jpeg","webp"]).optional(),quality:T().min(0).max(100).optional(),uid:X().min(1).optional()}},({format:e="png",quality:t,uid:r})=>n4(async()=>{let i=await n.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...r?{uid:r}:{}}),{data:o,...a}=i;return n2({captured:!0,...a},{image:{data:o,mimeType:i.mimeType}})},{captured:!1})),n5(e,"scroll_to",{annotations:n3,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:X().min(1).optional(),x:T().min(0).optional(),y:T().min(0).optional()}},({uid:e,x:t,y:r})=>n4(async()=>n2({scrolled:!0,...await n.execute("scroll_to",{uid:e,x:t,y:r})}),{scrolled:!1})),n5(e,"set_viewport",{annotations:n3,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:T().int().min(1).max(9999),width:T().int().min(1).max(9999)}},({height:e,width:t})=>n4(async()=>n2({updated:!0,viewport:await n.execute("set_viewport",{height:e,width:t})}),{updated:!1})),n5(e,"render_page",{annotations:n1,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:X().min(1)}},({url:e})=>n4(async()=>n2({rendered:!0,target:(await n.execute("render_page",{url:e})).target}),{rendered:!1})),n5(e,"render_widget",{annotations:n1,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:B(X(),C()).optional(),widgetId:X().min(1)}},({structuredContent:e,widgetId:t})=>n4(async()=>n2({rendered:!0,target:(await n.execute("render_widget",{structuredContent:e??{},widgetId:t})).target}),{rendered:!1})),n5(e,"submit_chat_query",{annotations:n1,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:X().trim().min(1)}},({query:e})=>n4(async()=>n2({submitted:!0,...await n.execute("submit_chat_query",{query:e})}),{submitted:!1})),n5(e,"list_agent_trace_events",{annotations:n0,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:ei(X()).optional(),event:X().optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),requestId:X().optional()}},t),n5(e,"list_agent_tool_calls",{annotations:n0,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:X().optional(),requestId:X().optional(),status:ei(X()).optional(),toolName:X().optional()}},async e=>{var t;let n=nz(r);if(!n.stored)return n2(n);let i=nK((t=n.snapshot,(t.simulator?.tool_calls??[]).map(nZ)).filter(t=>{let r,n,i,o;return r=e.requestId?.trim(),n=e.toolName?.trim(),i=e.status??[],o=e.query?.trim().toLowerCase(),(!r||t.requestId===r)&&(!n||t.toolName===n)&&(!(i.length>0)||!!i.includes(t.status))&&(!o||[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(o)))}),e);return n2({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:i.total,pageIdx:i.pageIdx,pageSize:i.pageSize,hasMore:i.hasMore,toolCalls:i.items})}),e},{legacy:"stateless",responseMode:"json"}),o=en(i);try{await o(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):nC(t,500,e instanceof Error?e.message:String(e))}finally{await i.close().catch(()=>void 0)}}let n6="/__web_sdk_debug_scenes",n7="/__web_sdk_widget_view_data_templates",ie={"Cache-Control":"no-cache"};async function it(e,t){try{let r=await t?.()??{templatesByEntry:{},templatesByWidget:{}};nO(e,200,r,ie)}catch(t){nm.error("加载 Widget viewData 模板失败",{error:t}),nO(e,500,{templatesByEntry:{},templatesByWidget:{}},ie)}}let ir=f("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),ii={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},io={"http:":"80","https:":"443"},ia=new Map;function is(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function il(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function ip(e,t={}){let r=function(e){var t,r;let n="string"==typeof e?new URL(e):e;if(function(e){let t=iu(["NO_PROXY","no_proxy"]);if(!t)return!1;let r=im(e.hostname),n=e.port||io[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:im(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:im(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)?iu(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?iu(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!i)return;let o=(r=i,/^[a-z][a-z\d+.-]*:\/\//i.test(r)?r:`http://${r}`),a=ia.get(o);return a||(a=new ir.kT(o),ia.set(o,a)),a}(e),n=r?{...t,dispatcher:r}:t;return await fetch(e,n)}async function id({internal:e,domainId:t,path:r,query:n,method:i="GET",body:o,headers:a,signal:s,auth:l=!0}){let p={method:i,body:o,headers:{...is(),...a}};s&&(p.signal=s);let d=function({internal:e,domainId:t,path:r,query:n}){let i=r.startsWith("/")?r:`/${r}`,o=new URLSearchParams;for(let[e,t]of Object.entries(n||{}))null!=t&&o.append(e,t.toString());let a=o.toString(),s=a?`${i.includes("?")?"&":"?"}${a}`:"",l=il(i)?es:t?ii[t]:e?ii["sso-internal"]:ii["sms-external"];return`https://${l}${i}${s}`}({internal:e,domainId:t,path:r,query:n}),c=new Headers(p.headers),u=c.has("Cookie");if(!l||!il(r)||c.has("Authorization")||c.has("X-Developer-Open-Build-Token"))return await ip(d,p);let m=new URL(d).origin,h=L(ip,{baseUrl:m,allowedOrigins:[m]});try{return await h(d,p)}catch(e){if(!(e instanceof H||e instanceof O))throw e;if(u)return await ip(d,p);throw Error(e instanceof O?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function ic(e){let t=await id(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 iu(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function im(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let ih="/__mcp_proxy",ig={"Cache-Control":"no-cache"};async function iy({request:e,response:t,url:r},n,i){var o;let a,s;if("OPTIONS"===e.method){nT(t,ig),t.writeHead(204),t.end();return}if("GET"===e.method){let e;return void nO(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,null!=(e=r.searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase())??{stored:!1},ig)}if("POST"!==e.method)return void nO(t,405,{error:"Method not allowed"},ig);try{a=JSON.parse(await nP(e,t,0xa00000))}catch(e){nO(t,400,{error:e.message},ig);return}a=function(e,t){let r=e?.snapshot,n=t.snapshot,i=r?.runtime_snapshot,o=n.runtime_snapshot;if(!r||!i||r.client_id!==n.client_id)return t;if(!o){var a;let e;if(a=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),a&&e&&(1===Object.keys(e).length?e.type!==a.type:JSON.stringify(e)!==JSON.stringify(a)))return t;let{root:r,...o}=i;return{...t,snapshot:{...n,runtime_snapshot:i},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:o}}:{}}}return Object.hasOwn(o,"root")||!Object.hasOwn(i,"root")||i.updatedAtMs!==o.updatedAtMs||JSON.stringify(i.target)!==JSON.stringify(o.target)?t:{...t,snapshot:{...n,runtime_snapshot:{...o,root:i.root}}}}(n.snapshot,a),n.snapshot=a,n.updatedAtMs=Date.now(),i.noteSnapshot("string"==typeof(s=(o=a).snapshot.client_id??o.debug_snapshot?.client_id)&&s.trim()?s.trim():void 0),nO(t,200,{ok:!0,updated_at_ms:n.updatedAtMs},ig)}let ib=f("node:crypto"),i_="/__dbx_real_device_debug",iw=`${i_}/state`,iv=`${i_}/start`,iE=`${i_}/cancel`,iS=`${i_}/qr`;class ix{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:iw,startEndpoint:iv,cancelEndpoint:iE,qrEndpoint:iS,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?ib.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(i_),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===iw||r.pathname===iv){if(Object.keys(i).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=r.pathname===iw?await n.getState():await n.start();nO(t,200,e);return}if(r.pathname===iE){let e=i.operationId;if("string"!=typeof e||!e||1!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");nO(t,200,await n.cancel(e));return}if(r.pathname===iS){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 o=await n.getQrImage(e,r);if(!o)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");nT(t),t.writeHead(200,{"Content-Length":o.body.byteLength,"Content-Type":o.contentType}),t.end(o.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,o,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||(r=s,n=this.accessToken,o=(i=new TextEncoder).encode(r),a=i.encode(n),!(o.length===a.length&&ib.timingSafeEqual(o,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 r,n;try{r=await nP(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||nO(e,t,{error:{code:r,message:n}})}}let iA="/app_developer/api/sandbox/",iT=`${iA}session/business_info/update`,iC=new Set([`${iA}resources/notices/pull`,`${iA}resources/tasks/pull`]),iO={"Access-Control-Expose-Headers":nw},iI=new Set;function iP(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return!1;let a=`${i[n_]??""} ${e} ${t.pathname}`,s=iC.has(t.pathname);if(s&&r>=500){if(iI.has(a))return!1;iI.add(a)}else s&&r<500&&iI.delete(a);let l=Number(process.hrtime.bigint()-n)/1e6;return nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:l,headers:i,logId:o}),!0}function ik({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}function iD(e,t,r){return r&&!(iC.has(e.pathname)&&t>=500)}function i$(e,t){if(e.pathname!==iT||!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 iN({method:e,request:t,requestBody:r,requestHeaders:n,response:i,targetUrl:o,usePlatformFetch:a}){let s=new AbortController,l=process.hrtime.bigint(),p=()=>s.abort();t.once("aborted",p),i.once("close",()=>{i.writableEnded||p()});try{let t,p=a?await id({internal:!0,path:`${o.pathname}${o.search}`,method:e,body:r,headers:n,signal:s.signal}):await fetch(o,{body:"GET"===e||"HEAD"===e?void 0:r,headers:n,method:e,signal:s.signal}),d=iP(e,o,p.status,l,n,p.headers.get(nw)??void 0);if(i.destroyed||i.writableEnded)return void p.body?.cancel().catch(()=>void 0);let c=await nk(p);return iD(o,p.status,d)&&ik({method:e,requestBody:i$(o,r),requestHeaders:n,responseBody:c,responseHeaders:p.headers,statusCode:p.status,targetUrl:o}),i.destroyed||i.writableEnded||(t=nA(p.headers,[nw]),nT(i,iO),i.writeHead(p.status,t),i.end(c)),{body:c,ok:p.ok}}catch(p){if(i.destroyed||i.writableEnded||s.signal.aborted)return;let t=`Failed to proxy sandbox request: ${p instanceof Error?p.message:String(p)}`,a=iP(e,o,502,l,n);iD(o,502,a)&&ik({method:e,requestBody:i$(o,r),requestHeaders:n,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:o}),nC(i,502,t,iO)}}async function iR(e,t,r={}){let n;if("POST"!==e.method)return void nC(t,405,"Method not allowed",iO);try{n=JSON.parse(await nP(e,t,0xa00000))}catch(e){nC(t,400,`Invalid sandbox proxy payload: ${e.message}`,iO);return}let i=function(e,t){if(!e.url)return;let r=new URL(e.url,t);if(!r.pathname.startsWith(iA))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 nC(t,404,"Sandbox endpoint not found",iO);if(!r.sandboxSessionId)return void nO(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},iO);let o=function(e,t,r,n){if(t.pathname.startsWith(`${iA}session/`)&&t.pathname!==`${iA}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(`${iA}jsb/`)&&"app_key"in i&&(i.app_key=r),t.pathname===`${iA}passport/open/auth`&&"client_key"in i&&(i.client_key=r),JSON.stringify(i)}(n,i,r.sandboxAppId,r.sandboxSessionId),a=n.method||"POST",s=function(e,t,r,n,i){let o=Object.fromEntries(Object.entries(nS({...e.headers,...r,...void 0===n?{}:{"content-length":String(Buffer.byteLength(n))},"content-type":"application/json"},t,{...is(),...i?{[n_]: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(o))"accept-encoding"===e.toLowerCase()&&delete o[e];return o["accept-encoding"]="identity",o}(e,i,n.headers,o,r.sandboxSessionId),l=await iN({method:a,request:e,requestBody:o,requestHeaders:s,response:t,targetUrl:i,usePlatformFetch:!r.targetOrigin});if(i.pathname===iT&&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 iL=f("node:util"),iM="/app_developer/api/sandbox/bridge/events",ij="/app_developer/api/sandbox/bridge/response",iU=new Set(["connection","content-length","host"]),iB=new Set(["heartbeat"]),iF=[500,1e3,2e3,5e3],iW=0;function iH(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function iV(e,t=new Headers,r=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:r}}async function iG(e){let t,r,n=e.request_id||"";if(!n)return iV({error_message:"bridge request_id is required",http_status:0,request_id:n,success:!1});if(!e.path?.startsWith("/"))return iV({error_message:`invalid bridge request path: ${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 iV({error_message:`invalid bridge request origin: ${e.origin??""}`,http_status:0,request_id:n,success:!1});let o=(e.method||"GET").toUpperCase(),a=function(e){let t={};for(let[r,n]of Object.entries(e??{}))!r||iU.has(r.toLowerCase())||(t[r]=n);return t}(e.headers),s="GET"===o||"HEAD"===o?void 0:e.body??"",l=new AbortController,p=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 d;let e=await fetch(i,{body:s,headers:a,method:o,redirect:"manual",signal:l.signal}),t=await e.text();return d={method:o,requestBody:s,requestHeaders:a,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:i},nN(d),iV({body:t,http_status:e.status,request_id:n,success:!0},e.headers,e.statusText)}catch(e){return nN({method:o,requestBody:s,requestHeaders:a,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:i}),iV({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:n,success:!1})}finally{clearTimeout(p)}}function iq(e,t=new Set){if(Array.isArray(e)){for(let r of e)iq(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}iq(n,t)}return[...t]}function iJ(e,t){e.onLog?.(t)}function iK(e){try{return JSON.parse(e)}catch{return}}function iz({detail:e,requestHeaders:t,status:r,targetUrl:n}){if("applet0930"===process.env.DEBUG){if("number"==typeof r)return void nm.request({method:"CONNECT",url:n.pathname,statusCode:r,headers:t,context:{detail:e}});nm.info("Bridge connection pending",{url:n.pathname,detail:e,ppe:e_(t)})}}function iY(e,t={}){"applet0930"===process.env.DEBUG&&nm.info(e,t)}async function iX(e,t){let r=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),n={"content-type":"application/json",[n_]:e.sandboxSessionId,...is()};if(e.targetOrigin){let t=new URL(ij,e.targetOrigin),i=await fetch(t,{body:r,headers:n,method:"POST"}),o=await i.text();if(nN({method:"POST",requestBody:r,requestHeaders:n,responseBody:o,responseHeaders:i.headers,statusCode:i.status,targetUrl:t}),!i.ok)throw Error(`upload bridge response failed: ${i.status} ${o}`);return{responseBody:o,responseHeaders:Object.fromEntries(i.headers),responsePayload:iK(o)}}let i=new URL(ij,ee),o=await id({body:r,headers:n,internal:!0,method:"POST",path:ij}),a=await o.text();if(nN({method:"POST",requestBody:r,requestHeaders:n,responseBody:a,responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),!o.ok)throw Error(`upload bridge response failed: ${o.status} ${a}`);return{responseBody:a,responseHeaders:Object.fromEntries(o.headers),responsePayload:iK(a)}}async function iZ(e,t){let r;try{r=JSON.parse(t)}catch(e){nm.warn("Sandbox Bridge request parse failed",{reason:e.message});return}let n=Date.now(),i=`bridge-${n}-${++iW}`,o=r.request_id||"",a={id:i,request:r,requestId:o,sandboxSessionId:e.sandboxSessionId,timestamp:n};iJ(e,{...a,logIds:iq(r),status:"pending",updatedAtMs:n});let s=await iG(r),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await iX(e,s.response);iJ(e,{...a,logIds:iq([r,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw iJ(e,{...a,errorMessage:t instanceof Error?t.message:String(t),logIds:iq([r,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function iQ(e,t,r){let n={sandbox_session_id:e.sandboxSessionId},i=new URL(`${iM}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,ee),o=(d=e.sandboxSessionId,{accept:"text/event-stream",host:i.host,[n_]:d,...is()});iz({detail:`host=${o.host} session=${iH(e.sandboxSessionId)}`,requestHeaders:o,status:"pending",targetUrl:i}),iY("bridge/events request",{headers:{accept:o.accept,host:o.host,[n_]:iH(e.sandboxSessionId),"x-tt-env":o["x-tt-env"],"x-use-ppe":o["x-use-ppe"]},path:iM,query:n});let a=await id({headers:o,internal:!0,method:"GET",path:iM,query:n,signal:t});if(iz({detail:`content-type=${a.headers.get("content-type")??""}`,requestHeaders:o,status:a.status,targetUrl:i}),!a.ok||!a.body){let e=await a.text().catch(()=>"");nN({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:e,responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),nm.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}nN({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:"",responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),r?.();let s=a.body.getReader(),l=new iL.TextDecoder,p="";for(;!t.aborted;){let{done:t,value:r}=await s.read();if(t){iY("bridge/events stream ended",{session:iH(e.sandboxSessionId)});break}let n=(p+=l.decode(r,{stream:!0})).search(/\r?\n\r?\n/);for(;n>=0;){let t=p.slice(0,n),r=p.slice(n).match(/^\r?\n\r?\n/);p=p.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("applet0930"!==process.env.DEBUG||iB.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);nm.info("Bridge event received",{event:e.name,requestId:r,ppe:e_(t)}),nm.info(`Event detail
164
- ${e.data}`)}(s,o),"bridge_request"===s.name){var d,c=a.headers,u=a.status;nN({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:o,responseBody:"",responseHeaders:c,statusCode:u,targetUrl:i}),iZ(e,s.data).catch(e=>{nm.warn("Sandbox Bridge request failed",{reason:e.message})})}else if("TOOL_CALL"===s.name){let t=V(iK(s.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{nm.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})}):nm.warn("Sandbox tool call event parse failed")}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=iK(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,o=r?.resource_id,a=r?.revision;if(("notice"===n||"task"===n)&&("upsert"===i||"remove"===i)&&"string"==typeof o&&o&&("number"==typeof a||"string"==typeof a))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:o,revision:a}}(s.data);t?e.onResourceChanged?.(t):nm.warn("Sandbox resource event parse failed")}else if("card_delta"===s.name){let t=function(e){let t=iK(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"}):nm.warn("Sandbox simulator event parse failed",{event:s.name})}else if("get_simulator_card_snapshots"===s.name){let t=iK(s.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:s.name}):nm.warn("Sandbox simulator event parse failed",{event:s.name})}n=p.search(/\r?\n\r?\n/)}}}async function i0(e,t){let r=0,n=!1;for(;!t.aborted;){try{await iQ(e,t,()=>{n=!1,e.onConnectionStatusChange?.("connected")}),r=0}catch(r){if(t.aborted)return;let e=r.status;if(n||(nm.warn("无法接收来自平台服务的请求",{reason:r.message}),n=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,v.setTimeout)(iF[Math.min(r,iF.length-1)],void 0,{signal:t}).catch(()=>void 0),r+=1}}let i1=f("node:net"),i3="/__web_sdk_sandbox_bridge_logs",i2="/__web_sdk_sandbox_resource_events",i4="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",i5="/app_developer/api/sandbox/session/business_info/update";function i9(e){if(!e)return!1;try{return tr.statSync(e).isFile()}catch{return!1}}async function i8({body:e,headers:t,method:r,sandboxPath:n,targetOrigin:i,targetUrl:o}){let a=new AbortController,s=setTimeout(()=>a.abort(),3e4);try{return i?await fetch(o,{body:e,headers:t,method:r,signal:a.signal}):await id({internal:!0,path:n,body:e,headers:t,method:r,signal:a.signal})}catch(e){if(a.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${o}`);throw e}finally{clearTimeout(s)}}function i6(e,t){return(e?.[t]??process.env[t])?.trim()??""}function i7(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}function oe({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}async function ot(e,t,r,n,i,o){let a,s,l="/app_developer/api/sandbox/session/create",p="POST",d=function(){let e=new Set;for(let t of(process.env[i4]??"").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,i1.isIP)(n)&&n.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!i)throw Error("only loopback HTTP(S) origins are allowed");e.add(t.origin)}catch(e){throw Error(`${i4} contains an invalid origin: ${r} (${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),c=JSON.stringify({sandbox_project_id:e,manifest:r?.()??(i9(t)?tr.readFileSync(t,"utf8"):""),business_templates:i9(n)?tr.readFileSync(n,"utf8"):"",...o?{app_id:o}:{},...d.length>0?{bridge_origins:d}:{}}),u={"content-type":"application/json",...is()},m=new URL(l,i??ee),h=process.hrtime.bigint();try{a=await i8({body:c,headers:u,method:p,sandboxPath:l,targetOrigin:i,targetUrl:m})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw i7(p,m,502,h,u),oe({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(nw)||"",g=await a.text();i7(p,m,a.status,h,u,f),oe({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 or(e,t,r,n,i,o){try{return await ot(e,t,r,n,i,o)}catch(e){return nm.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function on(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function oi(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function oo(e,t){let r,n,i="/app_developer/api/sandbox/session/business_info/get",o="POST",a=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...is()},l=new URL(i,t??ee),p=process.hrtime.bigint();try{r=await i8({body:a,headers:s,method:o,sandboxPath:i,targetOrigin:t,targetUrl:l})}catch(e){throw i7(o,l,502,p,s),e}let d=r.headers.get(nw)||"",c=await r.text();i7(o,l,r.status,p,s,d);try{n=JSON.parse(c||"{}")}catch{throw oe({method:o,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({omitted:"invalid business info response"}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}let u={csrUploaded:!!n.data?.csr_pem?.trim(),phoneNumberUploaded:!!n.data?.phone_num?.trim()};if(oe({method:o,requestBody:a,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||d?`,log_id=${n.log_id||d}`:""}`);return u}async function oa(e,t){if(!e)return on();try{return await oo(e,t)}catch(e){return nm.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),on()}}async function os(e,t,r){let n,i,o="POST",a=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...is(),[n_]:t},l=new URL(i5,r??ee),p=process.hrtime.bigint();try{n=await i8({body:a,headers:s,method:o,sandboxPath:i5,targetOrigin:r,targetUrl:l})}catch(e){throw i7(o,l,502,p,s),e}let d=n.headers.get(nw)||"",c=await n.text();i7(o,l,n.status,p,s,d),oe({method:o,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:c,responseHeaders:n.headers,statusCode:n.status,targetUrl:l});try{i=JSON.parse(c||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}if(!n.ok||void 0!==i.code&&0!==i.code)throw Error(`更新 Sandbox session 信息失败:${i.message||n.statusText||n.status}${i.log_id||d?`,log_id=${i.log_id||d}`:""}`)}async function ol(e,t,r,n){if(e&&t.phoneNum&&(!r||t.csrPem))try{return await os({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,n),nm.info("Sandbox business info 已自动上传",{sessionId:e}),oi(t.csrPem)}catch(e){nm.warn(`Sandbox business info 自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function op(e,t){let r,n="/app_developer/api/sandbox/session/revoke",i="POST",o=JSON.stringify({sandbox_session_id:e}),a={"content-type":"application/json",...is()},s=new URL(n,t??ee),l=process.hrtime.bigint();try{r=await i8({body:o,headers:a,method:i,sandboxPath:n,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw i7(i,s,502,l,a),oe({method:i,requestBody:o,requestHeaders:a,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let p=r.headers.get(nw)||"",d=await r.text();i7(i,s,r.status,l,a,p),oe({method:i,requestBody:o,requestHeaders:a,responseBody:d,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});let c=JSON.parse(d||"{}");if(!r.ok||0!==c.code)throw Error(`撤回 Sandbox session 失败:${c.message||r.statusText||r.status}${c.log_id||p?`,log_id=${c.log_id||p}`:""}`)}async function od(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let r=e.sandboxSessionId;r&&await op(r,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let n=await ot(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),i=n.sessionId,o=!e.sandboxSessionAppId,a=await ol(i,e.businessInfoInput,o,e.sandboxTargetOrigin)??await oa(i,e.sandboxTargetOrigin);return e.sandboxAppId=n.appId,e.sandboxSessionId=i,e.businessInfo=a,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,oc(t),e.bridge=ou(e,i),nm.info("Sandbox session 已重建",{sessionId:i}),{...n,businessInfoUploaded:a.phoneNumberUploaded&&(!o||a.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function oc(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1)}function ou(e,t){var r={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,oc(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)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),oc(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),oc(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!r.sandboxSessionId)return void nm.warn("Sandbox Bridge skipped: missing sandbox session id");let n=new AbortController;return iY("start sandbox bridge",{session:iH(r.sandboxSessionId)}),r.onConnectionStatusChange?.("connecting"),i0(r,n.signal),{close:()=>n.abort()}}async function om(e,t,r){if("POST"!==e.method)return void nC(t,405,"Method not allowed");if(!r)return void nC(t,503,"Sandbox session is not initialized");try{let n=await nP(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 nC(t,400,"Invalid Sandbox business info");r.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let i=await od(r);nO(t,200,{code:0,data:{sandbox_appid:i.appId,business_info_uploaded:i.businessInfoUploaded,sandbox_session_id:i.sessionId},message:"ok"})}catch(e){nC(t,500,e.message)}}function oh(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=tr.realpathSync.native(t)}catch{}return(0,ib.createHash)("sha256").update(r).digest("hex")}(e.appDirectory),i=function(e,t){let r=i6(e,"DOUBAO_SANDBOX_PHONE_NUM"),n=i6(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 i9(r)?r:void 0}(n,t),o="";if(n&&!i)nm.warn(`Sandbox CSR 文件不存在:${n}`);else if(i)try{o=tr.readFileSync(i,"utf8").trim()}catch(e){nm.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...r?{phoneNum:r}:{},...o?{csrPem:o}:{}}}(e.env,e.appDirectory),o=`${i.phoneNum??""}\0${i.csrPem??""}`;return{businessInfoInput:i,businessInfoInputKey:o,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([o,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 of{configKey;manifestReader;state;constructor(e,t,r){this.state=e,this.configKey=t,this.manifestReader=r}static async start(e){let t=oh(e),r=await or(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),n=!t.sessionAppId,i={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await ol(r.sessionId,t.businessInfoInput,n,t.targetOrigin)??await oa(r.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,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},o=new of(i,t.key,t.manifestReader);return i.bridge=r.sessionId?ou(i,r.sessionId):void 0,o}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close()}matches(e){let t=oh(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,ib.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:i3,sandboxResourceEventsEndpoint:i2,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(){return[{match:i3,handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method&&"DELETE"!==e.method?nC(t,405,"Method not allowed"):("DELETE"===e.method&&r&&(r.bridgeLogs.length=0,r.bridgeLogsUpdatedAtMs=Math.max(Date.now(),r.bridgeLogsUpdatedAtMs+1)),nO(t,200,{logs:r?.bridgeLogs??[],updatedAtMs:r?.bridgeLogsUpdatedAtMs??0},{"Cache-Control":"no-cache"})))}},{match:i2,handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method?nC(t,405,"Method not allowed"):nO(t,200,{connectionStatus:r?.resourceConnectionStatus??"connecting",events:r?.resourceEvents??[],generation:r?.resourceGeneration??0,simulatorEvents:r?.simulatorEvents??[],updatedAtMs:r?.resourceEventsUpdatedAtMs??0},{"Cache-Control":"no-cache"}))}},{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>iR(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=oi(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})=>om(e,t,this.state)}]}}let og=f("node:stream"),oy="/app_developer/api",ob=`${oy}/simulator/images/upload`,o_=new Set([`${oy}/simulator/chat`,ob,`${oy}/simulator/tool/report`]),ow={"Access-Control-Expose-Headers":nw};async function ov(e,t,r,n){if(!o_.has(r.pathname))return void nC(t,404,"未找到模拟器接口",ow);let i=n.targetOrigin??ee,o=new URL(`${r.pathname}${r.search}`,i),a=new AbortController,s=()=>a.abort();e.once("aborted",s),t.once("close",()=>{t.writableEnded||s()});try{var l;let i=e.method??"GET",s=process.hrtime.bigint(),p=function(e,t,r){return Object.fromEntries(Object.entries(nS(e.headers,t,{...is(),...r?{[n_]:r}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,o,n.getSandboxSessionId?.()),d=await oE(e,t,r,i),c=n.targetOrigin?await fetch(o,{body:d,headers:p,method:i,signal:a.signal}):await id({internal:!0,path:`${r.pathname}${r.search}`,method:i,body:d,headers:p,signal:a.signal});if(function(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}(i,r,c.status,s,p,c.headers.get(nw)??void 0),t.destroyed||t.writableEnded)return void c.body?.cancel().catch(()=>void 0);await oS({method:i,requestBody:(l=d)instanceof Uint8Array?`(binary, ${l.byteLength} bytes)`:l,requestHeaders:p,requestUrl:r,response:t,upstreamResponse:c})}catch(e){if(t.destroyed||t.writableEnded||a.signal.aborted)return;nC(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,ow)}}async function oE(e,t,r,n){if("GET"!==n&&"HEAD"!==n)return r.pathname===ob?await nI(e,t,0xb00000):await nP(e,t,0xb00000)}async function oS({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){var a,s;if(nT(i,ow),i.writeHead(o.status,nA(o.headers,[nw])),a=n,s=o,a.pathname===`${oy}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await ox({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o});if("applet0930"!==process.env.DEBUG)return o.body?void await (0,g.pipeline)(og.Readable.fromWeb(o.body),i):void i.end();let l=await nk(o);nN({method:e,requestBody:t,requestHeaders:r,responseBody:l,responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end(l)}async function ox({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){if(!o.body){nN({method:e,requestBody:t,requestHeaders:r,responseBody:"",responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end();return}let a=og.Readable.fromWeb(o.body);if("applet0930"!==process.env.DEBUG)return void await (0,g.pipeline)(a,i);nN({method:e,requestBody:t,requestHeaders:r,responseBody:"(event stream)",responseHeaders:o.headers,statusCode:o.status,targetUrl:n});let s=new og.Transform({transform(e,t,r){let i;try{i=String(e).split("\n\n").filter(Boolean)}catch(t){return nm.error(`failed to decode event stream chunk: ${t?.toString()}`),r(null,e)}for(let e of i)nm.info(`Event from ${n.pathname}${n.search}
165
- ${e}`);r(null,e)}});await (0,g.pipeline)(a,s,i)}function oA(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let oT="/__tools/tools.json",oC="/__events/events.json",oO="manifest.yaml",oI="skill",oP=tn.join(".dbx","config.json");function ok(e){if(!e)return!1;try{return tr.statSync(e).isFile()}catch{return!1}}function oD(e,t){if(!e)return;let r=tn.isAbsolute(e)?e:tn.resolve(t??process.cwd(),e);return ok(r)?r:void 0}function o$(e,t){if(e&&t)return tn.relative(t,e).split(tn.sep).join("/")||"."}function oN(e){let t=tn.resolve(e);for(;;){let e;if(e=t,ok(tn.join(e,oP)))return t;let r=tn.dirname(t);if(r===t)break;t=r}}function oR(e){try{return tr.lstatSync(e),!0}catch{return!1}}function oL(e,t,r,n){let i;if(!t.reader&&ok(t.sourcePath)){var o;let r,i=tr.statSync(t.sourcePath);nT(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":n}),o=t.sourcePath,(r=tr.createReadStream(o)).once("error",()=>e.destroy()),r.pipe(e);return}try{i=t.reader?.()}catch{i=void 0}void 0===i?nC(e,404,`${r} not found`):(nT(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(i),"Content-Type":n}),e.end(i))}function oM(e,t){return function(e){let t,r;if(!e)return{layout:"missing",entries:[]};let n=tn.resolve(e);try{t=tr.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 tr.readdirSync(r,{withFileTypes:!0})){if(n.isSymbolicLink())continue;let o=tn.join(r,n.name);n.isDirectory()?t(o):n.isFile()&&"SKILL.md"===n.name&&e.push(function(e,t){let r=tn.relative(e,t).split(tn.sep).join("/");return{content:tr.readFileSync(t,"utf8"),relativePath:r}}(i,o))}}(i),r=e}catch(e){return{directory:n,layout:"invalid",entries:[],error:`skill directory is not readable: ${n}: ${e.message}`}}return r.sort(oA),r.length>0?{directory:n,layout:"resolved",entries:r}:{directory:n,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;let r=e?oN(e):void 0,n=(tn.isAbsolute(t)?[void 0]:[e,r,process.cwd()]).map(e=>tn.isAbsolute(t)?t:tn.resolve(e??process.cwd(),t));return[...new Set(n)].find(oR)??n[0]}if(!e)return;let r=oN(e);return[...new Set([r?tn.join(r,oI):void 0,tn.join(e,oI),tn.join(process.cwd(),oI)].filter(Boolean))].find(oR)}(e,t))}class oj{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?oD(e.manifestPath,e.appDirectory):function(e){if(!e)return;let t=oN(e);return[...new Set([t?tn.join(t,oO):void 0,tn.join(e,oO),tn.join(process.cwd(),oO)].filter(Boolean))].find(ok)}(e.appDirectory),this.businessTemplatesPath=(t=this.manifestPath,r=e.businessTemplatesPath,n=e.appDirectory,r?oD(r,n):t?oD(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=oM(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 oj(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=oM(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,r=o$(this.businessTemplatesPath,this.appDirectory),n=o$(this.eventsConfigSource.sourcePath,this.appDirectory),i=o$(this.toolsConfigSource.sourcePath,this.appDirectory),o=o$(this.manifestSource.sourcePath,this.appDirectory),a=o$(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:oC,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...n?{eventsConfigRelativePath:n}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:oT,...i?{toolsConfigRelativePath:i}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...o?{simulatorManifestRelativePath:o}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...r?{simulatorBusinessTemplatesRelativePath:r}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...a?{simulatorSkillsDirectoryRelativePath:a}:{}}:{}}}getRequestRoutes(){return[{match:oC,handle:({response:e})=>oL(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:oT,handle:({response:e})=>oL(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>oL(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=oM(this.appDirectory,this.skillsDirectory)).layout?nC(e,404,"Simulator skills directory not found"):"invalid"===t.layout?nC(e,422,t.error??"Invalid simulator Skill layout"):nO(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}async function oU(e,t){if("POST"!==e.method)return void nO(t,405,{message:"Method Not Allowed"});try{var r,n;let i,o,a,s=JSON.parse(await nP(e,t,0xa00000)),l=nE(s.url),p=(s.method??"GET").toUpperCase(),d=(r=s.header,o=new Headers(r??{"content-type":"application/json"}),["connection","content-length","host","origin","referer"].forEach(e=>o.delete(e)),o),c=await fetch(l,{body:"GET"!==p&&"HEAD"!==p?function(e,t){let r=e.data;if(null==r)return;if("base64"===e.dataEncoding&&"string"==typeof r){var n;let e;return e=new ArrayBuffer((n=Buffer.from(r,"base64")).byteLength),new Uint8Array(e).set(n),e}if("string"==typeof r)return r;let i=t.get("content-type")?.toLowerCase()??"";if(i.includes("application/x-www-form-urlencoded")&&"object"==typeof r){let e=new URLSearchParams;return Object.entries(r).forEach(([t,r])=>{e.set(t,String(r))}),e.toString()}return i.includes("application/json")||"object"==typeof r?JSON.stringify(r):String(r)}(s,d):void 0,headers:d,method:p}),u="arraybuffer"===s.dataType||"arraybuffer"===s.responseType;if(u)i=Buffer.from(await c.arrayBuffer()).toString("base64");else{let e=await c.text();i="string"===s.dataType||0===e.length?e:JSON.parse(e)}nO(t,200,{data:i,dataEncoding:u?"base64":void 0,header:(n=c.headers,a={},n.forEach((e,t)=>{a[t]=e}),a),statusCode:c.status})}catch(e){nO(t,500,{message:e instanceof Error?e.message:String(e)})}}let oB="/__webview",oF=`${oB}/client.js`,oW=`${oB}/page`,oH=`${oB}/runtime`,oV=`${oB}/sw.js`,oG="x-doubao-web-view-target",oq="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",oJ=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.1_f61de653352e1ffdfcf3cfbd2dcb3ac0/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),oK=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.11_@emnapi+core@1.11.3_@emnapi+runtime@1.1_f61de653352e1ffdfcf3cfbd2dcb3ac0/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function oz(e,t,r,n=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void nC(t,405,"Method Not Allowed");let i=tr.readFileSync(r,"utf8");nT(t),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)}async function oY(e,t,r){if("GET"!==e.method&&"HEAD"!==e.method)return void nC(t,405,"Method Not Allowed");try{let n=nE(r.searchParams.get("url")??void 0),i=await fetch(n,{headers:{"user-agent":oq,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),o=i.url?new URL(i.url):n,a=i.headers.get("content-type")??"",s=nx(Object.fromEntries(i.headers));if(s["cache-control"]="no-cache",delete s["content-encoding"],delete s["content-length"],"HEAD"===e.method||!a.includes("text/html")){let r="HEAD"===e.method?void 0:Buffer.from(await i.arrayBuffer());nT(t),t.writeHead(i.status,{...s,[oG]:o.toString(),...r?{"content-length":r.byteLength}:{}}),t.end(r);return}let l=function(e,t){let r=new URLSearchParams({mobileUserAgent:oq,originalPath:`${t.pathname}${t.search}${t.hash}`}).toString().replaceAll("&","&amp;"),n=`<script src="${oF}?${r}"></script>`,i=/<head[^>]*>/i.exec(e);if(i){let t=i.index+i[0].length;return`${e.slice(0,t)}${n}${e.slice(t)}`}return`${n}${e}`}(await i.text(),o);nT(t),t.writeHead(i.status,{...s,[oG]:o.toString(),"content-length":Buffer.byteLength(l)}),t.end(l)}catch(e){nC(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}let oX=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),oZ="/__web_artifacts",oQ="/wsd";function o0(e){return e.replace(/^\/web-sdk\/[^/]+(?=\/wsd(?:\/|$))/,"")}function o1(e,t,r,n,i={}){nT(t,i.headers),oX(e,n,{root:r}).once("error",n=>{if(404===n.statusCode&&i.fallbackPath)return void o1(e,t,r,i.fallbackPath,{headers:i.headers});if(t.headersSent)return void t.destroy(n);let o=n.statusCode??500;nC(t,o,nh.STATUS_CODES[o]??"Internal Server Error")}).pipe(t)}let o3=f("node:child_process");async function o2(e){let{command:t,args:r}="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};await new Promise((e,n)=>{let i=(0,o3.spawn)(t,r,{detached:!0,stdio:"ignore"});i.once("error",n),i.once("spawn",()=>{i.unref(),e()})})}async function o4(e,t,r=o2){let n,i=(n=new URL(e),t&&n.searchParams.set("mcp",ih),n.toString());try{await r(i)}catch(e){nm.error("打开 Web 模拟器失败",{error:e}),nm.info("请手动打开 Web 模拟器(本地)",{url:i})}return i}async function o5(e,t){await new Promise((r,n)=>{let i=t=>{e.off("listening",o),n(t)},o=()=>{e.off("error",i),r()};e.once("error",i),e.once("listening",o),e.listen(t,"127.0.0.1")})}async function o9(e){let t=await Y(9e3),r=nh.createServer(function({artifactOrigin:e,debugScenes:t,debuggerProtocol:r,distPath:n,getWidgetViewDataTemplates:i,mcpEndpoint:o,mcpHeaders:a,physicalDeviceDebugGateway:s,sandboxRuntime:l,simulatorAssets:p,simulatorTargetOrigin:d}){var c,u,m;let h={routes:[{match:e=>e.pathname.startsWith(oZ),handle:({request:t,response:r,url:n})=>{let i,o;return i=n.pathname.replace(oZ,"")||"/",o=new URL(`${i}${n.search}`,e),void nR(t,r,{createResponseHeaders:e=>({...nx(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nS(t.headers,o),targetUrl:o})}},{match:e=>{let t=o0(e.pathname);return t===oQ||t.startsWith(`${oQ}/`)},handle:({request:e,response:t,url:r})=>{let i;!(i=o0(r.pathname).slice(`${oQ}/`.length))||i!==tn.basename(i)?nC(t,404,"Not found"):o1(e,t,tn.join(n,"wsd"),i,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>oU(e,t)},{match:oV,handle:({request:e,response:t})=>oz(e,t,oK,!0)},{match:oF,handle:({request:e,response:t})=>oz(e,t,oJ)},{match:oH,handle:({request:e,response:t,url:r})=>(function(e,t,r){let n;try{n=nE(r.searchParams.get("url")??void 0)}catch(e){nC(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let i=nS(e.headers,n,{"user-agent":oq});for(let e of Object.keys(i))e.startsWith("sec-fetch-")&&delete i[e];nR(e,t,{createResponseHeaders:e=>{let t=nx(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=`${oH}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:i,targetUrl:n})})(e,t,r)},{match:oW,handle:({request:e,response:t,url:r})=>oY(e,t,r)},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:r})=>o1(e,t,n,r.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>nC(e,404,"Debugger resource not found")}],fallback:({request:e,response:t,url:r})=>o1(e,t,n,r.pathname,{fallbackPath:"/index.html"})};return u=[...(c={artifactOrigin:e,debugScenes:t,getWidgetViewDataTemplates:i,mcpEndpoint:o,physicalDeviceDebugGateway:s,sandboxRuntime:l,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 nO(t,200,{homeDir:rA.homedir(),launchDir:c.simulatorAssets.appDirectory,debugScenesEndpoint:n6,widgetViewDataTemplatesEndpoint:n7,debuggerMcpEndpoint:n?new URL(n9,n).toString():n9,manifestOriginalUrl:new URL("/base/manifest.json",c.artifactOrigin).toString(),mcpOriginalEndpoint:c.mcpEndpoint,realDeviceDebug:c.physicalDeviceDebugGateway?.getDebugContext(),...c.simulatorAssets.getDebugContext(),...c.sandboxRuntime.getDebugContext()},ie)}},{match:n6,handle:({response:e})=>nO(e,200,c.debugScenes??{errors:[],scenes:[]},ie)},{match:n7,handle:({response:e})=>it(e,c.getWidgetViewDataTemplates)}]),...s.getRequestRoutes(),...r,...function(e={}){return[{match:e=>e.pathname===oy||e.pathname.startsWith(`${oy}/`),handle:({request:t,response:r,url:n})=>ov(t,r,n,e)}]}({getSandboxSessionId:()=>l.sessionId,targetOrigin:d}),...l.getRequestRoutes(),...function(e={}){return[{match:ih,handle:({request:t,response:r,url:n})=>(function(e,t,r={},n=nv(e)){let i=et(r.targetEndpoint);if(!n)return void nC(t,400,"Bad request");if(!i)return void nC(t,404,"MCP endpoint not configured");let o=new URL(i);for(let[e,t]of new URLSearchParams(n.search))o.searchParams.append(e,t);nR(e,t,{createResponseHeaders:nx,errorMessage:"代理 MCP 请求失败",requestHeaders:nS(e.headers,o,{...is(),...r.headers}),targetUrl:o})})(t,r,e,n)}]}({headers:a,targetEndpoint:o}),...p.getRequestRoutes(),...h.routes],m=h.fallback,(e,t)=>{let r=nv(e);r?nL({request:e,response:t,url:r},u,m).catch(e=>(function(e,t){if(nm.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);nC(e,500,"Internal server error")}})(t,e)):nC(t,400,"Bad request")}}(e));return await o5(r,t),{origin:`http://127.0.0.1:${t}`,server:r}}async function o8(e){e.listening&&await new Promise((t,r)=>{e.close(e=>{e?r(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function o6(){if(!n)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:r}=n;n=void 0,e.dispose(),t.close(),await o8(r)}async function o7(e){let t,{targetOrigin:r,...i}=e.simulator??{},o={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...i},a=new oj(o);try{var s,l;let i,p,d=et(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=n,s?.server.listening){if(n?.artifactOrigin===e.artifactOrigin&&n.mcpEndpoint===d&&n.simulatorAssets.matches(o)&&n.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&n.sandboxRuntime.matches(c)&&n.simulatorTargetOrigin===r)return await o4(n.origin,d,e.openBrowser),n;await o6()}let u={distPath:l=e.debuggerDistPath,indexPath:tn.join(l,"index.html")};if(!tr.existsSync(u.indexPath))return void nm.error("Web 模拟器资源缺失,请联系框架开发者。");let m=(i={},p=new nH(i),Object.assign([{match:"/__agent_trace",handle:e=>iy(e,i,p)},{match:"/__wsd_control_events",handle:e=>(function({request:e,response:t,url:r},n){if("GET"!==e.method)return void nO(t,405,{error:"Method not allowed"});let i=r.searchParams.get("clientId")?.trim();i?(nT(t,{"Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}),t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8"}),t.write(": connected\n\n"),n.registerClient(i,t)):nO(t,400,{error:"clientId is required"})})(e,p)},{match:"/__wsd_control_results",handle:e=>nV(e,p)},{match:n9,handle:e=>n8(e,i,p)}],{executeSandboxToolCall:e=>p.execute("execute_sandbox_tool_call",{toolCall:e})})),h=await of.start({...c,onSimulatorToolCall:async e=>{await m.executeSandboxToolCall(e)}});t=h;let f=new ix,{origin:g,server:y}=await o9({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:r}),b=()=>{y.close()};y.once("close",()=>{process.off("exit",b)}),process.once("exit",b);let _=await o4(g,d,e.openBrowser);return n={artifactOrigin:e.artifactOrigin,close:()=>o6(),debuggerMcpEndpoint:new URL(n9,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:d,origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:h,get sandboxSessionId(){return h.sessionId},server:y,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:a,simulatorTargetOrigin:r,url:_}}catch(e){t?.close(),nm.error("启动 Web SDK 调试器失败",{error:e});return}}async function ae(e,t){let r={errors:[],scenes:[]};if(!e)return r;for(let n of(await tN(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await tR(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 at(e,t){let r=e.metadata.getData(),n=e.widgets,i=await ae(e.appDirectory,{widgetIds:new Set(Object.keys(n).map(e=>ry(n,r.widgets,e)))});return o7({...t,debuggerDistPath:t.debuggerDistPath??F(),debugScenes:i,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function ar(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function an(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function ai(e){ar(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||tI.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let ao=e=>ep.bgHex("#9873b9")(ep.italic(ep.black(` ${e} `))),aa=e=>ep.bgBlueBright(ep.italic(ep.black(` ${e} `))),as=e=>ep.bold(ep.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))} ${ep.gray(`- ${e.description}`)}`)}async function ac(e){let t=K(e);if(0!==t.length)return await Q.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function au({matchedScene:e,appId:t,driver:r}){let n=await tR(e.path);if(!n)return;let i=await ac(n);await tL({matchedScene:e,appId:t,driver:r,variables:i},n)}async function am(e,t,r,n,i,o,{interactive:a=!0}={}){if(await i.load({appletUrl:t,appId:e,isSigned:o}),!a)return;let s=await tN(process.cwd()),l=Object.values(r),p=Object.values(n),d=p.filter(({id:e})=>!e8(e));return l.length>0&&(console.log(`
163
+ `)}catch{t.timeout&&clearTimeout(t.timeout),e.activeJob=void 0,t.reject(new nj("DEBUGGER_DISCONNECTED","Debugger control connection was closed")),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);let n=new nj("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.response.writableEnded&&e.response.end()}}async function nV({request:e,response:t},r){let n;if("POST"!==e.method)return void nO(t,405,{error:"Method not allowed"});try{n=JSON.parse(await nP(e,t,0xa00000))}catch(e){nO(t,400,{error:e.message});return}r.handleResult(n)?nO(t,200,{ok:!0}):nO(t,404,{error:"Pending debugger command not found"})}let nG=["page","widget","app"],nq=["log","info","warn","error","debug","eval"],nJ=new Set(["id","class","role","title","href","src","type","name","value","placeholder","disabled","checked","selected"]);function nK(e,t){let r=t.pageIdx??0,n=t.pageSize??50,i=r*n,o=e.slice(i,i+n);return{pageIdx:r,pageSize:n,total:e.length,hasMore:i+o.length<e.length,items:o}}function nz(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 nY(e){return e.value??e.unserializableValue??e.description??e.type??""}function nX(e,t){var r,n;let i;return(r=e,"all"===(n=t)?nG:"page"===n||"widget"===n||"app"===n?[n]:(i=r.context,i?.page_id||i?.page_path?["page","app"]:i?.widget_id?["widget"]:nG)).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 o,a,s,l;return i=n.updatedAtMs,o=e.url??e.location?.url,a=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(nY).filter(Boolean).join(" "),...o?{url:o}:{},...void 0===a?{}:{lineNumber:a},...void 0===s?{}:{columnNumber:s},...void 0===i?{}:{updatedAtMs:i},entry:e}})})}function nZ(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 nQ(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 n0={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},n1={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},n2={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function n3(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 n4(e,t={}){try{return await e()}catch(e){return function(e,t={}){let r=e instanceof nj?e:new nj("INSPECTION_FAILED",String(e));return n3({...t,error:{code:r.code,message:r.message}},{isError:!0})}(e,t)}}function n5(e,t,r,n){let i=D(r.inputSchema);e.registerTool(t,{...r,inputSchema:i},n)}let n9="/__wsd_mcp";async function n8({request:e,response:t},r,n){if("OPTIONS"===e.method){nT(t),t.writeHead(204),t.end();return}if("POST"!==e.method)return void nC(t,405,"Method not allowed");let i=$(()=>{let e,t;return e=new z({name:"doubao-web-sdk-debugger-log",version:"0.0.1"}),t=async e=>{var t;let n=nz(r);if(!n.stored)return n3(n);let i=nK((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,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 n3({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:i.total,pageIdx:i.pageIdx,pageSize:i.pageSize,hasMore:i.hasMore,events:i.items})},n5(e,"list_console_messages",{annotations:n0,description:"List runtime console messages captured by the Doubao Web SDK debugger.",inputSchema:{levels:ei(A(nq)).optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:X().optional(),target:A(["current","page","widget","app","all"]).optional()}},async e=>{let t=nz(r);if(!t.stored)return n3(t);let n=nK(nX(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 n3({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)})}),n5(e,"get_console_message",{annotations:n0,description:"Get one full runtime console message, including args and stack trace.",inputSchema:{msgid:X()}},async e=>{let t=nz(r);if(!t.stored)return n3(t);let n=nX(t.snapshot,"all").find(t=>t.msgid===e.msgid);return n3({stored:!0,storedAt:t.storedAt,updatedAtMs:t.updatedAtMs,found:!!n,...n?{message:n}:{msgid:e.msgid}})}),n5(e,"get_log_snapshot",{annotations:n0,description:"Return the latest compact debugger log snapshot.",inputSchema:{}},async()=>{let e=nz(r);return e.stored?n3({stored:!0,storedAt:e.storedAt,updatedAtMs:e.updatedAtMs,snapshot:e.snapshot}):n3(e)}),n5(e,"list_render_targets",{annotations:n0,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 i,o=nz(r);return o.stored?n3({stored:!0,storedAt:o.storedAt,updatedAtMs:o.updatedAtMs,...(t=o.snapshot,n=e.type??"all",i=t.render_targets??{},{pages:"widget"===n?[]:(i.pages??[]).map(e=>nQ(e,"page")).filter(Boolean),widgets:"page"===n?[]:(i.widgets??[]).map(e=>nQ(e,"widget")).filter(Boolean),...i.currentTarget?{currentTarget:i.currentTarget}:{}})}):n3(o)}),n5(e,"take_snapshot",{annotations:n0,description:"Capture and return a fresh text snapshot of the currently rendered Page or Widget card.",inputSchema:{target:A(["current","page","widget"]).optional(),verbose:R().optional()}},e=>n4(async()=>{let t=function(e,t){var r,n;let i,o,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=(r=s.root,n=!0===t.verbose,i=[],o=0,(a=(e,t)=>{var r,s;let{name:l,uid:p}=e;if(!p||!l)return;o+=1;let d=" ".repeat(t);if("text"===e.type)return void i.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&&(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||nJ.has(e.name)||e.name.startsWith("aria-")))))u.push((r=t.name,(s=t.value)?`${r}=${JSON.stringify(s)}`:r));for(let r of(p===c&&u.push("[selected]"),i.push(`${d}${u.join(" ")}`),e.children??[]))a(r,t+1)})(r,0),{actualNodeCount:o,text:i.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 n.execute("take_snapshot",{target:e.target??"current"})).runtimeSnapshot},e),i=nz(r),o={stored:i.stored,...i.stored?{storedAt:i.storedAt,updatedAtMs:i.updatedAtMs}:{},...t};return n3(o,{text:t.available?t.snapshot:JSON.stringify(o,null,2)})},{available:!1,stored:!1})),n5(e,"get_computed_style",{annotations:n0,description:"Get computed CSS styles for an element uid in the current Page or Widget target.",inputSchema:{properties:ei(X().min(1)).max(100).optional(),uid:X().min(1)}},({properties:e,uid:t})=>n4(async()=>n3(await n.execute("get_computed_style",{uid:t,...e?{properties:e}:{}})))),n5(e,"get_element_rect",{annotations:n0,description:"Get x, y, width, and height for an element uid in the emulated viewport.",inputSchema:{uid:X().min(1)}},({uid:e})=>n4(async()=>n3(await n.execute("get_element_rect",{uid:e})))),n5(e,"take_screenshot",{annotations:n0,description:"Take a screenshot of the current Page or Widget target, or of one element uid.",inputSchema:{format:A(["png","jpeg","webp"]).optional(),quality:T().min(0).max(100).optional(),uid:X().min(1).optional()}},({format:e="png",quality:t,uid:r})=>n4(async()=>{let i=await n.execute("take_screenshot",{format:e,...void 0!==t?{quality:t}:{},...r?{uid:r}:{}}),{data:o,...a}=i;return n3({captured:!0,...a},{image:{data:o,mimeType:i.mimeType}})},{captured:!1})),n5(e,"scroll_to",{annotations:n2,description:"Scroll a Page or Widget container to absolute coordinates, or return its current scroll position.",inputSchema:{uid:X().min(1).optional(),x:T().min(0).optional(),y:T().min(0).optional()}},({uid:e,x:t,y:r})=>n4(async()=>n3({scrolled:!0,...await n.execute("scroll_to",{uid:e,x:t,y:r})}),{scrolled:!1})),n5(e,"set_viewport",{annotations:n2,description:"Set the current Page or Widget emulated viewport size.",inputSchema:{height:T().int().min(1).max(9999),width:T().int().min(1).max(9999)}},({height:e,width:t})=>n4(async()=>n3({updated:!0,viewport:await n.execute("set_viewport",{height:e,width:t})}),{updated:!1})),n5(e,"render_page",{annotations:n1,description:"Render a Page route in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{url:X().min(1)}},({url:e})=>n4(async()=>n3({rendered:!0,target:(await n.execute("render_page",{url:e})).target}),{rendered:!1})),n5(e,"render_widget",{annotations:n1,description:"Render a Widget card in the local debugger. This runs application lifecycle code and may issue network requests.",inputSchema:{structuredContent:B(X(),C()).optional(),widgetId:X().min(1)}},({structuredContent:e,widgetId:t})=>n4(async()=>n3({rendered:!0,target:(await n.execute("render_widget",{structuredContent:e??{},widgetId:t})).target}),{rendered:!1})),n5(e,"submit_chat_query",{annotations:n1,description:"Submit a chat query through the connected Web SDK debugger and wait for the simulator response to complete.",inputSchema:{query:X().trim().min(1)}},({query:e})=>n4(async()=>n3({submitted:!0,...await n.execute("submit_chat_query",{query:e})}),{submitted:!1})),n5(e,"list_agent_trace_events",{annotations:n0,description:"List Agent-side simulator and runtime trace events captured by the debugger.",inputSchema:{category:ei(X()).optional(),event:X().optional(),pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),requestId:X().optional()}},t),n5(e,"list_agent_tool_calls",{annotations:n0,description:"List Agent-side simulator tool calls captured by the debugger.",inputSchema:{pageIdx:T().int().min(0).optional(),pageSize:T().int().min(1).max(200).optional(),query:X().optional(),requestId:X().optional(),status:ei(X()).optional(),toolName:X().optional()}},async e=>{var t;let n=nz(r);if(!n.stored)return n3(n);let i=nK((t=n.snapshot,(t.simulator?.tool_calls??[]).map(nZ)).filter(t=>{let r,n,i,o;return r=e.requestId?.trim(),n=e.toolName?.trim(),i=e.status??[],o=e.query?.trim().toLowerCase(),(!r||t.requestId===r)&&(!n||t.toolName===n)&&(!(i.length>0)||!!i.includes(t.status))&&(!o||[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(o)))}),e);return n3({stored:!0,storedAt:n.storedAt,updatedAtMs:n.updatedAtMs,total:i.total,pageIdx:i.pageIdx,pageSize:i.pageSize,hasMore:i.hasMore,toolCalls:i.items})}),e},{legacy:"stateless",responseMode:"json"}),o=en(i);try{await o(e,t)}catch(e){t.headersSent?t.destroy(e instanceof Error?e:void 0):nC(t,500,e instanceof Error?e.message:String(e))}finally{await i.close().catch(()=>void 0)}}let n6="/__web_sdk_debug_scenes",n7="/__web_sdk_widget_view_data_templates",ie={"Cache-Control":"no-cache"};async function it(e,t){try{let r=await t?.()??{templatesByEntry:{},templatesByWidget:{}};nO(e,200,r,ie)}catch(t){nm.error("加载 Widget viewData 模板失败",{error:t}),nO(e,500,{templatesByEntry:{},templatesByWidget:{}},ie)}}let ir=f("../../../node_modules/.pnpm/undici@6.22.0/node_modules/undici/index.js"),ii={"sso-internal":"doubao-developer.bytedance.net","sms-internal":"doubao-developer-open.bytedance.net","sms-external":"hello.doubao-dev.com"},io={"http:":"80","https:":"443"},ia=new Map;function is(){return process.env.X_TT_ENV?{"x-use-ppe":"1","x-tt-env":process.env.X_TT_ENV}:{}}function il(e){let t=e.startsWith("/")?e:`/${e}`;return"/app_developer"===t||t.startsWith("/app_developer/")}async function ip(e,t={}){let r=function(e){var t,r;let n="string"==typeof e?new URL(e):e;if(function(e){let t=iu(["NO_PROXY","no_proxy"]);if(!t)return!1;let r=im(e.hostname),n=e.port||io[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:im(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:im(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)?iu(["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):"http:"===t?iu(["HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"]):void 0;if(!i)return;let o=(r=i,/^[a-z][a-z\d+.-]*:\/\//i.test(r)?r:`http://${r}`),a=ia.get(o);return a||(a=new ir.kT(o),ia.set(o,a)),a}(e),n=r?{...t,dispatcher:r}:t;return await fetch(e,n)}async function id({internal:e,domainId:t,path:r,query:n,method:i="GET",body:o,headers:a,signal:s,auth:l=!0}){let p={method:i,body:o,headers:{...is(),...a}};s&&(p.signal=s);let d=function({internal:e,domainId:t,path:r,query:n}){let i=r.startsWith("/")?r:`/${r}`,o=new URLSearchParams;for(let[e,t]of Object.entries(n||{}))null!=t&&o.append(e,t.toString());let a=o.toString(),s=a?`${i.includes("?")?"&":"?"}${a}`:"",l=il(i)?es:t?ii[t]:e?ii["sso-internal"]:ii["sms-external"];return`https://${l}${i}${s}`}({internal:e,domainId:t,path:r,query:n}),c=new Headers(p.headers),u=c.has("Cookie");if(!l||!il(r)||c.has("Authorization")||c.has("X-Developer-Open-Build-Token"))return await ip(d,p);let m=new URL(d).origin,h=L(ip,{baseUrl:m,allowedOrigins:[m]});try{return await h(d,p)}catch(e){if(!(e instanceof H||e instanceof O))throw e;if(u)return await ip(d,p);throw Error(e instanceof O?"Doubao Apps Platform 登录已过期,请运行 `dbx auth login` 后重试。":"Doubao Apps Platform 请求需要登录,请运行 `dbx auth login` 后重试。")}}async function ic(e){let t=await id(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 iu(e){for(let t of e){let e=process.env[t]?.trim();if(e)return e}}function im(e){return e.trim().toLowerCase().replace(/^\[/,"").replace(/\]$/,"")}let ih="/__mcp_proxy",ig={"Cache-Control":"no-cache"};async function iy({request:e,response:t,url:r},n,i){var o;let a,s;if("OPTIONS"===e.method){nT(t,ig),t.writeHead(204),t.end();return}if("GET"===e.method){let e;return void nO(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,null!=(e=r.searchParams.get("DEBUG"))&&"0"!==e&&"false"!==e.toLowerCase())??{stored:!1},ig)}if("POST"!==e.method)return void nO(t,405,{error:"Method not allowed"},ig);try{a=JSON.parse(await nP(e,t,0xa00000))}catch(e){nO(t,400,{error:e.message},ig);return}a=function(e,t){let r=e?.snapshot,n=t.snapshot,i=r?.runtime_snapshot,o=n.runtime_snapshot;if(!r||!i||r.client_id!==n.client_id)return t;if(!o){var a;let e;if(a=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),a&&e&&(1===Object.keys(e).length?e.type!==a.type:JSON.stringify(e)!==JSON.stringify(a)))return t;let{root:r,...o}=i;return{...t,snapshot:{...n,runtime_snapshot:i},...t.debug_snapshot?{debug_snapshot:{...t.debug_snapshot,runtime_snapshot:o}}:{}}}return Object.hasOwn(o,"root")||!Object.hasOwn(i,"root")||i.updatedAtMs!==o.updatedAtMs||JSON.stringify(i.target)!==JSON.stringify(o.target)?t:{...t,snapshot:{...n,runtime_snapshot:{...o,root:i.root}}}}(n.snapshot,a),n.snapshot=a,n.updatedAtMs=Date.now(),i.noteSnapshot("string"==typeof(s=(o=a).snapshot.client_id??o.debug_snapshot?.client_id)&&s.trim()?s.trim():void 0),nO(t,200,{ok:!0,updated_at_ms:n.updatedAtMs},ig)}let ib=f("node:crypto"),i_="/__dbx_real_device_debug",iw=`${i_}/state`,iv=`${i_}/start`,iE=`${i_}/cancel`,iS=`${i_}/qr`;class ix{accessToken;provider;getDebugContext(){if(this.provider&&this.accessToken)return{stateEndpoint:iw,startEndpoint:iv,cancelEndpoint:iE,qrEndpoint:iS,accessToken:this.accessToken,pollIntervalMs:500}}setProvider(e){this.provider=e,this.accessToken=e?ib.randomBytes(32).toString("hex"):void 0}dispose(){this.setProvider(void 0)}getRequestRoutes(){return[{match:e=>e.pathname.startsWith(i_),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===iw||r.pathname===iv){if(Object.keys(i).length>0)return this.writeError(t,400,"INVALID_REQUEST","Unexpected request fields");let e=r.pathname===iw?await n.getState():await n.start();nO(t,200,e);return}if(r.pathname===iE){let e=i.operationId;if("string"!=typeof e||!e||1!==Object.keys(i).length)return this.writeError(t,400,"INVALID_REQUEST","Invalid operationId");nO(t,200,await n.cancel(e));return}if(r.pathname===iS){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 o=await n.getQrImage(e,r);if(!o)return this.writeError(t,404,"QR_NOT_FOUND","QR image is unavailable");nT(t),t.writeHead(200,{"Content-Length":o.body.byteLength,"Content-Type":o.contentType}),t.end(o.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,o,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||(r=s,n=this.accessToken,o=(i=new TextEncoder).encode(r),a=i.encode(n),!(o.length===a.length&&ib.timingSafeEqual(o,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 r,n;try{r=await nP(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||nO(e,t,{error:{code:r,message:n}})}}let iA="/app_developer/api/sandbox/",iT=`${iA}session/business_info/update`,iC=new Set([`${iA}resources/notices/pull`,`${iA}resources/tasks/pull`]),iO={"Access-Control-Expose-Headers":nw},iI=new Set;function iP(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return!1;let a=`${i[n_]??""} ${e} ${t.pathname}`,s=iC.has(t.pathname);if(s&&r>=500){if(iI.has(a))return!1;iI.add(a)}else s&&r<500&&iI.delete(a);let l=Number(process.hrtime.bigint()-n)/1e6;return nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:l,headers:i,logId:o}),!0}function ik({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}function iD(e,t,r){return r&&!(iC.has(e.pathname)&&t>=500)}function i$(e,t){if(e.pathname!==iT||!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 iN({method:e,request:t,requestBody:r,requestHeaders:n,response:i,targetUrl:o,usePlatformFetch:a}){let s=new AbortController,l=process.hrtime.bigint(),p=()=>s.abort();t.once("aborted",p),i.once("close",()=>{i.writableEnded||p()});try{let t,p=a?await id({internal:!0,path:`${o.pathname}${o.search}`,method:e,body:r,headers:n,signal:s.signal}):await fetch(o,{body:"GET"===e||"HEAD"===e?void 0:r,headers:n,method:e,signal:s.signal}),d=iP(e,o,p.status,l,n,p.headers.get(nw)??void 0);if(i.destroyed||i.writableEnded)return void p.body?.cancel().catch(()=>void 0);let c=await nk(p);return iD(o,p.status,d)&&ik({method:e,requestBody:i$(o,r),requestHeaders:n,responseBody:c,responseHeaders:p.headers,statusCode:p.status,targetUrl:o}),i.destroyed||i.writableEnded||(t=nA(p.headers,[nw]),nT(i,iO),i.writeHead(p.status,t),i.end(c)),{body:c,ok:p.ok}}catch(p){if(i.destroyed||i.writableEnded||s.signal.aborted)return;let t=`Failed to proxy sandbox request: ${p instanceof Error?p.message:String(p)}`,a=iP(e,o,502,l,n);iD(o,502,a)&&ik({method:e,requestBody:i$(o,r),requestHeaders:n,responseBody:t,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:o}),nC(i,502,t,iO)}}async function iR(e,t,r={}){let n;if("POST"!==e.method)return void nC(t,405,"Method not allowed",iO);try{n=JSON.parse(await nP(e,t,0xa00000))}catch(e){nC(t,400,`Invalid sandbox proxy payload: ${e.message}`,iO);return}let i=function(e,t){if(!e.url)return;let r=new URL(e.url,t);if(!r.pathname.startsWith(iA))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 nC(t,404,"Sandbox endpoint not found",iO);if(!r.sandboxSessionId)return void nO(t,200,{code:-1,message:"无法模拟平台服务:当前未获取到开发者登录态或 Sandbox session 创建失败。"},iO);let o=function(e,t,r,n){if(t.pathname.startsWith(`${iA}session/`)&&t.pathname!==`${iA}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(`${iA}jsb/`)&&"app_key"in i&&(i.app_key=r),t.pathname===`${iA}passport/open/auth`&&"client_key"in i&&(i.client_key=r),JSON.stringify(i)}(n,i,r.sandboxAppId,r.sandboxSessionId),a=n.method||"POST",s=function(e,t,r,n,i){let o=Object.fromEntries(Object.entries(nS({...e.headers,...r,...void 0===n?{}:{"content-length":String(Buffer.byteLength(n))},"content-type":"application/json"},t,{...is(),...i?{[n_]: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(o))"accept-encoding"===e.toLowerCase()&&delete o[e];return o["accept-encoding"]="identity",o}(e,i,n.headers,o,r.sandboxSessionId),l=await iN({method:a,request:e,requestBody:o,requestHeaders:s,response:t,targetUrl:i,usePlatformFetch:!r.targetOrigin});if(i.pathname===iT&&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 iL=f("node:util"),iM="/app_developer/api/sandbox/bridge/events",ij="/app_developer/api/sandbox/bridge/response",iU=new Set(["connection","content-length","host"]),iB=new Set(["heartbeat"]),iF=[500,1e3,2e3,5e3],iW=0;function iH(e){return e.length<=8?e:`${e.slice(0,4)}...${e.slice(-4)}`}function iV(e,t=new Headers,r=""){return{response:e,responseHeaders:Object.fromEntries(t),statusText:r}}async function iG(e){let t,r,n=e.request_id||"";if(!n)return iV({error_message:"bridge request_id is required",http_status:0,request_id:n,success:!1});if(!e.path?.startsWith("/"))return iV({error_message:`invalid bridge request path: ${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 iV({error_message:`invalid bridge request origin: ${e.origin??""}`,http_status:0,request_id:n,success:!1});let o=(e.method||"GET").toUpperCase(),a=function(e){let t={};for(let[r,n]of Object.entries(e??{}))!r||iU.has(r.toLowerCase())||(t[r]=n);return t}(e.headers),s="GET"===o||"HEAD"===o?void 0:e.body??"",l=new AbortController,p=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 d;let e=await fetch(i,{body:s,headers:a,method:o,redirect:"manual",signal:l.signal}),t=await e.text();return d={method:o,requestBody:s,requestHeaders:a,responseBody:t,responseHeaders:e.headers,statusCode:e.status,targetUrl:i},nN(d),iV({body:t,http_status:e.status,request_id:n,success:!0},e.headers,e.statusText)}catch(e){return nN({method:o,requestBody:s,requestHeaders:a,responseBody:e instanceof Error?e.message:String(e),responseHeaders:new Headers,statusCode:0,targetUrl:i}),iV({error_message:e instanceof Error?e.message:String(e),http_status:0,request_id:n,success:!1})}finally{clearTimeout(p)}}function iq(e,t=new Set){if(Array.isArray(e)){for(let r of e)iq(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}iq(n,t)}return[...t]}function iJ(e,t){e.onLog?.(t)}function iK(e){try{return JSON.parse(e)}catch{return}}function iz({detail:e,requestHeaders:t,status:r,targetUrl:n}){if("applet0930"===process.env.DEBUG){if("number"==typeof r)return void nm.request({method:"CONNECT",url:n.pathname,statusCode:r,headers:t,context:{detail:e}});nm.info("Bridge connection pending",{url:n.pathname,detail:e,ppe:e_(t)})}}function iY(e,t={}){"applet0930"===process.env.DEBUG&&nm.info(e,t)}async function iX(e,t){let r=JSON.stringify({sandbox_session_id:e.sandboxSessionId,...t}),n={"content-type":"application/json",[n_]:e.sandboxSessionId,...is()};if(e.targetOrigin){let t=new URL(ij,e.targetOrigin),i=await fetch(t,{body:r,headers:n,method:"POST"}),o=await i.text();if(nN({method:"POST",requestBody:r,requestHeaders:n,responseBody:o,responseHeaders:i.headers,statusCode:i.status,targetUrl:t}),!i.ok)throw Error(`upload bridge response failed: ${i.status} ${o}`);return{responseBody:o,responseHeaders:Object.fromEntries(i.headers),responsePayload:iK(o)}}let i=new URL(ij,ee),o=await id({body:r,headers:n,internal:!0,method:"POST",path:ij}),a=await o.text();if(nN({method:"POST",requestBody:r,requestHeaders:n,responseBody:a,responseHeaders:o.headers,statusCode:o.status,targetUrl:i}),!o.ok)throw Error(`upload bridge response failed: ${o.status} ${a}`);return{responseBody:a,responseHeaders:Object.fromEntries(o.headers),responsePayload:iK(a)}}async function iZ(e,t){let r;try{r=JSON.parse(t)}catch(e){nm.warn("Sandbox Bridge request parse failed",{reason:e.message});return}let n=Date.now(),i=`bridge-${n}-${++iW}`,o=r.request_id||"",a={id:i,request:r,requestId:o,sandboxSessionId:e.sandboxSessionId,timestamp:n};iJ(e,{...a,logIds:iq(r),status:"pending",updatedAtMs:n});let s=await iG(r),l={...s.response,headers:s.responseHeaders,status_text:s.statusText};try{let t=await iX(e,s.response);iJ(e,{...a,logIds:iq([r,l,t]),response:l,status:s.response.success?"success":"error",updatedAtMs:Date.now()})}catch(t){throw iJ(e,{...a,errorMessage:t instanceof Error?t.message:String(t),logIds:iq([r,l]),response:l,status:"error",updatedAtMs:Date.now()}),t}}async function iQ(e,t,r){let n={sandbox_session_id:e.sandboxSessionId},i=new URL(`${iM}?sandbox_session_id=${encodeURIComponent(e.sandboxSessionId)}`,ee),o=(d=e.sandboxSessionId,{accept:"text/event-stream",host:i.host,[n_]:d,...is()});iz({detail:`host=${o.host} session=${iH(e.sandboxSessionId)}`,requestHeaders:o,status:"pending",targetUrl:i}),iY("bridge/events request",{headers:{accept:o.accept,host:o.host,[n_]:iH(e.sandboxSessionId),"x-tt-env":o["x-tt-env"],"x-use-ppe":o["x-use-ppe"]},path:iM,query:n});let a=await id({headers:o,internal:!0,method:"GET",path:iM,query:n,signal:t});if(iz({detail:`content-type=${a.headers.get("content-type")??""}`,requestHeaders:o,status:a.status,targetUrl:i}),!a.ok||!a.body){let e=await a.text().catch(()=>"");nN({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:e,responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),nm.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}nN({method:"GET",requestBody:void 0,requestHeaders:o,responseBody:"",responseHeaders:a.headers,statusCode:a.status,targetUrl:i}),r?.();let s=a.body.getReader(),l=new iL.TextDecoder,p="";for(;!t.aborted;){let{done:t,value:r}=await s.read();if(t){iY("bridge/events stream ended",{session:iH(e.sandboxSessionId)});break}let n=(p+=l.decode(r,{stream:!0})).search(/\r?\n\r?\n/);for(;n>=0;){let t=p.slice(0,n),r=p.slice(n).match(/^\r?\n\r?\n/);p=p.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("applet0930"!==process.env.DEBUG||iB.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);nm.info("Bridge event received",{event:e.name,requestId:r,ppe:e_(t)}),nm.info(`Event detail
164
+ ${e.data}`)}(s,o),"bridge_request"===s.name){var d,c=a.headers,u=a.status;nN({method:`EVENT ${s.name}`,requestBody:s.data,requestHeaders:o,responseBody:"",responseHeaders:c,statusCode:u,targetUrl:i}),iZ(e,s.data).catch(e=>{nm.warn("Sandbox Bridge request failed",{reason:e.message})})}else if("TOOL_CALL"===s.name){let t=V(iK(s.data));t?Promise.resolve(e.onSimulatorToolCall?.(t)).catch(e=>{nm.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})}):nm.warn("Sandbox tool call event parse failed")}else if("sandbox_resource_changed"===s.name){let t=function(e){let t=iK(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,o=r?.resource_id,a=r?.revision;if(("notice"===n||"task"===n)&&("upsert"===i||"remove"===i)&&"string"==typeof o&&o&&("number"==typeof a||"string"==typeof a))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:o,revision:a}}(s.data);t?e.onResourceChanged?.(t):nm.warn("Sandbox resource event parse failed")}else if("card_delta"===s.name){let t=function(e){let t=iK(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"}):nm.warn("Sandbox simulator event parse failed",{event:s.name})}else if("get_simulator_card_snapshots"===s.name){let t=iK(s.data);t&&"object"==typeof t&&!Array.isArray(t)?e.onSimulatorEvent?.({payload:t,type:s.name}):nm.warn("Sandbox simulator event parse failed",{event:s.name})}n=p.search(/\r?\n\r?\n/)}}}async function i0(e,t){let r=0,n=!1;for(;!t.aborted;){try{await iQ(e,t,()=>{n=!1,e.onConnectionStatusChange?.("connected")}),r=0}catch(r){if(t.aborted)return;let e=r.status;if(n||(nm.warn("无法接收来自平台服务的请求",{reason:r.message}),n=!0),401===e||403===e||404===e)return}e.onConnectionStatusChange?.("reconnecting"),await (0,v.setTimeout)(iF[Math.min(r,iF.length-1)],void 0,{signal:t}).catch(()=>void 0),r+=1}}let i1=f("node:net"),i2="/__web_sdk_sandbox_bridge_logs",i3="/__web_sdk_sandbox_resource_events",i4="DOUBAO_APPS_SANDBOX_BRIDGE_ORIGINS",i5="/app_developer/api/sandbox/session/business_info/update";function i9(e){if(!e)return!1;try{return tr.statSync(e).isFile()}catch{return!1}}async function i8({body:e,headers:t,method:r,sandboxPath:n,targetOrigin:i,targetUrl:o}){let a=new AbortController,s=setTimeout(()=>a.abort(),3e4);try{return i?await fetch(o,{body:e,headers:t,method:r,signal:a.signal}):await id({internal:!0,path:n,body:e,headers:t,method:r,signal:a.signal})}catch(e){if(a.signal.aborted)throw Error(`Sandbox session 请求超时(30000ms):${o}`);throw e}finally{clearTimeout(s)}}function i6(e,t){return(e?.[t]??process.env[t])?.trim()??""}function i7(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}function oe({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a}){nN({method:e,requestBody:t,requestHeaders:r,responseBody:n,responseHeaders:i,statusCode:o,targetUrl:a})}async function ot(e,t,r,n,i,o){let a,s,l="/app_developer/api/sandbox/session/create",p="POST",d=function(){let e=new Set;for(let t of(process.env[i4]??"").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,i1.isIP)(n)&&n.startsWith("127.");if("http:"!==t.protocol&&"https:"!==t.protocol||!i)throw Error("only loopback HTTP(S) origins are allowed");e.add(t.origin)}catch(e){throw Error(`${i4} contains an invalid origin: ${r} (${e instanceof Error?e.message:String(e)})`)}}return[...e]}(),c=JSON.stringify({sandbox_project_id:e,manifest:r?.()??(i9(t)?tr.readFileSync(t,"utf8"):""),business_templates:i9(n)?tr.readFileSync(n,"utf8"):"",...o?{app_id:o}:{},...d.length>0?{bridge_origins:d}:{}}),u={"content-type":"application/json",...is()},m=new URL(l,i??ee),h=process.hrtime.bigint();try{a=await i8({body:c,headers:u,method:p,sandboxPath:l,targetOrigin:i,targetUrl:m})}catch(t){let e=`创建 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw i7(p,m,502,h,u),oe({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(nw)||"",g=await a.text();i7(p,m,a.status,h,u,f),oe({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 or(e,t,r,n,i,o){try{return await ot(e,t,r,n,i,o)}catch(e){return nm.warn(`Sandbox 平台服务模拟已跳过:${e instanceof Error?e.message:String(e)}`),{appId:"",sessionId:""}}}function on(){return{csrUploaded:!1,phoneNumberUploaded:!1}}function oi(e){return{csrUploaded:!!e,phoneNumberUploaded:!0}}async function oo(e,t){let r,n,i="/app_developer/api/sandbox/session/business_info/get",o="POST",a=JSON.stringify({sandbox_session_id:e}),s={"content-type":"application/json",...is()},l=new URL(i,t??ee),p=process.hrtime.bigint();try{r=await i8({body:a,headers:s,method:o,sandboxPath:i,targetOrigin:t,targetUrl:l})}catch(e){throw i7(o,l,502,p,s),e}let d=r.headers.get(nw)||"",c=await r.text();i7(o,l,r.status,p,s,d);try{n=JSON.parse(c||"{}")}catch{throw oe({method:o,requestBody:a,requestHeaders:s,responseBody:JSON.stringify({omitted:"invalid business info response"}),responseHeaders:r.headers,statusCode:r.status,targetUrl:l}),Error(`获取 Sandbox session 信息失败:HTTP ${r.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}let u={csrUploaded:!!n.data?.csr_pem?.trim(),phoneNumberUploaded:!!n.data?.phone_num?.trim()};if(oe({method:o,requestBody:a,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||d?`,log_id=${n.log_id||d}`:""}`);return u}async function oa(e,t){if(!e)return on();try{return await oo(e,t)}catch(e){return nm.warn(`Sandbox session 信息查询已跳过:${e instanceof Error?e.message:String(e)}`),on()}}async function os(e,t,r){let n,i,o="POST",a=JSON.stringify({...e.csrPem?{csr_pem:e.csrPem}:{},phone_num:e.phoneNum,sandbox_session_id:t}),s={"content-type":"application/json",...is(),[n_]:t},l=new URL(i5,r??ee),p=process.hrtime.bigint();try{n=await i8({body:a,headers:s,method:o,sandboxPath:i5,targetOrigin:r,targetUrl:l})}catch(e){throw i7(o,l,502,p,s),e}let d=n.headers.get(nw)||"",c=await n.text();i7(o,l,n.status,p,s,d),oe({method:o,requestBody:JSON.stringify({...e.csrPem?{csr_pem:"[redacted]"}:{},phone_num:"[redacted]",sandbox_session_id:t}),requestHeaders:s,responseBody:c,responseHeaders:n.headers,statusCode:n.status,targetUrl:l});try{i=JSON.parse(c||"{}")}catch{throw Error(`更新 Sandbox session 信息失败:HTTP ${n.status} 响应不是有效 JSON${d?`,log_id=${d}`:""}`)}if(!n.ok||void 0!==i.code&&0!==i.code)throw Error(`更新 Sandbox session 信息失败:${i.message||n.statusText||n.status}${i.log_id||d?`,log_id=${i.log_id||d}`:""}`)}async function ol(e,t,r,n){if(e&&t.phoneNum&&(!r||t.csrPem))try{return await os({...t.csrPem?{csrPem:t.csrPem}:{},phoneNum:t.phoneNum},e,n),nm.info("Sandbox business info 已自动上传",{sessionId:e}),oi(t.csrPem)}catch(e){nm.warn(`Sandbox business info 自动上传已跳过:${e instanceof Error?e.message:String(e)}`);return}}async function op(e,t){let r,n="/app_developer/api/sandbox/session/revoke",i="POST",o=JSON.stringify({sandbox_session_id:e}),a={"content-type":"application/json",...is()},s=new URL(n,t??ee),l=process.hrtime.bigint();try{r=await i8({body:o,headers:a,method:i,sandboxPath:n,targetOrigin:t,targetUrl:s})}catch(t){let e=`撤回 Sandbox session 请求失败:${t instanceof Error?t.message:String(t)}`;throw i7(i,s,502,l,a),oe({method:i,requestBody:o,requestHeaders:a,responseBody:e,responseHeaders:new Headers({"content-type":"text/plain; charset=utf-8"}),statusCode:502,targetUrl:s}),t}let p=r.headers.get(nw)||"",d=await r.text();i7(i,s,r.status,l,a,p),oe({method:i,requestBody:o,requestHeaders:a,responseBody:d,responseHeaders:r.headers,statusCode:r.status,targetUrl:s});let c=JSON.parse(d||"{}");if(!r.ok||0!==c.code)throw Error(`撤回 Sandbox session 失败:${c.message||r.statusText||r.status}${c.log_id||p?`,log_id=${c.log_id||p}`:""}`)}async function od(e){if(e.recreatePromise)return e.recreatePromise;e.recreatePromise=(async()=>{var t;let r=e.sandboxSessionId;r&&await op(r,e.sandboxTargetOrigin),e.bridge?.close(),e.bridge=void 0;let n=await ot(e.sandboxProjectId,e.simulatorManifestPath,e.simulatorManifestReader,e.simulatorBusinessTemplatesPath,e.sandboxTargetOrigin,e.sandboxSessionAppId),i=n.sessionId,o=!e.sandboxSessionAppId,a=await ol(i,e.businessInfoInput,o,e.sandboxTargetOrigin)??await oa(i,e.sandboxTargetOrigin);return e.sandboxAppId=n.appId,e.sandboxSessionId=i,e.businessInfo=a,(t=e).resourceConnectionStatus="connecting",t.resourceEventSequence=0,t.resourceEvents.length=0,t.simulatorEventSequence=0,t.simulatorEvents.length=0,t.resourceGeneration+=1,oc(t),e.bridge=ou(e,i),nm.info("Sandbox session 已重建",{sessionId:i}),{...n,businessInfoUploaded:a.phoneNumberUploaded&&(!o||a.csrUploaded)}})();try{return await e.recreatePromise}finally{e.recreatePromise=void 0}}function oc(e){e.resourceEventsUpdatedAtMs=Math.max(Date.now(),e.resourceEventsUpdatedAtMs+1)}function ou(e,t){var r={onConnectionStatusChange:t=>{e.resourceConnectionStatus!==t&&(e.resourceConnectionStatus=t,oc(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)},onResourceChanged:t=>{e.resourceEvents.push({...t,sequence:++e.resourceEventSequence}),e.resourceEvents.length>200&&e.resourceEvents.splice(0,e.resourceEvents.length-200),oc(e)},onSimulatorEvent:t=>{e.simulatorEvents.push({...t,sequence:++e.simulatorEventSequence}),e.simulatorEvents.length>200&&e.simulatorEvents.splice(0,e.simulatorEvents.length-200),oc(e)},onSimulatorToolCall:e.onSimulatorToolCall,sandboxSessionId:t,targetOrigin:e.sandboxTargetOrigin};if(!r.sandboxSessionId)return void nm.warn("Sandbox Bridge skipped: missing sandbox session id");let n=new AbortController;return iY("start sandbox bridge",{session:iH(r.sandboxSessionId)}),r.onConnectionStatusChange?.("connecting"),i0(r,n.signal),{close:()=>n.abort()}}async function om(e,t,r){if("POST"!==e.method)return void nC(t,405,"Method not allowed");if(!r)return void nC(t,503,"Sandbox session is not initialized");try{let n=await nP(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 nC(t,400,"Invalid Sandbox business info");r.businessInfoInput={..."string"==typeof e.csrPem&&e.csrPem.trim()?{csrPem:e.csrPem.trim()}:{},phoneNum:e.phoneNum.trim()}}let i=await od(r);nO(t,200,{code:0,data:{sandbox_appid:i.appId,business_info_uploaded:i.businessInfoUploaded,sandbox_session_id:i.sessionId},message:"ok"})}catch(e){nC(t,500,e.message)}}function oh(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=tr.realpathSync.native(t)}catch{}return(0,ib.createHash)("sha256").update(r).digest("hex")}(e.appDirectory),i=function(e,t){let r=i6(e,"DOUBAO_SANDBOX_PHONE_NUM"),n=i6(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 i9(r)?r:void 0}(n,t),o="";if(n&&!i)nm.warn(`Sandbox CSR 文件不存在:${n}`);else if(i)try{o=tr.readFileSync(i,"utf8").trim()}catch(e){nm.warn(`Sandbox CSR 文件读取失败:${e instanceof Error?e.message:String(e)}`)}return{...r?{phoneNum:r}:{},...o?{csrPem:o}:{}}}(e.env,e.appDirectory),o=`${i.phoneNum??""}\0${i.csrPem??""}`;return{businessInfoInput:i,businessInfoInputKey:o,businessTemplatesPath:e.businessTemplatesPath,key:JSON.stringify([o,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 of{configKey;manifestReader;state;constructor(e,t,r){this.state=e,this.configKey=t,this.manifestReader=r}static async start(e){let t=oh(e),r=await or(t.projectId,t.manifestPath,t.manifestReader,t.businessTemplatesPath,t.targetOrigin,t.sessionAppId),n=!t.sessionAppId,i={bridgeLogs:[],bridgeLogsUpdatedAtMs:0,businessInfo:await ol(r.sessionId,t.businessInfoInput,n,t.targetOrigin)??await oa(r.sessionId,t.targetOrigin),businessInfoInput:t.businessInfoInput,onSimulatorToolCall:t.onSimulatorToolCall,resourceConnectionStatus:"connecting",resourceEventSequence:0,resourceEvents:[],resourceEventsUpdatedAtMs:0,resourceGeneration:1,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},o=new of(i,t.key,t.manifestReader);return i.bridge=r.sessionId?ou(i,r.sessionId):void 0,o}get sessionId(){return this.state.sandboxSessionId}close(){this.state.bridge?.close()}matches(e){let t=oh(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,ib.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:i2,sandboxResourceEventsEndpoint:i3,...this.state.businessInfoInput.csrPem?{sandboxCsrPem:this.state.businessInfoInput.csrPem}:{},...this.state.businessInfoInput.phoneNum?{sandboxPhoneNum:this.state.businessInfoInput.phoneNum}:{}}}getRequestRoutes(){return[{match:i2,handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method&&"DELETE"!==e.method?nC(t,405,"Method not allowed"):("DELETE"===e.method&&r&&(r.bridgeLogs.length=0,r.bridgeLogsUpdatedAtMs=Math.max(Date.now(),r.bridgeLogsUpdatedAtMs+1)),nO(t,200,{logs:r?.bridgeLogs??[],updatedAtMs:r?.bridgeLogsUpdatedAtMs??0},{"Cache-Control":"no-cache"})))}},{match:i3,handle:({request:e,response:t})=>{var r;return r=this.state,void("GET"!==e.method?nC(t,405,"Method not allowed"):nO(t,200,{connectionStatus:r?.resourceConnectionStatus??"connecting",events:r?.resourceEvents??[],generation:r?.resourceGeneration??0,simulatorEvents:r?.simulatorEvents??[],updatedAtMs:r?.resourceEventsUpdatedAtMs??0},{"Cache-Control":"no-cache"}))}},{match:"/__web_sdk_sandbox_proxy__",handle:({request:e,response:t})=>iR(e,t,{onBusinessInfoUpdated:e=>{this.state.businessInfo=oi(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})=>om(e,t,this.state)}]}}let og=f("node:stream"),oy="/app_developer/api",ob=`${oy}/simulator/images/upload`,o_=new Set([`${oy}/simulator/chat`,ob,`${oy}/simulator/tool/report`]),ow={"Access-Control-Expose-Headers":nw};async function ov(e,t,r,n){if(!o_.has(r.pathname))return void nC(t,404,"未找到模拟器接口",ow);let i=n.targetOrigin??ee,o=new URL(`${r.pathname}${r.search}`,i),a=new AbortController,s=()=>a.abort();e.once("aborted",s),t.once("close",()=>{t.writableEnded||s()});try{var l;let i=e.method??"GET",s=process.hrtime.bigint(),p=function(e,t,r){return Object.fromEntries(Object.entries(nS(e.headers,t,{...is(),...r?{[n_]:r}:{}})).filter(([e,t])=>"host"!==e.toLowerCase()&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)]))}(e,o,n.getSandboxSessionId?.()),d=await oE(e,t,r,i),c=n.targetOrigin?await fetch(o,{body:d,headers:p,method:i,signal:a.signal}):await id({internal:!0,path:`${r.pathname}${r.search}`,method:i,body:d,headers:p,signal:a.signal});if(function(e,t,r,n,i,o){if("applet0930"!==process.env.DEBUG)return;let a=Number(process.hrtime.bigint()-n)/1e6;nm.request({method:e,url:`${t.pathname}${t.search}`,statusCode:r,durationMs:a,headers:i,logId:o})}(i,r,c.status,s,p,c.headers.get(nw)??void 0),t.destroyed||t.writableEnded)return void c.body?.cancel().catch(()=>void 0);await oS({method:i,requestBody:(l=d)instanceof Uint8Array?`(binary, ${l.byteLength} bytes)`:l,requestHeaders:p,requestUrl:r,response:t,upstreamResponse:c})}catch(e){if(t.destroyed||t.writableEnded||a.signal.aborted)return;nC(t,502,`代理模拟器请求失败:${e instanceof Error?e.message:String(e)}`,ow)}}async function oE(e,t,r,n){if("GET"!==n&&"HEAD"!==n)return r.pathname===ob?await nI(e,t,0xb00000):await nP(e,t,0xb00000)}async function oS({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){var a,s;if(nT(i,ow),i.writeHead(o.status,nA(o.headers,[nw])),a=n,s=o,a.pathname===`${oy}/simulator/chat`||s.headers.get("content-type")?.toLowerCase().includes("text/event-stream")===!0)return void await ox({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o});if("applet0930"!==process.env.DEBUG)return o.body?void await (0,g.pipeline)(og.Readable.fromWeb(o.body),i):void i.end();let l=await nk(o);nN({method:e,requestBody:t,requestHeaders:r,responseBody:l,responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end(l)}async function ox({method:e,requestBody:t,requestHeaders:r,requestUrl:n,response:i,upstreamResponse:o}){if(!o.body){nN({method:e,requestBody:t,requestHeaders:r,responseBody:"",responseHeaders:o.headers,statusCode:o.status,targetUrl:n}),i.end();return}let a=og.Readable.fromWeb(o.body);if("applet0930"!==process.env.DEBUG)return void await (0,g.pipeline)(a,i);nN({method:e,requestBody:t,requestHeaders:r,responseBody:"(event stream)",responseHeaders:o.headers,statusCode:o.status,targetUrl:n});let s=new og.Transform({transform(e,t,r){let i;try{i=String(e).split("\n\n").filter(Boolean)}catch(t){return nm.error(`failed to decode event stream chunk: ${t?.toString()}`),r(null,e)}for(let e of i)nm.info(`Event from ${n.pathname}${n.search}
165
+ ${e}`);r(null,e)}});await (0,g.pipeline)(a,s,i)}function oA(e,t){return e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath)}let oT="/__tools/tools.json",oC="/__events/events.json",oO="manifest.yaml",oI="skill",oP=tn.join(".dbx","config.json");function ok(e){if(!e)return!1;try{return tr.statSync(e).isFile()}catch{return!1}}function oD(e,t){if(!e)return;let r=tn.isAbsolute(e)?e:tn.resolve(t??process.cwd(),e);return ok(r)?r:void 0}function o$(e,t){if(e&&t)return tn.relative(t,e).split(tn.sep).join("/")||"."}function oN(e){let t=tn.resolve(e);for(;;){let e;if(e=t,ok(tn.join(e,oP)))return t;let r=tn.dirname(t);if(r===t)break;t=r}}function oR(e){try{return tr.lstatSync(e),!0}catch{return!1}}function oL(e,t,r,n){let i;if(!t.reader&&ok(t.sourcePath)){var o;let r,i=tr.statSync(t.sourcePath);nT(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":i.size,"Content-Type":n}),o=t.sourcePath,(r=tr.createReadStream(o)).once("error",()=>e.destroy()),r.pipe(e);return}try{i=t.reader?.()}catch{i=void 0}void 0===i?nC(e,404,`${r} not found`):(nT(e),e.writeHead(200,{"Cache-Control":"no-cache","Content-Length":Buffer.byteLength(i),"Content-Type":n}),e.end(i))}function oM(e,t){return function(e){let t,r;if(!e)return{layout:"missing",entries:[]};let n=tn.resolve(e);try{t=tr.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 tr.readdirSync(r,{withFileTypes:!0})){if(n.isSymbolicLink())continue;let o=tn.join(r,n.name);n.isDirectory()?t(o):n.isFile()&&"SKILL.md"===n.name&&e.push(function(e,t){let r=tn.relative(e,t).split(tn.sep).join("/");return{content:tr.readFileSync(t,"utf8"),relativePath:r}}(i,o))}}(i),r=e}catch(e){return{directory:n,layout:"invalid",entries:[],error:`skill directory is not readable: ${n}: ${e.message}`}}return r.sort(oA),r.length>0?{directory:n,layout:"resolved",entries:r}:{directory:n,layout:"missing",entries:[]}}(function(e,t){if(t){if(!t)return;let r=e?oN(e):void 0,n=(tn.isAbsolute(t)?[void 0]:[e,r,process.cwd()]).map(e=>tn.isAbsolute(t)?t:tn.resolve(e??process.cwd(),t));return[...new Set(n)].find(oR)??n[0]}if(!e)return;let r=oN(e);return[...new Set([r?tn.join(r,oI):void 0,tn.join(e,oI),tn.join(process.cwd(),oI)].filter(Boolean))].find(oR)}(e,t))}class oj{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?oD(e.manifestPath,e.appDirectory):function(e){if(!e)return;let t=oN(e);return[...new Set([t?tn.join(t,oO):void 0,tn.join(e,oO),tn.join(process.cwd(),oO)].filter(Boolean))].find(ok)}(e.appDirectory),this.businessTemplatesPath=(t=this.manifestPath,r=e.businessTemplatesPath,n=e.appDirectory,r?oD(r,n):t?oD(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=oM(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 oj(e);return this.sourceKey===t.sourceKey&&this.eventsConfigReader===t.eventsConfigReader&&this.toolsConfigReader===t.toolsConfigReader&&this.manifestReader===t.manifestReader}getDebugContext(){let e=oM(this.appDirectory,this.skillsDirectory),t="resolved"===e.layout?e.directory:void 0,r=o$(this.businessTemplatesPath,this.appDirectory),n=o$(this.eventsConfigSource.sourcePath,this.appDirectory),i=o$(this.toolsConfigSource.sourcePath,this.appDirectory),o=o$(this.manifestSource.sourcePath,this.appDirectory),a=o$(t,this.appDirectory);return{...this.eventsConfigSource.reader||this.eventsConfigSource.sourcePath?{eventsConfigUrl:oC,...this.eventsConfigSource.sourcePath?{eventsConfigOriginalUrl:this.eventsConfigSource.sourcePath,...n?{eventsConfigRelativePath:n}:{}}:{}}:{},...this.toolsConfigSource.sourcePath?{toolsConfigOriginalUrl:this.toolsConfigSource.sourcePath,toolsConfigUrl:oT,...i?{toolsConfigRelativePath:i}:{}}:{},...this.manifestSource.sourcePath?{simulatorManifestOriginalUrl:this.manifestSource.sourcePath,...o?{simulatorManifestRelativePath:o}:{}}:{},...this.businessTemplatesPath?{simulatorBusinessTemplatesOriginalUrl:this.businessTemplatesPath,...r?{simulatorBusinessTemplatesRelativePath:r}:{}}:{},...t?{simulatorSkillsDirectoryOriginalUrl:t,...a?{simulatorSkillsDirectoryRelativePath:a}:{}}:{}}}getRequestRoutes(){return[{match:oC,handle:({response:e})=>oL(e,this.eventsConfigSource,"Events config","application/json; charset=utf-8")},{match:oT,handle:({response:e})=>oL(e,this.toolsConfigSource,"Tools config","application/json; charset=utf-8")},{match:"/__simulator_manifest/manifest.yaml",handle:({response:e})=>oL(e,this.manifestSource,"Simulator manifest","application/yaml; charset=utf-8")},{match:"/__simulator_skills/index.json",handle:({response:e})=>{let t;"missing"===(t=oM(this.appDirectory,this.skillsDirectory)).layout?nC(e,404,"Simulator skills directory not found"):"invalid"===t.layout?nC(e,422,t.error??"Invalid simulator Skill layout"):nO(e,200,{skills:t.entries},{"Cache-Control":"no-cache"})}}]}}async function oU(e,t){if("POST"!==e.method)return void nO(t,405,{message:"Method Not Allowed"});try{var r,n;let i,o,a,s=JSON.parse(await nP(e,t,0xa00000)),l=nE(s.url),p=(s.method??"GET").toUpperCase(),d=(r=s.header,o=new Headers(r??{"content-type":"application/json"}),["connection","content-length","host","origin","referer"].forEach(e=>o.delete(e)),o),c=await fetch(l,{body:"GET"!==p&&"HEAD"!==p?function(e,t){let r=e.data;if(null==r)return;if("base64"===e.dataEncoding&&"string"==typeof r){var n;let e;return e=new ArrayBuffer((n=Buffer.from(r,"base64")).byteLength),new Uint8Array(e).set(n),e}if("string"==typeof r)return r;let i=t.get("content-type")?.toLowerCase()??"";if(i.includes("application/x-www-form-urlencoded")&&"object"==typeof r){let e=new URLSearchParams;return Object.entries(r).forEach(([t,r])=>{e.set(t,String(r))}),e.toString()}return i.includes("application/json")||"object"==typeof r?JSON.stringify(r):String(r)}(s,d):void 0,headers:d,method:p}),u="arraybuffer"===s.dataType||"arraybuffer"===s.responseType;if(u)i=Buffer.from(await c.arrayBuffer()).toString("base64");else{let e=await c.text();i="string"===s.dataType||0===e.length?e:JSON.parse(e)}nO(t,200,{data:i,dataEncoding:u?"base64":void 0,header:(n=c.headers,a={},n.forEach((e,t)=>{a[t]=e}),a),statusCode:c.status})}catch(e){nO(t,500,{message:e instanceof Error?e.message:String(e)})}}let oB="/__webview",oF=`${oB}/client.js`,oW=`${oB}/page`,oH=`${oB}/runtime`,oV=`${oB}/sw.js`,oG="x-doubao-web-view-target",oq="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",oJ=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.1_df7782748b6d5198f7cf2625253ae483/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-page-client.js"),f.b),oK=new URL(f("../../../node_modules/.pnpm/@byted-doubao-apps+debugger-server@0.0.43-rc.12_@emnapi+core@1.11.3_@emnapi+runtime@1.1_df7782748b6d5198f7cf2625253ae483/node_modules/@byted-doubao-apps/debugger-server/dist/web-view-proxy-service-worker.js"),f.b);function oz(e,t,r,n=!1){if("GET"!==e.method&&"HEAD"!==e.method)return void nC(t,405,"Method Not Allowed");let i=tr.readFileSync(r,"utf8");nT(t),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)}async function oY(e,t,r){if("GET"!==e.method&&"HEAD"!==e.method)return void nC(t,405,"Method Not Allowed");try{let n=nE(r.searchParams.get("url")??void 0),i=await fetch(n,{headers:{"user-agent":oq,..."string"==typeof e.headers.accept?{accept:e.headers.accept}:{},..."string"==typeof e.headers["accept-language"]?{"accept-language":e.headers["accept-language"]}:{}},method:e.method}),o=i.url?new URL(i.url):n,a=i.headers.get("content-type")??"",s=nx(Object.fromEntries(i.headers));if(s["cache-control"]="no-cache",delete s["content-encoding"],delete s["content-length"],"HEAD"===e.method||!a.includes("text/html")){let r="HEAD"===e.method?void 0:Buffer.from(await i.arrayBuffer());nT(t),t.writeHead(i.status,{...s,[oG]:o.toString(),...r?{"content-length":r.byteLength}:{}}),t.end(r);return}let l=function(e,t){let r=new URLSearchParams({mobileUserAgent:oq,originalPath:`${t.pathname}${t.search}${t.hash}`}).toString().replaceAll("&","&amp;"),n=`<script src="${oF}?${r}"></script>`,i=/<head[^>]*>/i.exec(e);if(i){let t=i.index+i[0].length;return`${e.slice(0,t)}${n}${e.slice(t)}`}return`${n}${e}`}(await i.text(),o);nT(t),t.writeHead(i.status,{...s,[oG]:o.toString(),"content-length":Buffer.byteLength(l)}),t.end(l)}catch(e){nC(t,502,`代理 web-view 页面失败: ${e instanceof Error?e.message:String(e)}`)}}let oX=f("../../../node_modules/.pnpm/send@1.2.0/node_modules/send/index.js"),oZ="/__web_artifacts",oQ="/wsd";function o0(e){return e.replace(/^\/web-sdk\/[^/]+(?=\/wsd(?:\/|$))/,"")}function o1(e,t,r,n,i={}){nT(t,i.headers),oX(e,n,{root:r}).once("error",n=>{if(404===n.statusCode&&i.fallbackPath)return void o1(e,t,r,i.fallbackPath,{headers:i.headers});if(t.headersSent)return void t.destroy(n);let o=n.statusCode??500;nC(t,o,nh.STATUS_CODES[o]??"Internal Server Error")}).pipe(t)}let o2=f("node:child_process");async function o3(e){let{command:t,args:r}="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};await new Promise((e,n)=>{let i=(0,o2.spawn)(t,r,{detached:!0,stdio:"ignore"});i.once("error",n),i.once("spawn",()=>{i.unref(),e()})})}async function o4(e,t,r=o3){let n,i=(n=new URL(e),t&&n.searchParams.set("mcp",ih),n.toString());try{await r(i)}catch(e){nm.error("打开 Web 模拟器失败",{error:e}),nm.info("请手动打开 Web 模拟器(本地)",{url:i})}return i}async function o5(e,t){await new Promise((r,n)=>{let i=t=>{e.off("listening",o),n(t)},o=()=>{e.off("error",i),r()};e.once("error",i),e.once("listening",o),e.listen(t,"127.0.0.1")})}async function o9(e){let t=await Y(9e3),r=nh.createServer(function({artifactOrigin:e,debugScenes:t,debuggerProtocol:r,distPath:n,getWidgetViewDataTemplates:i,mcpEndpoint:o,mcpHeaders:a,physicalDeviceDebugGateway:s,sandboxRuntime:l,simulatorAssets:p,simulatorTargetOrigin:d}){var c,u,m;let h={routes:[{match:e=>e.pathname.startsWith(oZ),handle:({request:t,response:r,url:n})=>{let i,o;return i=n.pathname.replace(oZ,"")||"/",o=new URL(`${i}${n.search}`,e),void nR(t,r,{createResponseHeaders:e=>({...nx(e),"cache-control":"no-cache"}),errorMessage:"代理 Web 产物失败",requestHeaders:nS(t.headers,o),targetUrl:o})}},{match:e=>{let t=o0(e.pathname);return t===oQ||t.startsWith(`${oQ}/`)},handle:({request:e,response:t,url:r})=>{let i;!(i=o0(r.pathname).slice(`${oQ}/`.length))||i!==tn.basename(i)?nC(t,404,"Not found"):o1(e,t,tn.join(n,"wsd"),i,{headers:{"Cache-Control":"no-cache"}})}},{match:"/__web_sdk_request_proxy__",handle:({request:e,response:t})=>oU(e,t)},{match:oV,handle:({request:e,response:t})=>oz(e,t,oK,!0)},{match:oF,handle:({request:e,response:t})=>oz(e,t,oJ)},{match:oH,handle:({request:e,response:t,url:r})=>(function(e,t,r){let n;try{n=nE(r.searchParams.get("url")??void 0)}catch(e){nC(t,400,`无效的 web-view 请求地址: ${e instanceof Error?e.message:String(e)}`);return}let i=nS(e.headers,n,{"user-agent":oq});for(let e of Object.keys(i))e.startsWith("sec-fetch-")&&delete i[e];nR(e,t,{createResponseHeaders:e=>{let t=nx(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=`${oH}?url=${encodeURIComponent(e.toString())}`}return t["cache-control"]="no-cache",t},errorMessage:"代理 web-view 运行时请求失败",requestHeaders:i,targetUrl:n})})(e,t,r)},{match:oW,handle:({request:e,response:t,url:r})=>oY(e,t,r)},{match:e=>e.pathname.startsWith("/__doubao_web_sdk_native_modules"),handle:({request:e,response:t,url:r})=>o1(e,t,n,r.pathname)},{match:e=>e.pathname.startsWith("/__"),handle:({response:e})=>nC(e,404,"Debugger resource not found")}],fallback:({request:e,response:t,url:r})=>o1(e,t,n,r.pathname,{fallbackPath:"/index.html"})};return u=[...(c={artifactOrigin:e,debugScenes:t,getWidgetViewDataTemplates:i,mcpEndpoint:o,physicalDeviceDebugGateway:s,sandboxRuntime:l,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 nO(t,200,{homeDir:rA.homedir(),launchDir:c.simulatorAssets.appDirectory,debugScenesEndpoint:n6,widgetViewDataTemplatesEndpoint:n7,debuggerMcpEndpoint:n?new URL(n9,n).toString():n9,manifestOriginalUrl:new URL("/base/manifest.json",c.artifactOrigin).toString(),mcpOriginalEndpoint:c.mcpEndpoint,realDeviceDebug:c.physicalDeviceDebugGateway?.getDebugContext(),...c.simulatorAssets.getDebugContext(),...c.sandboxRuntime.getDebugContext()},ie)}},{match:n6,handle:({response:e})=>nO(e,200,c.debugScenes??{errors:[],scenes:[]},ie)},{match:n7,handle:({response:e})=>it(e,c.getWidgetViewDataTemplates)}]),...s.getRequestRoutes(),...r,...function(e={}){return[{match:e=>e.pathname===oy||e.pathname.startsWith(`${oy}/`),handle:({request:t,response:r,url:n})=>ov(t,r,n,e)}]}({getSandboxSessionId:()=>l.sessionId,targetOrigin:d}),...l.getRequestRoutes(),...function(e={}){return[{match:ih,handle:({request:t,response:r,url:n})=>(function(e,t,r={},n=nv(e)){let i=et(r.targetEndpoint);if(!n)return void nC(t,400,"Bad request");if(!i)return void nC(t,404,"MCP endpoint not configured");let o=new URL(i);for(let[e,t]of new URLSearchParams(n.search))o.searchParams.append(e,t);nR(e,t,{createResponseHeaders:nx,errorMessage:"代理 MCP 请求失败",requestHeaders:nS(e.headers,o,{...is(),...r.headers}),targetUrl:o})})(t,r,e,n)}]}({headers:a,targetEndpoint:o}),...p.getRequestRoutes(),...h.routes],m=h.fallback,(e,t)=>{let r=nv(e);r?nL({request:e,response:t,url:r},u,m).catch(e=>(function(e,t){if(nm.error("处理 Web SDK 调试器请求失败",{error:t}),!e.destroyed&&!e.writableEnded){if(e.headersSent)return void e.destroy(t instanceof Error?t:void 0);nC(e,500,"Internal server error")}})(t,e)):nC(t,400,"Bad request")}}(e));return await o5(r,t),{origin:`http://127.0.0.1:${t}`,server:r}}async function o8(e){e.listening&&await new Promise((t,r)=>{e.close(e=>{e?r(e):t()}),e.closeIdleConnections(),e.closeAllConnections()})}async function o6(){if(!n)return;let{physicalDeviceDebugGateway:e,sandboxRuntime:t,server:r}=n;n=void 0,e.dispose(),t.close(),await o8(r)}async function o7(e){let t,{targetOrigin:r,...i}=e.simulator??{},o={appDirectory:e.appDirectory,eventsConfigReader:e.eventsConfigReader,eventsConfigSourcePath:e.eventsConfigSourcePath,toolsConfigReader:e.toolsConfigReader,toolsConfigSourcePath:e.toolsConfigSourcePath,manifestReader:e.simulatorManifestReader,manifestSourcePath:e.simulatorManifestSourcePath,...i},a=new oj(o);try{var s,l;let i,p,d=et(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=n,s?.server.listening){if(n?.artifactOrigin===e.artifactOrigin&&n.mcpEndpoint===d&&n.simulatorAssets.matches(o)&&n.getWidgetViewDataTemplates===e.getWidgetViewDataTemplates&&n.sandboxRuntime.matches(c)&&n.simulatorTargetOrigin===r)return await o4(n.origin,d,e.openBrowser),n;await o6()}let u={distPath:l=e.debuggerDistPath,indexPath:tn.join(l,"index.html")};if(!tr.existsSync(u.indexPath))return void nm.error("Web 模拟器资源缺失,请联系框架开发者。");let m=(i={},p=new nH(i),Object.assign([{match:"/__agent_trace",handle:e=>iy(e,i,p)},{match:"/__wsd_control_events",handle:e=>(function({request:e,response:t,url:r},n){if("GET"!==e.method)return void nO(t,405,{error:"Method not allowed"});let i=r.searchParams.get("clientId")?.trim();i?(nT(t,{"Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}),t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8"}),t.write(": connected\n\n"),n.registerClient(i,t)):nO(t,400,{error:"clientId is required"})})(e,p)},{match:"/__wsd_control_results",handle:e=>nV(e,p)},{match:n9,handle:e=>n8(e,i,p)}],{executeSandboxToolCall:e=>p.execute("execute_sandbox_tool_call",{toolCall:e})})),h=await of.start({...c,onSimulatorToolCall:async e=>{await m.executeSandboxToolCall(e)}});t=h;let f=new ix,{origin:g,server:y}=await o9({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:r}),b=()=>{y.close()};y.once("close",()=>{process.off("exit",b)}),process.once("exit",b);let _=await o4(g,d,e.openBrowser);return n={artifactOrigin:e.artifactOrigin,close:()=>o6(),debuggerMcpEndpoint:new URL(n9,g).toString(),getWidgetViewDataTemplates:e.getWidgetViewDataTemplates,mcpEndpoint:d,origin:g,physicalDeviceDebugGateway:f,sandboxRuntime:h,get sandboxSessionId(){return h.sessionId},server:y,setRealDeviceDebugProvider(e){f.setProvider(e)},simulatorAssets:a,simulatorTargetOrigin:r,url:_}}catch(e){t?.close(),nm.error("启动 Web SDK 调试器失败",{error:e});return}}async function ae(e,t){let r={errors:[],scenes:[]};if(!e)return r;for(let n of(await tN(e)).sort((e,t)=>e.name.localeCompare(t.name))){let e=await tR(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 at(e,t){let r=e.metadata.getData(),n=e.widgets,i=await ae(e.appDirectory,{widgetIds:new Set(Object.keys(n).map(e=>ry(n,r.widgets,e)))});return o7({...t,debuggerDistPath:t.debuggerDistPath??F(),debugScenes:i,getWidgetViewDataTemplates:e.getWidgetViewDataTemplates})}function ar(e){return!!(e&&!/<%=?\s*appId\s*%>/.test(e))}function an(e){if(!(e instanceof Error))return!1;try{let t=JSON.parse(e.message);return t?.code===0x2fb1799}catch{return!1}}async function ai(e){ar(e.appId)&&(await e.getCachedLoginCookie().catch(()=>void 0)||tI.warn(e.appId.startsWith("db_")?"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `dbx auth login` 后重新启动开发服务。":"[DoubaoApps] 获取豆包应用信息需要登录,请运行 `npx doubao login` 后重新启动开发服务。"))}let ao=e=>ep.bgHex("#9873b9")(ep.italic(ep.black(` ${e} `))),aa=e=>ep.bgBlueBright(ep.italic(ep.black(` ${e} `))),as=e=>ep.bold(ep.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))} ${ep.gray(`- ${e.description}`)}`)}async function ac(e){let t=K(e);if(0!==t.length)return await Q.prompt(t.map(([e,t])=>({type:"input",name:e,message:`请输入调试场景变量 "${e}" 的值:`,default:t??void 0})))}async function au({matchedScene:e,appId:t,driver:r}){let n=await tR(e.path);if(!n)return;let i=await ac(n);await tL({matchedScene:e,appId:t,driver:r,variables:i},n)}async function am(e,t,r,n,i,o,{interactive:a=!0}={}){if(await i.load({appletUrl:t,appId:e,isSigned:o}),!a)return;let s=await tN(process.cwd()),l=Object.values(r),p=Object.values(n),d=p.filter(({id:e})=>!e8(e));return l.length>0&&(console.log(`
166
166
 
167
167
  ${aa("可用 pages 列表")}
168
168
  `),l.forEach(e=>{console.log(` - ${as(e.path)}`)})),d.length>0&&(console.log(`
@@ -182,13 +182,13 @@ ${r}
182
182
  `}return`
183
183
  ${ao("豆包应用服务信息")}:
184
184
 
185
- 调试服务未运行。`})(l,p)),await ai(e)}let d=(o=!1,a=[],{add(e){e&&(o?e():a.push(e))},cleanup:()=>{o=!0,a.splice(0).forEach(e=>e())},isDisposed:()=>o});if(e.devServerInteractive){let t={context:e,appId:l,appletUrl:p,pages:s.pages,widgets:s.widgets,driver:r,isSigned:n,openWebDebugger:()=>{let t;return t=e.webDebuggerLaunchOptions,at(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:p,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??th(),mcpHeaders:t?.mcpHeaders,openBrowser:t?.openBrowser,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})},isDisposed:d.isDisposed};d.add(nd.instance.addListener(e=>{let r=e.trim().toLowerCase();return("r"===r||"web"===r)&&(process.stdout.write(W(2)),"r"===r?ah(t).catch(nc):t.openWebDebugger(),!0)},"devCommands",-1))}i(d.cleanup);try{if(!r){e.devServerInteractive&&tI.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}d.add(await am(l,p,s.pages,s.widgets,r,n,{interactive:e.devServerInteractive}))}catch(e){throw d.cleanup(),e}}let ag=(e,t,r)=>{if(!tc())return void r();let n=process.hrtime.bigint(),i=e.method,o=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-n)/1e6,r=o?new URL(o,"http://localhost").pathname:"",a=t.statusCode;tI.request({method:i||"UNKNOWN",url:r,statusCode:a,durationMs:e})}),r()},ay=new Set(["EACCES","EPERM"]),ab=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),a_=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),aw=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),av=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),aE={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 aS(e,t){if(!e||"object"!=typeof e||!(t in e))return;let r=e[t];return"string"==typeof r?r: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[]}}var aA=JSON.parse('{"rE":"0.0.43-rc.11"}');function aT(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 aC(e,t){Object.assign(e,aT(t))}function aO(e,{scene:t,commandStartTime:r,compileStartTime:n}){let i=e.commandStartTime===r,o=e.prepareDurations,a=e.builderInitStartTime,s=e.appInfoDurationMs,l=e.appInfoMeasured;i&&void 0!==a&&(o.builderInitMs=Math.max(0,n-a)),aC(e,r),e.scene=t,e.compileStartTime=n,i&&(e.prepareDurations=o,e.appInfoDurationMs=s,e.appInfoMeasured=l)}function aI(e,t,r){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,r)}function aP(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let ak=new class{uploader;constructor(e){this.uploader=e}async report(e){try{var t,r;let n,i,o,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 ar(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:(n=e.context.signingEncryptionOptions,i=!!n?.signing.enabled,o=!!n?.encryption.enabled,i&&o?"signing_and_encryption":i?"signing":o?"encryption":"none"),durations:(t=e.context.compileLifecycle,r=e.compileEndTime,a=t.commandStartTime??r,s=t.compileStartTime??r,l=Math.min(r,Math.max(s,t.compilePhaseEndTimes.moduleProcess??r)),p=Math.min(r,Math.max(l,t.compilePhaseEndTimes.assetProcess??r)),{totalMs:r-a,prepareMs:s-a,compileMs:r-s,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-s,assetProcessMs:p-l,outputWriteMs:r-p})};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.uploader??=new ed).upload(function(e,t){let r={kit_compile_id:function(){let e="unknown";try{e=(0,rA.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,ib.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&&(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=aP(e.durations.totalMs),r.kit_prepare_ms=aP(e.durations.prepareMs),r.kit_compile_ms=aP(e.durations.compileMs),r.kit_config_load_ms=aP(e.durations.configLoadMs),r.kit_project_scan_ms=aP(e.durations.projectScanMs),r.kit_context_bootstrap_ms=aP(e.durations.contextBootstrapMs),r.kit_app_info_ms=aP(e.durations.appInfoMs),r.kit_app_template_process_ms=aP(e.durations.appTemplateProcessMs),r.kit_view_template_process_ms=aP(e.durations.viewTemplateProcessMs),r.kit_plugin_bootstrap_ms=aP(e.durations.pluginBootstrapMs),r.kit_builder_init_ms=aP(e.durations.builderInitMs),r.kit_module_process_ms=aP(e.durations.moduleProcessMs),r.kit_asset_process_ms=aP(e.durations.assetProcessMs),r.kit_output_write_ms=aP(e.durations.outputWriteMs);else{r.kit_error_type=function(e){let t=aS(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(aw.has(t))return"network_error";if(av.has(t))return"filesystem_error"}let r="string"==typeof e?e:aS(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/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)/i.test(r))return"config_error";if(/loader/i.test(r))return"loader_error";if(/plugin/i.test(r))return"plugin_error";let n=aS(e,"name");return n&&aE[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,iL.stripVTControlCharacters)(i).replaceAll(tn.resolve(n),"<project>").replaceAll((0,rA.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(r.kit_error_message=e)}}return{name:"kit_compile",params:r}}(r,{appDirectory:t,kitVersion:aA.rE,runEnv:process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL"}))}};function aD(e,t,r){r?.hasErrors()?ak.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:ax(r)[0]}):ak.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let a$=f("crypto");class aN{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,a$.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class aR extends aN{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=eo(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){eo(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){eo(this._manifest.applet,e)}setRenderType(e=M.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 aL{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 aM{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:r}=this.options;e.hooks.thisCompilation.tap({name:aM.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},n=>{n.hooks.processAssets.tapPromise({name:aM.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new aL,n.getAssets().forEach(e=>{let r=new aN(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,r)});let{entrypoints:i}=n,o={};i.forEach((e,r)=>{o[r]=e.getFiles().map(e=>{let r=t.getAsset(e);if(!r)throw Error(`Asset ${e} not found`);return new aN(r.source,r.content,r.hashCode)})});let a=this.options.context.appId;a&&tr.mkdirSync(tn.join(this.options.context.rootPath,a),{recursive:!0}),await r.callAssetsHooks("beforeEmit",{assets:t,chunks:o}),Object.keys(t.getAssets()).forEach(r=>{let i=t.getAsset(r);if(!i)return;let{source:o,destination:a}=i;if(!o||!a)return;n.getAsset(o)?n.renameAsset(o,a):n.emitAsset(a,new e.rspack.sources.RawSource(i.content));let s=n.getAsset(`${o}.map`);s&&n.renameAsset(s.name,`${a}.map`)}),await r.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let aj=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class aU{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(aU.name,e=>{e.hooks.finishModules.tap(aU.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&&aj.has(r))return!0;let n=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...aj].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 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 aF(e){return e.replaceAll("\\","/")}function aW(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 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,r;let n=this.context.metadata.getData(),i=this.context.command===eR.DEV?"all":"configured",o=r_(this.context.pages,this.context.normalizedAppConfig.pages.entries,i),a=r_(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,i),s=n.app.appId||this.context.appId;if(!s&&Object.keys(o).length>0)throw Error("appId is required to resolve Web page entry paths");s&&(e=n.pages,Object.keys(o).forEach(r=>{let n=aF(r),i=rg(n);aW(t,`${i}/template.js`,re(s,e[r]?.path??t7(n),rm),`${i}/background.js.map`)})),r=n.widgets,Object.keys(a).forEach(e=>{var n;let i=rg(aF(e));aW(t,`${i}/template.js`,(n=ry(a,r,e),`${n}/${rm}`),`${i}/background.js.map`)})})})}}class aV{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(aV.name,()=>{t.writeModule(eY,""),t.writeModule(eX,eZ),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function aG(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let aq={templatesByEntry:{},templatesByWidget:{}},aJ="/doubao-apps-framework.template.js",aK="/doubao-apps-api.template.js",az=(e,t)=>{let r=(r,n,i)=>{var o;return o=(r=>{if(!t)return r;let n="0.0.43-rc.11";return e||!n?`/wsd${r}`:`/web-sdk/${encodeURIComponent(n)}/wsd${r}`})(r),{libraryName:i,url:o,background:{sectionPath:n},mainThread:{sectionPath:`${n}__main-thread`},async:!!t}};return{"@byted-doubao-apps/bridge-base":r(aK,"api"),"@byted-doubao-apps/open-api":r(aK,"api"),...Object.fromEntries(Object.entries(e5).map(([t,n])=>[t,r(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",n])])),[`${ti}/api`]:r(aK,"api"),[`${to}/api`]:r(aK,"api"),[ti]:r(aJ,"framework"),[to]:r(aJ,"framework"),"@byted-doubao-apps/components":r(aJ,"components"),[ts(ti)]:r(aJ,"components"),[ts(to)]:r(aJ,"components")}},aY=f("node:url"),aX=(0,S.createRequire)(import.meta.url);function aZ(e,t){for(let r of e)try{return aX.resolve(r,{paths:t})}catch{}throw Error(`Cannot resolve package from candidates: ${e.join(", ")}`)}class aQ{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,o;let{appDirectory:a,command:p,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=p===eR.DEV,_=await this.createEntry(),w=tp(a),v=[a,tn.dirname((0,aY.fileURLToPath)(import.meta.url))],E=aX.resolve("@lynx-js/react/transform"),x=b?"all":"configured",A=r_(e.context.pages,e.context.normalizedAppConfig.pages.entries,x),T=new Set([...Object.keys(r_(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,x)),...Object.keys(A)]);if(e.web&&0===T.size)throw Error(b?"No Web entries are available. Add page/widget entries under src/pages or src/widgets.":"No Web entries are configured. Add `web: true` to page/widget entries in src/app.config.ts.");e.web&&await r7({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":"({})"}},O=e=>[eY,eX,e.filename],I={...C,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,O(t)]))},k=Object.fromEntries(Object.entries(_).filter(([e])=>T.has(e))),D=new Map(Object.keys(k).map(e=>[rg(e),e])),$={...I,entry:Object.fromEntries(Object.entries(k).map(([e,t])=>[rg(e),O(t)])),define:{...I.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},N=[...tu()?[]:[q({externals:az(b),globalObject:"lynx"})]],R=[function({metadata:e,resolveAppInfo:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name==="web"?rc:rd;r.plugin(ru.name).use(ru,[{metadata:e,resolveAppInfo:t,shouldInjectAsset:i}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo()})],L={source:I,plugins:N},M=[function e({metadata:t,entry:r,resolveSigningEncryptionOptions:n,onProcessDuration:i}){return{name:e.name,setup(e){e.modifyBundlerChain((o,a)=>{if(a?.environment?.name==="web")return;let s=e.useExposed(Symbol.for("LynxTemplatePlugin"));o.plugin(np.name).use(np,[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(aU,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,i)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?D.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(aM,[n])})}}),...p===eR.DEV&&e.web?[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,S.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))],o=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,tr.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}),a=o.getTypeChecker(),s=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let r,i=o.getSourceFile(t);return[P(e),i?(r={},!function e(t){if(n.isCallExpression(t)&&("getViewData"===aG(n,t.expression)||"useViewData"===aG(n,t.expression))&&t.typeArguments?.[0]){let e=a.getTypeFromTypeNode(t.typeArguments[0]);for(let i of a.getPropertiesOfType(e)){let o=i.valueDeclaration??i.declarations?.[0]??t;r[i.getName()]=function e(t,r,n,i,o){let a=(r.isUnion()?r.types:[r]).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=>n.isArrayType(e)||n.isTupleType(e)))return[];let s=a.find(e=>e.flags&t.TypeFlags.Object);if(!s||o.has(s))return{};o.add(s);let l=Object.fromEntries(n.getPropertiesOfType(s).map(r=>{let a=r.valueDeclaration??r.declarations?.[0]??i;return[r.getName(),e(t,n.getTypeOfSymbolAtLocation(r,a),n,a,o)]}));return o.delete(s),l}(n,a.getTypeOfSymbolAtLocation(i,o),a,o,new Set([e]))}}n.forEachChild(t,e)}(i),r):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let n=P(e);return[ry(t,r,e),s[n]??{}]}));return{templatesByEntry:s,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=aq}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(ag)}}})),t.onAfterDevCompile(async({stats:o})=>{if(o.hasErrors()||n)return;let{devServer:a}=t.context;if(!a)return;n=!0;let s=await tD({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(nc);i||await af({context:e,port:a.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){i?e():r=e}})}),t.onCloseDevServer(()=>{i=!0,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,()=>{aI(e.compileLifecycle,"moduleProcess",Date.now())}),n.hooks.emit.tap(t,()=>{aI(e.compileLifecycle,"assetProcess",Date.now())}),n.hooks.failed.tap(t,t=>{ak.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===eR.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==eR.DEV){let t=e.command;r.onBeforeBuild(()=>{let r=Date.now();aO(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??r,compileStartTime:r})}),r.onAfterBuild(({stats:r})=>{aD(e,t,r)})}else r.onBeforeDevCompile(({isFirstCompile:t})=>{let r=Date.now();aO(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??r:r,compileStartTime:r})}),r.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}=aX(aZ(["@byted/rsdoctor"],v));for(let r of e)r.plugins??=[],r.plugins.push(new t({disableClientServer:!0,supports:{banner:!0}}))})}}]:[],(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(aB,[{pluginSystem:n,context:i}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o})=>({name:"lynx:encode-worker",async setup(a){tm()||a.modifyBundlerChain((a,s)=>{s?.environment?.name!=="web"&&a.plugin(nl.name).use(nl,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o}]).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(aV.name).use(aV,[k])})}},(o=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=o.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),o=i?aF(n):aF(e).replace(/^\/+/,"");return`${i?"file":"webpack"}:///${o}${t}`},e}),e.plugin(aH.name).use(aH,[o])}}})}})],U=d({mode:p===eR.DEV?"development":"production",environments:e.web?{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:[q({externals:az(p===eR.DEV,!0),globalObject:"lynx"})]}}:{lynx:L},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,r=tn.join(tn.dirname((0,aY.fileURLToPath)(import.meta.url)),"components-loader.js"),n=aZ){try{return n(t===to?["@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,tr.existsSync)(r))return r;throw e}}(v,w),options:{frameworkPackage:w}}]},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:{host:nn()},dev:{writeToDisk:tc(),hmr:p===eR.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:tc(),...tu()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){er({LAYERS:s,lazy:!1,rootPath:tn.dirname((0,aY.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:w,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...ta]}}),{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 transform loader not found for layer: ${e}`);t.tap(e=>({...e,transformPath:E}))}})}},function(e){let{compilerOptionsKeys:t=rC.compilerOptionsKeys,configKeys:r=rC.configKeys,validate:n=rz,dslPluginName2PkgName:i=rY,upgradeRspeedyLink:o="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(a=>{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(`\
185
+ 调试服务未运行。`})(l,p)),await ai(e)}let d=(o=!1,a=[],{add(e){e&&(o?e():a.push(e))},cleanup:()=>{o=!0,a.splice(0).forEach(e=>e())},isDisposed:()=>o});if(e.devServerInteractive){let t={context:e,appId:l,appletUrl:p,pages:s.pages,widgets:s.widgets,driver:r,isSigned:n,openWebDebugger:()=>{let t;return t=e.webDebuggerLaunchOptions,at(e,{appId:e.appId,appDirectory:e.appDirectory,artifactOrigin:p,env:{...e.env,...t?.env??{}},mcpEndpoint:t?.mcpEndpoint??th(),mcpHeaders:t?.mcpHeaders,openBrowser:t?.openBrowser,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})},isDisposed:d.isDisposed};d.add(nd.instance.addListener(e=>{let r=e.trim().toLowerCase();return("r"===r||"web"===r)&&(process.stdout.write(W(2)),"r"===r?ah(t).catch(nc):t.openWebDebugger(),!0)},"devCommands",-1))}i(d.cleanup);try{if(!r){e.devServerInteractive&&tI.info("尝试将应用推送到 Android 设备,但未检测到可用设备。\n");return}d.add(await am(l,p,s.pages,s.widgets,r,n,{interactive:e.devServerInteractive}))}catch(e){throw d.cleanup(),e}}let ag=(e,t,r)=>{if(!tc())return void r();let n=process.hrtime.bigint(),i=e.method,o=e.url;t.on("finish",()=>{let e=Number(process.hrtime.bigint()-n)/1e6,r=o?new URL(o,"http://localhost").pathname:"",a=t.statusCode;tI.request({method:i||"UNKNOWN",url:r,statusCode:a,durationMs:e})}),r()},ay=new Set(["EACCES","EPERM"]),ab=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"]),a_=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT","ERR_REQUEST_TIMEOUT"]),aw=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN","EPIPE"]),av=new Set(["EEXIST","EISDIR","EMFILE","ENOENT","ENOSPC","ENOTDIR","EROFS"]),aE={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 aS(e,t){if(!e||"object"!=typeof e||!(t in e))return;let r=e[t];return"string"==typeof r?r: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[]}}var aA=JSON.parse('{"rE":"0.0.43-rc.12"}');function aT(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 aC(e,t){Object.assign(e,aT(t))}function aO(e,{scene:t,commandStartTime:r,compileStartTime:n}){let i=e.commandStartTime===r,o=e.prepareDurations,a=e.builderInitStartTime,s=e.appInfoDurationMs,l=e.appInfoMeasured;i&&void 0!==a&&(o.builderInitMs=Math.max(0,n-a)),aC(e,r),e.scene=t,e.compileStartTime=n,i&&(e.prepareDurations=o,e.appInfoDurationMs=s,e.appInfoMeasured=l)}function aI(e,t,r){e.compilePhaseEndTimes[t]=Math.max(e.compilePhaseEndTimes[t]??0,r)}function aP(e){return Math.max(0,Math.round(Number.isFinite(e)?e:0))}let ak=new class{uploader;constructor(e){this.uploader=e}async report(e){try{var t,r;let n,i,o,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 ar(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:(n=e.context.signingEncryptionOptions,i=!!n?.signing.enabled,o=!!n?.encryption.enabled,i&&o?"signing_and_encryption":i?"signing":o?"encryption":"none"),durations:(t=e.context.compileLifecycle,r=e.compileEndTime,a=t.commandStartTime??r,s=t.compileStartTime??r,l=Math.min(r,Math.max(s,t.compilePhaseEndTimes.moduleProcess??r)),p=Math.min(r,Math.max(l,t.compilePhaseEndTimes.assetProcess??r)),{totalMs:r-a,prepareMs:s-a,compileMs:r-s,...t.prepareDurations,appInfoMs:t.appInfoDurationMs,appTemplateProcessMs:t.appTemplateProcessDurationMs,viewTemplateProcessMs:t.viewTemplateProcessDurationMs,moduleProcessMs:l-s,assetProcessMs:p-l,outputWriteMs:r-p})};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.uploader??=new ed).upload(function(e,t){let r={kit_compile_id:function(){let e="unknown";try{e=(0,rA.userInfo)().username||e}catch{}return`${Date.now()}_${e}_${(0,ib.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&&(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=aP(e.durations.totalMs),r.kit_prepare_ms=aP(e.durations.prepareMs),r.kit_compile_ms=aP(e.durations.compileMs),r.kit_config_load_ms=aP(e.durations.configLoadMs),r.kit_project_scan_ms=aP(e.durations.projectScanMs),r.kit_context_bootstrap_ms=aP(e.durations.contextBootstrapMs),r.kit_app_info_ms=aP(e.durations.appInfoMs),r.kit_app_template_process_ms=aP(e.durations.appTemplateProcessMs),r.kit_view_template_process_ms=aP(e.durations.viewTemplateProcessMs),r.kit_plugin_bootstrap_ms=aP(e.durations.pluginBootstrapMs),r.kit_builder_init_ms=aP(e.durations.builderInitMs),r.kit_module_process_ms=aP(e.durations.moduleProcessMs),r.kit_asset_process_ms=aP(e.durations.assetProcessMs),r.kit_output_write_ms=aP(e.durations.outputWriteMs);else{r.kit_error_type=function(e){let t=aS(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(aw.has(t))return"network_error";if(av.has(t))return"filesystem_error"}let r="string"==typeof e?e:aS(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/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)/i.test(r))return"config_error";if(/loader/i.test(r))return"loader_error";if(/plugin/i.test(r))return"plugin_error";let n=aS(e,"name");return n&&aE[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,iL.stripVTControlCharacters)(i).replaceAll(tn.resolve(n),"<project>").replaceAll((0,rA.homedir)(),"<home>").replace(/\s+/g," ").trim().slice(0,1024));e&&(r.kit_error_message=e)}}return{name:"kit_compile",params:r}}(r,{appDirectory:t,kitVersion:aA.rE,runEnv:process.env.BUILD_VERSION?"SCM":process.env.CI_REPO_NAME?"CI":"LOCAL"}))}};function aD(e,t,r){r?.hasErrors()?ak.report({appDirectory:e.appDirectory,context:e,scene:t,status:"failed",errorStage:"compile",error:ax(r)[0]}):ak.report({appDirectory:e.appDirectory,context:e,scene:t,status:"success",compileEndTime:Date.now()})}let a$=f("crypto");class aN{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,a$.createHash("sha256").update("string"==typeof e?e:new DataView(e.buffer,e.byteOffset,e.byteLength)).digest("hex").substring(0,8))}}class aR extends aN{constructor(e,t){super(e,t),this._manifest={applet:{pages:[],tools:[]},widgets:[]};try{this._manifest=eo(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){eo(this._manifest,e)}setSCMVersion(e){this._manifest.scmVersion=e}setVersionCode(e){this._manifest.versionCode=e}setAppletManifest(e){this._manifest.applet=e}mergeAppletManifest(e){eo(this._manifest.applet,e)}setRenderType(e=M.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 aL{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 aM{options;constructor(e){this.options=e}apply(e){let t,{pluginSystem:r}=this.options;e.hooks.thisCompilation.tap({name:aM.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},n=>{n.hooks.processAssets.tapPromise({name:aM.name,stage:e.rspack.Compilation.PROCESS_ASSETS_STAGE_REPORT},async()=>{t=new aL,n.getAssets().forEach(e=>{let r=new aN(e.name,e.source.source(),e.info.contenthash?.[0]);t.addAsset(e.name,r)});let{entrypoints:i}=n,o={};i.forEach((e,r)=>{o[r]=e.getFiles().map(e=>{let r=t.getAsset(e);if(!r)throw Error(`Asset ${e} not found`);return new aN(r.source,r.content,r.hashCode)})});let a=this.options.context.appId;a&&tr.mkdirSync(tn.join(this.options.context.rootPath,a),{recursive:!0}),await r.callAssetsHooks("beforeEmit",{assets:t,chunks:o}),Object.keys(t.getAssets()).forEach(r=>{let i=t.getAsset(r);if(!i)return;let{source:o,destination:a}=i;if(!o||!a)return;n.getAsset(o)?n.renameAsset(o,a):n.emitAsset(a,new e.rspack.sources.RawSource(i.content));let s=n.getAsset(`${o}.map`);s&&n.renameAsset(s.name,`${a}.map`)}),await r.callAssetsHooks("afterEmit",{assets:{...t.getAssets()}})})})}}let aj=new Set(["@doubao-dev/template","@byted-doubao-apps/template"]);class aU{options;constructor(e){this.options=e}apply(e){e.hooks.thisCompilation.tap(aU.name,e=>{e.hooks.finishModules.tap(aU.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&&aj.has(r))return!0;let n=(t=e.resource,t?.split(/[?#]/)[0].replace(/\\/g,"/"));return[...aj].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 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 aF(e){return e.replaceAll("\\","/")}function aW(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 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,r;let n=this.context.metadata.getData(),i=this.context.command===eR.DEV?"all":"configured",o=r_(this.context.pages,this.context.normalizedAppConfig.pages.entries,i),a=r_(this.context.widgets,this.context.normalizedAppConfig.widgets.entries,i),s=n.app.appId||this.context.appId;if(!s&&Object.keys(o).length>0)throw Error("appId is required to resolve Web page entry paths");s&&(e=n.pages,Object.keys(o).forEach(r=>{let n=aF(r),i=rg(n);aW(t,`${i}/template.js`,re(s,e[r]?.path??t7(n),rm),`${i}/background.js.map`)})),r=n.widgets,Object.keys(a).forEach(e=>{var n;let i=rg(aF(e));aW(t,`${i}/template.js`,(n=ry(a,r,e),`${n}/${rm}`),`${i}/background.js.map`)})})})}}class aV{entry;constructor(e){this.entry=e}apply(e){let t=new e.webpack.experiments.VirtualModulesPlugin;t.apply(e),e.hooks.thisCompilation.tap(aV.name,()=>{t.writeModule(eY,""),t.writeModule(eX,eZ),Object.values(this.entry).forEach(e=>{t.writeModule(e.filename,e.toString())})})}}function aG(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:void 0}let aq={templatesByEntry:{},templatesByWidget:{}},aJ="/doubao-apps-framework.template.js",aK="/doubao-apps-api.template.js",az=(e,t)=>{let r=(r,n,i)=>{var o;return o=(r=>{if(!t)return r;let n="0.0.43-rc.12";return e||!n?`/wsd${r}`:`/web-sdk/${encodeURIComponent(n)}/wsd${r}`})(r),{libraryName:i,url:o,background:{sectionPath:n},mainThread:{sectionPath:`${n}__main-thread`},async:!!t}};return{"@byted-doubao-apps/bridge-base":r(aK,"api"),"@byted-doubao-apps/open-api":r(aK,"api"),...Object.fromEntries(Object.entries(e5).map(([t,n])=>[t,r(e?"/doubao-apps-react-dev.template.js":"/doubao-apps-react.template.js","reactLynx",["reactLynx",n])])),[`${ti}/api`]:r(aK,"api"),[`${to}/api`]:r(aK,"api"),[ti]:r(aJ,"framework"),[to]:r(aJ,"framework"),"@byted-doubao-apps/components":r(aJ,"components"),[ts(ti)]:r(aJ,"components"),[ts(to)]:r(aJ,"components")}},aY=f("node:url"),aX=(0,S.createRequire)(import.meta.url);function aZ(e,t){for(let r of e)try{return aX.resolve(r,{paths:t})}catch{}throw Error(`Cannot resolve package from candidates: ${e.join(", ")}`)}class aQ{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,o;let{appDirectory:a,command:p,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=p===eR.DEV,_=await this.createEntry(),w=tp(a),v=[a,tn.dirname((0,aY.fileURLToPath)(import.meta.url))],E=aX.resolve("@lynx-js/react/transform"),x=b?"all":"configured",A=r_(e.context.pages,e.context.normalizedAppConfig.pages.entries,x),T=new Set([...Object.keys(r_(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,x)),...Object.keys(A)]);if(e.web&&0===T.size)throw Error(b?"No Web entries are available. Add page/widget entries under src/pages or src/widgets.":"No Web entries are configured. Add `web: true` to page/widget entries in src/app.config.ts.");e.web&&await r7({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":"({})"}},O=e=>[eY,eX,e.filename],I={...C,entry:Object.fromEntries(Object.entries(_).map(([e,t])=>[e,O(t)]))},k=Object.fromEntries(Object.entries(_).filter(([e])=>T.has(e))),D=new Map(Object.keys(k).map(e=>[rg(e),e])),$={...I,entry:Object.fromEntries(Object.entries(k).map(([e,t])=>[rg(e),O(t)])),define:{...I.define,__DOUBAO_APPS_WEB__:JSON.stringify(!0),__LYNXVIEW__:JSON.stringify(!0)}},N=[...tu()?[]:[q({externals:az(b),globalObject:"lynx"})]],R=[function({metadata:e,resolveAppInfo:t}){return{name:"ai-manifest-plugin",setup(r){r.modifyBundlerChain((r,n)=>{let i=n?.environment?.name==="web"?rc:rd;r.plugin(ru.name).use(ru,[{metadata:e,resolveAppInfo:t,shouldInjectAsset:i}])})}}}({metadata:h,resolveAppInfo:()=>e.context.resolveAppInfo()})],L={source:I,plugins:N},M=[function e({metadata:t,entry:r,resolveSigningEncryptionOptions:n,onProcessDuration:i}){return{name:e.name,setup(e){e.modifyBundlerChain((o,a)=>{if(a?.environment?.name==="web")return;let s=e.useExposed(Symbol.for("LynxTemplatePlugin"));o.plugin(np.name).use(np,[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(aU,[{markTemplateWidgetEntry:t=>{e.addTemplateWidgetEntry(t)},normalizeEntryName:e=>t?.(e,i)}])})}}}({context:e.context,normalizeEntryName:(e,t)=>"web"===t?D.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(aM,[n])})}}),...p===eR.DEV&&e.web?[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,S.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))],o=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,tr.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}),a=o.getTypeChecker(),s=Object.fromEntries(Object.entries(t).map(([e,{filename:t}])=>{let r,i=o.getSourceFile(t);return[P(e),i?(r={},!function e(t){if(n.isCallExpression(t)&&("getViewData"===aG(n,t.expression)||"useViewData"===aG(n,t.expression))&&t.typeArguments?.[0]){let e=a.getTypeFromTypeNode(t.typeArguments[0]);for(let i of a.getPropertiesOfType(e)){let o=i.valueDeclaration??i.declarations?.[0]??t;r[i.getName()]=function e(t,r,n,i,o){let a=(r.isUnion()?r.types:[r]).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=>n.isArrayType(e)||n.isTupleType(e)))return[];let s=a.find(e=>e.flags&t.TypeFlags.Object);if(!s||o.has(s))return{};o.add(s);let l=Object.fromEntries(n.getPropertiesOfType(s).map(r=>{let a=r.valueDeclaration??r.declarations?.[0]??i;return[r.getName(),e(t,n.getTypeOfSymbolAtLocation(r,a),n,a,o)]}));return o.delete(s),l}(n,a.getTypeOfSymbolAtLocation(i,o),a,o,new Set([e]))}}n.forEachChild(t,e)}(i),r):{}]})),l=Object.fromEntries(Object.keys(t).map(e=>{let n=P(e);return[ry(t,r,e),s[n]??{}]}));return{templatesByEntry:s,templatesByWidget:l}}(e.appDirectory,e.widgets,e.metadata.getData().widgets)}catch{t=aq}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(ag)}}})),t.onAfterDevCompile(async({stats:o})=>{if(o.hasErrors()||n)return;let{devServer:a}=t.context;if(!a)return;n=!0;let s=await tD({debugDriver:e.userConfig.debugDriver,skipAdbForegroundAppWatch:e.userConfig.skipAdbForegroundAppWatch}).catch(nc);i||await af({context:e,port:a.port,driver:s,isSigned:e.isSignedEncryption,onCleanupReady(e){i?e():r=e}})}),t.onCloseDevServer(()=>{i=!0,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,()=>{aI(e.compileLifecycle,"moduleProcess",Date.now())}),n.hooks.emit.tap(t,()=>{aI(e.compileLifecycle,"assetProcess",Date.now())}),n.hooks.failed.tap(t,t=>{ak.report({appDirectory:e.appDirectory,context:e,scene:e.compileLifecycle.scene??(e.command===eR.DEV?"dev_initial":e.command),status:"failed",errorStage:"compile",error:t})})}),e.command!==eR.DEV){let t=e.command;r.onBeforeBuild(()=>{let r=Date.now();aO(e.compileLifecycle,{scene:t,commandStartTime:e.compileLifecycle.commandStartTime??r,compileStartTime:r})}),r.onAfterBuild(({stats:r})=>{aD(e,t,r)})}else r.onBeforeDevCompile(({isFirstCompile:t})=>{let r=Date.now();aO(e.compileLifecycle,{scene:t?"dev_initial":"hot_update",commandStartTime:t?e.compileLifecycle.commandStartTime??r:r,compileStartTime:r})}),r.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}=aX(aZ(["@byted/rsdoctor"],v));for(let r of e)r.plugins??=[],r.plugins.push(new t({disableClientServer:!0,supports:{banner:!0}}))})}}]:[],(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(aB,[{pluginSystem:n,context:i}])})}}),(({getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o})=>({name:"lynx:encode-worker",async setup(a){tm()||a.modifyBundlerChain((a,s)=>{s?.environment?.name!=="web"&&a.plugin(nl.name).use(nl,[{getAppAssetPath:e,getAppMapAssetPath:t,engineVersion:r,metadata:n,resolveSigningEncryptionOptions:i,onProcessDuration:o}]).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(aV.name).use(aV,[k])})}},(o=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=o.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),o=i?aF(n):aF(e).replace(/^\/+/,"");return`${i?"file":"webpack"}:///${o}${t}`},e}),e.plugin(aH.name).use(aH,[o])}}})}})],U=d({mode:p===eR.DEV?"development":"production",environments:e.web?{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:[q({externals:az(p===eR.DEV,!0),globalObject:"lynx"})]}}:{lynx:L},tools:{rspack:{module:{rules:[{enforce:"pre",test:/\.(t|j)sx$/,loader:function(e,t,r=tn.join(tn.dirname((0,aY.fileURLToPath)(import.meta.url)),"components-loader.js"),n=aZ){try{return n(t===to?["@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,tr.existsSync)(r))return r;throw e}}(v,w),options:{frameworkPackage:w}}]},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:{host:nn()},dev:{writeToDisk:tc(),hmr:p===eR.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:tc(),...tu()&&!y?{chunkSplit:{strategy:"split-by-experience"}}:{}},...y?{splitChunks:!1}:{},plugins:[{name:"replace-lynx-react-alias",setup(e){er({LAYERS:s,lazy:!1,rootPath:tn.dirname((0,aY.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:w,oldRuntimePkg:[],legacySlot:!0},enableCSSInheritance:!0,shake:{pkgName:[...ta]}}),{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 transform loader not found for layer: ${e}`);t.tap(e=>({...e,transformPath:E}))}})}},function(e){let{compilerOptionsKeys:t=rC.compilerOptionsKeys,configKeys:r=rC.configKeys,validate:n=rz,dslPluginName2PkgName:i=rY,upgradeRspeedyLink:o="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(a=>{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(`\
186
186
  [pluginLynxConfig] No \`LynxTemplatePlugin\` exposed to ${rB("the plugin API","https://rsbuild.rs/plugins/dev/core#apiexpose")}.
187
187
 
188
188
  Please upgrade ${e} to latest version.
189
189
 
190
190
  See ${rB(rJ().yellow("Upgrade Rspeedy"),o)} for more details.
191
- `)}let{LynxTemplatePlugin:l}=s;a.plugin("lynx:config").use(rH,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:r}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableSimultaneousTap:!0,enableReloadLifecycle:!0}),m(),u(),...e.web?[]:N,...R,...M,...e.web?j:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:U}),U}}async function a0(e,t){let r=new aQ(t),n=await r.createConfig({config:e}),i=await p({rspeedyConfig:n,cwd:e.context.appDirectory});return i.removePlugins(["lynx:react-alias"]),i}async function a1(e,t){var r;let{entry:n}=await rl({config:e,pluginSystem:t});return await a0({...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,o;let a;("lynx"===t.name||"web"===t.name)&&(n=e,i=r,o=t.name,n.entry??={},a=n.entry,Object.entries(i.entry).forEach(([e,t])=>{a[e]={filename:"web"===o?`${e}.js`:`base/${e}${tm()?".js":".template.js"}`,import:"web"===o&&"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 rx(r,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new rw))})}})]},t)}function a3(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 a2=e=>{try{return tr.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function a4({internal:e,appKey:t}){try{return await ic({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw tA.error("Failed to get KEK",{error:e,appKey:t,operation:"get-kek"}),e}}async function a5(e,t,r,n){if(!(n||td("DISABLE_SIGNING_ENCRYPTION")||td("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===eR.DEPLOY){if(!r)throw Error("appId is required to get KEK");let{data:e}=await a4({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 a9=eK.join("node_modules",".doubao-dev","config.json");function a8(e,t,r){if(r){let t=eK.isAbsolute(r)?r:eK.resolve(e,r);if(t3.existsSync(t))return t;tx.warn("Cannot find config file",{path:t})}for(let r of e7.map(r=>eK.resolve(e,`${t}${r}`)))if(a2(r))return r;return!1}async function a6(e){let t=(0,E.createJiti)((0,aY.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function a7({cwd:e=process.cwd(),customConfigFile:t}){let r=a8(e,"doubao.config",t);if(!r)return{};try{return await a6(r)}catch(e){throw tx.error("Failed to load config file",{path:r}),e}}async function se({cwd:e=process.cwd()}={}){let t=a8(eK.resolve(e,"src"),e6);if(t)try{return await a6(t)}catch(e){throw tx.error("Failed to load app config file",{path:t}),e}}async function st(e){let t=globalThis,r=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),n=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await a6(e)}finally{r?t.defineAppConfig=n:delete t.defineAppConfig}}async function sr({cwd:e=process.cwd()}={}){let t=a8(eK.resolve(e,"src"),e6);if(t)try{let e=await st(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 tx.error("Failed to load Taro app config file",{path:t}),e}}let sn=f("fs/promises"),si=async(e,t=eK.basename(e))=>{if(!t3.existsSync(e))return{};let r={};for(let n of(await sn.readdir(e))){let i=eK.resolve(e,n);if(!t3.statSync(i).isDirectory())continue;let o=eK.resolve(i,"index.tsx");t3.existsSync(o)&&(r[`${t}/${n}/index`]={folderName:`${n}/index`,renderType:M.REACT_LYNX,filename:o})}return r},so=async(e,t=eK.basename(e))=>{if(!t3.existsSync(e))return{viewEntries:{},apiEntries:{}};let r=await si(e,t),n={},i=eK.resolve(e,"login.ts");t3.existsSync(i)&&(n[`${t}/login`]={filename:i,folderName:e});let o=eK.resolve(e,"privacy.ts");return t3.existsSync(o)&&(n[`${t}/privacy`]={filename:o,folderName:e}),{viewEntries:r,apiEntries:n}},sa=async(e,t)=>t3.existsSync(e)?(await sn.readdir(e)).reduce((r,n)=>{let i=eK.resolve(e,n);return t3.statSync(i).isDirectory()&&t3.existsSync(eK.resolve(i,t))&&(r[n]=eK.resolve(i,t)),r},{}):{};function ss(e){return tn.resolve(e,"app.ts")}function sl(e,t,r,n){let i=`${r}/`;if(!t.startsWith(i))throw Error(`${r} config key must start with "${i}": ${t}`);let o=t.slice(i.length),a=tn.resolve(e,r,`${o}${n}`);if(!tr.existsSync(a))throw Error(`Configured entry file does not exist for ${t}: ${a}`);return{relativeEntry:o,filename:a}}function sp(e,t){let r=t.entries[e]?.name;if(void 0===r)return t6(e);if("string"!=typeof r||!r.trim())throw Error(`Configured Tool name must be a non-empty string: ${e}`);return r.trim()}let sd=async(e,t={entryNames:[],entries:{}})=>{let r=tn.resolve(e,"tools"),n={...await sa(r,"index.ts")};t.entryNames.forEach(r=>{let{filename:i}=sl(e,r,"tools",".ts"),o=sp(r,t),a=n[o];if(a&&a!==i)throw Error(`Tool name "${o}" is already used by another entry: ${a}`);n[o]=i});let i=ss(e);return{tools:n,app:tr.existsSync(i)?i:void 0}},sc=async(e,t)=>{let r=tn.resolve(e,"pages"),n=tn.resolve(e,"widgets"),i=tn.resolve(e,"auth"),o=tn.resolve(e,"mcp-ui"),[a,s,l,p]=await Promise.all([si(r),si(n),so(o),so(i)]),d=Object.keys(p.viewEntries).length>0||Object.keys(p.apiEntries).length>0?p:l,c=t.pages,u=t.widgets,m=(t,r,n)=>{let i={...t};return r.forEach(t=>{if(i[t])return;let{relativeEntry:r,filename:o}=sl(e,t,n,".tsx");i[t]={folderName:r,renderType:M.REACT_LYNX,filename:o,isVirtualFile:!1}}),i},h=m(a,c.entryNames,"pages");return{widgets:m(s,u.entryNames,"widgets"),pages:h,auth:d}};function su(e,t,r=!1,n=!1){let i=tp(t);return Object.keys(e).reduce((o,a)=>{let{filename:s}=e[a],l=n&&e[a].isLoginPage?"defineLoginPage":n?"definePage":"defineWidget",p=`${ez}${tn.sep}${a}${tn.extname(s)}`,d=rr(tn.join(t,p,".."),s);return o[a]=new rn(p),o[a].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]},{moduleSpecifier:i,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]}),o[a].appendContent(`
191
+ `)}let{LynxTemplatePlugin:l}=s;a.plugin("lynx:config").use(rH,[{LynxTemplatePlugin:l,config:e,compilerOptionsKeys:t,configKeys:r}])})}}}({enableMultiTouch:!0,enableNewGesture:!0,enableCSSInlineVariables:!0,enableSimultaneousTap:!0,enableReloadLifecycle:!0}),m(),u(),...e.web?[]:N,...R,...M,...e.web?j:[]]});return await this.pluginSystem.callViewHooks("beforeBuild",{buildConfig:U}),U}}async function a0(e,t){let r=new aQ(t),n=await r.createConfig({config:e}),i=await p({rspeedyConfig:n,cwd:e.context.appDirectory});return i.removePlugins(["lynx:react-alias"]),i}async function a1(e,t){var r;let{entry:n}=await rl({config:e,pluginSystem:t});return await a0({...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,o;let a;("lynx"===t.name||"web"===t.name)&&(n=e,i=r,o=t.name,n.entry??={},a=n.entry,Object.entries(i.entry).forEach(([e,t])=>{a[e]={filename:"web"===o?`${e}.js`:`base/${e}${tm()?".js":".template.js"}`,import:"web"===o&&"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 rx(r,"lynx"===t.name)),"web"===t.name&&e.plugins.push(new rw))})}})]},t)}function a2(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 a3=e=>{try{return tr.statSync(e,{throwIfNoEntry:!1})?.isFile()}catch(e){return!1}};async function a4({internal:e,appKey:t}){try{return await ic({internal:e,path:`/developer/resource_api/apps/${encodeURIComponent(t)}/dek/public_key`})}catch(e){throw tA.error("Failed to get KEK",{error:e,appKey:t,operation:"get-kek"}),e}}async function a5(e,t,r,n){if(!(n||td("DISABLE_SIGNING_ENCRYPTION")||td("LEGACY_FRAMEWORK"))){if(e)return e;if("production"===process.env.NODE_ENV&&t===eR.DEPLOY){if(!r)throw Error("appId is required to get KEK");let{data:e}=await a4({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 a9=eK.join("node_modules",".doubao-dev","config.json");function a8(e,t,r){if(r){let t=eK.isAbsolute(r)?r:eK.resolve(e,r);if(t2.existsSync(t))return t;tx.warn("Cannot find config file",{path:t})}for(let r of e7.map(r=>eK.resolve(e,`${t}${r}`)))if(a3(r))return r;return!1}async function a6(e){let t=(0,E.createJiti)((0,aY.fileURLToPath)(import.meta.url),{requireCache:!1,interopDefault:!0});return await t.import(e,{default:!0})}async function a7({cwd:e=process.cwd(),customConfigFile:t}){let r=a8(e,"doubao.config",t);if(!r)return{};try{return await a6(r)}catch(e){throw tx.error("Failed to load config file",{path:r}),e}}async function se({cwd:e=process.cwd()}={}){let t=a8(eK.resolve(e,"src"),e6);if(t)try{return await a6(t)}catch(e){throw tx.error("Failed to load app config file",{path:t}),e}}async function st(e){let t=globalThis,r=Object.prototype.hasOwnProperty.call(t,"defineAppConfig"),n=t.defineAppConfig;t.defineAppConfig=e=>e;try{return await a6(e)}finally{r?t.defineAppConfig=n:delete t.defineAppConfig}}async function sr({cwd:e=process.cwd()}={}){let t=a8(eK.resolve(e,"src"),e6);if(t)try{let e=await st(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 tx.error("Failed to load Taro app config file",{path:t}),e}}let sn=f("fs/promises"),si=async(e,t=eK.basename(e))=>{if(!t2.existsSync(e))return{};let r={};for(let n of(await sn.readdir(e))){let i=eK.resolve(e,n);if(!t2.statSync(i).isDirectory())continue;let o=eK.resolve(i,"index.tsx");t2.existsSync(o)&&(r[`${t}/${n}/index`]={folderName:`${n}/index`,renderType:M.REACT_LYNX,filename:o})}return r},so=async(e,t=eK.basename(e))=>{if(!t2.existsSync(e))return{viewEntries:{},apiEntries:{}};let r=await si(e,t),n={},i=eK.resolve(e,"login.ts");t2.existsSync(i)&&(n[`${t}/login`]={filename:i,folderName:e});let o=eK.resolve(e,"privacy.ts");return t2.existsSync(o)&&(n[`${t}/privacy`]={filename:o,folderName:e}),{viewEntries:r,apiEntries:n}},sa=async(e,t)=>t2.existsSync(e)?(await sn.readdir(e)).reduce((r,n)=>{let i=eK.resolve(e,n);return t2.statSync(i).isDirectory()&&t2.existsSync(eK.resolve(i,t))&&(r[n]=eK.resolve(i,t)),r},{}):{};function ss(e){return tn.resolve(e,"app.ts")}function sl(e,t,r,n){let i=`${r}/`;if(!t.startsWith(i))throw Error(`${r} config key must start with "${i}": ${t}`);let o=t.slice(i.length),a=tn.resolve(e,r,`${o}${n}`);if(!tr.existsSync(a))throw Error(`Configured entry file does not exist for ${t}: ${a}`);return{relativeEntry:o,filename:a}}function sp(e,t){let r=t.entries[e]?.name;if(void 0===r)return t6(e);if("string"!=typeof r||!r.trim())throw Error(`Configured Tool name must be a non-empty string: ${e}`);return r.trim()}let sd=async(e,t={entryNames:[],entries:{}})=>{let r=tn.resolve(e,"tools"),n={...await sa(r,"index.ts")};t.entryNames.forEach(r=>{let{filename:i}=sl(e,r,"tools",".ts"),o=sp(r,t),a=n[o];if(a&&a!==i)throw Error(`Tool name "${o}" is already used by another entry: ${a}`);n[o]=i});let i=ss(e);return{tools:n,app:tr.existsSync(i)?i:void 0}},sc=async(e,t)=>{let r=tn.resolve(e,"pages"),n=tn.resolve(e,"widgets"),i=tn.resolve(e,"auth"),o=tn.resolve(e,"mcp-ui"),[a,s,l,p]=await Promise.all([si(r),si(n),so(o),so(i)]),d=Object.keys(p.viewEntries).length>0||Object.keys(p.apiEntries).length>0?p:l,c=t.pages,u=t.widgets,m=(t,r,n)=>{let i={...t};return r.forEach(t=>{if(i[t])return;let{relativeEntry:r,filename:o}=sl(e,t,n,".tsx");i[t]={folderName:r,renderType:M.REACT_LYNX,filename:o,isVirtualFile:!1}}),i},h=m(a,c.entryNames,"pages");return{widgets:m(s,u.entryNames,"widgets"),pages:h,auth:d}};function su(e,t,r=!1,n=!1){let i=tp(t);return Object.keys(e).reduce((o,a)=>{let{filename:s}=e[a],l=n&&e[a].isLoginPage?"defineLoginPage":n?"definePage":"defineWidget",p=`${ez}${tn.sep}${a}${tn.extname(s)}`,d=rr(tn.join(t,p,".."),s);return o[a]=new rn(p),o[a].appendImports({moduleSpecifier:"@lynx-js/react",importSpecifiers:[{propertyName:"root",name:"root"}]},{moduleSpecifier:d,importSpecifiers:[{propertyName:"default",name:"ViewEntry"}]},{moduleSpecifier:i,importSpecifiers:[{propertyName:"bootstrapReactLynx",name:"bootstrapReactLynx"},{propertyName:l,name:l},{propertyName:"getViewContext",name:"getViewContext"}]}),o[a].appendContent(`
192
192
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
193
193
 
194
194
  const View =
@@ -206,7 +206,7 @@ root.render(<FC />);
206
206
  if (import.meta.webpackHot) {
207
207
  import.meta.webpackHot.accept()
208
208
  }
209
- `),o},{})}let sm={name:"AuthPlugin",async setup(e){td("DISABLE_GENERATE_LOGIN_CARD")||td("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(sm.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:sm.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,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],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=tp(c),n=`${ez}${eK.sep}${eQ}${eK.sep}${e3}.tsx`,u[i=`${eQ}/${e3}`]={filename:n,renderType:M.REACT_LYNX,folderName:e3,isVirtualFile:!0,isSpecial:!0},o=new rn(n),a=eK.join(c,eK.dirname(n)),s=Object.values(d.apiEntries).find(e=>"login"===eK.parse(e.filename).name),l=Object.values(d.apiEntries).find(e=>"privacy"===eK.parse(e.filename).name),s&&o.appendImports({moduleSpecifier:rr(a,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&o.appendImports({moduleSpecifier:rr(a,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),o.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"}]}),o.appendContent(`
209
+ `),o},{})}let sm={name:"AuthPlugin",async setup(e){td("DISABLE_GENERATE_LOGIN_CARD")||td("LEGACY_FRAMEWORK")||(e.view.hooks.modifyEnvironment.tapPromise(sm.name,async({environment:e})=>{e.useAuth=!0}),e.view.hooks.modifyEntryOption.tapPromise({name:sm.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,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],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=tp(c),n=`${ez}${eK.sep}${eQ}${eK.sep}${e2}.tsx`,u[i=`${eQ}/${e2}`]={filename:n,renderType:M.REACT_LYNX,folderName:e2,isVirtualFile:!0,isSpecial:!0},o=new rn(n),a=eK.join(c,eK.dirname(n)),s=Object.values(d.apiEntries).find(e=>"login"===eK.parse(e.filename).name),l=Object.values(d.apiEntries).find(e=>"privacy"===eK.parse(e.filename).name),s&&o.appendImports({moduleSpecifier:rr(a,s.filename),importSpecifiers:[{propertyName:"default",name:"loginApi"}]}),l&&o.appendImports({moduleSpecifier:rr(a,l.filename),importSpecifiers:[{propertyName:"default",name:"privacyApi"}]}),o.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"}]}),o.appendContent(`
210
210
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
211
211
 
212
212
  const View = definePrivacyLoginWidget({
@@ -228,7 +228,7 @@ root.render(<FC />);
228
228
  if (import.meta.webpackHot) {
229
229
  import.meta.webpackHot.accept()
230
230
  }
231
- `:""),{[i]:o}),su(m,c,p,!0)),e.context.appendWidgets(u),{entry:t}}))}};(eC=eU||(eU={}))[eC.DISABLED=0]="DISABLED",eC[eC.ENABLED=1]="ENABLED";let sh="AppletDoubaoAppInfoPlugin",sf={name:sh,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sh,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==eR.DEV&&e.context.command!==eR.BUILD&&e.context.command!==eR.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===eU.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:tj(r.iconUrl)})}})}},sg={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:sg.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,{isDev:a,appDirectory:s}=e.context,l={};return t=Object.assign(t,(r=tp(s),n=`${ez}${eK.sep}${eQ}${eK.sep}${e2}.tsx`,l[i=`${eQ}/${e2}`]={filename:n,renderType:M.REACT_LYNX,folderName:e2,isVirtualFile:!0,isSpecial:!0},(o=new rn(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"}]}),o.appendContent(`
231
+ `:""),{[i]:o}),su(m,c,p,!0)),e.context.appendWidgets(u),{entry:t}}))}};(eC=eU||(eU={}))[eC.DISABLED=0]="DISABLED",eC[eC.ENABLED=1]="ENABLED";let sh="AppletDoubaoAppInfoPlugin",sf={name:sh,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sh,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-1},async({assets:t})=>{if(e.context.command!==eR.DEV&&e.context.command!==eR.BUILD&&e.context.command!==eR.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===eU.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:tj(r.iconUrl)})}})}},sg={name:"ExpiredWidgetPlugin",async setup(e){e.view.hooks.modifyEntryOption.tapPromise({name:sg.name,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:t})=>{let r,n,i,o,{isDev:a,appDirectory:s}=e.context,l={};return t=Object.assign(t,(r=tp(s),n=`${ez}${eK.sep}${eQ}${eK.sep}${e3}.tsx`,l[i=`${eQ}/${e3}`]={filename:n,renderType:M.REACT_LYNX,folderName:e3,isVirtualFile:!0,isSpecial:!0},(o=new rn(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"}]}),o.appendContent(`
232
232
  const viewId = __LEPUS__ ? '' : getViewContext()?.viewId ?? '';
233
233
 
234
234
  const View = defineWidget({
@@ -245,7 +245,7 @@ root.render(<FC />);
245
245
  if (import.meta.webpackHot) {
246
246
  import.meta.webpackHot.accept()
247
247
  }
248
- `:""),{[i]:o})),e.context.appendWidgets(l),{entry:t}})}},sy="LynxPlugin",sb={name:sy,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(sy,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:sy,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:r})=>{let{appDirectory:n,isDev:i,widgets:o,pages:a}=e.context;return t=r=Object.assign(r,su(o,n,i),su(a,n,i,!0)),{entry:r}}),e.view.hooks.collectMetaData.tapPromise({name:sy,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:r})=>{let{normalizedAppConfig:n,userConfig:i,widgets:o,pages:a}=e.context;await r7({widgets:o,pages:a,entries:t,collector:r,normalizedAppConfig:n,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:sy,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:r,pages:n,app:i}=e.context.metadata.getInstance(),o=e.context.templateWidgetEntries;Object.keys(r).forEach(n=>{let i=r[n],a=`${n}/template.js`,s=t.getAsset(a);if(i&&s){let r=`${i.metadata.id}/template.js`;s.destination=r;let a=t.getManifestAsset(e.context.manifestAssetPath),l=i.toManifest(r,s.hashCode,M.LYNX);o.has(n)&&(l.titleType=U.NONE),a.appendWidget(l)}}),Object.keys(n).forEach(r=>{let o=n[r],a=`${r}/template.js`,s=t.getAsset(a);if(o&&s){let r=re(i.metadata.appId,o.metadata.path,"template.js");s.destination=r,t.getManifestAsset(e.context.manifestAssetPath).appendPage(o.toManifest(r,s.hashCode,M.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(sy,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(sy,async({stats:e})=>{})}};async function s_(e,t,r){let{app:n,tools:i,collector:o,define:a}=r,s=i[t],l=e;(s||n===t)&&(a&&Object.keys(a).length>0&&(l=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),el((0,r5.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(rX(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(r1(t)){for(let e of t.properties)if(r2(e)&&rX(e.key)&&"aiMeta"===e.key.value){let t=r4(e.value);s?o.addToolMeta(s,t):o.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function sw({tools:e,app:t,collector:r,define:n,appConfig:i}){let o={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})}),t3.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&t3.existsSync(e)).map(e=>s_(t3.readFileSync(e,"utf-8"),e,o))):tx.warn("App file does not exist",{path:t});let a=r.app,s=i?.appId??a.appId;if(!s)throw Error("appId is required in app config or AI metadata");r.addAppMeta({...a,name:i?.name??a.name,description:i?.description??a.description,icons:i?.icons??a.icons,keywords:i?.keywords??a.keywords,version:i?.version??a.version,darkMode:i?.darkMode??a.darkMode,chat:i?.chat??a.chat,appId:s})}let sv={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var r,n,i;let o,{app:a,tools:s}=e.context,l=Object.fromEntries((r=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=sp(e,r),n=s[t];if(!n)throw Error(`Configured Tool entry was not analyzed: ${e}`);return[t,n]}));return Object.assign(t,{app:(n=`${e.context.appDirectory}${tn.sep}${ez}${tn.sep}app.js`,o=(({dirname:e,app:t,tools:r})=>{let n=[],i=[],o=tp(eK.resolve(t,"..",".."));Object.entries(r).forEach(([t,r],o)=>{let a=JSON.stringify(t);n.push(`import Tool${o} from "${rr(e,r)}";`),i.push(`toAppRuntimeTool(Tool${o}, ${a})`)});let a=i.length>0?`function toAppRuntimeTool(tool, id) {
248
+ `:""),{[i]:o})),e.context.appendWidgets(l),{entry:t}})}},sy="LynxPlugin",sb={name:sy,async setup(e){e.view.hooks.modifyEnvironment.tapPromise(sy,async({environment:e})=>{e.useLynx=!0});let t={};e.view.hooks.modifyEntryOption.tapPromise({name:sy,stage:e.view.MODIFY_ENTRY_OPTION_STAGE_CREATE_BASE},async({entry:r})=>{let{appDirectory:n,isDev:i,widgets:o,pages:a}=e.context;return t=r=Object.assign(r,su(o,n,i),su(a,n,i,!0)),{entry:r}}),e.view.hooks.collectMetaData.tapPromise({name:sy,stage:e.view.COLLECT_METADATA_STAGE_PROCESS_METADATA},async({collector:r})=>{let{normalizedAppConfig:n,userConfig:i,widgets:o,pages:a}=e.context;await r7({widgets:o,pages:a,entries:t,collector:r,normalizedAppConfig:n,define:i.source?.define})}),e.assets.hooks.beforeEmit.tapPromise({name:sy,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_VIEW_ASSETS},async({assets:t})=>{let{widgets:r,pages:n,app:i}=e.context.metadata.getInstance(),o=e.context.templateWidgetEntries;Object.keys(r).forEach(n=>{let i=r[n],a=`${n}/template.js`,s=t.getAsset(a);if(i&&s){let r=`${i.metadata.id}/template.js`;s.destination=r;let a=t.getManifestAsset(e.context.manifestAssetPath),l=i.toManifest(r,s.hashCode,M.LYNX);o.has(n)&&(l.titleType=U.NONE),a.appendWidget(l)}}),Object.keys(n).forEach(r=>{let o=n[r],a=`${r}/template.js`,s=t.getAsset(a);if(o&&s){let r=re(i.metadata.appId,o.metadata.path,"template.js");s.destination=r,t.getManifestAsset(e.context.manifestAssetPath).appendPage(o.toManifest(r,s.hashCode,M.LYNX))}})}),e.assets.hooks.afterEmit.tapPromise(sy,async({assets:e})=>{}),e.view.hooks.afterBuild.tapPromise(sy,async({stats:e})=>{})}};async function s_(e,t,r){let{app:n,tools:i,collector:o,define:a}=r,s=i[t],l=e;(s||n===t)&&(a&&Object.keys(a).length>0&&(l=Object.keys(a).reduce((e,t)=>{let r=a[t];if("string"==typeof r)return e.replaceAll(t,r);throw Error(`Define value ${t} is not a string`)},e)),el((0,r5.parseSync)(l,{syntax:"typescript",tsx:!0,decorators:!0}),{CallExpression(e){if(rX(e.callee)&&["defineTool","defineApp"].includes(e.callee.value)){let t=e.arguments[0]?.expression;if(r1(t)){for(let e of t.properties)if(r3(e)&&rX(e.key)&&"aiMeta"===e.key.value){let t=r4(e.value);s?o.addToolMeta(s,t):o.addAppMeta({...t,appId:t.appId??t.package})}}}}}))}async function sw({tools:e,app:t,collector:r,define:n,appConfig:i}){let o={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})}),t2.existsSync(t)?await Promise.all(Object.values({...e,app:t}).filter(e=>/\.(ts|tsx|jsx|js)$/i.test(e)&&t2.existsSync(e)).map(e=>s_(t2.readFileSync(e,"utf-8"),e,o))):tx.warn("App file does not exist",{path:t});let a=r.app,s=i?.appId??a.appId;if(!s)throw Error("appId is required in app config or AI metadata");r.addAppMeta({...a,name:i?.name??a.name,description:i?.description??a.description,icons:i?.icons??a.icons,keywords:i?.keywords??a.keywords,version:i?.version??a.version,darkMode:i?.darkMode??a.darkMode,chat:i?.chat??a.chat,appId:s})}let sv={name:"AppletMainPlugin",setup:async e=>{e.context.app&&(e.worker.hooks.modifyEntryOption.tapPromise("AppletMainPlugin",async({entry:t})=>{var r,n,i;let o,{app:a,tools:s}=e.context,l=Object.fromEntries((r=e.context.normalizedAppConfig.tools).entryNames.map(e=>{let t=sp(e,r),n=s[t];if(!n)throw Error(`Configured Tool entry was not analyzed: ${e}`);return[t,n]}));return Object.assign(t,{app:(n=`${e.context.appDirectory}${tn.sep}${ez}${tn.sep}app.js`,o=(({dirname:e,app:t,tools:r})=>{let n=[],i=[],o=tp(eK.resolve(t,"..",".."));Object.entries(r).forEach(([t,r],o)=>{let a=JSON.stringify(t);n.push(`import Tool${o} from "${rr(e,r)}";`),i.push(`toAppRuntimeTool(Tool${o}, ${a})`)});let a=i.length>0?`function toAppRuntimeTool(tool, id) {
249
249
  return typeof tool === 'object' &&
250
250
  tool !== null &&
251
251
  '__FUNCTIONAL__' in tool &&
@@ -278,7 +278,7 @@ import { bootstrapClientToolRuntime } from "${n}";
278
278
  ${i.join("\n")}
279
279
 
280
280
  bootstrapClientToolRuntime([${o.join(", ")}]);
281
- `}({appDirectory:e.context.appDirectory,clientTools:l,dirname:tn.dirname(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:o}=e.context;await sw({appConfig:n,tools:i,app:r,collector:t,define:o.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:o,pages:a,tools:s}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),p=r[e9]?.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=o.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=o.toManifest({toolsMetadata:s,hashCode:l?.hashCode??(n=l?.hashCode??c?.applet?.digest,i=u.join(""),a$.createHash("sha256").update(n+i).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})=>{}))}},sE={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,r=ss(t);if(!tr.existsSync(r))throw Error("ENOENT: no such file or directory")}},sS={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:o}=i,{buffer:a,status:s,error_msg:l}=await n(Buffer.from(i.content),rt(r,{extra_config:{app_id:o.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let p=new aN(e1,a);p.destination=e1,t.addAsset(e1,p)}})}},sx="AppletWebManifestPlugin",sA={name:sx,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sx,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var r,n;let i=e.context.metadata.getData(),o=i.app.appId||e.context.appId,a=e.context.command===eR.DEV?"all":"configured",s=r_(e.context.pages,e.context.normalizedAppConfig.pages.entries,a),l=r_(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,a);if(!o&&Object.keys(s).length>0)throw Error("appId is required to resolve Web page entry paths");let p=o?(r=i.pages,Object.keys(s).map(e=>{let t=r[e]??{},n=t.path??t7(e),i={entry:re(o,n,rm)},a=rb(s[e]);return{path:n,entryName:e,web:i,debugHidden:a,manifest:{...t,path:n,digest:"",entry:"",renderType:M.LYNX,web:i,...a?{debugHidden:!0}:{}}}})):[],d=(n=i.widgets,Object.keys(l).map(e=>{let{id:t,...r}=n[e]??{},i=t??ry(l,n,e),o={entry:`${i}/${rm}`},a=rb(l[e]);return{id:i,entryName:e,web:o,debugHidden:a,manifest:{...r,widgetId:i,digest:"",entry:"",renderType:M.LYNX,web:o,...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 r=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(r.titleType=U.NONE),c.appendWidget(r)}e.context.app&&(c.manifest.applet.web={appRuntimeEntry:rh,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:rf}:{}})})}};function sT(e=((e=process.cwd())=>tl(e)===ti)()){return e?"sso":"sms"}async function sC(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sT(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function sO(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sT(t)})}function sI(e,t){let r;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))r=e;else if("object"==typeof e)t&&tx.warn(`${t} config object map is deprecated. Use an array of strings or { entry, ...metadata } objects instead.`),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("Entry config must be an array or object map.");let n=[],i={},o=new Set,a=[],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 config object must include "entry".');t=n,r=i}o.has(t)?s.has(t)||(a.push(t),s.add(t)):(n.push(t),o.add(t)),i[t]=r}),t&&a.length>0&&tx.warn(`${t} config contains duplicate entries: ${a.join(", ")}. Entries are deduplicated, and the last metadata config takes effect.`),{entryNames:n,entries:i}}class sP{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:o=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=r,this._srcDirectory=n,this._virtualEntryDir=i,this._appDirectory=o,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===eR.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(tr.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 e0}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 sk({internal:e,domainId:t,appLimit:r,appOffset:n,keyWord:i,appKey:o,cookie:a}){return await ic({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:r,app_offset:n,key_word:i,app_key:o},method:"GET",headers:a?{Cookie:a}:void 0})}async function sD({source:e,internal:t,domainId:r,appLimit:n,appOffset:i,releaseStatus:o,keyWord:a,appKey:s,cookie:l}){return await ic({internal:t,domainId:r,path:"/developer/api/apps",query:{source:e,app_limit:n,app_offset:i,release_status:o,key_word:a,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function s$({appKey:e,source:t,internal:r,domainId:n,releaseStatus:i,limit:o,offset:a,status:s,keyWord:l,versionTag:p,cookie:d}){return await ic({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:i,limit:o,offset:a,status:s,key_word:l,version_tag:p},method:"GET",headers:d?{Cookie:d}:void 0})}async function sN({appKey:e,versionTag:t,internal:r,domainId:n,pageSize:i,pageNum:o,cookie:a}){return await ic({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:i,page_num:o},method:"GET",headers:a?{Cookie:a}:void 0})}function sR(e){return e.is_latest||e.is_current}function sL(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function sM(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function sj(e){return e.version_tag}function sU(e,t){tc()&&tx.info(e,t)}async function sB({appKey:e,internal:t=!1,cookie:r,source:n=eH.REQUEST_SOURCE_IDE}){sU("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:r?"present":"absent"});let i=await sk({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 sU("[app-info] MGetApps 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),i}).catch(t=>{if(sU("[app-info] MGetApps 请求失败",{appKey:e,reason:a3(t)}),an(t))throw t}),o=i?void 0:await sD({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),o=i||n[0];return sU("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),o?.app_meta}).catch(t=>{sU("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:a3(t)})});if(!i&&!o)throw sU("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let a=i?void 0:await s$({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(sU("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:n.length,logId:r}),0===n.length)return;let i=n.find(sR);return i||n.reduce((e,t)=>{let r,n;return!e||(r=sL(t),n=sL(e),(Number.isNaN(r)&&Number.isNaN(n)?sM(t)-sM(e):(Number.isNaN(r)?-1/0:r)-(Number.isNaN(n)?-1/0:n))>0)?t:e},void 0)}).catch(t=>{sU("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:a3(t)})}),s=i?.current_version_tag||(a?sj(a):""),l=i?.icon_url||(a?a.icon_url:void 0)||o?.icon_url,p=i?.name||o?.name,d=a&&sj(a)===s?a: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:p,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:d};let c=await sN({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:r}).then(t=>(sU("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw sU("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:a3(t)}),t});return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:c.data?.permission_list||[],permissionTotal:c.data?.total||0,version:d}}function sF(){return function({fetch:e,getCacheKey:t,ttl:r,timeout:n,cacheFailures:i=!1,now:o=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=o(),m=a.get(c);if(m&&m.expiresAt>u)return m.promise;let h=(p=e(...s),void 0===n?p:Promise.race([p,new Promise((e,t)=>{d=setTimeout(()=>{t(Error(`Request timed out after ${n}ms`))},n)})]).finally(()=>{d&&clearTimeout(d)})).catch(e=>{throw i||a.get(c)?.promise!==h||a.delete(c),e});return a.set(c,{expiresAt:u+r,promise:h}),h}}({fetch:sB,getCacheKey:({appKey:e,internal:t,cookie:r})=>[e,t,r],ttl:6e4,timeout:1e4,cacheFailures:!0})}(eO=eB||(eB={}))[eO.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",eO[eO.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(eI=eF||(eF={}))[eI.DRAFT=0]="DRAFT",eI[eI.UNDER_REVIEW=1]="UNDER_REVIEW",eI[eI.APPROVED=2]="APPROVED",eI[eI.REJECTED=3]="REJECTED",eI[eI.WITHDRAWN=4]="WITHDRAWN",eI[eI.PUBLISHING=5]="PUBLISHING",eI[eI.PUBLISHED=6]="PUBLISHED",eI[eI.ARCHIVED=7]="ARCHIVED",eI[eI.DELETED=8]="DELETED",(eP=eW||(eW={}))[eP.DRAFT=0]="DRAFT",eP[eP.PUBLISHED=1]="PUBLISHED",eP[eP.ARCHIVED=2]="ARCHIVED",(ek=eH||(eH={}))[ek.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",ek[ek.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",ek[ek.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",ek[ek.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class sW extends sP{devServerInteractive=!0;getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=aT();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=sF();_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(!ar(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!==eR.DEV&&this.command!==eR.BUILD)throw e;if(an(e))return n;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,tx.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:a3(e)})),n}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:r,userConfig:n,appConfig:i={},normalizedAppConfig:o={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:w=!0,env:v={},loginCookieResolver:E,cachedLoginCookieResolver:S}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:tn.resolve(t,ez),rootPath:r,manifestPath:tn.resolve(`${r}/${e0}`),command:a,metadata:s,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:E,cachedLoginCookieResolver:S});let{icons:x,...A}=i??{};this._userConfig=n,this.devServerInteractive=w,this._env={...v},this._appConfig={...A,...void 0!==d?{appId:d}:{},...void 0!==x?{icons:tj(x)}:{}},this._normalizedAppConfig=o,this._internal=y??((e=process.cwd())=>tl(e)===ti)(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??i?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=sF()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await a5(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(),tc()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function sH({appId:e,versionTag:t,versionCode:r,packagePath:n,internal:i,domainId:o,cookie:a,token:s,needAuth:l=!0}){let p=new FormData,d=new Blob([new Uint8Array(tr.readFileSync(n))],{type:"application/zip"});p.append("applet_file",d,"doubao_app.zip"),p.append("applet_version_code",r.toString());let c=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await ic({internal:i,domainId:s?"sms-external":o,path:c,method:"POST",body:p,headers:{...a?{Cookie:a}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function sV({versionTag:e,appKey:t,manifest:r,rootPath:n,internal:i,needAuth:o=!0,cookie:a,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:p,versionCode:d}=r,c=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 t5({channelName:"doubao_app",manifest:r,rootPath:n});if(!u)throw Error("Failed to archive package");let m=await sH({appId:t||l||p,versionTag:c,versionCode:d,packagePath:u.resource,internal:i,needAuth:o,cookie:a,token:s});return console.log("Deploy success:",m),m}let sG=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),sq="x-db-llm-modifiable",sJ="x-db-is-entity-id",sK="x-db-is-refresh-key",sz=["entity_type"];function sY(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sX(e,t,r){if(!sY(e))throw Error(`Tool "${r}" requires an object ${t}`);return e}function sZ(e,t,r,n,i=!1){let o=`Tool "${t}" ${r} property "${n}"`;if(!sY(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${o} requires a string type`);let a=e.type.trim(),s=e[sq];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${o} ${sq} must be a boolean`);if(s&&"outputSchema"!==r)throw Error(`${o} ${sq} is only supported in outputSchema`);if(s&&"array"!==a)throw Error(`${o} ${sq} is only supported for array fields`);let l=e[sJ];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${o} ${sJ} must be a boolean`);if(l&&!i)throw Error(`${o} ${sJ} is only supported on top-level card output fields`);let p=e[sK];if(void 0!==p&&"boolean"!=typeof p)throw Error(`${o} ${sK} must be a boolean`);if(p&&!i)throw Error(`${o} ${sK} 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,o),...s?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===a){if(!sY(e.properties))throw Error(`${o} requires object properties`);if(d.properties=Object.fromEntries(Object.entries(e.properties).map(([e,i])=>[e,sZ(i,t,r,`${n}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${o} required must be a string array`);d.required=e.required}}if("array"===a){if(!sY(e.items))throw Error(`${o} requires object array items`);d.items=sZ(e.items,t,r,`${n}[]`)}return d}function sQ(e,t,r){let n=e[t];if(void 0===n)return{};if(!sY(n))throw Error(`manifest.yaml ${t} must be an object: ${r}`);return{...n}}function s0(e,t){if(!tr.existsSync(e)||!tr.statSync(e).isFile())throw Error(`${t} does not exist: ${e}`);return tr.readFileSync(e,"utf8")}class s1{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),o={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tj(t.appIcon)}:{}},a={pages:sI(o?.pages,"pages"),tools:sI(o?.tools,"tools"),widgets:sI(o?.widgets,"widgets")},s=function(e){let t=tn.join(e,"events.json");if(tr.existsSync(t)&&tr.statSync(t).isFile())return{readJson:()=>tr.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let r=tn.join(e,"tools.json");if(!tr.existsSync(r))return;let n=tn.join(e,"manifest.yaml"),i=()=>s0(r,"tools.json"),o=()=>(function({tools:e,manifestPath:t,manifestText:r}){let n=function(e,t){let r;try{r=(0,sG.qg)(e)}catch(e){throw Error(`Failed to parse manifest.yaml: ${t}`,{cause:e})}if(!sY(r))throw Error(`manifest.yaml must contain an object: ${t}`);return r}(r,t),i=sQ(n,"tools",t),o=sQ(n,"entities",t);for(let t of e){if(t.name in i)throw Error(`Tool "${t.name}" conflicts with a tool in manifest.yaml`);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||!sY(e.properties))throw Error(`Tool "${t}" inputSchema requires type object and object properties`);let r=Object.fromEntries(Object.entries(e.properties).map(([e,r])=>[e,sZ(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 must be a string array`);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 o)throw Error(`Tool "${t.name}" conflicts with an entity in manifest.yaml`);o[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let r=t.name;if("array"!==e.type||!sY(e.items))throw Error(`Card Tool "${r}" outputSchema must be an array`);if("object"!==e.items.type||!sY(e.items.properties))throw Error(`Card Tool "${r}" outputSchema items must be objects`);let n=e.items.properties,i=sz.find(e=>e in n);if(i)throw Error(`Tool "${r}" outputSchema must not declare reserved field "${i}"`);let o=Object.entries(n).filter(([e,t])=>{if(!sY(t)||void 0===t[sJ])return!1;if("boolean"!=typeof t[sJ])throw Error(`Tool "${r}" outputSchema property "${e}" ${sJ} must be a boolean`);return t[sJ]});if(1!==o.length)throw Error(`Card Tool "${r}" outputSchema requires exactly one ${sJ} field; found ${o.length}`);let a=Object.entries(n).filter(([e,t])=>{if(!sY(t)||void 0===t[sK])return!1;if("boolean"!=typeof t[sK])throw Error(`Tool "${r}" outputSchema property "${e}" ${sK} must be a boolean`);return t[sK]});if("same_conversation"===t.expirePolicy){let e=o[0]?.[0];if(1!==a.length||a[0]?.[0]!==e)throw Error(`Card Tool "${r}" with expirePolicy "same_conversation" requires ${sK} on its ${sJ} field`)}return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,sZ(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,sG.As)({...n,tools:i,entities:o})})({tools:(()=>{let e=function(e,t){let r;try{r=JSON.parse(e)}catch(e){throw Error(`Failed to parse tools.json: ${t}`,{cause:e})}if(!sY(r)||!Array.isArray(r.tools)||0===r.tools.length)throw Error(`tools.json requires a non-empty tools array: ${t}`);let n=new Set;return{tools:r.tools.map((e,r)=>{let i=function(e,t,r){if(!sY(e))throw Error(`Tool at index ${t} must be an object: ${r}`);let n="string"==typeof e.name?e.name.trim():"",i="string"==typeof e.description?e.description.trim():"";if(!n||!i)throw Error(`Tool at index ${t} requires name and description: ${r}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${n}" tool_type must be "client" or "server"`);let o=function(e,t){if(void 0===e)return{};if(!sY(e))throw Error(`Tool "${t}" _meta must be an object`);if(void 0===e.ui)return{};if(!sY(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 r=e.ui.widgetId;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error(`Tool "${t}" _meta.ui.widgetId must be a non-empty string`);let n=e.ui.expirePolicy;if(void 0!==n&&"same_conversation"!==n)throw Error(`Tool "${t}" _meta.ui.expirePolicy must be "same_conversation" when provided`);if("same_conversation"===n&&"string"!=typeof r)throw Error(`Tool "${t}" _meta.ui.expirePolicy requires _meta.ui.widgetId`);return{..."string"==typeof r?{widgetId:r.trim()}:{},..."same_conversation"===n?{expirePolicy:n}:{}}}(e._meta,n);return{name:n,description:i,...o,inputSchema:sX(e.inputSchema,"inputSchema",n),outputSchema:sX(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 must be an array of non-empty strings`);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(`Duplicate Tool name: ${i.name}`);return n.add(i.name),i})}}(i(),r);var n=e.tools;let o=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??t6(e)));for(let e of n)if(e.widgetId&&!o.has(e.widgetId))throw Error(`Tool "${e.name}" references widgetId "${e.widgetId}" not declared in app.config.ts`);return e})().tools,manifestPath:n,manifestText:s0(n,"manifest.yaml")});return o(),{manifestSourcePath:n,readManifestYaml:o,readToolsJson:i,toolsSourcePath:r}}({appDirectory:this.appDirectory,normalizedAppConfig:a}),p=function(e){if(e)return!0===e?{mcpEndpoint:th()}:{...e,mcpEndpoint:th({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),d=Date.now()-n;this.rootPath=eK.resolve(this.appDirectory,"dist"),tr.existsSync(eK.resolve(this.rootPath))&&tr.rmSync(eK.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new sW,aC(this.context.compileLifecycle,n),this.context.compileLifecycle.prepareDurations.configLoadMs=d;let c=eK.resolve(this.appDirectory,"src"),u=Date.now(),{pages:m,widgets:h,auth:f,app:g,tools:y}=await this.analyzeConvention(c,a),b=e===eR.DEV||Object.values(a.pages.entries).some(e=>!0===e.web)||Object.values(a.widgets.entries).some(e=>!0===e.web)||a.tools.entryNames.length>0;this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let _=new tq,w=((e=process.cwd())=>tl(e)===ti)(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:c,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:i,env:this._env,appConfig:o,normalizedAppConfig:a,command:e,metadata:_,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:w,devServerInteractive:t.interactive,loginCookieResolver:()=>sC(t,{internal:w}),cachedLoginCookieResolver:()=>sO(t,w)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,this.context.webDebuggerLaunchOptions=p,this.context.eventsResources=s,this.context.toolsResources=l,this.pluginSystem=new t1(this.context,[sv,sb,sE,sm,sA,sf,sS,sg,...i.experiments?.taro?[function({name:e,appId:t,icons:r,widgets:n}){return{name:ra,setup:i=>{let o=(0,ro.createRequire)(import.meta.url);i.view.hooks.modifyEntryOption.tapPromise({name:ra,stage:i.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:r,pages:n,widgets:o}=i.context,a=ri(n,t,!1,r);return{entry:e=Object.assign(e,a,ri(o,t,!0,r))}}),i.view.hooks.beforeBuild.tapPromise({name:ra,stage:i.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=i.context;rt(e,{resolve:{alias:{"@tarojs/components":o.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eK.dirname)(o.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),i.worker.hooks.modifyEntryOption.tapPromise({name:ra,stage:i.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:r})=>{let{appDirectory:n,isDev:o}=i.context,{app:a}=i.context;return a&&(r.app=function(e,t,r,n,i=!1){var o;let a=`${ez}${tn.sep}app.js`,s=(o=rr(tn.dirname(a),e)).startsWith(".")?o:`./${o}`,l=tp(t);return new rn(a,`
281
+ `}({appDirectory:e.context.appDirectory,clientTools:l,dirname:tn.dirname(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:o}=e.context;await sw({appConfig:n,tools:i,app:r,collector:t,define:o.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:o,pages:a,tools:s}=e.context.metadata.getInstance(),l=t.getAsset(e.context.appAssetPath),p=r[e9]?.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=o.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=o.toManifest({toolsMetadata:s,hashCode:l?.hashCode??(n=l?.hashCode??c?.applet?.digest,i=u.join(""),a$.createHash("sha256").update(n+i).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})=>{}))}},sE={name:"AppletMainEntryCheckPlugin",setup:async e=>{let{srcDirectory:t}=e.context,r=ss(t);if(!tr.existsSync(r))throw Error("ENOENT: no such file or directory")}},sS={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:o}=i,{buffer:a,status:s,error_msg:l}=await n(Buffer.from(i.content),rt(r,{extra_config:{app_id:o.appId,bundle_id:""},output_mode:"sign_block"}));if(0!==s)throw Error(l);let p=new aN(e1,a);p.destination=e1,t.addAsset(e1,p)}})}},sx="AppletWebManifestPlugin",sA={name:sx,setup:async e=>{e.assets.hooks.beforeEmit.tapPromise({name:sx,stage:e.assets.BEFORE_EMIT_STAGE_PROCESS_MANIFEST_ASSETS-2},async({assets:t})=>{var r,n;let i=e.context.metadata.getData(),o=i.app.appId||e.context.appId,a=e.context.command===eR.DEV?"all":"configured",s=r_(e.context.pages,e.context.normalizedAppConfig.pages.entries,a),l=r_(e.context.widgets,e.context.normalizedAppConfig.widgets.entries,a);if(!o&&Object.keys(s).length>0)throw Error("appId is required to resolve Web page entry paths");let p=o?(r=i.pages,Object.keys(s).map(e=>{let t=r[e]??{},n=t.path??t7(e),i={entry:re(o,n,rm)},a=rb(s[e]);return{path:n,entryName:e,web:i,debugHidden:a,manifest:{...t,path:n,digest:"",entry:"",renderType:M.LYNX,web:i,...a?{debugHidden:!0}:{}}}})):[],d=(n=i.widgets,Object.keys(l).map(e=>{let{id:t,...r}=n[e]??{},i=t??ry(l,n,e),o={entry:`${i}/${rm}`},a=rb(l[e]);return{id:i,entryName:e,web:o,debugHidden:a,manifest:{...r,widgetId:i,digest:"",entry:"",renderType:M.LYNX,web:o,...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 r=t.manifest;e.context.templateWidgetEntries.has(t.entryName)&&(r.titleType=U.NONE),c.appendWidget(r)}e.context.app&&(c.manifest.applet.web={appRuntimeEntry:rh,...e.context.normalizedAppConfig.tools.entryNames.length>0?{toolRuntimeEntry:rf}:{}})})}};function sT(e=((e=process.cwd())=>tl(e)===ti)()){return e?"sso":"sms"}async function sC(e={},t={}){if(e.cookie)return e.cookie;let{ensureLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sT(t.internal),browser:e.loginBrowser,browserPath:e.loginBrowserPath,force:t.force})}async function sO(e,t){if(e.cookie)return e.cookie;let{getCachedLoginCookie:r}=await import("./@byted-doubao-apps/login.js");return await r({route:sT(t)})}function sI(e,t){let r;if(!e)return{entryNames:[],entries:{}};if(Array.isArray(e))r=e;else if("object"==typeof e)t&&tx.warn(`${t} config object map is deprecated. Use an array of strings or { entry, ...metadata } objects instead.`),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("Entry config must be an array or object map.");let n=[],i={},o=new Set,a=[],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 config object must include "entry".');t=n,r=i}o.has(t)?s.has(t)||(a.push(t),s.add(t)):(n.push(t),o.add(t)),i[t]=r}),t&&a.length>0&&tx.warn(`${t} config contains duplicate entries: ${a.join(", ")}. Entries are deduplicated, and the last metadata config takes effect.`),{entryNames:n,entries:i}}class sP{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:o=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=r,this._srcDirectory=n,this._virtualEntryDir=i,this._appDirectory=o,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===eR.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(tr.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 e0}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 sk({internal:e,domainId:t,appLimit:r,appOffset:n,keyWord:i,appKey:o,cookie:a}){return await ic({internal:e,domainId:t,path:"/app_developer/api/apps",query:{app_limit:r,app_offset:n,key_word:i,app_key:o},method:"GET",headers:a?{Cookie:a}:void 0})}async function sD({source:e,internal:t,domainId:r,appLimit:n,appOffset:i,releaseStatus:o,keyWord:a,appKey:s,cookie:l}){return await ic({internal:t,domainId:r,path:"/developer/api/apps",query:{source:e,app_limit:n,app_offset:i,release_status:o,key_word:a,app_key:s},method:"GET",headers:l?{Cookie:l}:void 0})}async function s$({appKey:e,source:t,internal:r,domainId:n,releaseStatus:i,limit:o,offset:a,status:s,keyWord:l,versionTag:p,cookie:d}){return await ic({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/version`,query:{source:t,release_status:i,limit:o,offset:a,status:s,key_word:l,version_tag:p},method:"GET",headers:d?{Cookie:d}:void 0})}async function sN({appKey:e,versionTag:t,internal:r,domainId:n,pageSize:i,pageNum:o,cookie:a}){return await ic({internal:r,domainId:n,path:`/developer/api/apps/${encodeURIComponent(e)}/permission/versions/${encodeURIComponent(t)}/permission_list`,query:{page_size:i,page_num:o},method:"GET",headers:a?{Cookie:a}:void 0})}function sR(e){return e.is_latest||e.is_current}function sL(e){return Date.parse(e.updated_at??e.created_at??e.online_at??"")}function sM(e){return Number(e.version_code??e.qr_data?.artifact_version_code)}function sj(e){return e.version_tag}function sU(e,t){tc()&&tx.info(e,t)}async function sB({appKey:e,internal:t=!1,cookie:r,source:n=eH.REQUEST_SOURCE_IDE}){sU("[app-info] 开始获取应用信息",{appKey:e,internal:t,session:r?"present":"absent"});let i=await sk({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 sU("[app-info] MGetApps 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),i}).catch(t=>{if(sU("[app-info] MGetApps 请求失败",{appKey:e,reason:a2(t)}),an(t))throw t}),o=i?void 0:await sD({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),o=i||n[0];return sU("[app-info] MGetAppsDeprecated 请求完成",{appKey:e,appCount:n.length,exactMatch:!!i,logId:r}),o?.app_meta}).catch(t=>{sU("[app-info] MGetAppsDeprecated 请求失败",{appKey:e,reason:a2(t)})});if(!i&&!o)throw sU("[app-info] 应用信息查询结束,未找到可用结果",{appKey:e}),Error(`未找到应用 ${e}`);let a=i?void 0:await s$({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(sU("[app-info] MGetAppVersions 请求完成",{appKey:e,versionCount:n.length,logId:r}),0===n.length)return;let i=n.find(sR);return i||n.reduce((e,t)=>{let r,n;return!e||(r=sL(t),n=sL(e),(Number.isNaN(r)&&Number.isNaN(n)?sM(t)-sM(e):(Number.isNaN(r)?-1/0:r)-(Number.isNaN(n)?-1/0:n))>0)?t:e},void 0)}).catch(t=>{sU("[app-info] MGetAppVersions 请求失败",{appKey:e,reason:a2(t)})}),s=i?.current_version_tag||(a?sj(a):""),l=i?.icon_url||(a?a.icon_url:void 0)||o?.icon_url,p=i?.name||o?.name,d=a&&sj(a)===s?a: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:p,versionTag:s,iconUrl:l,permissionList:[],permissionTotal:0,version:d};let c=await sN({appKey:e,versionTag:s,pageSize:1e3,pageNum:1,internal:t,cookie:r}).then(t=>(sU("[app-info] FetchAppPermissionList 请求完成",{appKey:e,versionTag:s,permissionTotal:t.data?.total||0,logId:t.log_id}),t)).catch(t=>{throw sU("[app-info] FetchAppPermissionList 请求失败",{appKey:e,versionTag:s,reason:a2(t)}),t});return{appKey:e,appName:p,versionTag:s,iconUrl:l,permissionList:c.data?.permission_list||[],permissionTotal:c.data?.total||0,version:d}}function sF(){return function({fetch:e,getCacheKey:t,ttl:r,timeout:n,cacheFailures:i=!1,now:o=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=o(),m=a.get(c);if(m&&m.expiresAt>u)return m.promise;let h=(p=e(...s),void 0===n?p:Promise.race([p,new Promise((e,t)=>{d=setTimeout(()=>{t(Error(`Request timed out after ${n}ms`))},n)})]).finally(()=>{d&&clearTimeout(d)})).catch(e=>{throw i||a.get(c)?.promise!==h||a.delete(c),e});return a.set(c,{expiresAt:u+r,promise:h}),h}}({fetch:sB,getCacheKey:({appKey:e,internal:t,cookie:r})=>[e,t,r],ttl:6e4,timeout:1e4,cacheFailures:!0})}(eO=eB||(eB={}))[eO.APP_TYPE_MINI_APP=0]="APP_TYPE_MINI_APP",eO[eO.APP_TYPE_NATIVE=1]="APP_TYPE_NATIVE",(eI=eF||(eF={}))[eI.DRAFT=0]="DRAFT",eI[eI.UNDER_REVIEW=1]="UNDER_REVIEW",eI[eI.APPROVED=2]="APPROVED",eI[eI.REJECTED=3]="REJECTED",eI[eI.WITHDRAWN=4]="WITHDRAWN",eI[eI.PUBLISHING=5]="PUBLISHING",eI[eI.PUBLISHED=6]="PUBLISHED",eI[eI.ARCHIVED=7]="ARCHIVED",eI[eI.DELETED=8]="DELETED",(eP=eW||(eW={}))[eP.DRAFT=0]="DRAFT",eP[eP.PUBLISHED=1]="PUBLISHED",eP[eP.ARCHIVED=2]="ARCHIVED",(ek=eH||(eH={}))[ek.REQUEST_SOURCE_PLATFORM=0]="REQUEST_SOURCE_PLATFORM",ek[ek.REQUEST_SOURCE_IDE=1]="REQUEST_SOURCE_IDE",ek[ek.REQUEST_SOURCE_DEVICE=2]="REQUEST_SOURCE_DEVICE",ek[ek.REQUEST_SOURCE_OP_PLATFORM=3]="REQUEST_SOURCE_OP_PLATFORM";class sW extends sP{devServerInteractive=!0;getWidgetViewDataTemplates;webDebuggerLaunchOptions;compileLifecycle=aT();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=sF();_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(!ar(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!==eR.DEV&&this.command!==eR.BUILD)throw e;if(an(e))return n;return this._hasWarnedAppInfoFetchFailure||(this._hasWarnedAppInfoFetchFailure=!0,tx.warn("从平台获取 Doubao 应用信息失败,将使用本地 `app.config.ts` 配置的数据",{reason:a2(e)})),n}}async bootstrap({srcDirectory:e,appDirectory:t,rootPath:r,userConfig:n,appConfig:i={},normalizedAppConfig:o={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:w=!0,env:v={},loginCookieResolver:E,cachedLoginCookieResolver:S}){await super.bootstrap({srcDirectory:e,appDirectory:t,virtualEntryDir:tn.resolve(t,ez),rootPath:r,manifestPath:tn.resolve(`${r}/${e0}`),command:a,metadata:s,versionTag:c,pages:u,widgets:m,auth:h,app:f,tools:g,loginCookieResolver:E,cachedLoginCookieResolver:S});let{icons:x,...A}=i??{};this._userConfig=n,this.devServerInteractive=w,this._env={...v},this._appConfig={...A,...void 0!==d?{appId:d}:{},...void 0!==x?{icons:tj(x)}:{}},this._normalizedAppConfig=o,this._internal=y??((e=process.cwd())=>tl(e)===ti)(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??i?.appId,this._dek=Buffer.from(""),this._fetchCachedAppInfo=sF()}async resolveSigningEncryptionOptionsOnce(){let e=this._appId??this.metadata.appId;if(this._signingEncryptionOptions=await a5(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(),tc()&&console.log("DEK base64:",Buffer.from(this.dek.buffer,this.dek.byteOffset,this.dek.byteLength).toString("base64"))}return this.signingEncryptionOptions}}async function sH({appId:e,versionTag:t,versionCode:r,packagePath:n,internal:i,domainId:o,cookie:a,token:s,needAuth:l=!0}){let p=new FormData,d=new Blob([new Uint8Array(tr.readFileSync(n))],{type:"application/zip"});p.append("applet_file",d,"doubao_app.zip"),p.append("applet_version_code",r.toString());let c=`/developer/${l?"resource_api":"resource_internal_api"}/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/package/upload_applet`;return await ic({internal:i,domainId:s?"sms-external":o,path:c,method:"POST",body:p,headers:{...a?{Cookie:a}:{},...s?{"X-Developer-Open-Build-Token":s}:{}},auth:l&&!s})}async function sV({versionTag:e,appKey:t,manifest:r,rootPath:n,internal:i,needAuth:o=!0,cookie:a,token:s}){process.env.NODE_ENV="production";let{appId:l,packageName:p,versionCode:d}=r,c=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 t5({channelName:"doubao_app",manifest:r,rootPath:n});if(!u)throw Error("Failed to archive package");let m=await sH({appId:t||l||p,versionTag:c,versionCode:d,packagePath:u.resource,internal:i,needAuth:o,cookie:a,token:s});return console.log("Deploy success:",m),m}let sG=f("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js"),sq="x-db-llm-modifiable",sJ="x-db-is-entity-id",sK="x-db-is-refresh-key",sz=["entity_type"];function sY(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sX(e,t,r){if(!sY(e))throw Error(`Tool "${r}" requires an object ${t}`);return e}function sZ(e,t,r,n,i=!1){let o=`Tool "${t}" ${r} property "${n}"`;if(!sY(e)||"string"!=typeof e.type||!e.type.trim())throw Error(`${o} requires a string type`);let a=e.type.trim(),s=e[sq];if(void 0!==s&&"boolean"!=typeof s)throw Error(`${o} ${sq} must be a boolean`);if(s&&"outputSchema"!==r)throw Error(`${o} ${sq} is only supported in outputSchema`);if(s&&"array"!==a)throw Error(`${o} ${sq} is only supported for array fields`);let l=e[sJ];if(void 0!==l&&"boolean"!=typeof l)throw Error(`${o} ${sJ} must be a boolean`);if(l&&!i)throw Error(`${o} ${sJ} is only supported on top-level card output fields`);let p=e[sK];if(void 0!==p&&"boolean"!=typeof p)throw Error(`${o} ${sK} must be a boolean`);if(p&&!i)throw Error(`${o} ${sK} 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,o),...s?{llm_modifiable:!0}:{},...l?{is_entity_id:!0}:{},..."string"==typeof e.description&&e.description.trim()?{description:e.description.trim()}:{}};if("object"===a){if(!sY(e.properties))throw Error(`${o} requires object properties`);if(d.properties=Object.fromEntries(Object.entries(e.properties).map(([e,i])=>[e,sZ(i,t,r,`${n}.${e}`)])),void 0!==e.required){if(!Array.isArray(e.required)||e.required.some(e=>"string"!=typeof e))throw Error(`${o} required must be a string array`);d.required=e.required}}if("array"===a){if(!sY(e.items))throw Error(`${o} requires object array items`);d.items=sZ(e.items,t,r,`${n}[]`)}return d}function sQ(e,t,r){let n=e[t];if(void 0===n)return{};if(!sY(n))throw Error(`manifest.yaml ${t} must be an object: ${r}`);return{...n}}function s0(e,t){if(!tr.existsSync(e)||!tr.statSync(e).isFile())throw Error(`${t} does not exist: ${e}`);return tr.readFileSync(e,"utf8")}class s1{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),o={...await this.getAppConfig(),...t.appName?{name:t.appName}:{},...t.appIcon?{icons:tj(t.appIcon)}:{}},a={pages:sI(o?.pages,"pages"),tools:sI(o?.tools,"tools"),widgets:sI(o?.widgets,"widgets")},s=function(e){let t=tn.join(e,"events.json");if(tr.existsSync(t)&&tr.statSync(t).isFile())return{readJson:()=>tr.readFileSync(t,"utf8"),sourcePath:t}}(this.appDirectory),l=function({appDirectory:e,normalizedAppConfig:t}){let r=tn.join(e,"tools.json");if(!tr.existsSync(r))return;let n=tn.join(e,"manifest.yaml"),i=()=>s0(r,"tools.json"),o=()=>(function({tools:e,manifestPath:t,manifestText:r}){let n=function(e,t){let r;try{r=(0,sG.qg)(e)}catch(e){throw Error(`Failed to parse manifest.yaml: ${t}`,{cause:e})}if(!sY(r))throw Error(`manifest.yaml must contain an object: ${t}`);return r}(r,t),i=sQ(n,"tools",t),o=sQ(n,"entities",t);for(let t of e){if(t.name in i)throw Error(`Tool "${t.name}" conflicts with a tool in manifest.yaml`);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||!sY(e.properties))throw Error(`Tool "${t}" inputSchema requires type object and object properties`);let r=Object.fromEntries(Object.entries(e.properties).map(([e,r])=>[e,sZ(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 must be a string array`);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 o)throw Error(`Tool "${t.name}" conflicts with an entity in manifest.yaml`);o[t.name]={schema:{entity_type:{type:"string",llm_visible:!1},...function(e,t){let r=t.name;if("array"!==e.type||!sY(e.items))throw Error(`Card Tool "${r}" outputSchema must be an array`);if("object"!==e.items.type||!sY(e.items.properties))throw Error(`Card Tool "${r}" outputSchema items must be objects`);let n=e.items.properties,i=sz.find(e=>e in n);if(i)throw Error(`Tool "${r}" outputSchema must not declare reserved field "${i}"`);let o=Object.entries(n).filter(([e,t])=>{if(!sY(t)||void 0===t[sJ])return!1;if("boolean"!=typeof t[sJ])throw Error(`Tool "${r}" outputSchema property "${e}" ${sJ} must be a boolean`);return t[sJ]});if(1!==o.length)throw Error(`Card Tool "${r}" outputSchema requires exactly one ${sJ} field; found ${o.length}`);let a=Object.entries(n).filter(([e,t])=>{if(!sY(t)||void 0===t[sK])return!1;if("boolean"!=typeof t[sK])throw Error(`Tool "${r}" outputSchema property "${e}" ${sK} must be a boolean`);return t[sK]});if("same_conversation"===t.expirePolicy){let e=o[0]?.[0];if(1!==a.length||a[0]?.[0]!==e)throw Error(`Card Tool "${r}" with expirePolicy "same_conversation" requires ${sK} on its ${sJ} field`)}return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,sZ(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,sG.As)({...n,tools:i,entities:o})})({tools:(()=>{let e=function(e,t){let r;try{r=JSON.parse(e)}catch(e){throw Error(`Failed to parse tools.json: ${t}`,{cause:e})}if(!sY(r)||!Array.isArray(r.tools)||0===r.tools.length)throw Error(`tools.json requires a non-empty tools array: ${t}`);let n=new Set;return{tools:r.tools.map((e,r)=>{let i=function(e,t,r){if(!sY(e))throw Error(`Tool at index ${t} must be an object: ${r}`);let n="string"==typeof e.name?e.name.trim():"",i="string"==typeof e.description?e.description.trim():"";if(!n||!i)throw Error(`Tool at index ${t} requires name and description: ${r}`);if(void 0!==e.tool_type&&"client"!==e.tool_type&&"server"!==e.tool_type)throw Error(`Tool "${n}" tool_type must be "client" or "server"`);let o=function(e,t){if(void 0===e)return{};if(!sY(e))throw Error(`Tool "${t}" _meta must be an object`);if(void 0===e.ui)return{};if(!sY(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 r=e.ui.widgetId;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error(`Tool "${t}" _meta.ui.widgetId must be a non-empty string`);let n=e.ui.expirePolicy;if(void 0!==n&&"same_conversation"!==n)throw Error(`Tool "${t}" _meta.ui.expirePolicy must be "same_conversation" when provided`);if("same_conversation"===n&&"string"!=typeof r)throw Error(`Tool "${t}" _meta.ui.expirePolicy requires _meta.ui.widgetId`);return{..."string"==typeof r?{widgetId:r.trim()}:{},..."same_conversation"===n?{expirePolicy:n}:{}}}(e._meta,n);return{name:n,description:i,...o,inputSchema:sX(e.inputSchema,"inputSchema",n),outputSchema:sX(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 must be an array of non-empty strings`);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(`Duplicate Tool name: ${i.name}`);return n.add(i.name),i})}}(i(),r);var n=e.tools;let o=new Set(t.widgets.entryNames.map(e=>t.widgets.entries[e]?.id??t6(e)));for(let e of n)if(e.widgetId&&!o.has(e.widgetId))throw Error(`Tool "${e.name}" references widgetId "${e.widgetId}" not declared in app.config.ts`);return e})().tools,manifestPath:n,manifestText:s0(n,"manifest.yaml")});return o(),{manifestSourcePath:n,readManifestYaml:o,readToolsJson:i,toolsSourcePath:r}}({appDirectory:this.appDirectory,normalizedAppConfig:a}),p=function(e){if(e)return!0===e?{mcpEndpoint:th()}:{...e,mcpEndpoint:th({mcpEndpoint:e.mcpEndpoint})}}(t.openWebDebugger),d=Date.now()-n;this.rootPath=eK.resolve(this.appDirectory,"dist"),tr.existsSync(eK.resolve(this.rootPath))&&tr.rmSync(eK.resolve(this.rootPath),{recursive:!0,force:!0}),this.context=new sW,aC(this.context.compileLifecycle,n),this.context.compileLifecycle.prepareDurations.configLoadMs=d;let c=eK.resolve(this.appDirectory,"src"),u=Date.now(),{pages:m,widgets:h,auth:f,app:g,tools:y}=await this.analyzeConvention(c,a),b=e===eR.DEV||Object.values(a.pages.entries).some(e=>!0===e.web)||Object.values(a.widgets.entries).some(e=>!0===e.web)||a.tools.entryNames.length>0;this.context.compileLifecycle.prepareDurations.projectScanMs=Date.now()-u;let _=new tq,w=((e=process.cwd())=>tl(e)===ti)(this.appDirectory),v=Date.now();await this.context.bootstrap({srcDirectory:c,appDirectory:this.appDirectory,rootPath:this.rootPath,userConfig:i,env:this._env,appConfig:o,normalizedAppConfig:a,command:e,metadata:_,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:w,devServerInteractive:t.interactive,loginCookieResolver:()=>sC(t,{internal:w}),cachedLoginCookieResolver:()=>sO(t,w)}),this.context.compileLifecycle.prepareDurations.contextBootstrapMs=Date.now()-v,this.context.webDebuggerLaunchOptions=p,this.context.eventsResources=s,this.context.toolsResources=l,this.pluginSystem=new t1(this.context,[sv,sb,sE,sm,sA,sf,sS,sg,...i.experiments?.taro?[function({name:e,appId:t,icons:r,widgets:n}){return{name:ra,setup:i=>{let o=(0,ro.createRequire)(import.meta.url);i.view.hooks.modifyEntryOption.tapPromise({name:ra,stage:i.view.MODIFY_ENTRY_OPTION_STAGE_PROCESS_ENTRY},async({entry:e})=>{let{appDirectory:t,isDev:r,pages:n,widgets:o}=i.context,a=ri(n,t,!1,r);return{entry:e=Object.assign(e,a,ri(o,t,!0,r))}}),i.view.hooks.beforeBuild.tapPromise({name:ra,stage:i.view.BEFORE_BUILD_STAGE_MODIFY_BUNDLE_CONFIG},async({buildConfig:e})=>{let{appDirectory:t}=i.context;rt(e,{resolve:{alias:{"@tarojs/components":o.resolve("@doubao-dev/taro-runtime/components",{paths:[t]}),"@tarojs/taro":(0,eK.dirname)(o.resolve("@doubao-dev/taro-runtime/package.json",{paths:[t]}))}}})}),i.worker.hooks.modifyEntryOption.tapPromise({name:ra,stage:i.worker.MODIFY_ENTRY_OPTION_STAGE_OPTIMIZE},async({entry:r})=>{let{appDirectory:n,isDev:o}=i.context,{app:a}=i.context;return a&&(r.app=function(e,t,r,n,i=!1){var o;let a=`${ez}${tn.sep}app.js`,s=(o=rr(tn.dirname(a),e)).startsWith(".")?o:`./${o}`,l=tp(t);return new rn(a,`
282
282
  import { Applet } from "${l}";
283
283
  import { defineApp } from '${l}';
284
284
  import { APP_ID, getLifecycle, setCurrentId } from '@doubao-dev/taro-runtime/internal';
@@ -323,4 +323,4 @@ if (import.meta.webpackHot) {
323
323
  import.meta.webpackHot.accept()
324
324
  }
325
325
  `:""}
326
- `)}(a,n,e,t,o)),{entry:r}}),i.worker.hooks.collectMetaData.tapPromise(ra,async({collector:n})=>{n.addAppMeta({name:e,appId:t,icons:r})}),i.view.hooks.collectMetaData.tapPromise({name:ra,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:t6(t,n),path:t7(t)})}),Object.entries(r).forEach(([t,r])=>{let i,{folderName:o}=r;e.addWidgetMeta(t,(i=t6(t,o),{...n?.[o]??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(o.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let S=await a1({options:i,commandType:e,context:this.context,web:b,rsbuildPlugins:r},this.pluginSystem);return{userConfig:i,builder:S}}catch(t){throw ak.report({appDirectory:this.appDirectory,context:this.context===n?void 0:this.context,scene:e===eR.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,{builder:r}=await this.prepare(eR.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=function({cwd:e=process.cwd()}={}){let t=eK.resolve(e,a9);if(t3.existsSync(t))try{let e=JSON.parse(t3.readFileSync(t,"utf-8"));if(!J(e))throw TypeError("Development config must be a JSON object");return e}catch(e){tx.warn("Failed to load development config file; ignoring it",{path:t,reason:a3(e)});return}}({cwd:this.appDirectory});let n=await r.startDevServer(),i=ni(n.port),o=this.context.webDebuggerLaunchOptions;try{t=o?await at(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:i,env:{...this.context.env,...o.env??{}},mcpEndpoint:o.mcpEndpoint,mcpHeaders:o.mcpHeaders,openBrowser:o.openBrowser,simulator:o.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:o.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:o.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await n.server.close(),e}let a=async()=>{tI.info("Shutting down...");try{await t?.close(),await n.server.close()}finally{await ak.flush()}tI.info("dev server closed")};return{host:i,...t?{webDebugger:t}:{},closeServer:a}}async build(e){let{builder:t}=await this.prepare(eR.BUILD,e,e.rsbuildPlugins);try{await t.build()}finally{if(e.skipCleanupRootPath||tc()){if(e.archive&&e.channel){let{channel:t}=e;await t5({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else tr.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(eR.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(eR.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(eR.DEPLOY,e),r=e.deployType||t8.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!==t8.NORMAL)return void tO.error("Please use deploy plugin in 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(),await sV({...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===t8.NORMAL)&&await t.build();try{await this.pluginSystem.callDeployHooks("deploy",{deployType:r})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case tU.DEV:return await this.dev(t);case tU.BUILD:return await this.build(t);case tU.ANALYZE:return await this.analyze(t);case tU.PERF:return await this.perf(t);case tU.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 a7({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}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await sr({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await se({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:r,widgets:n,auth:i}=await sc(e,t),{app:o,tools:a}=await sd(e,t.tools);return{pages:r,widgets:n,auth:i,app:o,tools:a}}}async function s3({appKey:e,versionTag:t,cloudBuildSource:r,runner:n,config:i,variables:o,properties:a,internal:s,domainId:l,cookie:p}){return await ic({internal:s,domainId:l,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/cloud_build/create_job`,method:"POST",body:JSON.stringify({cloud_build_source:r,runner:n,config:i,variables:o,properties:a}),headers:{"Content-Type":"application/json",...p?{Cookie:p}:{}}})}async function s2({appKey:e,jobId:t,reason:r,internal:n,domainId:i,cookie:o}){return await ic({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/cancel`,method:"POST",body:JSON.stringify({reason:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}}})}async function s4({appKey:e,jobId:t,internal:r,domainId:n,cookie:i}){return await ic({internal:r,domainId:n,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}`,method:"GET",headers:i?{Cookie:i}:void 0})}async function s5({appKey:e,jobId:t,start:r,end:n,internal:i,domainId:o,cookie:a}){return await ic({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/logs`,query:{start:r,end:n},method:"GET",headers:a?{Cookie:a}:void 0})}async function s9({appKey:e,filename:t,sha256:r,category:n,internal:i,domainId:o,cookie:a,signal:s}){return await ic({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/start`,method:"POST",body:JSON.stringify({filename:t,sha256:r,category:n}),headers:{"Content-Type":"application/json",...a?{Cookie:a}:{}},signal:s})}async function s8({appKey:e,uploadToken:t,size:r,internal:n,domainId:i,cookie:o,signal:a}){return await ic({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/finish`,method:"POST",body:JSON.stringify({upload_token:t,size:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}},signal:a})}async function s6({appId:e,category:t,filePath:r,filename:n=tn.basename(r),...i}){let o=new Uint8Array(tr.readFileSync(r)),a=(0,ib.createHash)("sha256").update(o).digest("hex"),s=(await s9({appKey:e,filename:n,sha256:a,category:t,...i})).data;if(!s?.upload_url||!s.upload_token)throw Error("File upload session is incomplete");await s7({uploadUrl:s.upload_url,body:new Blob([o]),headers:s.upload_headers||{},signal:i.signal});let l=await s8({appKey:e,uploadToken:s.upload_token,size:o.byteLength,...i});if(!l.data?.stored_file_id)throw Error("File upload finish response did not return stored_file_id");return l.data}async function s7({uploadUrl:e,body:t,headers:r,signal:n}){let i=await ip(e,{method:"PUT",body:t,headers:r,signal:n}),o=i.headers.get("x-tt-logid")||"";if(!i.ok){let e=await i.text();throw Error([`File upload failed with HTTP ${i.status}`,e?`message: ${e}`:"",o?`log_id: ${o}`:""].filter(Boolean).join(", "))}}(eD=eV||(eV={}))[eD.WAITING=0]="WAITING",eD[eD.QUEUED=1]="QUEUED",eD[eD.RUNNING=2]="RUNNING",eD[eD.PENDING=3]="PENDING",eD[eD.SUCCESS=4]="SUCCESS",eD[eD.FAIL=5]="FAIL",eD[eD.CANCELED=6]="CANCELED",eD[eD.TIMEOUT=7]="TIMEOUT",eD[eD.UNKNOWN=8]="UNKNOWN",(e$=eG||(eG={}))[e$.UNKNOWN=0]="UNKNOWN",e$[e$.SOURCE=1]="SOURCE",e$[e$.ARTIFACT=2]="ARTIFACT";let le=f("../../../node_modules/.pnpm/ora@5.4.1/node_modules/ora/index.js"),lt=new Set([eV.SUCCESS,eV.FAIL,eV.CANCELED,eV.TIMEOUT]);class lr{options;cwd;appDir;internal;env;secretEnv;appInfo;constructor(e,t){this.options=e,this.cwd=t,this.appDir=tn.resolve(e.appDir||t),(0,y.loadEnv)({cwd:this.appDir,mode:e.envMode}),this.internal=((e=process.cwd())=>tl(e)===ti)(this.appDir)}async start({versionTag:e,logs:t,runner:r,config:n,variables:i,properties:o}={}){this.resolveEnv(),this.resolveSecretEnv();let a=await this.upload();if(!a)throw Error("Cloud upload did not return stored_file_id");let s=await this.build({sourceRef:a,versionTag:e,runner:r,config:n,variables:i,properties:o});return t&&await this.waitForBuildJob({jobId:s}),s}async package({outputDir:e}={}){let t={appDir:this.appDir,internal:this.internal,outputDir:e?tn.resolve(this.cwd,e):void 0},r=await this.runWithSpinner("Preparing cloud build source...",e=>N({...t,onProgress:e}));if(this.logSourceDiagnostics(r),tC.success("Cloud build source archive created",{archivePath:r.archivePath}),r.blockers.length>0)throw Error(r.blockers.join("\n"));return r.archivePath}async upload({packOnly:e,outputDir:t}={}){if(e)return void await this.package({outputDir:t});let r={appDir:this.appDir,internal:this.internal},n=await this.resolveAppId("upload"),i=await this.resolveCookie(),o=await this.runWithSpinner("Preparing cloud build source...",e=>N({...r,onProgress:e}));if(this.logSourceDiagnostics(o),o.blockers.length>0)throw Error(o.blockers.join("\n"));let a=(await this.runWithSpinner("Uploading cloud build source...",()=>s6({appId:n,category:eG.SOURCE,filePath:o.archivePath,internal:this.internal,cookie:i}))).stored_file_id;if(!a)throw Error("Cloud build source upload did not return stored_file_id");return tC.success("Cloud build source uploaded",{storedFileId:a}),a}async build({sourceRef:e,versionTag:t,runner:r,config:n,variables:i,properties:o}={}){let a;if(!e)throw Error("Cloud build requires --source-ref.");let{appId:s,appConfig:l}=await this.resolveAppInfo();if(!s)throw Error("Cloud build requires appId in doubao.config.ts or src/app.config.ts.");try{a=JSON.parse(tr.readFileSync(tn.resolve(this.appDir,"package.json"),"utf-8")).version}catch{a=void 0}let p=t||l.version||a;if(!p)throw Error("Cloud build requires --version-tag or version in src/app.config.ts/package.json.");let d=await this.resolveCookie(),c=(await this.runWithSpinner("Creating cloud build job...",()=>s3({appKey:s,versionTag:p,cloudBuildSource:{type:"stored_file",ref:e},runner:r,config:n,variables:this.resolveBuildVariables(i),properties:o,internal:this.internal,cookie:d}))).data;if(!c?.job_id)throw Error("Cloud build create_job response did not return job_id");let u=eV[c.status]||String(c.status);return tC.success("Cloud build job created",{jobId:c.job_id}),tC.info("Cloud build status",{status:u}),c.job_id}async cancel({jobId:e,reason:t}){if(!e)throw Error("Cloud cancel requires job id.");let r=await this.resolveAppId("cancel"),n=await this.resolveCookie(),i=await this.runWithSpinner("Canceling cloud build job...",()=>s2({appKey:r,jobId:e,reason:t||"Canceled by doubao CLI",internal:this.internal,cookie:n})),o=i.data?.job_id;if(!o)throw Error("Cloud build cancel response did not return job_id");return tC.success("Cloud build job canceled",{jobId:o}),o}async getStatus({jobId:e}){if(!e)throw Error("Cloud status requires job id.");let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=(await s4({appKey:t,jobId:e,internal:this.internal,cookie:r})).data;if(!n)throw Error("Cloud build status response did not return data");let i=eV[n.status]||String(n.status);return tC.info("Cloud build job",{jobId:n.job_id}),tC.info("Cloud build status",{status:i}),n}async log({jobId:e,start:t,end:r}){if(!e)throw Error("Cloud log requires job id.");let n=Number(t??1),i=Number(r??n+200-1);if(!Number.isInteger(n)||!Number.isInteger(i)||n<1||i<n)throw Error("Cloud log requires a valid line range.");let o=await this.resolveAppId("log"),a=await this.resolveCookie(),s=(await s5({appKey:o,jobId:e,start:n,end:i,internal:this.internal,cookie:a})).data;if(!s)throw Error("Cloud build log response did not return data");return this.printLogLines(s.lines),tC.info("Cloud build logs fetched",{start:s.start??n,end:s.end??i,totalLineCount:s.total_line_count}),s}async waitForBuildJob({jobId:e}){let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=le("Waiting for cloud build to finish...").start(),i=!1;try{for(;;){let o=await s4({appKey:t,jobId:e,internal:this.internal,cookie:r}),a=o.data?.status,s=void 0===a?"UNKNOWN":eV[a]||String(a);if(n.text=`Cloud build status: ${s}`,void 0!==a&&lt.has(a)){if(a===eV.SUCCESS){n.succeed(`Cloud build status: ${s}`),i=!0;return}throw n.fail(`Cloud build status: ${s}`),i=!0,await this.printFailureLogs({appId:t,jobId:e,cookie:r}),Error(`Cloud build ended with status: ${s}`)}await new Promise(e=>setTimeout(e,5e3))}}catch(e){throw i||n.fail(),e}}async printFailureLogs({appId:e,jobId:t,cookie:r}){let n=1,i=0,o=!1;try{for(tC.info("Fetching cloud build failure logs");i<1e3&&n<=1e3;){let a=Math.min(n+200-1,1e3),s=(await s5({appKey:e,jobId:t,start:n,end:a,internal:this.internal,cookie:r})).data;if(!s||0===s.lines.length)break;this.printLogLines(s.lines),i+=s.lines.length;let l=s.lines.at(-1)?.line_number,p=void 0!==l&&l>=n?l+1:void 0!==s.end&&s.end>=n?s.end+1:n,d=p>n;if(!(o=s.has_more_after&&d))break;n=p}o&&tC.warn("Cloud build failure logs truncated",{limit:1e3,jobId:t})}catch(e){tC.warn("Failed to fetch cloud build failure logs",{reason:a3(e)})}}async resolveCookie(){return await sC(this.options,{internal:this.internal})}resolveBuildVariables(e){let t=new Map;for(let[e,r]of Object.entries(this.resolveEnv()))t.set(e,{name:e,value:r,env_var_name:e});for(let[e,r]of Object.entries(this.resolveSecretEnv()))t.set(e,{name:e,value:r,env_var_name:e,is_secret:!0});for(let r of e||[])t.set(r.env_var_name||r.name,r);return t.size>0?Array.from(t.values()):void 0}resolveEnv(){return this.options.env?(this.env??=ln(this.resolveAppPath(this.options.env),"Env"),this.env):{}}resolveSecretEnv(){return this.options.secretEnv?(this.secretEnv??=ln(this.resolveAppPath(this.options.secretEnv),"Secret env"),this.secretEnv):{}}resolveAppPath(e){return tn.isAbsolute(e)?e:tn.resolve(this.appDir,e)}async resolveAppId(e){let{appId:t}=await this.resolveAppInfo();if(!t)throw Error(`Cloud ${e} requires appId in doubao.config.ts or src/app.config.ts.`);return t}async resolveAppInfo(){if(this.appInfo)return this.appInfo;let e=await a7({cwd:this.appDir,customConfigFile:this.options.config}),t=await se({cwd:this.appDir})??{};return this.appInfo={appId:e.experiments?.taro?.appId?e.experiments?.taro?.appId:t.appId,appConfig:t},this.appInfo}logSourceDiagnostics(e){for(let t of e.warnings)tC.warn(t);for(let t of e.blockers)tC.error(t)}printLogLines(e){for(let t of e)console.log(t.content)}async runWithSpinner(e,t){let r=le(e).start();try{let e=await t(e=>{r.text=e});return r.succeed(),e}catch(e){throw r.fail(),e}}}function ln(e,t){if(!tr.existsSync(e))throw Error(`${t} file does not exist: ${e}`);return function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.trim();if(!e||e.startsWith("#"))continue;let n=e.startsWith("export ")?e.slice(7).trimStart():e,i=n.indexOf("=");if(i<=0)continue;let o=n.slice(0,i).trim();/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)&&(t[o]=function(e){let t=e[0];if(('"'===t||"'"===t)&&e.endsWith(t))return e.slice(1,-1);let r=e.indexOf(" #");return -1===r?e:e.slice(0,r).trimEnd()}(n.slice(i+1).trim()))}return t}(tr.readFileSync(e,"utf8"))}async function li(e){let t=await tD(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function lo({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))},o=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:a})=>{0===r.size&&o(Object.keys(a)),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})=>{o(Object.keys(e))})),n.onDevCompileDone(()=>{if(r.size>0){for(let e of r.keys())r.set(e,{percentage:1,stage:"done"});i()}e?.onDevCompileDone?.()})}}]}class la{appDirectory;launcher;constructor(e,t=s1){this.appDirectory=e,this.launcher=new t(e)}createCloudBuildLauncher(e={}){return new lr(e,this.appDirectory||process.cwd())}async create(e){await ec(e)}async dev(e={}){let{compileHooks:t,output:r,simulator:n,...i}=e,o=n;if("object"==typeof n){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i,...a}=n;o={...a,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i}}}let a=()=>this.launcher.dev({...i,...void 0!==o?{openWebDebugger:o}:{},rsbuildPlugins:lo({compileHooks:t,output:r}),signingEncryptionOptions:e.signingEncryptionOptions});return r?await ef.run(r,a):await a()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...r}=e;await this.launcher.build({...r,rsbuildPlugins:lo({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!e8(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:o,skipAdbForegroundAppWatch:a}=e,s=await li({debugDriver:o,deviceId:r,skipAdbForegroundAppWatch:a}),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:o,deviceId:a,skipAdbForegroundAppWatch:s}=e,l=await li({debugDriver:o,deviceId:a,skipAdbForegroundAppWatch:s}),p=this.launcher.context.metadata.appId;l.openPage({appId:p,pageId:t,pageData:r,pageSettings:n,mode:i})}async callTool(e){let{toolId:t,toolData:r,debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}=e,a=await li({debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}),s=this.launcher.context.metadata.appId;a.callTool({appId:s,toolId:t,toolData:r})}async executeDebugScene(e){let{matchedScene:t,variables:r,deviceId:n,debugDriver:i,skipAdbForegroundAppWatch:o}=e,a=this.launcher.context.metadata.appId,s=await li({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:o});await tL({matchedScene:t,appId:a,driver:s,variables:r})}async getDebugScenes(){let e=await tN(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await tR(e.path)})))}async cloud(e={}){let{versionTag:t,logs:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).start({versionTag:t,logs:r,runner:n,config:i,variables:o,properties:a})}async cloudUpload(e={}){let{packOnly:t,outputDir:r,...n}=e;return await this.createCloudBuildLauncher(n).upload({packOnly:t,outputDir:r})}async cloudPackage(e={}){let{outputDir:t,...r}=e;return await this.createCloudBuildLauncher(r).package({outputDir:t})}async cloudBuild(e){let{sourceRef:t,versionTag:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).build({sourceRef:t,versionTag:r,runner:n,config:i,variables:o,properties:a})}async cloudCancel(e){let{jobId:t,reason:r,...n}=e;return await this.createCloudBuildLauncher(n).cancel({jobId:t,reason:r})}async cloudGetStatus(e){let{jobId:t,...r}=e;return await this.createCloudBuildLauncher(r).getStatus({jobId:t})}async cloudLog(e){let{jobId:t,start:r,end:n,...i}=e;return await this.createCloudBuildLauncher(i).log({jobId:t,start:r,end:n})}async deploy(e){let{versionTag:t,cookie:r,token:n,appKey:i,signingEncryptionOptions:o}=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:o,token:n,versionTag:t});let{manifest:a}=this.launcher.context;try{return await sV({versionTag:this.launcher.context.versionTag,...i?{appKey:i}:{},manifest:a,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:r,token:n})}finally{tc()||t3.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{la as DoubaoAppsSDK,a3 as error_getErrorMessage};
326
+ `)}(a,n,e,t,o)),{entry:r}}),i.worker.hooks.collectMetaData.tapPromise(ra,async({collector:n})=>{n.addAppMeta({name:e,appId:t,icons:r})}),i.view.hooks.collectMetaData.tapPromise({name:ra,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:t6(t,n),path:t7(t)})}),Object.entries(r).forEach(([t,r])=>{let i,{folderName:o}=r;e.addWidgetMeta(t,(i=t6(t,o),{...n?.[o]??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(o.version),this.context.compileLifecycle.builderInitStartTime=Date.now();let S=await a1({options:i,commandType:e,context:this.context,web:b,rsbuildPlugins:r},this.pluginSystem);return{userConfig:i,builder:S}}catch(t){throw ak.report({appDirectory:this.appDirectory,context:this.context===n?void 0:this.context,scene:e===eR.DEV?"dev_initial":e,status:"failed",errorStage:"prepare",error:t}),t}}async dev(e){let t,{builder:r}=await this.prepare(eR.DEV,e,e.rsbuildPlugins);this.context.manifestSettings=function({cwd:e=process.cwd()}={}){let t=eK.resolve(e,a9);if(t2.existsSync(t))try{let e=JSON.parse(t2.readFileSync(t,"utf-8"));if(!J(e))throw TypeError("Development config must be a JSON object");return e}catch(e){tx.warn("Failed to load development config file; ignoring it",{path:t,reason:a2(e)});return}}({cwd:this.appDirectory});let n=await r.startDevServer(),i=ni(n.port),o=this.context.webDebuggerLaunchOptions;try{t=o?await at(this.context,{appId:this.context.appId,appDirectory:this.appDirectory,artifactOrigin:i,env:{...this.context.env,...o.env??{}},mcpEndpoint:o.mcpEndpoint,mcpHeaders:o.mcpHeaders,openBrowser:o.openBrowser,simulator:o.simulator,eventsConfigReader:this.context.eventsResources?.readJson,eventsConfigSourcePath:this.context.eventsResources?.sourcePath,toolsConfigReader:this.context.toolsResources?.readToolsJson,toolsConfigSourcePath:this.context.toolsResources?.toolsSourcePath,simulatorManifestReader:o.simulator?.manifestPath?void 0:this.context.toolsResources?.readManifestYaml,simulatorManifestSourcePath:o.simulator?.manifestPath?void 0:this.context.toolsResources?.manifestSourcePath}):void 0}catch(e){throw await n.server.close(),e}let a=async()=>{tI.info("Shutting down...");try{await t?.close(),await n.server.close()}finally{await ak.flush()}tI.info("dev server closed")};return{host:i,...t?{webDebugger:t}:{},closeServer:a}}async build(e){let{builder:t}=await this.prepare(eR.BUILD,e,e.rsbuildPlugins);try{await t.build()}finally{if(e.skipCleanupRootPath||tc()){if(e.archive&&e.channel){let{channel:t}=e;await t5({channelName:t,manifest:this.context.manifest,rootPath:this.rootPath})}}else tr.rmSync(this.rootPath,{recursive:!0,force:!0})}}async analyze(e){let{builder:t}=await this.prepare(eR.ANALYZE,e);await t.build()}async perf(e){let{builder:t}=await this.prepare(eR.PERF,e);await t.build()}async deploy(e){let{builder:t}=await this.prepare(eR.DEPLOY,e),r=e.deployType||t8.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!==t8.NORMAL)return void tO.error("Please use deploy plugin in 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(),await sV({...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===t8.NORMAL)&&await t.build();try{await this.pluginSystem.callDeployHooks("deploy",{deployType:r})}finally{await this.pluginSystem.callDeployHooks("afterDeploy",{})}}async run(e,t){switch(e){case tU.DEV:return await this.dev(t);case tU.BUILD:return await this.build(t);case tU.ANALYZE:return await this.analyze(t);case tU.PERF:return await this.perf(t);case tU.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 a7({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}async getAppConfig(){if(!this._appConfigLoaded){let e=await this.getUserConfig({});if(e.experiments?.taro)return this._appConfig=await sr({cwd:this.appDirectory}),this._appConfigLoaded=!0,this._appConfig;this._appConfig=await se({cwd:this.appDirectory}),this._appConfigLoaded=!0}return this._appConfig}async analyzeConvention(e,t){let{pages:r,widgets:n,auth:i}=await sc(e,t),{app:o,tools:a}=await sd(e,t.tools);return{pages:r,widgets:n,auth:i,app:o,tools:a}}}async function s2({appKey:e,versionTag:t,cloudBuildSource:r,runner:n,config:i,variables:o,properties:a,internal:s,domainId:l,cookie:p}){return await ic({internal:s,domainId:l,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/versions/${encodeURIComponent(t)}/cloud_build/create_job`,method:"POST",body:JSON.stringify({cloud_build_source:r,runner:n,config:i,variables:o,properties:a}),headers:{"Content-Type":"application/json",...p?{Cookie:p}:{}}})}async function s3({appKey:e,jobId:t,reason:r,internal:n,domainId:i,cookie:o}){return await ic({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/cancel`,method:"POST",body:JSON.stringify({reason:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}}})}async function s4({appKey:e,jobId:t,internal:r,domainId:n,cookie:i}){return await ic({internal:r,domainId:n,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}`,method:"GET",headers:i?{Cookie:i}:void 0})}async function s5({appKey:e,jobId:t,start:r,end:n,internal:i,domainId:o,cookie:a}){return await ic({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/jobs/${encodeURIComponent(t)}/logs`,query:{start:r,end:n},method:"GET",headers:a?{Cookie:a}:void 0})}async function s9({appKey:e,filename:t,sha256:r,category:n,internal:i,domainId:o,cookie:a,signal:s}){return await ic({internal:i,domainId:o,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/start`,method:"POST",body:JSON.stringify({filename:t,sha256:r,category:n}),headers:{"Content-Type":"application/json",...a?{Cookie:a}:{}},signal:s})}async function s8({appKey:e,uploadToken:t,size:r,internal:n,domainId:i,cookie:o,signal:a}){return await ic({internal:n,domainId:i,path:`/developer/resource_api/apps/${encodeURIComponent(e)}/cloud_build/file_upload/finish`,method:"POST",body:JSON.stringify({upload_token:t,size:r}),headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}},signal:a})}async function s6({appId:e,category:t,filePath:r,filename:n=tn.basename(r),...i}){let o=new Uint8Array(tr.readFileSync(r)),a=(0,ib.createHash)("sha256").update(o).digest("hex"),s=(await s9({appKey:e,filename:n,sha256:a,category:t,...i})).data;if(!s?.upload_url||!s.upload_token)throw Error("File upload session is incomplete");await s7({uploadUrl:s.upload_url,body:new Blob([o]),headers:s.upload_headers||{},signal:i.signal});let l=await s8({appKey:e,uploadToken:s.upload_token,size:o.byteLength,...i});if(!l.data?.stored_file_id)throw Error("File upload finish response did not return stored_file_id");return l.data}async function s7({uploadUrl:e,body:t,headers:r,signal:n}){let i=await ip(e,{method:"PUT",body:t,headers:r,signal:n}),o=i.headers.get("x-tt-logid")||"";if(!i.ok){let e=await i.text();throw Error([`File upload failed with HTTP ${i.status}`,e?`message: ${e}`:"",o?`log_id: ${o}`:""].filter(Boolean).join(", "))}}(eD=eV||(eV={}))[eD.WAITING=0]="WAITING",eD[eD.QUEUED=1]="QUEUED",eD[eD.RUNNING=2]="RUNNING",eD[eD.PENDING=3]="PENDING",eD[eD.SUCCESS=4]="SUCCESS",eD[eD.FAIL=5]="FAIL",eD[eD.CANCELED=6]="CANCELED",eD[eD.TIMEOUT=7]="TIMEOUT",eD[eD.UNKNOWN=8]="UNKNOWN",(e$=eG||(eG={}))[e$.UNKNOWN=0]="UNKNOWN",e$[e$.SOURCE=1]="SOURCE",e$[e$.ARTIFACT=2]="ARTIFACT";let le=f("../../../node_modules/.pnpm/ora@5.4.1/node_modules/ora/index.js"),lt=new Set([eV.SUCCESS,eV.FAIL,eV.CANCELED,eV.TIMEOUT]);class lr{options;cwd;appDir;internal;env;secretEnv;appInfo;constructor(e,t){this.options=e,this.cwd=t,this.appDir=tn.resolve(e.appDir||t),(0,y.loadEnv)({cwd:this.appDir,mode:e.envMode}),this.internal=((e=process.cwd())=>tl(e)===ti)(this.appDir)}async start({versionTag:e,logs:t,runner:r,config:n,variables:i,properties:o}={}){this.resolveEnv(),this.resolveSecretEnv();let a=await this.upload();if(!a)throw Error("Cloud upload did not return stored_file_id");let s=await this.build({sourceRef:a,versionTag:e,runner:r,config:n,variables:i,properties:o});return t&&await this.waitForBuildJob({jobId:s}),s}async package({outputDir:e}={}){let t={appDir:this.appDir,internal:this.internal,outputDir:e?tn.resolve(this.cwd,e):void 0},r=await this.runWithSpinner("Preparing cloud build source...",e=>N({...t,onProgress:e}));if(this.logSourceDiagnostics(r),tC.success("Cloud build source archive created",{archivePath:r.archivePath}),r.blockers.length>0)throw Error(r.blockers.join("\n"));return r.archivePath}async upload({packOnly:e,outputDir:t}={}){if(e)return void await this.package({outputDir:t});let r={appDir:this.appDir,internal:this.internal},n=await this.resolveAppId("upload"),i=await this.resolveCookie(),o=await this.runWithSpinner("Preparing cloud build source...",e=>N({...r,onProgress:e}));if(this.logSourceDiagnostics(o),o.blockers.length>0)throw Error(o.blockers.join("\n"));let a=(await this.runWithSpinner("Uploading cloud build source...",()=>s6({appId:n,category:eG.SOURCE,filePath:o.archivePath,internal:this.internal,cookie:i}))).stored_file_id;if(!a)throw Error("Cloud build source upload did not return stored_file_id");return tC.success("Cloud build source uploaded",{storedFileId:a}),a}async build({sourceRef:e,versionTag:t,runner:r,config:n,variables:i,properties:o}={}){let a;if(!e)throw Error("Cloud build requires --source-ref.");let{appId:s,appConfig:l}=await this.resolveAppInfo();if(!s)throw Error("Cloud build requires appId in doubao.config.ts or src/app.config.ts.");try{a=JSON.parse(tr.readFileSync(tn.resolve(this.appDir,"package.json"),"utf-8")).version}catch{a=void 0}let p=t||l.version||a;if(!p)throw Error("Cloud build requires --version-tag or version in src/app.config.ts/package.json.");let d=await this.resolveCookie(),c=(await this.runWithSpinner("Creating cloud build job...",()=>s2({appKey:s,versionTag:p,cloudBuildSource:{type:"stored_file",ref:e},runner:r,config:n,variables:this.resolveBuildVariables(i),properties:o,internal:this.internal,cookie:d}))).data;if(!c?.job_id)throw Error("Cloud build create_job response did not return job_id");let u=eV[c.status]||String(c.status);return tC.success("Cloud build job created",{jobId:c.job_id}),tC.info("Cloud build status",{status:u}),c.job_id}async cancel({jobId:e,reason:t}){if(!e)throw Error("Cloud cancel requires job id.");let r=await this.resolveAppId("cancel"),n=await this.resolveCookie(),i=await this.runWithSpinner("Canceling cloud build job...",()=>s3({appKey:r,jobId:e,reason:t||"Canceled by doubao CLI",internal:this.internal,cookie:n})),o=i.data?.job_id;if(!o)throw Error("Cloud build cancel response did not return job_id");return tC.success("Cloud build job canceled",{jobId:o}),o}async getStatus({jobId:e}){if(!e)throw Error("Cloud status requires job id.");let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=(await s4({appKey:t,jobId:e,internal:this.internal,cookie:r})).data;if(!n)throw Error("Cloud build status response did not return data");let i=eV[n.status]||String(n.status);return tC.info("Cloud build job",{jobId:n.job_id}),tC.info("Cloud build status",{status:i}),n}async log({jobId:e,start:t,end:r}){if(!e)throw Error("Cloud log requires job id.");let n=Number(t??1),i=Number(r??n+200-1);if(!Number.isInteger(n)||!Number.isInteger(i)||n<1||i<n)throw Error("Cloud log requires a valid line range.");let o=await this.resolveAppId("log"),a=await this.resolveCookie(),s=(await s5({appKey:o,jobId:e,start:n,end:i,internal:this.internal,cookie:a})).data;if(!s)throw Error("Cloud build log response did not return data");return this.printLogLines(s.lines),tC.info("Cloud build logs fetched",{start:s.start??n,end:s.end??i,totalLineCount:s.total_line_count}),s}async waitForBuildJob({jobId:e}){let t=await this.resolveAppId("build"),r=await this.resolveCookie(),n=le("Waiting for cloud build to finish...").start(),i=!1;try{for(;;){let o=await s4({appKey:t,jobId:e,internal:this.internal,cookie:r}),a=o.data?.status,s=void 0===a?"UNKNOWN":eV[a]||String(a);if(n.text=`Cloud build status: ${s}`,void 0!==a&&lt.has(a)){if(a===eV.SUCCESS){n.succeed(`Cloud build status: ${s}`),i=!0;return}throw n.fail(`Cloud build status: ${s}`),i=!0,await this.printFailureLogs({appId:t,jobId:e,cookie:r}),Error(`Cloud build ended with status: ${s}`)}await new Promise(e=>setTimeout(e,5e3))}}catch(e){throw i||n.fail(),e}}async printFailureLogs({appId:e,jobId:t,cookie:r}){let n=1,i=0,o=!1;try{for(tC.info("Fetching cloud build failure logs");i<1e3&&n<=1e3;){let a=Math.min(n+200-1,1e3),s=(await s5({appKey:e,jobId:t,start:n,end:a,internal:this.internal,cookie:r})).data;if(!s||0===s.lines.length)break;this.printLogLines(s.lines),i+=s.lines.length;let l=s.lines.at(-1)?.line_number,p=void 0!==l&&l>=n?l+1:void 0!==s.end&&s.end>=n?s.end+1:n,d=p>n;if(!(o=s.has_more_after&&d))break;n=p}o&&tC.warn("Cloud build failure logs truncated",{limit:1e3,jobId:t})}catch(e){tC.warn("Failed to fetch cloud build failure logs",{reason:a2(e)})}}async resolveCookie(){return await sC(this.options,{internal:this.internal})}resolveBuildVariables(e){let t=new Map;for(let[e,r]of Object.entries(this.resolveEnv()))t.set(e,{name:e,value:r,env_var_name:e});for(let[e,r]of Object.entries(this.resolveSecretEnv()))t.set(e,{name:e,value:r,env_var_name:e,is_secret:!0});for(let r of e||[])t.set(r.env_var_name||r.name,r);return t.size>0?Array.from(t.values()):void 0}resolveEnv(){return this.options.env?(this.env??=ln(this.resolveAppPath(this.options.env),"Env"),this.env):{}}resolveSecretEnv(){return this.options.secretEnv?(this.secretEnv??=ln(this.resolveAppPath(this.options.secretEnv),"Secret env"),this.secretEnv):{}}resolveAppPath(e){return tn.isAbsolute(e)?e:tn.resolve(this.appDir,e)}async resolveAppId(e){let{appId:t}=await this.resolveAppInfo();if(!t)throw Error(`Cloud ${e} requires appId in doubao.config.ts or src/app.config.ts.`);return t}async resolveAppInfo(){if(this.appInfo)return this.appInfo;let e=await a7({cwd:this.appDir,customConfigFile:this.options.config}),t=await se({cwd:this.appDir})??{};return this.appInfo={appId:e.experiments?.taro?.appId?e.experiments?.taro?.appId:t.appId,appConfig:t},this.appInfo}logSourceDiagnostics(e){for(let t of e.warnings)tC.warn(t);for(let t of e.blockers)tC.error(t)}printLogLines(e){for(let t of e)console.log(t.content)}async runWithSpinner(e,t){let r=le(e).start();try{let e=await t(e=>{r.text=e});return r.succeed(),e}catch(e){throw r.fail(),e}}}function ln(e,t){if(!tr.existsSync(e))throw Error(`${t} file does not exist: ${e}`);return function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.trim();if(!e||e.startsWith("#"))continue;let n=e.startsWith("export ")?e.slice(7).trimStart():e,i=n.indexOf("=");if(i<=0)continue;let o=n.slice(0,i).trim();/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)&&(t[o]=function(e){let t=e[0];if(('"'===t||"'"===t)&&e.endsWith(t))return e.slice(1,-1);let r=e.indexOf(" #");return -1===r?e:e.slice(0,r).trimEnd()}(n.slice(i+1).trim()))}return t}(tr.readFileSync(e,"utf8"))}async function li(e){let t=await tD(e);if(!t)throw Error("未检测到可用的 Android 设备。");return t}function lo({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))},o=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:a})=>{0===r.size&&o(Object.keys(a)),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})=>{o(Object.keys(e))})),n.onDevCompileDone(()=>{if(r.size>0){for(let e of r.keys())r.set(e,{percentage:1,stage:"done"});i()}e?.onDevCompileDone?.()})}}]}class la{appDirectory;launcher;constructor(e,t=s1){this.appDirectory=e,this.launcher=new t(e)}createCloudBuildLauncher(e={}){return new lr(e,this.appDirectory||process.cwd())}async create(e){await ec(e)}async dev(e={}){let{compileHooks:t,output:r,simulator:n,...i}=e,o=n;if("object"==typeof n){let{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i,...a}=n;o={...a,simulator:{businessTemplatesPath:e,manifestPath:t,skillsDirectory:r,targetOrigin:i}}}let a=()=>this.launcher.dev({...i,...void 0!==o?{openWebDebugger:o}:{},rsbuildPlugins:lo({compileHooks:t,output:r}),signingEncryptionOptions:e.signingEncryptionOptions});return r?await ef.run(r,a):await a()}async build(e={}){process.env.NODE_ENV="production";let{compileHooks:t,...r}=e;await this.launcher.build({...r,rsbuildPlugins:lo({compileHooks:t}),signingEncryptionOptions:e.signingEncryptionOptions,versionTag:e.versionTag})}async discoverWidgets(){return Object.values(this.launcher.context.metadata.getData().widgets).filter(({id:e})=>!e8(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:o,skipAdbForegroundAppWatch:a}=e,s=await li({debugDriver:o,deviceId:r,skipAdbForegroundAppWatch:a}),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:o,deviceId:a,skipAdbForegroundAppWatch:s}=e,l=await li({debugDriver:o,deviceId:a,skipAdbForegroundAppWatch:s}),p=this.launcher.context.metadata.appId;l.openPage({appId:p,pageId:t,pageData:r,pageSettings:n,mode:i})}async callTool(e){let{toolId:t,toolData:r,debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}=e,a=await li({debugDriver:n,deviceId:i,skipAdbForegroundAppWatch:o}),s=this.launcher.context.metadata.appId;a.callTool({appId:s,toolId:t,toolData:r})}async executeDebugScene(e){let{matchedScene:t,variables:r,deviceId:n,debugDriver:i,skipAdbForegroundAppWatch:o}=e,a=this.launcher.context.metadata.appId,s=await li({debugDriver:i,deviceId:n,skipAdbForegroundAppWatch:o});await tL({matchedScene:t,appId:a,driver:s,variables:r})}async getDebugScenes(){let e=await tN(this.appDirectory||process.cwd());return await Promise.all(e.map(async e=>({...e,content:await tR(e.path)})))}async cloud(e={}){let{versionTag:t,logs:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).start({versionTag:t,logs:r,runner:n,config:i,variables:o,properties:a})}async cloudUpload(e={}){let{packOnly:t,outputDir:r,...n}=e;return await this.createCloudBuildLauncher(n).upload({packOnly:t,outputDir:r})}async cloudPackage(e={}){let{outputDir:t,...r}=e;return await this.createCloudBuildLauncher(r).package({outputDir:t})}async cloudBuild(e){let{sourceRef:t,versionTag:r,runner:n,createJobConfig:i,variables:o,properties:a,...s}=e;return await this.createCloudBuildLauncher(s).build({sourceRef:t,versionTag:r,runner:n,config:i,variables:o,properties:a})}async cloudCancel(e){let{jobId:t,reason:r,...n}=e;return await this.createCloudBuildLauncher(n).cancel({jobId:t,reason:r})}async cloudGetStatus(e){let{jobId:t,...r}=e;return await this.createCloudBuildLauncher(r).getStatus({jobId:t})}async cloudLog(e){let{jobId:t,start:r,end:n,...i}=e;return await this.createCloudBuildLauncher(i).log({jobId:t,start:r,end:n})}async deploy(e){let{versionTag:t,cookie:r,token:n,appKey:i,signingEncryptionOptions:o}=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:o,token:n,versionTag:t});let{manifest:a}=this.launcher.context;try{return await sV({versionTag:this.launcher.context.versionTag,...i?{appKey:i}:{},manifest:a,rootPath:this.launcher.rootPath,internal:e.internal??this.launcher.context.internal,cookie:r,token:n})}finally{tc()||t2.rmSync(this.launcher.rootPath,{recursive:!0,force:!0})}}}export{la as DoubaoAppsSDK,a2 as error_getErrorMessage};